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

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

see #11593, see #11579 - MapCSS: display mapcss parsing exceptions early in case of later JavaCC exception

File size: 28.9 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 = new ArrayList<Selector>();
607    Selector sel;
608    Declaration decl;
609}
610{
611    sel=child_selector() { selectors.add(sel); }
612    (
613        <COMMA> w()
614        sel=child_selector() { selectors.add(sel); }
615    )*
616    decl=declaration()
617    {
618        for (Selector s : selectors) {
619            sheet.rules.add(new MapCSSRule(s, decl));
620        }
621    }
622}
623
624Selector child_selector() :
625{
626    Selector.ChildOrParentSelectorType type = null;
627    Condition c;
628    List<Condition> conditions = new ArrayList<Condition>();
629    Selector selLeft;
630    LinkSelector selLink = null;
631    Selector selRight = null;
632}
633{
634    selLeft=selector() w()
635    (
636        (
637            (
638                (
639                    <GREATER> { type = Selector.ChildOrParentSelectorType.CHILD; }
640                |
641                    <LESS> { type = Selector.ChildOrParentSelectorType.PARENT; }
642                |
643                    <PLUS> { type = Selector.ChildOrParentSelectorType.SIBLING; }
644                )
645                ( ( c=condition(Context.LINK) | c=class_or_pseudoclass(Context.LINK) ) { conditions.add(c); } )*
646            |
647                <ELEMENT_OF> { type = Selector.ChildOrParentSelectorType.ELEMENT_OF; }
648            |
649                <CROSSING> { type = Selector.ChildOrParentSelectorType.CROSSING; }
650            )
651            w()
652        |
653            { /* <GREATER> is optional for child selector */ type = Selector.ChildOrParentSelectorType.CHILD; }
654        )
655        { selLink = new LinkSelector(conditions); }
656        selRight=selector() w()
657    )?
658    { return selRight != null ? new ChildOrParentSelector(selLeft, selLink, selRight, type) : selLeft; }
659}
660
661Selector selector() :
662{
663    Token base;
664    Condition c;
665    Pair<Integer, Integer> r = null;
666    List<Condition> conditions = new ArrayList<Condition>();
667    Subpart sub = null;
668}
669{
670    ( base=<IDENT> | base=<STAR> )
671    ( r=zoom() )?
672    ( ( c=condition(Context.PRIMITIVE) | c=class_or_pseudoclass(Context.PRIMITIVE) ) { conditions.add(c); } )*
673    ( sub=subpart() )?
674    { return new GeneralSelector(base.image, r, conditions, sub); }
675}
676
677Pair<Integer, Integer> zoom() :
678{
679    Integer min = 0;
680    Integer max = Integer.MAX_VALUE;
681}
682{
683    <PIPE_Z>
684    (
685            <MINUS> max=uint()
686        |
687        LOOKAHEAD(2)
688            min=uint() <MINUS> ( max=uint() )?
689        |
690            min=uint() { max = min; }
691    )
692    { return new Pair<Integer, Integer>(min, max); }
693}
694
695Condition condition(Context context) :
696{
697    Condition c;
698    Expression e;
699}
700{
701    <LSQUARE> s()
702    (
703        LOOKAHEAD( simple_key_condition(context) s() <RSQUARE> )
704            c=simple_key_condition(context) s() <RSQUARE> { return c; }
705        |
706        LOOKAHEAD( simple_key_value_condition(context) s() <RSQUARE> )
707            c=simple_key_value_condition(context) s() <RSQUARE> { return c; }
708        |
709            e=expression() <RSQUARE> { return Condition.createExpressionCondition(e, context); }
710    )
711}
712
713String tag_key() :
714{
715    String s, s2;
716    Token t;
717}
718{
719        s=string() { return s; }
720    |
721        s=ident() ( <COLON> s2=ident() { s += ':' + s2; } )* { return s; }
722}
723
724Condition simple_key_condition(Context context) :
725{
726    boolean not = false;
727    Condition.KeyMatchType matchType = null;;
728    String key;
729}
730{
731    ( <EXCLAMATION> { not = true; } )?
732    (
733        { matchType = Condition.KeyMatchType.REGEX; } key = regex()
734    |
735        key = tag_key()
736    )
737    ( LOOKAHEAD(2) <QUESTION> <EXCLAMATION> { matchType = Condition.KeyMatchType.FALSE; } )?
738    (              <QUESTION>               { matchType = Condition.KeyMatchType.TRUE;  } )?
739    { return Condition.createKeyCondition(key, not, matchType, context); }
740}
741
742Condition simple_key_value_condition(Context context) :
743{
744    String key;
745    String val;
746    float f;
747    int i;
748    Condition.Op op;
749    boolean considerValAsKey = false;
750}
751{
752    key=tag_key() s()
753    (
754        LOOKAHEAD(3)
755            (
756                    <EQUAL> <TILDE> { op=Condition.Op.REGEX; }
757                |
758                    <EXCLAMATION> <TILDE> { op=Condition.Op.NREGEX; }
759            )
760            s()
761            ( <STAR> { considerValAsKey=true; } )?
762            val=regex()
763        |
764            (
765                    <EXCLAMATION> <EQUAL> { op=Condition.Op.NEQ; }
766                |
767                    <EQUAL> { op=Condition.Op.EQ; }
768                |
769                    <TILDE> <EQUAL> { op=Condition.Op.ONE_OF; }
770                |
771                    <CARET> <EQUAL> { op=Condition.Op.BEGINS_WITH; }
772                |
773                    <DOLLAR> <EQUAL> { op=Condition.Op.ENDS_WITH; }
774                |
775                    <STAR> <EQUAL> { op=Condition.Op.CONTAINS; }
776            )
777            s()
778            ( <STAR> { considerValAsKey=true; } )?
779            (
780                LOOKAHEAD(2)
781                        i=int_() { val=Integer.toString(i); }
782                    |
783                        f=float_() { val=Float.toString(f); }
784                    |
785                        val=string_or_ident()
786            )
787        |
788            (
789                    <GREATER_EQUAL> { op=Condition.Op.GREATER_OR_EQUAL; }
790                |
791                    <GREATER> { op=Condition.Op.GREATER; }
792                |
793                    <LESS_EQUAL> { op=Condition.Op.LESS_OR_EQUAL; }
794                |
795                    <LESS> { op=Condition.Op.LESS; }
796            )
797            s()
798            f=float_() { val=Float.toString(f); }
799    )
800    { return Condition.createKeyValueCondition(key, val, op, context, considerValAsKey); }
801}
802
803Condition class_or_pseudoclass(Context context) :
804{
805    String s;
806    boolean not = false;
807    boolean pseudo;
808}
809{
810    ( <EXCLAMATION> { not = true; } )?
811    (
812        <FULLSTOP> { pseudo = false; }
813    |
814        <COLON> { pseudo = true; }
815    )
816    s=ident()
817    { return pseudo
818        ? Condition.createPseudoClassCondition(s, not, context)
819        : Condition.createClassCondition(s, not, context); }
820}
821
822Subpart subpart() :
823{
824    String s;
825    Expression e;
826}
827{
828    <DCOLON>
829    (
830        s=ident() { return new Subpart.StringSubpart(s); }
831    |
832        <STAR> { return new Subpart.StringSubpart("*"); }
833    |
834        <LPAR> e=expression() <RPAR> { return new Subpart.ExpressionSubpart(e); }
835    )
836}
837
838Declaration declaration() :
839{
840    List<Instruction> ins = new ArrayList<Instruction>();
841    Instruction i;
842    Token key;
843    Object val = null;
844}
845{
846    <LBRACE> w()
847    (
848        (
849            <SET> w()
850            (<FULLSTOP>)? // specification allows "set .class" to set "class". we also support "set class"
851            key=<IDENT> w()
852            ( <EQUAL> val=expression() )?
853            { ins.add(new Instruction.AssignmentInstruction(key.image, val == null ? true : val, true)); }
854            ( <RBRACE> { return new Declaration(ins, declarationCounter++); } | <SEMICOLON> w() )
855        )
856    |
857        key=<IDENT> w() <COLON> w()
858        (
859            LOOKAHEAD( float_array() w() ( <SEMICOLON> | <RBRACE> ) )
860                val=float_array()
861                { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
862                w()
863                ( <RBRACE> { return new Declaration(ins, declarationCounter++); } | <SEMICOLON> w() )
864            |
865            LOOKAHEAD( expression() ( <SEMICOLON> | <RBRACE> ) )
866                val=expression()
867                { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
868                ( <RBRACE> { return new Declaration(ins, declarationCounter++); } | <SEMICOLON> w() )
869            |
870                val=readRaw() w() { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
871        )
872    )*
873    <RBRACE>
874    { return new Declaration(ins, declarationCounter++); }
875}
876
877/**
878 * General expression.
879 * Separate production rule for each level of operator precedence (recursive descent).
880 */
881Expression expression() :
882{
883    Expression e;
884}
885{
886    e=conditional_expression()
887    {
888        return e;
889    }
890}
891
892Expression conditional_expression() :
893{
894    Expression e, e1, e2;
895    String op = null;
896}
897{
898    e=or_expression()
899    (
900        <QUESTION> w()
901        e1=conditional_expression()
902        <COLON> w()
903        e2=conditional_expression()
904        {
905            e = ExpressionFactory.createFunctionExpression("cond", Arrays.asList(e, e1, e2));
906        }
907    )?
908    {
909        return e;
910    }
911}
912
913Expression or_expression() :
914{
915    Expression e, e2;
916    String op = null;
917}
918{
919    e=and_expression()
920    (
921        <PIPE> <PIPE> w()
922        e2=and_expression()
923        {
924            e = ExpressionFactory.createFunctionExpression("or", Arrays.asList(e, e2));
925        }
926    )*
927    {
928        return e;
929    }
930}
931
932Expression and_expression() :
933{
934    Expression e, e2;
935    String op = null;
936}
937{
938    e=relational_expression()
939    (
940        <AMPERSAND> <AMPERSAND> w()
941        e2=relational_expression()
942        {
943            e = ExpressionFactory.createFunctionExpression("and", Arrays.asList(e, e2));
944        }
945    )*
946    {
947        return e;
948    }
949}
950
951Expression relational_expression() :
952{
953    Expression e, e2;
954    String op = null;
955}
956{
957    e=additive_expression()
958    (
959        (
960            <GREATER_EQUAL> { op = "greater_equal"; }
961            |
962            <LESS_EQUAL> { op = "less_equal"; }
963            |
964            <GREATER> { op = "greater"; }
965            |
966            <LESS> { op = "less"; }
967            |
968            <EQUAL> ( <EQUAL> )? { op = "equal"; }
969            |
970            <EXCLAMATION> <EQUAL> { op = "not_equal"; }
971        ) w()
972        e2=additive_expression()
973        {
974            e = ExpressionFactory.createFunctionExpression(op, Arrays.asList(e, e2));
975        }
976    )?
977    {
978        return e;
979    }
980}
981
982Expression additive_expression() :
983{
984    Expression e, e2;
985    String op = null;
986}
987{
988    e=multiplicative_expression()
989    (
990        ( <PLUS> { op = "plus"; } | <MINUS> { op = "minus"; } ) w()
991        e2=multiplicative_expression()
992        {
993            e = ExpressionFactory.createFunctionExpression(op, Arrays.asList(e, e2));
994        }
995    )*
996    {
997        return e;
998    }
999}
1000
1001Expression multiplicative_expression() :
1002{
1003    Expression e, e2;
1004    String op = null;
1005}
1006{
1007    e=unary_expression()
1008    (
1009        ( <STAR> { op = "times"; } | <SLASH> { op = "divided_by"; } ) w()
1010        e2=unary_expression()
1011        {
1012            e = ExpressionFactory.createFunctionExpression(op, Arrays.asList(e, e2));
1013        }
1014    )*
1015    {
1016        return e;
1017    }
1018}
1019
1020Expression unary_expression() :
1021{
1022    Expression e;
1023    String op = null;
1024}
1025{
1026    (
1027        <MINUS> { op = "minus"; } w()
1028    |
1029        <EXCLAMATION> { op = "not"; } w()
1030    )?
1031    e=primary() w()
1032    {
1033        if (op == null)
1034            return e;
1035        return ExpressionFactory.createFunctionExpression(op, Collections.singletonList(e));
1036    }
1037}
1038
1039Expression primary() :
1040{
1041    Expression nested;
1042    Expression fn;
1043    Object lit;
1044}
1045{
1046    LOOKAHEAD(3) // both function and identifier start with an identifier (+ optional whitespace)
1047        fn=function() { return fn; }
1048    |
1049        lit=literal()
1050        {
1051            if (lit == null)
1052                return NullExpression.INSTANCE;
1053            return new LiteralExpression(lit);
1054        }
1055    |
1056        <LPAR> w() nested=expression() <RPAR> { return nested; }
1057}
1058
1059Expression function() :
1060{
1061    Expression arg;
1062    String name;
1063    List<Expression> args = new ArrayList<Expression>();
1064}
1065{
1066    name=ident() w()
1067    <LPAR> w()
1068    (
1069        arg=expression() { args.add(arg); }
1070        ( <COMMA> w() arg=expression() { args.add(arg); } )*
1071    )?
1072    <RPAR>
1073    { return ExpressionFactory.createFunctionExpression(name, args); }
1074}
1075
1076Object literal() :
1077{
1078    String val, pref;
1079    Token t;
1080    Float f;
1081}
1082{
1083        LOOKAHEAD(2)
1084        pref=ident() t=<HEXCOLOR>
1085        { return Main.pref.getColor("mappaint." + (sheet == null ? "MapCSS" : sheet.title) + "." + pref, ColorHelper.html2color(t.image)); }
1086    |
1087        t=<IDENT> { return new Keyword(t.image); }
1088    |
1089        val=string() { return val; }
1090    |
1091        <PLUS> f=ufloat() { return new Instruction.RelativeFloat(f); }
1092    |
1093        LOOKAHEAD(2)
1094        f=ufloat_unit() { return f; }
1095    |
1096        f=ufloat() { return f; }
1097    |
1098        t=<HEXCOLOR> { return ColorHelper.html2color(t.image); }
1099}
1100
1101/**
1102 * Number followed by a unit.
1103 *
1104 * Returns angles in radians and lengths in pixels.
1105 */
1106Float ufloat_unit() :
1107{
1108    float f;
1109    String u;
1110}
1111{
1112    f=ufloat() ( u=ident() | <DEG> { u = "°"; } )
1113    {
1114        Double m = unit_factor(u);
1115        if (m == null)
1116            return null;
1117        return (float) (f * m);
1118    }
1119}
1120
1121JAVACODE
1122private Double unit_factor(String unit) {
1123    switch (unit) {
1124        case "deg":
1125        case "°": return Math.PI / 180;
1126        case "rad": return 1.;
1127        case "grad": return Math.PI / 200;
1128        case "turn": return 2 * Math.PI;
1129        case "px": return 1.;
1130        case "cm": return 96/2.54;
1131        case "mm": return 9.6/2.54;
1132        case "in": return 96.;
1133        case "q": return 2.4/2.54;
1134        case "pc": return 16.;
1135        case "pt": return 96./72;
1136        default: return null;
1137    }
1138}
1139
1140JAVACODE
1141void error_skipto(int kind, MapCSSException me) {
1142    if (token.kind == EOF)
1143        throw new ParseException("Reached end of file while parsing");
1144       
1145    Exception e = null;       
1146    ParseException pe = generateParseException();
1147
1148    if (me != null) {
1149        final Token token = Utils.firstNonNull(pe.currentToken.next, pe.currentToken);
1150        me.setLine(token.beginLine);
1151        me.setColumn(token.beginColumn);
1152        e = me;
1153    } else {
1154        e = new ParseException(pe.getMessage()); // prevent memory leak
1155    }
1156   
1157    Main.error("Skipping to the next rule, because of an error:");
1158    Main.error(e);
1159    if (sheet != null) {
1160        sheet.logError(e);
1161    }
1162    Token t;
1163    do {
1164        t = getNextToken();
1165    } while (t.kind != kind && t.kind != EOF);
1166    if (t.kind == EOF)
1167        throw new ParseException("Reached end of file while parsing");
1168}
1169
1170JAVACODE
1171/**
1172 * read everything to the next semicolon
1173 */
1174String readRaw() {
1175    Token t;
1176    StringBuilder s = new StringBuilder();
1177    while (true) {
1178        t = getNextToken();
1179        if ((t.kind == S || t.kind == STRING || t.kind == UNEXPECTED_CHAR) &&
1180                t.image.contains("\n")) {
1181            ParseException e = new ParseException(String.format("Warning: end of line while reading an unquoted string at line %s column %s.", t.beginLine, t.beginColumn));
1182            Main.error(e);
1183            if (sheet != null) {
1184                sheet.logError(e);
1185            }
1186        }
1187        if (t.kind == SEMICOLON || t.kind == EOF)
1188            break;
1189        s.append(t.image);
1190    }
1191    if (t.kind == EOF)
1192        throw new ParseException("Reached end of file while parsing");
1193    return s.toString();
1194}
1195
Note: See TracBrowser for help on using the repository browser.