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

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

Refactoring: use StandardCharsets

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