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

Last change on this file since 8874 was 8874, checked in by simon04, 6 years ago

fix #10467 - MapCSS: allow comparisons in regexp key conditions

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