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

Last change on this file since 9239 was 9239, checked in by Don-vip, 9 years ago

javadoc update

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