source: josm/trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/MapCSSParser.jj @ 10837

Last change on this file since 10837 was 10837, checked in by Don-vip, 3 years ago

see #11924 - extract MapCSS conditions to new class ConditionFactory (on the same model than ExpressionFactory) - should workaround Groovy bug with Java 9 (https://issues.apache.org/jira/browse/GROOVY-7879 ?)

  • Property svn:eol-style set to native
File size: 30.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2options {
3  STATIC = false;
4  OUTPUT_DIRECTORY = "parsergen";
5}
6
7PARSER_BEGIN(MapCSSParser)
8package org.openstreetmap.josm.gui.mappaint.mapcss.parsergen;
9
10import static org.openstreetmap.josm.tools.I18n.tr;
11
12import java.io.InputStream;
13import java.io.Reader;
14import java.util.ArrayList;
15import java.util.Arrays;
16import java.util.Collections;
17import java.util.List;
18import java.util.Locale;
19
20import org.openstreetmap.josm.Main;
21import org.openstreetmap.josm.gui.mappaint.Keyword;
22import org.openstreetmap.josm.gui.mappaint.mapcss.Condition;
23import org.openstreetmap.josm.gui.mappaint.mapcss.Condition.Context;
24import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory;
25import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.KeyMatchType;
26import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.Op;
27import org.openstreetmap.josm.gui.mappaint.mapcss.Expression;
28import org.openstreetmap.josm.gui.mappaint.mapcss.ExpressionFactory;
29import org.openstreetmap.josm.gui.mappaint.mapcss.ExpressionFactory.NullExpression;
30import org.openstreetmap.josm.gui.mappaint.mapcss.Instruction;
31import org.openstreetmap.josm.gui.mappaint.mapcss.LiteralExpression;
32import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSException;
33import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
34import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule.Declaration;
35import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
36import org.openstreetmap.josm.gui.mappaint.mapcss.Selector;
37import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.ChildOrParentSelector;
38import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector;
39import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.LinkSelector;
40import org.openstreetmap.josm.gui.mappaint.mapcss.Subpart;
41import org.openstreetmap.josm.tools.ColorHelper;
42import org.openstreetmap.josm.tools.Pair;
43import org.openstreetmap.josm.tools.Utils;
44
45/**
46 * MapCSS parser.
47 *
48 * Contains two independent grammars:
49 * (a) the preprocessor and (b) the main mapcss parser.
50 *
51 * The preprocessor handles @supports and @media syntax (@media is deprecated).
52 * Basically this allows to write one style for different versions of JOSM (or different editors).
53 * When the @supports condition is not fulfilled, it should simply skip over
54 * the whole section and not attempt to parse the possibly unknown
55 * grammar. It preserves whitespace and comments, in order to keep the
56 * line and column numbers in the error messages correct for the second pass.
57 *
58 */
59public class MapCSSParser {
60    MapCSSStyleSource sheet;
61    StringBuilder sb;
62    int declarationCounter;
63
64    /**
65     * Nicer way to refer to a lexical state.
66     */
67    public static enum LexicalState {
68        PREPROCESSOR(0), /* the preprocessor */
69        DEFAULT(2);      /* the main parser */
70       
71        int idx; // the integer, which javacc assigns to this state
72       
73        LexicalState(int idx) {
74            if (!this.name().equals(MapCSSParserTokenManager.lexStateNames[idx])) {
75                throw new RuntimeException();
76            }
77            this.idx = idx;
78        }
79    };
80   
81    /**
82     * Constructor which initializes the parser with a certain lexical state.
83     * @param in input
84     * @param encoding contents encoding
85     * @param initState initial state
86     */
87    public MapCSSParser(InputStream in, String encoding, LexicalState initState) {
88        this(createTokenManager(in, encoding, initState));
89        declarationCounter = 0;
90    }
91
92    protected static MapCSSParserTokenManager createTokenManager(InputStream in, String encoding, LexicalState initState) {
93        SimpleCharStream scs;
94        try {
95            scs = new SimpleCharStream(in, encoding, 1, 1);
96        } catch (java.io.UnsupportedEncodingException e) {
97            throw new RuntimeException(e);
98        }
99        return new MapCSSParserTokenManager(scs, initState.idx);
100    }
101
102    /**
103     * Constructor which initializes the parser with a certain lexical state.
104     * @param in input
105     * @param initState initial state
106     */
107    public MapCSSParser(Reader in, LexicalState initState) {
108        this(createTokenManager(in, initState));
109        declarationCounter = 0;
110    }
111
112    protected static MapCSSParserTokenManager createTokenManager(Reader in, LexicalState initState) {
113        final SimpleCharStream scs = new SimpleCharStream(in, 1, 1);
114        return new MapCSSParserTokenManager(scs, initState.idx);
115    }
116}
117PARSER_END(MapCSSParser)
118
119/**
120 * Token definitions
121 *
122 * Lexical states for the preprocessor: <PREPROCESSOR>, <PP_COMMENT>
123 * Lexical states for the main parser: <DEFAULT>, <COMMENT>
124 */
125 
126<PREPROCESSOR>
127TOKEN:
128{
129    < PP_AND: "and" >
130|   < PP_OR: "or" >
131|   < PP_NOT: "not" >
132|   < PP_SUPPORTS: "@supports" >
133|   < PP_MEDIA: "@media" >
134|   < PP_NEWLINECHAR: "\n" | "\r" | "\f" >
135|   < PP_WHITESPACE: " " | "\t" >
136|   < PP_COMMENT_START: "/*" > : PP_COMMENT
137}
138
139<PP_COMMENT>
140TOKEN:
141{
142    < PP_COMMENT_END: "*/" > : PREPROCESSOR
143}
144
145<PP_COMMENT>
146MORE:
147{
148    < ~[] >
149}
150
151<DEFAULT>
152TOKEN [IGNORE_CASE]:
153{
154 /* Special keyword in some contexts, ordinary identifier in other contexts.
155    Use the parsing rule <code>ident()</code> to refer to a general
156    identifier, including "set". */
157   < SET: "set" >
158}
159
160<DEFAULT,PREPROCESSOR>
161TOKEN:
162{
163    < IDENT: ["a"-"z","A"-"Z","_"] ( ["a"-"z","A"-"Z","_","-","0"-"9"] )* >
164|   < UINT: ( ["0"-"9"] )+ >
165|   < STRING: "\"" ( [" ","!","#"-"[","]"-"~","\u0080"-"\uFFFF"] | "\\\"" | "\\\\" )*  "\"" >
166|   < #PREDEFINED: "\\" ["d","D","s","S","w","W","b","B","A","G","Z","z"] >
167|   < #REGEX_CHAR_WITHOUT_STAR: [" "-")","+"-".","0"-"[","]"-"~","\u0080"-"\uFFFF"] | "\\/" | "\\\\" | "\\[" | "\\]" | "\\+" | "\\." | "\\'" | "\\\"" |  "\\(" | "\\)" | "\\{" | "\\}" | "\\?" | "\\*" | "\\^" | "\\$" | "\\|" | "\\p" |<PREDEFINED> >
168|   < REGEX: "/" <REGEX_CHAR_WITHOUT_STAR> ( <REGEX_CHAR_WITHOUT_STAR> | "*" )*  "/" >
169|   < LBRACE: "{" >
170|   < RBRACE: "}" >
171|   < LPAR: "(" >
172|   < RPAR: ")" >
173|   < COMMA: "," >
174|   < COLON: ":" >
175}
176
177<PREPROCESSOR>
178TOKEN:
179{
180    < PP_SOMETHING_ELSE : ~[] >
181}
182
183<DEFAULT>
184TOKEN:
185{
186    < UFLOAT: ( ["0"-"9"] )+ ( "." ( ["0"-"9"] )+ )? >
187|   < #H: ["0"-"9","a"-"f","A"-"F"] >
188|   < HEXCOLOR: "#" ( <H><H><H><H><H><H><H><H> | <H><H><H><H><H><H> | <H><H><H> ) >
189|   < S: ( " " | "\t" | "\n" | "\r" | "\f" )+ >
190|   < STAR: "*" >
191|   < SLASH: "/" >
192|   < LSQUARE: "[" >
193|   < RSQUARE: "]" >
194|   < GREATER_EQUAL: ">=" >
195|   < LESS_EQUAL: "<=" >
196|   < GREATER: ">" >
197|   < LESS: "<" >
198|   < EQUAL: "=" >
199|   < EXCLAMATION: "!" >
200|   < TILDE: "~" >
201|   < DCOLON: "::" >
202|   < SEMICOLON: ";" >
203|   < PIPE: "|" >
204|   < PIPE_Z: "|z" >
205|   < PLUS: "+" >
206|   < MINUS: "-" >
207|   < AMPERSAND: "&" >
208|   < QUESTION: "?" >
209|   < DOLLAR: "$" >
210|   < CARET: "^" >
211|   < FULLSTOP: "." >
212|   < DEG: "°" >
213|   < ELEMENT_OF: "∈" >
214|   < CROSSING: "⧉" >
215|   < PERCENT: "%" >
216|   < COMMENT_START: "/*" > : COMMENT
217|   < UNEXPECTED_CHAR : ~[] > // avoid TokenMgrErrors because they are hard to recover from
218}
219
220<COMMENT>
221TOKEN:
222{
223    < COMMENT_END: "*/" > : DEFAULT
224}
225
226<COMMENT>
227SKIP:
228{
229    < ~[] >
230}
231
232
233/*
234 * Preprocessor parser definitions:
235 *
236 * <pre>
237 *
238 * {@literal @media} { ... } queries are supported, following http://www.w3.org/TR/css3-mediaqueries/#syntax
239 *
240 *                               media_query
241 *         ___________________________|_______________________________
242 *        |                                                           |
243 * {@literal @media} all and (min-josm-version: 7789) and (max-josm-version: 7790), all and (user-agent: xyz) { ... }
244 *                |______________________|
245 *                          |
246 *                    media_expression
247 * </pre>
248 */
249 
250
251/**
252 * root method for the preprocessor.
253 * @param sheet MapCSS style source
254 * @return result string
255 * @throws ParseException in case of parsing error
256 */
257String pp_root(MapCSSStyleSource sheet):
258{
259}
260{
261    { sb = new StringBuilder(); this.sheet = sheet; }
262    pp_black_box(true) <EOF>
263    { return sb.toString(); }
264}
265
266/**
267 * Parse any unknown grammar (black box).
268 *
269 * Only stop when "@media" is encountered and keep track of correct number of
270 * opening and closing curly brackets.
271 *
272 * @param write false if this content should be skipped (@pp_media condition is not fulfilled), true otherwise
273 * @throws ParseException in case of parsing error
274 */
275void pp_black_box(boolean write):
276{
277    Token t;
278}
279{
280    (
281        (t=<PP_AND> | t=<PP_OR> | t=<PP_NOT> | t=<UINT> | t=<STRING> | t=<REGEX> | t=<LPAR> | t=<RPAR> | t=<COMMA> | t=<COLON> | t=<IDENT> | t=<PP_SOMETHING_ELSE>) { if (write) sb.append(t.image); }
282        |
283            pp_w1()
284        |
285            pp_supports(!write)
286        |
287            pp_media(!write)
288        |
289            t=<LBRACE> { if (write) sb.append(t.image); } pp_black_box(write) t=<RBRACE> { if (write) sb.append(t.image); }
290    )*
291}
292
293/**
294 * Parses an @supports rule.
295 *
296 * @param ignore if the content of this rule should be ignored
297 * (because we are already inside a @supports block that didn't pass)
298 * @throws ParseException in case of parsing error
299 */
300void pp_supports(boolean ignore):
301{
302    boolean pass;
303}
304{
305    <PP_SUPPORTS> pp_w()
306    pass=pp_supports_condition()
307    <LBRACE>
308    pp_black_box(pass && !ignore)
309    <RBRACE>
310}
311
312/**
313 * Parses the condition of the @supports rule.
314 *
315 * Unlike other parsing rules, grabs trailing whitespace.
316 * @return true, if the condition is fulfilled
317 * @throws ParseException in case of parsing error
318 */
319boolean pp_supports_condition():
320{
321    boolean pass;
322    boolean q;
323}
324{
325    (
326        <PP_NOT> pp_w() q=pp_supports_condition_in_parens() { pass = !q; } pp_w()
327    |
328        LOOKAHEAD(pp_supports_condition_in_parens() pp_w() <PP_AND>)
329        pass=pp_supports_condition_in_parens() pp_w()
330        ( <PP_AND> pp_w() q=pp_supports_condition_in_parens() { pass = pass && q; } pp_w() )+
331    |
332        LOOKAHEAD(pp_supports_condition_in_parens() pp_w() <PP_OR>)
333        pass=pp_supports_condition_in_parens() pp_w()
334        ( <PP_OR> pp_w() q=pp_supports_condition_in_parens() { pass = pass || q; } pp_w() )+
335    |
336        pass=pp_supports_condition_in_parens() pp_w()
337    )
338    { return pass; }
339}
340
341/**
342 * Parses something in parenthesis inside the condition of the @supports rule.
343 *
344 * @return true, if the condition is fulfilled
345 * @throws ParseException in case of parsing error
346 */
347boolean pp_supports_condition_in_parens():
348{
349    boolean pass;
350}
351{
352    (
353        LOOKAHEAD(pp_supports_declaration_condition())
354        pass=pp_supports_declaration_condition()
355    |
356        <LPAR> pp_w() pass=pp_supports_condition() <RPAR>
357    )
358    { return pass; }
359}
360
361/**
362 * Parse an @supports declaration condition, e.&nbsp;g. a single (key:value) or (key) statement.
363 *
364 * The parsing rule {@link #literal()} from the main mapcss parser is reused here.
365 *
366 * @return true if the condition is fulfilled
367 * @throws ParseException in case of parsing error
368 */
369boolean pp_supports_declaration_condition():
370{
371    Token t;
372    String feature;
373    Object val = null;
374}
375{
376    <LPAR> pp_w() t=<IDENT> { feature = t.image; } pp_w() ( <COLON> pp_w() val=literal() )? <RPAR>
377    { return this.sheet.evalSupportsDeclCondition(feature, val); }
378}
379
380// deprecated
381void pp_media(boolean ignore):
382{
383    boolean pass = false;
384    boolean q;
385    boolean empty = true;
386}
387{
388    {
389        if (sheet != null) {
390            String msg = tr("Detected deprecated ''{0}'' in ''{1}'' which will be removed shortly. Use ''{2}'' instead.",
391                            "@media", sheet.getDisplayString(), "@supports");
392            Main.error(msg);
393            sheet.logWarning(msg);
394        }
395    }
396    <PP_MEDIA> pp_w()
397    ( q=pp_media_query() { pass = pass || q; empty = false; }
398        ( <COMMA> pp_w() q=pp_media_query() { pass = pass || q; } )*
399    )?
400    <LBRACE>
401    pp_black_box((empty || pass) && !ignore)
402    <RBRACE>
403}
404
405// deprecated
406boolean pp_media_query():
407{
408    Token t;
409    String mediatype = "all";
410    boolean pass = true;
411    boolean invert = false;
412    boolean e;
413}
414{
415    ( <PP_NOT> { invert = true; } pp_w() )?
416    (
417            t=<IDENT> { mediatype = t.image.toLowerCase(Locale.ENGLISH); } pp_w()
418            ( <PP_AND> pp_w() e=pp_media_expression() { pass = pass && e; } pp_w() )*
419        |
420            e=pp_media_expression() { pass = pass && e; } pp_w()
421            ( <PP_AND> pp_w() e=pp_media_expression() { pass = pass && e; } pp_w() )*
422    )
423    {
424        if (!"all".equals(mediatype)) {
425            pass = false;
426        }
427        return invert ? (!pass) : pass;
428    }
429}
430
431/**
432 * Parse an @media expression.
433 *
434 * The parsing rule {@link #literal()} from the main mapcss parser is reused here.
435 *
436 * @return true if the condition is fulfilled
437 * @throws ParseException in case of parsing error
438 */
439// deprecated
440boolean pp_media_expression():
441{
442    Token t;
443    String feature;
444    Object val = null;
445}
446{
447    <LPAR> pp_w() t=<IDENT> { feature = t.image; } pp_w() ( <COLON> pp_w() val=literal() )? <RPAR>
448    { return this.sheet.evalSupportsDeclCondition(feature, val); }
449}
450
451void pp_w1():
452{
453    Token t;
454}
455{
456    t=<PP_NEWLINECHAR> { sb.append(t.image); }
457        |
458    t=<PP_WHITESPACE> { sb.append(t.image); }
459        |
460    t=<PP_COMMENT_START> { sb.append(t.image); } t=<PP_COMMENT_END> { sb.append(t.image); }
461}
462
463void pp_w():
464{
465}
466{
467 ( pp_w1() )*
468}
469
470/*
471 * Parser definition for the main MapCSS parser:
472 *
473 * <pre>
474 *
475 *                       rule
476 *  _______________________|______________________________
477 * |                                                      |
478 *        selector                      declaration
479 *  _________|___________________   _________|____________
480 * |                             | |                      |
481 *
482 * way|z11-12[highway=residential] { color: red; width: 3 }
483 *
484 *    |_____||___________________|   |_________|
485 *       |            |                   |
486 *     zoom       condition          instruction
487 *
488 * more general:
489 *
490 * way|z13-[a=b][c=d]::subpart, way|z-3[u=v]:closed::subpart2 { p1 : val; p2 : val; }
491 *
492 * 'val' can be a literal, or an expression like "prop(width, default) + 0.8".
493 *
494 * </pre>
495 */
496
497int uint() :
498{
499    Token i;
500}
501{
502    i=<UINT> { return Integer.parseInt(i.image); }
503}
504
505int int_() :
506{
507    int i;
508}
509{
510    <MINUS> i=uint() { return -i; } | i=uint() { return i; }
511}
512
513float ufloat() :
514{
515    Token f;
516}
517{
518    ( f=<UFLOAT> | f=<UINT> )
519    { return Float.parseFloat(f.image); }
520}
521
522float float_() :
523{
524    float f;
525}
526{
527    <MINUS> f=ufloat() { return -f; } | f=ufloat() { return f; }
528}
529
530String string() :
531{
532    Token t;
533}
534{
535    t=<STRING>
536    { return t.image.substring(1, t.image.length() - 1).replace("\\\"", "\"").replace("\\\\", "\\"); }
537}
538
539String ident():
540{
541    Token t;
542    String s;
543}
544{
545    ( t=<IDENT> | t=<SET> ) { return t.image; }
546}
547
548String string_or_ident() :
549{
550    Token t;
551    String s;
552}
553{
554    ( s=ident() | s=string() ) { return s; }
555}
556
557String regex() :
558{
559    Token t;
560}
561{
562    t=<REGEX>
563    { return t.image.substring(1, t.image.length() - 1); }
564}
565
566/**
567 * white-space
568 * @throws ParseException in case of parsing error
569 */
570void s() :
571{
572}
573{
574    ( <S> )?
575}
576
577/**
578 * mix of white-space and comments
579 * @throws ParseException in case of parsing error
580 */
581void w() :
582{
583}
584{
585    ( <S> | <COMMENT_START> <COMMENT_END> )*
586}
587
588/**
589 * comma delimited list of floats (at least 2, all &gt;= 0)
590 * @return list of floats
591 * @throws ParseException in case of parsing error
592 */
593List<Float> float_array() :
594{
595    float f;
596    List<Float> fs = new ArrayList<Float>();
597}
598{
599    f=ufloat() { fs.add(f); }
600    (
601        <COMMA> s()
602        f=ufloat() { fs.add(f); }
603    )+
604    {
605        return fs;
606    }
607}
608
609/**
610 * entry point for the main parser
611 * @param sheet MapCSS style source
612 * @throws ParseException in case of parsing error
613 */
614void sheet(MapCSSStyleSource sheet):
615{
616}
617{
618    { this.sheet = sheet; }
619    w()
620    (
621        try {
622            rule() w()
623        } catch (MapCSSException mex) {
624            Main.error(mex);
625            error_skipto(RBRACE, mex);
626            w();
627        } catch (ParseException ex) {
628            error_skipto(RBRACE, null);
629            w();
630        }
631    )*
632    <EOF>
633}
634
635void rule():
636{
637    List<Selector> selectors;
638    Declaration decl;
639}
640{
641    selectors=selectors()
642    decl=declaration()
643    {
644        for (Selector s : selectors) {
645            sheet.rules.add(new MapCSSRule(s, decl));
646        }
647    }
648}
649
650List<Selector> selectors():
651{
652    List<Selector> selectors = new ArrayList<Selector>();
653    Selector sel;
654}
655{
656    sel=child_selector() { selectors.add(sel); }
657    (
658        <COMMA> w()
659        sel=child_selector() { selectors.add(sel); }
660    )*
661    { return selectors; }
662}
663
664Selector child_selector() :
665{
666    Selector.ChildOrParentSelectorType type = null;
667    Condition c;
668    List<Condition> conditions = new ArrayList<Condition>();
669    Selector selLeft;
670    LinkSelector selLink = null;
671    Selector selRight = null;
672}
673{
674    selLeft=selector() w()
675    (
676        (
677            (
678                (
679                    <GREATER> { type = Selector.ChildOrParentSelectorType.CHILD; }
680                |
681                    <LESS> { type = Selector.ChildOrParentSelectorType.PARENT; }
682                |
683                    <PLUS> { type = Selector.ChildOrParentSelectorType.SIBLING; }
684                )
685                ( ( c=condition(Context.LINK) | c=class_or_pseudoclass(Context.LINK) ) { conditions.add(c); } )*
686            |
687                <ELEMENT_OF> { type = Selector.ChildOrParentSelectorType.ELEMENT_OF; }
688            |
689                <CROSSING> { type = Selector.ChildOrParentSelectorType.CROSSING; }
690            )
691            w()
692        |
693            { /* <GREATER> is optional for child selector */ type = Selector.ChildOrParentSelectorType.CHILD; }
694        )
695        { selLink = new LinkSelector(conditions); }
696        selRight=selector() w()
697    )?
698    { return selRight != null ? new ChildOrParentSelector(selLeft, selLink, selRight, type) : selLeft; }
699}
700
701Selector selector() :
702{
703    Token base;
704    Condition c;
705    Pair<Integer, Integer> r = null;
706    List<Condition> conditions = new ArrayList<Condition>();
707    Subpart sub = null;
708}
709{
710    ( base=<IDENT> | base=<STAR> )
711    ( r=zoom() )?
712    ( ( c=condition(Context.PRIMITIVE) | c=class_or_pseudoclass(Context.PRIMITIVE) ) { conditions.add(c); } )*
713    ( sub=subpart() )?
714    { return new GeneralSelector(base.image, r, conditions, sub); }
715}
716
717Pair<Integer, Integer> zoom() :
718{
719    Integer min = 0;
720    Integer max = Integer.MAX_VALUE;
721}
722{
723    <PIPE_Z>
724    (
725            <MINUS> max=uint()
726        |
727        LOOKAHEAD(2)
728            min=uint() <MINUS> ( max=uint() )?
729        |
730            min=uint() { max = min; }
731    )
732    { return new Pair<Integer, Integer>(min, max); }
733}
734
735Condition condition(Context context) :
736{
737    Condition c;
738    Expression e;
739}
740{
741    <LSQUARE> s()
742    (
743        LOOKAHEAD( simple_key_condition(context) s() <RSQUARE> )
744            c=simple_key_condition(context) s() <RSQUARE> { return c; }
745        |
746        LOOKAHEAD( simple_key_value_condition(context) s() <RSQUARE> )
747            c=simple_key_value_condition(context) s() <RSQUARE> { return c; }
748        |
749            e=expression() <RSQUARE> { return ConditionFactory.createExpressionCondition(e, context); }
750    )
751}
752
753String tag_key() :
754{
755    String s, s2;
756    Token t;
757}
758{
759        s=string() { return s; }
760    |
761        s=ident() ( <COLON> s2=ident() { s += ':' + s2; } )* { return s; }
762}
763
764Condition simple_key_condition(Context context) :
765{
766    boolean not = false;
767    KeyMatchType matchType = null;;
768    String key;
769}
770{
771    ( <EXCLAMATION> { not = true; } )?
772    (
773        { matchType = KeyMatchType.REGEX; } key = regex()
774    |
775        key = tag_key()
776    )
777    ( LOOKAHEAD(2) <QUESTION> <EXCLAMATION> { matchType = KeyMatchType.FALSE; } )?
778    (              <QUESTION>               { matchType = KeyMatchType.TRUE;  } )?
779    { return ConditionFactory.createKeyCondition(key, not, matchType, context); }
780}
781
782Condition simple_key_value_condition(Context context) :
783{
784    String key;
785    String val;
786    float f;
787    int i;
788    KeyMatchType matchType = null;;
789    Op op;
790    boolean considerValAsKey = false;
791}
792{
793    (
794        key = regex() s() { matchType = KeyMatchType.REGEX; }
795    |
796        key=tag_key() s()
797    )
798    (
799        LOOKAHEAD(3)
800            (
801                    <EQUAL> <TILDE> { op=Op.REGEX; }
802                |
803                    <EXCLAMATION> <TILDE> { op=Op.NREGEX; }
804            )
805            s()
806            ( <STAR> { considerValAsKey=true; } )?
807            val=regex()
808        |
809            (
810                    <EXCLAMATION> <EQUAL> { op=Op.NEQ; }
811                |
812                    <EQUAL> { op=Op.EQ; }
813                |
814                    <TILDE> <EQUAL> { op=Op.ONE_OF; }
815                |
816                    <CARET> <EQUAL> { op=Op.BEGINS_WITH; }
817                |
818                    <DOLLAR> <EQUAL> { op=Op.ENDS_WITH; }
819                |
820                    <STAR> <EQUAL> { op=Op.CONTAINS; }
821            )
822            s()
823            ( <STAR> { considerValAsKey=true; } )?
824            (
825                LOOKAHEAD(2)
826                        i=int_() { val=Integer.toString(i); }
827                    |
828                        f=float_() { val=Float.toString(f); }
829                    |
830                        val=string_or_ident()
831            )
832        |
833            (
834                    <GREATER_EQUAL> { op=Op.GREATER_OR_EQUAL; }
835                |
836                    <GREATER> { op=Op.GREATER; }
837                |
838                    <LESS_EQUAL> { op=Op.LESS_OR_EQUAL; }
839                |
840                    <LESS> { op=Op.LESS; }
841            )
842            s()
843            f=float_() { val=Float.toString(f); }
844    )
845    { return KeyMatchType.REGEX == matchType
846            ? ConditionFactory.createRegexpKeyRegexpValueCondition(key, val, op)
847            : ConditionFactory.createKeyValueCondition(key, val, op, context, considerValAsKey); }
848}
849
850Condition class_or_pseudoclass(Context context) :
851{
852    String s;
853    boolean not = false;
854    boolean pseudo;
855}
856{
857    ( <EXCLAMATION> { not = true; } )?
858    (
859        <FULLSTOP> { pseudo = false; }
860    |
861        <COLON> { pseudo = true; }
862    )
863    s=ident()
864    { return pseudo
865        ? ConditionFactory.createPseudoClassCondition(s, not, context)
866        : ConditionFactory.createClassCondition(s, not, context); }
867}
868
869Subpart subpart() :
870{
871    String s;
872    Expression e;
873}
874{
875    <DCOLON>
876    (
877        s=ident() { return new Subpart.StringSubpart(s); }
878    |
879        <STAR> { return new Subpart.StringSubpart("*"); }
880    |
881        <LPAR> e=expression() <RPAR> { return new Subpart.ExpressionSubpart(e); }
882    )
883}
884
885Declaration declaration() :
886{
887    List<Instruction> ins = new ArrayList<Instruction>();
888    Instruction i;
889    Token key;
890    Object val = null;
891}
892{
893    <LBRACE> w()
894    (
895        (
896            <SET> w()
897            (<FULLSTOP>)? // specification allows "set .class" to set "class". we also support "set class"
898            key=<IDENT> w()
899            ( <EQUAL> val=expression() )?
900            { ins.add(new Instruction.AssignmentInstruction(key.image, val == null ? true : val, true)); }
901            ( <RBRACE> { return new Declaration(ins, declarationCounter++); } | <SEMICOLON> w() )
902        )
903    |
904        key=<IDENT> w() <COLON> w()
905        (
906            LOOKAHEAD( float_array() w() ( <SEMICOLON> | <RBRACE> ) )
907                val=float_array()
908                { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
909                w()
910                ( <RBRACE> { return new Declaration(ins, declarationCounter++); } | <SEMICOLON> w() )
911            |
912            LOOKAHEAD( expression() ( <SEMICOLON> | <RBRACE> ) )
913                val=expression()
914                { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
915                ( <RBRACE> { return new Declaration(ins, declarationCounter++); } | <SEMICOLON> w() )
916            |
917                val=readRaw() w() { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
918        )
919    )*
920    <RBRACE>
921    { return new Declaration(ins, declarationCounter++); }
922}
923
924/**
925 * General expression.
926 * Separate production rule for each level of operator precedence (recursive descent).
927 */
928Expression expression() :
929{
930    Expression e;
931}
932{
933    e=conditional_expression()
934    {
935        return e;
936    }
937}
938
939Expression conditional_expression() :
940{
941    Expression e, e1, e2;
942    String op = null;
943}
944{
945    e=or_expression()
946    (
947        <QUESTION> w()
948        e1=conditional_expression()
949        <COLON> w()
950        e2=conditional_expression()
951        {
952            e = ExpressionFactory.createFunctionExpression("cond", Arrays.asList(e, e1, e2));
953        }
954    )?
955    {
956        return e;
957    }
958}
959
960Expression or_expression() :
961{
962    Expression e, e2;
963    String op = null;
964}
965{
966    e=and_expression()
967    (
968        <PIPE> <PIPE> w()
969        e2=and_expression()
970        {
971            e = ExpressionFactory.createFunctionExpression("or", Arrays.asList(e, e2));
972        }
973    )*
974    {
975        return e;
976    }
977}
978
979Expression and_expression() :
980{
981    Expression e, e2;
982    String op = null;
983}
984{
985    e=relational_expression()
986    (
987        <AMPERSAND> <AMPERSAND> w()
988        e2=relational_expression()
989        {
990            e = ExpressionFactory.createFunctionExpression("and", Arrays.asList(e, e2));
991        }
992    )*
993    {
994        return e;
995    }
996}
997
998Expression relational_expression() :
999{
1000    Expression e, e2;
1001    String op = null;
1002}
1003{
1004    e=additive_expression()
1005    (
1006        (
1007            <GREATER_EQUAL> { op = "greater_equal"; }
1008            |
1009            <LESS_EQUAL> { op = "less_equal"; }
1010            |
1011            <GREATER> { op = "greater"; }
1012            |
1013            <LESS> { op = "less"; }
1014            |
1015            <EQUAL> ( <EQUAL> )? { op = "equal"; }
1016            |
1017            <EXCLAMATION> <EQUAL> { op = "not_equal"; }
1018        ) w()
1019        e2=additive_expression()
1020        {
1021            e = ExpressionFactory.createFunctionExpression(op, Arrays.asList(e, e2));
1022        }
1023    )?
1024    {
1025        return e;
1026    }
1027}
1028
1029Expression additive_expression() :
1030{
1031    Expression e, e2;
1032    String op = null;
1033}
1034{
1035    e=multiplicative_expression()
1036    (
1037        ( <PLUS> { op = "plus"; } | <MINUS> { op = "minus"; } ) w()
1038        e2=multiplicative_expression()
1039        {
1040            e = ExpressionFactory.createFunctionExpression(op, Arrays.asList(e, e2));
1041        }
1042    )*
1043    {
1044        return e;
1045    }
1046}
1047
1048Expression multiplicative_expression() :
1049{
1050    Expression e, e2;
1051    String op = null;
1052}
1053{
1054    e=unary_expression()
1055    (
1056        ( <STAR> { op = "times"; } | <SLASH> { op = "divided_by"; } ) w()
1057        e2=unary_expression()
1058        {
1059            e = ExpressionFactory.createFunctionExpression(op, Arrays.asList(e, e2));
1060        }
1061    )*
1062    {
1063        return e;
1064    }
1065}
1066
1067Expression unary_expression() :
1068{
1069    Expression e;
1070    String op = null;
1071}
1072{
1073    (
1074        <MINUS> { op = "minus"; } w()
1075    |
1076        <EXCLAMATION> { op = "not"; } w()
1077    )?
1078    e=primary() w()
1079    {
1080        if (op == null)
1081            return e;
1082        return ExpressionFactory.createFunctionExpression(op, Collections.singletonList(e));
1083    }
1084}
1085
1086Expression primary() :
1087{
1088    Expression nested;
1089    Expression fn;
1090    Object lit;
1091}
1092{
1093    LOOKAHEAD(3) // both function and identifier start with an identifier (+ optional whitespace)
1094        fn=function() { return fn; }
1095    |
1096        lit=literal()
1097        {
1098            if (lit == null)
1099                return NullExpression.INSTANCE;
1100            return new LiteralExpression(lit);
1101        }
1102    |
1103        <LPAR> w() nested=expression() <RPAR> { return nested; }
1104}
1105
1106Expression function() :
1107{
1108    Expression arg;
1109    String name;
1110    List<Expression> args = new ArrayList<Expression>();
1111}
1112{
1113    name=ident() w()
1114    <LPAR> w()
1115    (
1116        arg=expression() { args.add(arg); }
1117        ( <COMMA> w() arg=expression() { args.add(arg); } )*
1118    )?
1119    <RPAR>
1120    { return ExpressionFactory.createFunctionExpression(name, args); }
1121}
1122
1123Object literal() :
1124{
1125    String val, pref;
1126    Token t;
1127    Float f;
1128}
1129{
1130        LOOKAHEAD(2)
1131        pref=ident() t=<HEXCOLOR>
1132        { return Main.pref.getColor("mappaint." + (sheet == null ? "MapCSS" : sheet.title) + "." + pref, ColorHelper.html2color(t.image)); }
1133    |
1134        t=<IDENT> { return new Keyword(t.image); }
1135    |
1136        val=string() { return val; }
1137    |
1138        <PLUS> f=ufloat() { return new Instruction.RelativeFloat(f); }
1139    |
1140        LOOKAHEAD(2)
1141        f=ufloat_unit() { return f; }
1142    |
1143        f=ufloat() { return f; }
1144    |
1145        t=<HEXCOLOR> { return ColorHelper.html2color(t.image); }
1146}
1147
1148/**
1149 * Number followed by a unit.
1150 *
1151 * Returns angles in radians and lengths in pixels.
1152 */
1153Float ufloat_unit() :
1154{
1155    float f;
1156    String u;
1157}
1158{
1159    f=ufloat() ( u=ident() | <DEG> { u = "°"; } | <PERCENT> { u = "%"; } )
1160    {
1161        Double m = unit_factor(u);
1162        if (m == null)
1163            return null;
1164        return (float) (f * m);
1165    }
1166}
1167
1168JAVACODE
1169private Double unit_factor(String unit) {
1170    switch (unit) {
1171        case "deg":
1172        case "°": return Math.PI / 180;
1173        case "rad": return 1.;
1174        case "grad": return Math.PI / 200;
1175        case "turn": return 2 * Math.PI;
1176        case "%": return 0.01;
1177        case "px": return 1.;
1178        case "cm": return 96/2.54;
1179        case "mm": return 9.6/2.54;
1180        case "in": return 96.;
1181        case "q": return 2.4/2.54;
1182        case "pc": return 16.;
1183        case "pt": return 96./72;
1184        default: return null;
1185    }
1186}
1187
1188JAVACODE
1189void error_skipto(int kind, MapCSSException me) {
1190    if (token.kind == EOF)
1191        throw new ParseException("Reached end of file while parsing");
1192       
1193    Exception e = null;       
1194    ParseException pe = generateParseException();
1195
1196    if (me != null) {
1197        final Token token = Utils.firstNonNull(pe.currentToken.next, pe.currentToken);
1198        me.setLine(token.beginLine);
1199        me.setColumn(token.beginColumn);
1200        e = me;
1201    } else {
1202        e = new ParseException(pe.getMessage()); // prevent memory leak
1203    }
1204   
1205    Main.error("Skipping to the next rule, because of an error:");
1206    Main.error(e);
1207    if (sheet != null) {
1208        sheet.logError(e);
1209    }
1210    Token t;
1211    do {
1212        t = getNextToken();
1213    } while (t.kind != kind && t.kind != EOF);
1214    if (t.kind == EOF)
1215        throw new ParseException("Reached end of file while parsing");
1216}
1217
1218JAVACODE
1219/**
1220 * read everything to the next semicolon
1221 */
1222String readRaw() {
1223    Token t;
1224    StringBuilder s = new StringBuilder();
1225    while (true) {
1226        t = getNextToken();
1227        if ((t.kind == S || t.kind == STRING || t.kind == UNEXPECTED_CHAR) &&
1228                t.image.contains("\n")) {
1229            ParseException e = new ParseException(String.format("Warning: end of line while reading an unquoted string at line %s column %s.", t.beginLine, t.beginColumn));
1230            Main.error(e);
1231            if (sheet != null) {
1232                sheet.logError(e);
1233            }
1234        }
1235        if (t.kind == SEMICOLON || t.kind == EOF)
1236            break;
1237        s.append(t.image);
1238    }
1239    if (t.kind == EOF)
1240        throw new ParseException("Reached end of file while parsing");
1241    return s.toString();
1242}
1243
Note: See TracBrowser for help on using the repository browser.