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

Last change on this file since 15935 was 15935, checked in by simon04, 4 years ago

see #18749, see #16183 - Add non-regression test

  • Property svn:eol-style set to native
File size: 32.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 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.Range;
23import org.openstreetmap.josm.gui.mappaint.mapcss.Condition;
24import org.openstreetmap.josm.gui.mappaint.mapcss.Condition.Context;
25import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory;
26import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.KeyMatchType;
27import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.Op;
28import org.openstreetmap.josm.gui.mappaint.mapcss.Expression;
29import org.openstreetmap.josm.gui.mappaint.mapcss.ExpressionFactory;
30import org.openstreetmap.josm.gui.mappaint.mapcss.ExpressionFactory.NullExpression;
31import org.openstreetmap.josm.gui.mappaint.mapcss.Instruction;
32import org.openstreetmap.josm.gui.mappaint.mapcss.LiteralExpression;
33import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSException;
34import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
35import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule.Declaration;
36import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
37import org.openstreetmap.josm.gui.mappaint.mapcss.Selector;
38import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.ChildOrParentSelector;
39import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector;
40import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.LinkSelector;
41import org.openstreetmap.josm.gui.mappaint.mapcss.Subpart;
42import org.openstreetmap.josm.tools.ColorHelper;
43import org.openstreetmap.josm.tools.JosmRuntimeException;
44import org.openstreetmap.josm.tools.Logging;
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) ) { if (c!= null) 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 Range r = Range.ZERO_TO_INFINITY;
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) ) { if (c!= null) conditions.add(c); } )*
738 ( sub=subpart() )?
739 { return new GeneralSelector(base.image, r, conditions, sub); }
740}
741
742Range 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 GeneralSelector.fromLevel(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 {
890 if (pseudo && sheet != null && sheet.isRemoveAreaStylePseudoClass() && s.matches("areaStyle|area-style|area_style")) {
891 Logging.warn("Removing 'areaStyle' pseudo-class. This class is only meant for validator");
892 return null;
893 } else if (pseudo) {
894 return ConditionFactory.createPseudoClassCondition(s, not, context);
895 } else {
896 return ConditionFactory.createClassCondition(s, not, context);
897 }
898 }
899}
900
901Subpart subpart() :
902{
903 String s;
904 Expression e;
905}
906{
907 <DCOLON>
908 (
909 s=ident() { return new Subpart.StringSubpart(s); }
910 |
911 <STAR> { return new Subpart.StringSubpart("*"); }
912 |
913 <LPAR> e=expression() <RPAR> { return new Subpart.ExpressionSubpart(e); }
914 )
915}
916
917Declaration declaration() :
918{
919 List<Instruction> ins = new ArrayList<Instruction>();
920 Instruction i;
921 Token key;
922 Object val = null;
923}
924{
925 <LBRACE> w()
926 (
927 (
928 <SET> w()
929 (<FULLSTOP>)? // specification allows "set .class" to set "class". we also support "set class"
930 key=<IDENT> w()
931 ( <EQUAL> val=expression() )?
932 { ins.add(new Instruction.AssignmentInstruction(key.image, val == null ? true : val, true)); }
933 ( <RBRACE> { return new Declaration(ins, declarationCounter++); } | <SEMICOLON> w() )
934 )
935 |
936 <MINUS> <IDENT> w() <COLON> w() expression() <SEMICOLON> w()
937 |
938 key=<IDENT> w() <COLON> w()
939 (
940 LOOKAHEAD( float_array() w() ( <SEMICOLON> | <RBRACE> ) )
941 val=float_array()
942 { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
943 w()
944 ( <RBRACE> { return new Declaration(ins, declarationCounter++); } | <SEMICOLON> w() )
945 |
946 LOOKAHEAD( expression() ( <SEMICOLON> | <RBRACE> ) )
947 val=expression()
948 { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
949 ( <RBRACE> { return new Declaration(ins, declarationCounter++); } | <SEMICOLON> w() )
950 |
951 val=readRaw() w() { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
952 )
953 )*
954 <RBRACE>
955 { return new Declaration(ins, declarationCounter++); }
956}
957
958/**
959 * General expression.
960 * Separate production rule for each level of operator precedence (recursive descent).
961 */
962Expression expression() :
963{
964 Expression e;
965}
966{
967 e=conditional_expression()
968 {
969 return e;
970 }
971}
972
973Expression conditional_expression() :
974{
975 Expression e, e1, e2;
976 String op = null;
977}
978{
979 e=or_expression()
980 (
981 <QUESTION> w()
982 e1=conditional_expression()
983 <COLON> w()
984 e2=conditional_expression()
985 {
986 e = ExpressionFactory.createFunctionExpression("cond", Arrays.asList(e, e1, e2));
987 }
988 )?
989 {
990 return e;
991 }
992}
993
994Expression or_expression() :
995{
996 Expression e, e2;
997 String op = null;
998}
999{
1000 e=and_expression()
1001 (
1002 <PIPE> <PIPE> w()
1003 e2=and_expression()
1004 {
1005 e = ExpressionFactory.createFunctionExpression("or", Arrays.asList(e, e2));
1006 }
1007 )*
1008 {
1009 return e;
1010 }
1011}
1012
1013Expression and_expression() :
1014{
1015 Expression e, e2;
1016 String op = null;
1017}
1018{
1019 e=relational_expression()
1020 (
1021 <AMPERSAND> <AMPERSAND> w()
1022 e2=relational_expression()
1023 {
1024 e = ExpressionFactory.createFunctionExpression("and", Arrays.asList(e, e2));
1025 }
1026 )*
1027 {
1028 return e;
1029 }
1030}
1031
1032Expression relational_expression() :
1033{
1034 Expression e, e2;
1035 String op = null;
1036}
1037{
1038 e=additive_expression()
1039 (
1040 (
1041 <GREATER_EQUAL> { op = "greater_equal"; }
1042 |
1043 <LESS_EQUAL> { op = "less_equal"; }
1044 |
1045 <GREATER> { op = "greater"; }
1046 |
1047 <LESS> { op = "less"; }
1048 |
1049 <EQUAL> ( <EQUAL> )? { op = "equal"; }
1050 |
1051 <EXCLAMATION> <EQUAL> { op = "not_equal"; }
1052 ) w()
1053 e2=additive_expression()
1054 {
1055 e = ExpressionFactory.createFunctionExpression(op, Arrays.asList(e, e2));
1056 }
1057 )?
1058 {
1059 return e;
1060 }
1061}
1062
1063Expression additive_expression() :
1064{
1065 Expression e, e2;
1066 String op = null;
1067}
1068{
1069 e=multiplicative_expression()
1070 (
1071 ( <PLUS> { op = "plus"; } | <MINUS> { op = "minus"; } ) w()
1072 e2=multiplicative_expression()
1073 {
1074 e = ExpressionFactory.createFunctionExpression(op, Arrays.asList(e, e2));
1075 }
1076 )*
1077 {
1078 return e;
1079 }
1080}
1081
1082Expression multiplicative_expression() :
1083{
1084 Expression e, e2;
1085 String op = null;
1086}
1087{
1088 e=unary_expression()
1089 (
1090 ( <STAR> { op = "times"; } | <SLASH> { op = "divided_by"; } ) w()
1091 e2=unary_expression()
1092 {
1093 e = ExpressionFactory.createFunctionExpression(op, Arrays.asList(e, e2));
1094 }
1095 )*
1096 {
1097 return e;
1098 }
1099}
1100
1101Expression unary_expression() :
1102{
1103 Expression e;
1104 String op = null;
1105}
1106{
1107 (
1108 <MINUS> { op = "minus"; } w()
1109 |
1110 <EXCLAMATION> { op = "not"; } w()
1111 )?
1112 e=primary() w()
1113 {
1114 if (op == null)
1115 return e;
1116 return ExpressionFactory.createFunctionExpression(op, Collections.singletonList(e));
1117 }
1118}
1119
1120Expression primary() :
1121{
1122 Expression nested;
1123 Expression fn;
1124 Object lit;
1125}
1126{
1127 LOOKAHEAD(3) // both function and identifier start with an identifier (+ optional whitespace)
1128 fn=function() { return fn; }
1129 |
1130 lit=literal()
1131 {
1132 if (lit == null)
1133 return NullExpression.INSTANCE;
1134 return new LiteralExpression(lit);
1135 }
1136 |
1137 <LPAR> w() nested=expression() <RPAR> { return nested; }
1138}
1139
1140Expression function() :
1141{
1142 Expression arg;
1143 String name;
1144 List<Expression> args = new ArrayList<Expression>();
1145}
1146{
1147 name=ident() w()
1148 <LPAR> w()
1149 (
1150 arg=expression() { args.add(arg); }
1151 ( <COMMA> w() arg=expression() { args.add(arg); } )*
1152 )?
1153 <RPAR>
1154 { return ExpressionFactory.createFunctionExpression(name, args); }
1155}
1156
1157Object literal() :
1158{
1159 String val, pref;
1160 Token t;
1161 Float f;
1162}
1163{
1164 LOOKAHEAD(2)
1165 pref=ident() t=<HEXCOLOR>
1166 {
1167 return new NamedColorProperty(
1168 NamedColorProperty.COLOR_CATEGORY_MAPPAINT,
1169 sheet == null ? "MapCSS" : sheet.title, pref,
1170 ColorHelper.html2color(t.image)).get();
1171 }
1172 |
1173 t=<IDENT> { return new Keyword(t.image); }
1174 |
1175 val=string() { return val; }
1176 |
1177 <PLUS> f=ufloat() { return new Instruction.RelativeFloat(f); }
1178 |
1179 LOOKAHEAD(2)
1180 f=ufloat_unit() { return f; }
1181 |
1182 f=ufloat() { return f; }
1183 |
1184 t=<HEXCOLOR> { return ColorHelper.html2color(t.image); }
1185}
1186
1187/**
1188 * Number followed by a unit.
1189 *
1190 * Returns angles in radians and lengths in pixels.
1191 */
1192Float ufloat_unit() :
1193{
1194 float f;
1195 String u;
1196}
1197{
1198 f=ufloat() ( u=ident() | <DEG> { u = "°"; } | <PERCENT> { u = "%"; } )
1199 {
1200 Double m = unit_factor(u);
1201 if (m == null)
1202 return null;
1203 return (float) (f * m);
1204 }
1205}
1206
1207JAVACODE
1208private Double unit_factor(String unit) {
1209 switch (unit) {
1210 case "deg":
1211 case "°": return Math.PI / 180;
1212 case "rad": return 1.;
1213 case "grad": return Math.PI / 200;
1214 case "turn": return 2 * Math.PI;
1215 case "%": return 0.01;
1216 case "px": return 1.;
1217 case "cm": return 96/2.54;
1218 case "mm": return 9.6/2.54;
1219 case "in": return 96.;
1220 case "q": return 2.4/2.54;
1221 case "pc": return 16.;
1222 case "pt": return 96./72;
1223 default: return null;
1224 }
1225}
1226
1227JAVACODE
1228void error_skipto(int kind, MapCSSException me) {
1229 if (token.kind == EOF)
1230 throw new ParseException("Reached end of file while parsing");
1231
1232 Exception e = null;
1233 ParseException pe = generateParseException();
1234
1235 if (me != null) {
1236 final Token token = Utils.firstNonNull(pe.currentToken.next, pe.currentToken);
1237 me.setLine(token.beginLine);
1238 me.setColumn(token.beginColumn);
1239 e = me;
1240 } else {
1241 e = new ParseException(pe.getMessage()); // prevent memory leak
1242 }
1243
1244 Logging.error("Skipping to the next rule, because of an error:");
1245 Logging.error(e);
1246 if (sheet != null) {
1247 sheet.logError(e);
1248 }
1249 Token t;
1250 do {
1251 t = getNextToken();
1252 } while (t.kind != kind && t.kind != EOF);
1253 if (t.kind == EOF)
1254 throw new ParseException("Reached end of file while parsing");
1255}
1256
1257JAVACODE
1258/**
1259 * read everything to the next semicolon
1260 */
1261String readRaw() {
1262 Token t;
1263 StringBuilder s = new StringBuilder();
1264 while (true) {
1265 t = getNextToken();
1266 if ((t.kind == S || t.kind == STRING || t.kind == UNEXPECTED_CHAR) &&
1267 t.image.contains("\n")) {
1268 ParseException e = new ParseException(String.format("Warning: end of line while reading an unquoted string at line %s column %s.", t.beginLine, t.beginColumn));
1269 Logging.error(e);
1270 if (sheet != null) {
1271 sheet.logError(e);
1272 }
1273 }
1274 if (t.kind == SEMICOLON || t.kind == EOF)
1275 break;
1276 s.append(t.image);
1277 }
1278 if (t.kind == EOF)
1279 throw new ParseException("Reached end of file while parsing");
1280 return s.toString();
1281}
1282
Note: See TracBrowser for help on using the repository browser.