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

Last change on this file since 8331 was 8331, checked in by simon04, 8 years ago

fix #10278 - MapCSSTagChecker: preprocess MapCSS for media queries support

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