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

Last change on this file since 8515 was 8515, checked in by simon04, 11 years ago

see #11579 - MapCSS: improve error reporting on invalid pseudo classes

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