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

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

fix #10391: Add support for "not element of" operator

  • implement 4 new operators: ⊆,⊈,⊇,⊉
  • ⊆ is a synonym for the existing ∈ operator that uses the ContainsFinder, it

matches for elements which contain one or more elements matching the left Selectors

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