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

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

see #18802 - MapCSSRule: support list of selectors

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