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

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

see #11916 - Search: allow to use multiple MapCSS selectors and child/parent selectors

File size: 29.0 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.Op op;
758    boolean considerValAsKey = false;
759}
760{
761    key=tag_key() s()
762    (
763        LOOKAHEAD(3)
764            (
765                    <EQUAL> <TILDE> { op=Condition.Op.REGEX; }
766                |
767                    <EXCLAMATION> <TILDE> { op=Condition.Op.NREGEX; }
768            )
769            s()
770            ( <STAR> { considerValAsKey=true; } )?
771            val=regex()
772        |
773            (
774                    <EXCLAMATION> <EQUAL> { op=Condition.Op.NEQ; }
775                |
776                    <EQUAL> { op=Condition.Op.EQ; }
777                |
778                    <TILDE> <EQUAL> { op=Condition.Op.ONE_OF; }
779                |
780                    <CARET> <EQUAL> { op=Condition.Op.BEGINS_WITH; }
781                |
782                    <DOLLAR> <EQUAL> { op=Condition.Op.ENDS_WITH; }
783                |
784                    <STAR> <EQUAL> { op=Condition.Op.CONTAINS; }
785            )
786            s()
787            ( <STAR> { considerValAsKey=true; } )?
788            (
789                LOOKAHEAD(2)
790                        i=int_() { val=Integer.toString(i); }
791                    |
792                        f=float_() { val=Float.toString(f); }
793                    |
794                        val=string_or_ident()
795            )
796        |
797            (
798                    <GREATER_EQUAL> { op=Condition.Op.GREATER_OR_EQUAL; }
799                |
800                    <GREATER> { op=Condition.Op.GREATER; }
801                |
802                    <LESS_EQUAL> { op=Condition.Op.LESS_OR_EQUAL; }
803                |
804                    <LESS> { op=Condition.Op.LESS; }
805            )
806            s()
807            f=float_() { val=Float.toString(f); }
808    )
809    { return Condition.createKeyValueCondition(key, val, op, context, considerValAsKey); }
810}
811
812Condition class_or_pseudoclass(Context context) :
813{
814    String s;
815    boolean not = false;
816    boolean pseudo;
817}
818{
819    ( <EXCLAMATION> { not = true; } )?
820    (
821        <FULLSTOP> { pseudo = false; }
822    |
823        <COLON> { pseudo = true; }
824    )
825    s=ident()
826    { return pseudo
827        ? Condition.createPseudoClassCondition(s, not, context)
828        : Condition.createClassCondition(s, not, context); }
829}
830
831Subpart subpart() :
832{
833    String s;
834    Expression e;
835}
836{
837    <DCOLON>
838    (
839        s=ident() { return new Subpart.StringSubpart(s); }
840    |
841        <STAR> { return new Subpart.StringSubpart("*"); }
842    |
843        <LPAR> e=expression() <RPAR> { return new Subpart.ExpressionSubpart(e); }
844    )
845}
846
847Declaration declaration() :
848{
849    List<Instruction> ins = new ArrayList<Instruction>();
850    Instruction i;
851    Token key;
852    Object val = null;
853}
854{
855    <LBRACE> w()
856    (
857        (
858            <SET> w()
859            (<FULLSTOP>)? // specification allows "set .class" to set "class". we also support "set class"
860            key=<IDENT> w()
861            ( <EQUAL> val=expression() )?
862            { ins.add(new Instruction.AssignmentInstruction(key.image, val == null ? true : val, true)); }
863            ( <RBRACE> { return new Declaration(ins, declarationCounter++); } | <SEMICOLON> w() )
864        )
865    |
866        key=<IDENT> w() <COLON> w()
867        (
868            LOOKAHEAD( float_array() w() ( <SEMICOLON> | <RBRACE> ) )
869                val=float_array()
870                { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
871                w()
872                ( <RBRACE> { return new Declaration(ins, declarationCounter++); } | <SEMICOLON> w() )
873            |
874            LOOKAHEAD( expression() ( <SEMICOLON> | <RBRACE> ) )
875                val=expression()
876                { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
877                ( <RBRACE> { return new Declaration(ins, declarationCounter++); } | <SEMICOLON> w() )
878            |
879                val=readRaw() w() { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
880        )
881    )*
882    <RBRACE>
883    { return new Declaration(ins, declarationCounter++); }
884}
885
886/**
887 * General expression.
888 * Separate production rule for each level of operator precedence (recursive descent).
889 */
890Expression expression() :
891{
892    Expression e;
893}
894{
895    e=conditional_expression()
896    {
897        return e;
898    }
899}
900
901Expression conditional_expression() :
902{
903    Expression e, e1, e2;
904    String op = null;
905}
906{
907    e=or_expression()
908    (
909        <QUESTION> w()
910        e1=conditional_expression()
911        <COLON> w()
912        e2=conditional_expression()
913        {
914            e = ExpressionFactory.createFunctionExpression("cond", Arrays.asList(e, e1, e2));
915        }
916    )?
917    {
918        return e;
919    }
920}
921
922Expression or_expression() :
923{
924    Expression e, e2;
925    String op = null;
926}
927{
928    e=and_expression()
929    (
930        <PIPE> <PIPE> w()
931        e2=and_expression()
932        {
933            e = ExpressionFactory.createFunctionExpression("or", Arrays.asList(e, e2));
934        }
935    )*
936    {
937        return e;
938    }
939}
940
941Expression and_expression() :
942{
943    Expression e, e2;
944    String op = null;
945}
946{
947    e=relational_expression()
948    (
949        <AMPERSAND> <AMPERSAND> w()
950        e2=relational_expression()
951        {
952            e = ExpressionFactory.createFunctionExpression("and", Arrays.asList(e, e2));
953        }
954    )*
955    {
956        return e;
957    }
958}
959
960Expression relational_expression() :
961{
962    Expression e, e2;
963    String op = null;
964}
965{
966    e=additive_expression()
967    (
968        (
969            <GREATER_EQUAL> { op = "greater_equal"; }
970            |
971            <LESS_EQUAL> { op = "less_equal"; }
972            |
973            <GREATER> { op = "greater"; }
974            |
975            <LESS> { op = "less"; }
976            |
977            <EQUAL> ( <EQUAL> )? { op = "equal"; }
978            |
979            <EXCLAMATION> <EQUAL> { op = "not_equal"; }
980        ) w()
981        e2=additive_expression()
982        {
983            e = ExpressionFactory.createFunctionExpression(op, Arrays.asList(e, e2));
984        }
985    )?
986    {
987        return e;
988    }
989}
990
991Expression additive_expression() :
992{
993    Expression e, e2;
994    String op = null;
995}
996{
997    e=multiplicative_expression()
998    (
999        ( <PLUS> { op = "plus"; } | <MINUS> { op = "minus"; } ) w()
1000        e2=multiplicative_expression()
1001        {
1002            e = ExpressionFactory.createFunctionExpression(op, Arrays.asList(e, e2));
1003        }
1004    )*
1005    {
1006        return e;
1007    }
1008}
1009
1010Expression multiplicative_expression() :
1011{
1012    Expression e, e2;
1013    String op = null;
1014}
1015{
1016    e=unary_expression()
1017    (
1018        ( <STAR> { op = "times"; } | <SLASH> { op = "divided_by"; } ) w()
1019        e2=unary_expression()
1020        {
1021            e = ExpressionFactory.createFunctionExpression(op, Arrays.asList(e, e2));
1022        }
1023    )*
1024    {
1025        return e;
1026    }
1027}
1028
1029Expression unary_expression() :
1030{
1031    Expression e;
1032    String op = null;
1033}
1034{
1035    (
1036        <MINUS> { op = "minus"; } w()
1037    |
1038        <EXCLAMATION> { op = "not"; } w()
1039    )?
1040    e=primary() w()
1041    {
1042        if (op == null)
1043            return e;
1044        return ExpressionFactory.createFunctionExpression(op, Collections.singletonList(e));
1045    }
1046}
1047
1048Expression primary() :
1049{
1050    Expression nested;
1051    Expression fn;
1052    Object lit;
1053}
1054{
1055    LOOKAHEAD(3) // both function and identifier start with an identifier (+ optional whitespace)
1056        fn=function() { return fn; }
1057    |
1058        lit=literal()
1059        {
1060            if (lit == null)
1061                return NullExpression.INSTANCE;
1062            return new LiteralExpression(lit);
1063        }
1064    |
1065        <LPAR> w() nested=expression() <RPAR> { return nested; }
1066}
1067
1068Expression function() :
1069{
1070    Expression arg;
1071    String name;
1072    List<Expression> args = new ArrayList<Expression>();
1073}
1074{
1075    name=ident() w()
1076    <LPAR> w()
1077    (
1078        arg=expression() { args.add(arg); }
1079        ( <COMMA> w() arg=expression() { args.add(arg); } )*
1080    )?
1081    <RPAR>
1082    { return ExpressionFactory.createFunctionExpression(name, args); }
1083}
1084
1085Object literal() :
1086{
1087    String val, pref;
1088    Token t;
1089    Float f;
1090}
1091{
1092        LOOKAHEAD(2)
1093        pref=ident() t=<HEXCOLOR>
1094        { return Main.pref.getColor("mappaint." + (sheet == null ? "MapCSS" : sheet.title) + "." + pref, ColorHelper.html2color(t.image)); }
1095    |
1096        t=<IDENT> { return new Keyword(t.image); }
1097    |
1098        val=string() { return val; }
1099    |
1100        <PLUS> f=ufloat() { return new Instruction.RelativeFloat(f); }
1101    |
1102        LOOKAHEAD(2)
1103        f=ufloat_unit() { return f; }
1104    |
1105        f=ufloat() { return f; }
1106    |
1107        t=<HEXCOLOR> { return ColorHelper.html2color(t.image); }
1108}
1109
1110/**
1111 * Number followed by a unit.
1112 *
1113 * Returns angles in radians and lengths in pixels.
1114 */
1115Float ufloat_unit() :
1116{
1117    float f;
1118    String u;
1119}
1120{
1121    f=ufloat() ( u=ident() | <DEG> { u = "°"; } )
1122    {
1123        Double m = unit_factor(u);
1124        if (m == null)
1125            return null;
1126        return (float) (f * m);
1127    }
1128}
1129
1130JAVACODE
1131private Double unit_factor(String unit) {
1132    switch (unit) {
1133        case "deg":
1134        case "°": return Math.PI / 180;
1135        case "rad": return 1.;
1136        case "grad": return Math.PI / 200;
1137        case "turn": return 2 * Math.PI;
1138        case "px": return 1.;
1139        case "cm": return 96/2.54;
1140        case "mm": return 9.6/2.54;
1141        case "in": return 96.;
1142        case "q": return 2.4/2.54;
1143        case "pc": return 16.;
1144        case "pt": return 96./72;
1145        default: return null;
1146    }
1147}
1148
1149JAVACODE
1150void error_skipto(int kind, MapCSSException me) {
1151    if (token.kind == EOF)
1152        throw new ParseException("Reached end of file while parsing");
1153       
1154    Exception e = null;       
1155    ParseException pe = generateParseException();
1156
1157    if (me != null) {
1158        final Token token = Utils.firstNonNull(pe.currentToken.next, pe.currentToken);
1159        me.setLine(token.beginLine);
1160        me.setColumn(token.beginColumn);
1161        e = me;
1162    } else {
1163        e = new ParseException(pe.getMessage()); // prevent memory leak
1164    }
1165   
1166    Main.error("Skipping to the next rule, because of an error:");
1167    Main.error(e);
1168    if (sheet != null) {
1169        sheet.logError(e);
1170    }
1171    Token t;
1172    do {
1173        t = getNextToken();
1174    } while (t.kind != kind && t.kind != EOF);
1175    if (t.kind == EOF)
1176        throw new ParseException("Reached end of file while parsing");
1177}
1178
1179JAVACODE
1180/**
1181 * read everything to the next semicolon
1182 */
1183String readRaw() {
1184    Token t;
1185    StringBuilder s = new StringBuilder();
1186    while (true) {
1187        t = getNextToken();
1188        if ((t.kind == S || t.kind == STRING || t.kind == UNEXPECTED_CHAR) &&
1189                t.image.contains("\n")) {
1190            ParseException e = new ParseException(String.format("Warning: end of line while reading an unquoted string at line %s column %s.", t.beginLine, t.beginColumn));
1191            Main.error(e);
1192            if (sheet != null) {
1193                sheet.logError(e);
1194            }
1195        }
1196        if (t.kind == SEMICOLON || t.kind == EOF)
1197            break;
1198        s.append(t.image);
1199    }
1200    if (t.kind == EOF)
1201        throw new ParseException("Reached end of file while parsing");
1202    return s.toString();
1203}
1204
Note: See TracBrowser for help on using the repository browser.