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

Last change on this file since 6896 was 6896, checked in by bastiK, 10 years ago

mapcss: add support for @media expressions
includes part of the style sheet under certain condition
e.g. min josm version.

There is a major limitation: the intire file is still parsed.
So if new syntax is introduced, it will still generate
a parsing error for old josm version even if the new code
is wrapped in an @media section.

File size: 19.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.awt.Color;
11import java.util.ArrayList;
12import java.util.List;
13
14import org.openstreetmap.josm.gui.mappaint.Keyword;
15import org.openstreetmap.josm.gui.mappaint.mapcss.Condition;
16import org.openstreetmap.josm.gui.mappaint.mapcss.Condition.Context;
17import org.openstreetmap.josm.gui.mappaint.mapcss.Expression;
18import org.openstreetmap.josm.gui.mappaint.mapcss.Instruction;
19import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
20import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
21import org.openstreetmap.josm.gui.mappaint.mapcss.Selector;
22import org.openstreetmap.josm.gui.mappaint.mapcss.ExpressionFactory;
23import org.openstreetmap.josm.gui.mappaint.mapcss.LiteralExpression;
24import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSException;
25import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.ChildOrParentSelector;
26import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector;
27import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.LinkSelector;
28import org.openstreetmap.josm.tools.ColorHelper;
29import org.openstreetmap.josm.tools.Pair;
30import org.openstreetmap.josm.tools.Utils;
31import org.openstreetmap.josm.Main;
32
33public class MapCSSParser {
34 MapCSSStyleSource sheet;
35}
36PARSER_END(MapCSSParser)
37
38/*************
39 * Token definitions
40 */
41
42<DEFAULT>
43TOKEN [IGNORE_CASE]:
44{
45 /* Special keywords in some contexts, ordinary identifiers in other contexts.
46 Don't use the javacc token contexts (except DEFAULT and COMMENT) because
47 they complicate error handling. Instead simply add a parsing rule <code>ident()</code>
48 that parses the IDENT token and in addition all the keyword tokens. */
49 < AND: "and" >
50| < SET: "set" >
51| < NOT: "not" >
52| < MEDIA: "@media" >
53}
54
55<DEFAULT>
56TOKEN:
57{
58 < IDENT: ["a"-"z","A"-"Z","_"] ( ["a"-"z","A"-"Z","_","-","0"-"9"] )* >
59| < UINT: ["1"-"9"] ( ["0"-"9"] )* >
60| < UFLOAT: ( ["0"-"9"] )+ ( "." ( ["0"-"9"] )+ )? >
61| < STRING: "\"" ( [" ","!","#"-"[","]"-"~","\u0080"-"\uFFFF"] | "\\\"" | "\\\\" )* "\"" >
62| < #PREDEFINED: "\\" ["d","D","s","S","w","W"] >
63| < #REGEX_CHAR_WITHOUT_STAR: [" "-")","+"-".","0"-"[","]"-"~","\u0080"-"\uFFFF"] | "\\/" | "\\\\" | "\\[" | "\\]" | "\\+" | "\\." | "\\'" | "\\\"" | <PREDEFINED> >
64| < REGEX: "/" <REGEX_CHAR_WITHOUT_STAR> ( <REGEX_CHAR_WITHOUT_STAR> | "*" )* "/" >
65| < #H: ["0"-"9","a"-"f","A"-"F"] >
66| < HEXCOLOR: "#" ( <H><H><H><H><H><H><H><H> | <H><H><H><H><H><H> | <H><H><H> ) >
67| < S: ( " " | "\t" | "\n" | "\r" | "\f" )+ >
68| < STAR: "*" >
69| < SLASH: "/" >
70| < LBRACE: "{" >
71| < RBRACE: "}" >
72| < LSQUARE: "[" >
73| < RSQUARE: "]" >
74| < LPAR: "(" >
75| < RPAR: ")" >
76| < GREATER_EQUAL: ">=" >
77| < LESS_EQUAL: "<=" >
78| < GREATER: ">" >
79| < LESS: "<" >
80| < EQUAL: "=" >
81| < EXCLAMATION: "!" >
82| < TILDE: "~" >
83| < COLON: ":" >
84| < DCOLON: "::" >
85| < SEMICOLON: ";" >
86| < COMMA: "," >
87| < PIPE: "|" >
88| < PIPE_Z: "|z" >
89| < PLUS: "+" >
90| < MINUS: "-" >
91| < AMPERSAND: "&" >
92| < QUESTION: "?" >
93| < DOLLAR: "$" >
94| < CARET: "^" >
95| < FULLSTOP: "." >
96| < ELEMENT_OF: "∈" >
97| < CROSSING: "⧉" >
98| < COMMENT_START: "/*" > : COMMENT
99| < UNEXPECTED_CHAR : ~[] > // avoid TokenMgrErrors because they are hard to recover from
100}
101
102<COMMENT>
103TOKEN:
104{
105 < COMMENT_END: "*/" > : DEFAULT
106}
107
108<COMMENT>
109SKIP:
110{
111 < ~[] >
112}
113
114/*************
115 * Parser definitions
116 *
117 * rule
118 * _______________________|______________________________
119 * | |
120 * selector declaration
121 * _________|___________________ _________|____________
122 * | | | |
123 *
124 * way|z11-12[highway=residential] { color: red; width: 3 }
125 *
126 * |_____||___________________| |_________|
127 * | | |
128 * zoom condition instruction
129 *
130 * more general:
131 *
132 * way|z13-[a=b][c=d]::subpart, way|z-3[u=v]:closed::subpart2 { p1 : val; p2 : val; }
133 *
134 * 'val' can be a literal, or an expression like "prop(width, default) + 0.8".
135 *
136 * @media { ... } queries are supported, following http://www.w3.org/TR/css3-mediaqueries/#syntax
137 *
138 * media_query
139 * ___________________________|_______________________________
140 * | |
141 * @media all and (min-josm-version: 7789) and (max-josm-version: 7790), all and (user-agent: xyz) { ... }
142 * |______________________|
143 * |
144 * media_expression
145 */
146
147int uint() :
148{
149 Token i;
150}
151{
152 i=<UINT> { return Integer.parseInt(i.image); }
153}
154
155int int_() :
156{
157 int i;
158}
159{
160 <MINUS> i=uint() { return -i; } | i=uint() { return i; }
161}
162
163float ufloat() :
164{
165 Token f;
166}
167{
168 ( f=<UFLOAT> | f=<UINT> )
169 { return Float.parseFloat(f.image); }
170}
171
172float float_() :
173{
174 float f;
175}
176{
177 <MINUS> f=ufloat() { return -f; } | f=ufloat() { return f; }
178}
179
180String string() :
181{
182 Token t;
183}
184{
185 t=<STRING>
186 { return t.image.substring(1, t.image.length() - 1).replace("\\\"", "\"").replace("\\\\", "\\"); }
187}
188
189String ident():
190{
191 Token t;
192 String s;
193}
194{
195 ( t=<IDENT> | t=<SET> | t=<NOT> | t=<AND> ) { return t.image; }
196}
197
198String string_or_ident() :
199{
200 Token t;
201 String s;
202}
203{
204 ( s=ident() | s=string() ) { return s; }
205}
206
207String regex() :
208{
209 Token t;
210}
211{
212 t=<REGEX>
213 { return t.image.substring(1, t.image.length() - 1); }
214}
215
216/**
217 * white-space
218 */
219void s() :
220{
221}
222{
223 ( <S> )?
224}
225
226/**
227 * mix of white-space and comments
228 */
229void w() :
230{
231}
232{
233 ( <S> | <COMMENT_START> <COMMENT_END> )*
234}
235
236/**
237 * comma delimited list of floats (at least 2, all &gt;= 0)
238 */
239List<Float> float_array() :
240{
241 float f;
242 List<Float> fs = new ArrayList<Float>();
243}
244{
245 f=ufloat() { fs.add(f); }
246 (
247 <COMMA> s()
248 f=ufloat() { fs.add(f); }
249 )+
250 {
251 return fs;
252 }
253}
254
255/**
256 * root
257 */
258void sheet(MapCSSStyleSource sheet):
259{
260 MapCSSRule r;
261}
262{
263 { this.sheet = sheet; }
264 w()
265 rules(true) ( media() w() rules(true) )*
266 <EOF>
267}
268
269void media():
270{
271 boolean pass = false;
272 boolean q;
273 boolean empty = true;
274}
275{
276 <MEDIA> w()
277 ( q=media_query() { pass = pass || q; empty = false; }
278 ( <COMMA> w() q=media_query() { pass = pass || q; } )*
279 )?
280 <LBRACE> w()
281 rules(empty || pass)
282 <RBRACE>
283}
284
285boolean media_query():
286{
287 Token t;
288 String mediatype = "all";
289 boolean pass = true;
290 boolean invert = false;
291 boolean e;
292}
293{
294 ( <NOT> { invert = true; } w() )?
295 (
296 t=<IDENT> { mediatype = t.image.toLowerCase(); } w()
297 ( <AND> w() e=media_expression() { pass = pass && e; } w() )*
298 |
299 e=media_expression() { pass = pass && e; } w()
300 ( <AND> w() e=media_expression() { pass = pass && e; } w() )*
301 )
302 {
303 if (!"all".equals(mediatype)) {
304 pass = false;
305 }
306 return invert ? (!pass) : pass;
307 }
308}
309
310boolean media_expression():
311{
312 Token t;
313 String feature;
314 Object val = null;
315}
316{
317 <LPAR> w() t=<IDENT> { feature = t.image; } w() ( <COLON> w() val=literal() )? <RPAR>
318 { return this.sheet.evalMediaExpression(feature, val); }
319}
320
321void rules(boolean add):
322{
323 MapCSSRule r;
324}
325{
326 (
327 try {
328 r=rule() { if (add && r != null) { sheet.rules.add(r); } } w()
329 } catch (MapCSSException mex) {
330 error_skipto(RBRACE, mex);
331 w();
332 } catch (ParseException ex) {
333 error_skipto(RBRACE, null);
334 w();
335 }
336 )*
337}
338
339MapCSSRule rule():
340{
341 List<Selector> selectors = new ArrayList<Selector>();
342 Selector sel;
343 List<Instruction> decl;
344}
345{
346 sel=child_selector() { selectors.add(sel); }
347 (
348 <COMMA> w()
349 sel=child_selector() { selectors.add(sel); }
350 )*
351 decl=declaration()
352 { return new MapCSSRule(selectors, decl); }
353}
354
355Selector child_selector() :
356{
357 Selector.ChildOrParentSelectorType type = null;
358 Condition c;
359 List<Condition> conditions = new ArrayList<Condition>();
360 Selector selLeft;
361 LinkSelector selLink = null;
362 Selector selRight = null;
363}
364{
365 selLeft=selector() w()
366 (
367 (
368 ( <GREATER> { type = Selector.ChildOrParentSelectorType.CHILD; } | <LESS> { type = Selector.ChildOrParentSelectorType.PARENT; } )
369 ( ( c=condition(Context.LINK) | c=class_or_pseudoclass(Context.LINK) ) { conditions.add(c); } )*
370 |
371 <ELEMENT_OF> { type = Selector.ChildOrParentSelectorType.ELEMENT_OF; }
372 |
373 <CROSSING> { type = Selector.ChildOrParentSelectorType.CROSSING; }
374 )
375 { selLink = new LinkSelector(conditions); }
376 w()
377 selRight=selector() w()
378 )?
379 { return selRight != null ? new ChildOrParentSelector(selLeft, selLink, selRight, type) : selLeft; }
380}
381
382Selector selector() :
383{
384 Token base;
385 Condition c;
386 Pair<Integer, Integer> r = null;
387 List<Condition> conditions = new ArrayList<Condition>();
388 String sub = null;
389}
390{
391 ( base=<IDENT> | base=<STAR> )
392 ( r=zoom() )?
393 ( ( c=condition(Context.PRIMITIVE) | c=class_or_pseudoclass(Context.PRIMITIVE) ) { conditions.add(c); } )*
394 ( sub=subpart() )?
395 { return new GeneralSelector(base.image, r, conditions, sub); }
396}
397
398Pair<Integer, Integer> zoom() :
399{
400 Integer min = 0;
401 Integer max = Integer.MAX_VALUE;
402}
403{
404 <PIPE_Z>
405 (
406 <MINUS> max=uint()
407 |
408 LOOKAHEAD(2)
409 min=uint() <MINUS> ( max=uint() )?
410 |
411 min=uint() { max = min; }
412 )
413 { return new Pair<Integer, Integer>(min, max); }
414}
415
416Condition condition(Context context) :
417{
418 Condition c;
419 Expression e;
420}
421{
422 <LSQUARE> s()
423 (
424 LOOKAHEAD( simple_key_condition(context) s() <RSQUARE> )
425 c=simple_key_condition(context) s() <RSQUARE> { return c; }
426 |
427 LOOKAHEAD( simple_key_value_condition(context) s() <RSQUARE> )
428 c=simple_key_value_condition(context) s() <RSQUARE> { return c; }
429 |
430 e=expression() <RSQUARE> { return Condition.createExpressionCondition(e, context); }
431 )
432}
433
434String tag_key() :
435{
436 String s, s2;
437 Token t;
438}
439{
440 s=string() { return s; }
441 |
442 s=ident() ( <COLON> s2=ident() { s += ':' + s2; } )* { return s; }
443}
444
445Condition simple_key_condition(Context context) :
446{
447 boolean not = false;
448 Condition.KeyMatchType matchType = null;;
449 String key;
450}
451{
452 ( <EXCLAMATION> { not = true; } )?
453 (
454 { matchType = Condition.KeyMatchType.REGEX; } key = regex()
455 |
456 key = tag_key()
457 )
458 ( LOOKAHEAD(2) <QUESTION> <EXCLAMATION> { matchType = Condition.KeyMatchType.FALSE; } )?
459 ( <QUESTION> { matchType = Condition.KeyMatchType.TRUE; } )?
460 { return Condition.createKeyCondition(key, not, matchType, context); }
461}
462
463Condition simple_key_value_condition(Context context) :
464{
465 String key;
466 String val;
467 float f;
468 int i;
469 Condition.Op op;
470 boolean considerValAsKey = false;
471}
472{
473 key=tag_key() s()
474 (
475 LOOKAHEAD(3)
476 (
477 <EQUAL> <TILDE> { op=Condition.Op.REGEX; }
478 |
479 <EXCLAMATION> <TILDE> { op=Condition.Op.NREGEX; }
480 )
481 s()
482 ( <STAR> { considerValAsKey=true; } )?
483 val=regex()
484 |
485 (
486 <EXCLAMATION> <EQUAL> { op=Condition.Op.NEQ; }
487 |
488 <EQUAL> { op=Condition.Op.EQ; }
489 |
490 <TILDE> <EQUAL> { op=Condition.Op.ONE_OF; }
491 |
492 <CARET> <EQUAL> { op=Condition.Op.BEGINS_WITH; }
493 |
494 <DOLLAR> <EQUAL> { op=Condition.Op.ENDS_WITH; }
495 |
496 <STAR> <EQUAL> { op=Condition.Op.CONTAINS; }
497 )
498 s()
499 ( <STAR> { considerValAsKey=true; } )?
500 (
501 LOOKAHEAD(2)
502 i=int_() { val=Integer.toString(i); }
503 |
504 f=float_() { val=Float.toString(f); }
505 |
506 val=string_or_ident()
507 )
508 |
509 (
510 <GREATER_EQUAL> { op=Condition.Op.GREATER_OR_EQUAL; }
511 |
512 <GREATER> { op=Condition.Op.GREATER; }
513 |
514 <LESS_EQUAL> { op=Condition.Op.LESS_OR_EQUAL; }
515 |
516 <LESS> { op=Condition.Op.LESS; }
517 )
518 s()
519 f=float_() { val=Float.toString(f); }
520 )
521 { return Condition.createKeyValueCondition(key, val, op, context, considerValAsKey); }
522}
523
524Condition class_or_pseudoclass(Context context) :
525{
526 String s;
527 boolean not = false;
528 boolean pseudo;
529}
530{
531 ( <EXCLAMATION> { not = true; } )?
532 (
533 <FULLSTOP> { pseudo = false; }
534 |
535 <COLON> { pseudo = true; }
536 )
537 s=ident()
538 { return pseudo
539 ? Condition.createPseudoClassCondition(s, not, context)
540 : Condition.createClassCondition(s, not, context); }
541}
542
543String subpart() :
544{
545 String s;
546}
547{
548 <DCOLON>
549 ( s=ident() { return s; } | <STAR> { return "*"; } )
550}
551
552List<Instruction> declaration() :
553{
554 List<Instruction> ins = new ArrayList<Instruction>();
555 Instruction i;
556 Token key;
557 Object val = null;
558}
559{
560 <LBRACE> w()
561 (
562 (
563 <SET> w()
564 (<FULLSTOP>)? // specification allows "set .class" to set "class". we also support "set class"
565 key=<IDENT> w()
566 ( <EQUAL> val=expression() )?
567 { ins.add(new Instruction.AssignmentInstruction(key.image, val == null ? true : val, true)); }
568 ( <RBRACE> { return ins; } | <SEMICOLON> w() )
569 )
570 |
571 key=<IDENT> w() <COLON> w()
572 (
573 LOOKAHEAD( float_array() w() ( <SEMICOLON> | <RBRACE> ) )
574 val=float_array()
575 { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
576 w()
577 ( <RBRACE> { return ins; } | <SEMICOLON> w() )
578 |
579 LOOKAHEAD( expression() ( <SEMICOLON> | <RBRACE> ) )
580 val=expression()
581 { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
582 ( <RBRACE> { return ins; } | <SEMICOLON> w() )
583 |
584 val=readRaw() w() { ins.add(new Instruction.AssignmentInstruction(key.image, val, false)); }
585 )
586 )*
587 <RBRACE>
588 { return ins; }
589}
590
591Expression expression():
592{
593 List<Expression> args = new ArrayList<Expression>();
594 Expression e;
595 String op = null;
596}
597{
598 (
599 <EXCLAMATION> { op = "not"; } w() e=primary() { args.add(e); } w()
600 |
601 <MINUS> { op = "minus"; } w() e=primary() { args.add(e); } w()
602 |
603
604 (
605 e=primary() { args.add(e); } w()
606 (
607 ( <PLUS> { op = "plus"; } w() e=primary() { args.add(e); } w() )+
608 |
609 ( <STAR> { op = "times"; } w() e=primary() { args.add(e); } w() )+
610 |
611 ( <MINUS> { op = "minus"; } w() e=primary() { args.add(e); } w() )+
612 |
613 ( <SLASH> { op = "divided_by"; } w() e=primary() { args.add(e); } w() )+
614 |
615 <GREATER_EQUAL> { op = "greater_equal"; } w() e=primary() { args.add(e); } w()
616 |
617 <LESS_EQUAL> { op = "less_equal"; } w() e=primary() { args.add(e); } w()
618 |
619 <GREATER> { op = "greater"; } w() e=primary() { args.add(e); } w()
620 |
621 <EQUAL> ( <EQUAL> )? { op = "equal"; } w() e=primary() { args.add(e); } w()
622 |
623 <LESS> { op = "less"; } w() e=primary() { args.add(e); } w()
624 |
625 <AMPERSAND> <AMPERSAND> { op = "and"; } w() e=primary() { args.add(e); } w()
626 |
627 <PIPE> <PIPE> { op = "or"; } w() e=primary() { args.add(e); } w()
628 |
629 <QUESTION> { op = "cond"; } w() e=primary() { args.add(e); } w() <COLON> w() e=primary() { args.add(e); } w()
630 )?
631 )
632 )
633 {
634 if (op == null)
635 return args.get(0);
636 return ExpressionFactory.createFunctionExpression(op, args);
637 }
638}
639
640Expression primary() :
641{
642 Expression nested;
643 Expression fn;
644 Object lit;
645}
646{
647 LOOKAHEAD(3) // both function and identifier start with an identifier (+ optional whitespace)
648 fn=function() { return fn; }
649 |
650 lit=literal() { return new LiteralExpression(lit); }
651 |
652 <LPAR> w() nested=expression() <RPAR> { return nested; }
653}
654
655Expression function() :
656{
657 Token tmp;
658 Expression arg;
659 String name;
660 List<Expression> args = new ArrayList<Expression>();
661}
662{
663 name=ident() w()
664 <LPAR> w()
665 (
666 arg=expression() { args.add(arg); }
667 ( <COMMA> w() arg=expression() { args.add(arg); } )*
668 )?
669 <RPAR>
670 { return ExpressionFactory.createFunctionExpression(name, args); }
671}
672
673Object literal() :
674{
675 String val;
676 Token t, t2;
677 float f;
678}
679{
680 LOOKAHEAD(2)
681 t2=<IDENT> t=<HEXCOLOR>
682 { return Main.pref.getColor("mappaint." + (sheet == null ? "MapCSS" : sheet.title) + "." + t2.image, ColorHelper.html2color(t.image)); }
683 |
684 t=<IDENT> { return new Keyword(t.image); }
685 |
686 val=string() { return val; }
687 |
688 <PLUS> f=ufloat() { return new Instruction.RelativeFloat(f); }
689 |
690 f=ufloat() { return f; }
691 |
692 t=<HEXCOLOR> { return ColorHelper.html2color(t.image); }
693}
694
695JAVACODE
696void error_skipto(int kind, MapCSSException me) {
697 if (token.kind == EOF)
698 throw new ParseException("Reached end of file while parsing");
699
700 Exception e = null;
701 ParseException pe = generateParseException();
702
703 if (me != null) {
704 me.setLine(pe.currentToken.next.beginLine);
705 me.setColumn(pe.currentToken.next.beginColumn);
706 e = me;
707 } else {
708 e = new ParseException(pe.getMessage()); // prevent memory leak
709 }
710
711 Main.error("Skipping to the next rule, because of an error:");
712 Main.error(e);
713 if (sheet != null) {
714 sheet.logError(e);
715 }
716 Token t;
717 do {
718 t = getNextToken();
719 } while (t.kind != kind && t.kind != EOF);
720 if (t.kind == EOF)
721 throw new ParseException("Reached end of file while parsing");
722}
723
724JAVACODE
725/**
726 * read everything to the next semicolon
727 */
728String readRaw() {
729 Token t;
730 StringBuilder s = new StringBuilder();
731 while (true) {
732 t = getNextToken();
733 if ((t.kind == S || t.kind == STRING || t.kind == UNEXPECTED_CHAR) &&
734 t.image.contains("\n")) {
735 ParseException e = new ParseException(String.format("Warning: end of line while reading an unquoted string at line %s column %s.", t.beginLine, t.beginColumn));
736 Main.error(e);
737 if (sheet != null) {
738 sheet.logError(e);
739 }
740 }
741 if (t.kind == SEMICOLON || t.kind == EOF)
742 break;
743 s.append(t.image);
744 }
745 if (t.kind == EOF)
746 throw new ParseException("Reached end of file while parsing");
747 return s.toString();
748}
749
Note: See TracBrowser for help on using the repository browser.