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

Last change on this file since 15730 was 15113, checked in by GerdP, 6 years ago

fix #17746: Detect invalid MapCSS search expressions

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