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

Last change on this file since 6455 was 6455, checked in by simon04, 10 years ago

fix #7939 - MapCSS: add support for negated regular expressions

File size: 15.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2options {
3  STATIC = false;
4}
5
6PARSER_BEGIN(MapCSSParser)
7package org.openstreetmap.josm.gui.mappaint.mapcss.parsergen;
8
9import java.awt.Color;
10import java.util.ArrayList;
11import java.util.List;
12
13import org.openstreetmap.josm.gui.mappaint.Keyword;
14import org.openstreetmap.josm.gui.mappaint.mapcss.Condition;
15import org.openstreetmap.josm.gui.mappaint.mapcss.Condition.Context;
16import org.openstreetmap.josm.gui.mappaint.mapcss.Expression;
17import org.openstreetmap.josm.gui.mappaint.mapcss.Instruction;
18import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
19import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
20import org.openstreetmap.josm.gui.mappaint.mapcss.Selector;
21import org.openstreetmap.josm.gui.mappaint.mapcss.ExpressionFactory;
22import org.openstreetmap.josm.gui.mappaint.mapcss.LiteralExpression;
23import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSException;
24import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.ChildOrParentSelector;
25import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector;
26import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.LinkSelector;
27import org.openstreetmap.josm.tools.Pair;
28import org.openstreetmap.josm.tools.Utils;
29import org.openstreetmap.josm.Main;
30
31public class MapCSSParser {
32    MapCSSStyleSource sheet;
33}
34PARSER_END(MapCSSParser)
35
36/*************
37 * Token definitions
38 */
39
40<DEFAULT>
41TOKEN:
42{
43    < IDENT: ["a"-"z","A"-"Z","_"] ( ["a"-"z","A"-"Z","_","-","0"-"9"] )* >
44|   < UINT: ["1"-"9"] ( ["0"-"9"] )* >
45|   < UFLOAT: ( ["0"-"9"] )+ ( "." ( ["0"-"9"] )+ )? >
46|   < STRING: "\"" ( [" ","!","#"-"[","]"-"~","\u0080"-"\uFFFF"] | "\\\"" | "\\\\" )*  "\"" >
47|   < #REGEX_CHAR_WITHOUT_STAR: [" "-")","+"-".","0"-"[","]"-"~","\u0080"-"\uFFFF"] | "\\/" | "\\\\" | "\\[" | "\\]" >
48|   < REGEX: "/" <REGEX_CHAR_WITHOUT_STAR> ( <REGEX_CHAR_WITHOUT_STAR> | "*" )*  "/" >
49|   < #H: ["0"-"9","a"-"f","A"-"F"] >
50|   < HEXCOLOR: "#" ( <H><H><H><H><H><H> | <H><H><H> ) >
51|   < S: ( " " | "\t" | "\n" | "\r" | "\f" )+ >
52|   < STAR: "*" >
53|   < SLASH: "/" >
54|   < LBRACE: "{" >
55|   < RBRACE: "}" >
56|   < LSQUARE: "[" >
57|   < RSQUARE: "]" >
58|   < LPAR: "(" >
59|   < RPAR: ")" >
60|   < GREATER_EQUAL: ">=" >
61|   < LESS_EQUAL: "<=" >
62|   < GREATER: ">" >
63|   < LESS: "<" >
64|   < EQUAL: "=" >
65|   < EXCLAMATION: "!" >
66|   < TILDE: "~" >
67|   < COLON: ":" >
68|   < DCOLON: "::" >
69|   < SEMICOLON: ";" >
70|   < COMMA: "," >
71|   < PIPE: "|" >
72|   < PIPE_Z: "|z" >
73|   < PLUS: "+" >
74|   < MINUS: "-" >
75|   < AMPERSAND: "&" >
76|   < QUESTION: "?" >
77|   < DOLLAR: "$" >
78|   < CARET: "^" >
79|   < COMMENT_START: "/*" > : COMMENT
80|   < UNEXPECTED_CHAR : ~[] > // avoid TokenMgrErrors because they are hard to recover from
81}
82
83<COMMENT>
84TOKEN:
85{
86    < COMMENT_END: "*/" > : DEFAULT
87}
88
89<COMMENT>
90SKIP:
91{
92    < ~[] >
93}
94
95/*************
96 * Parser definitions
97 *
98 *                       rule
99 *  _______________________|______________________________
100 * |                                                      |
101 *        selector                      declaration
102 *  _________|___________________   _________|____________
103 * |                             | |                      |
104 *
105 * way|z11-12[highway=residential] { color: red; width: 3 }
106 *
107 *    |_____||___________________|   |_________|
108 *       |            |                   |
109 *     zoom       condition          instruction
110 *
111 * more general:
112 *
113 * way|z13-[a=b][c=d]::subpart, way|z-3[u=v]:closed::subpart2 { p1 : val; p2 : val; }
114 *
115 * 'val' can be a literal, or an expression like "prop(width, default) + 0.8".
116 *
117 */
118
119int uint() :
120{
121    Token i;
122}
123{
124    i=<UINT> { return Integer.parseInt(i.image); }
125}
126
127int int_() :
128{
129    int i;
130}
131{
132    <MINUS> i=uint() { return -i; } | i=uint() { return i; }
133}
134
135float ufloat() :
136{
137    Token f;
138}
139{
140    ( f=<UFLOAT> | f=<UINT> )
141    { return Float.parseFloat(f.image); }
142}
143
144float float_() :
145{
146    float f;
147}
148{
149    <MINUS> f=ufloat() { return -f; } | f=ufloat() { return f; }
150}
151
152String string() :
153{
154    Token t;
155}
156{
157    t=<STRING>
158    { return t.image.substring(1, t.image.length() - 1).replace("\\\"", "\"").replace("\\\\", "\\"); }
159}
160
161String string_or_ident() :
162{
163    Token t;
164    String s;
165}
166{
167    t=<IDENT> { return t.image; } | s=string() { return s; }
168}
169
170String regex() :
171{
172    Token t;
173}
174{
175    t=<REGEX>
176    { return t.image.substring(1, t.image.length() - 1); }
177}
178
179/**
180 * white-space
181 */
182void s() :
183{
184}
185{
186    ( <S> )?
187}
188
189/**
190 * mix of white-space and comments
191 */
192void w() :
193{
194}
195{
196    ( <S> | <COMMENT_START> <COMMENT_END> )*
197}
198
199/**
200 * comma delimited list of floats (at least 2, all >= 0)
201 */
202List<Float> float_array() :
203{
204    float f;
205    List<Float> fs = new ArrayList<Float>();
206}
207{
208    f=ufloat() { fs.add(f); }
209    (
210        <COMMA> s()
211        f=ufloat() { fs.add(f); }
212    )+
213    {
214        return fs;
215    }
216}
217
218/**
219 * root
220 */
221void sheet(MapCSSStyleSource sheet):
222{
223    MapCSSRule r;
224    Token com = null;
225}
226{
227    { this.sheet = sheet; }
228    w()
229    (
230        try {
231                r=rule() { if (r != null) { sheet.rules.add(r); } } w()
232        } catch (MapCSSException mex) {
233            error_skipto(RBRACE, mex);
234            w();
235        } catch (ParseException ex) {
236            error_skipto(RBRACE, null);
237            w();
238        }
239    )*
240    <EOF>
241}
242
243MapCSSRule rule():
244{
245    List<Selector> selectors = new ArrayList<Selector>();
246    Selector sel;
247    List<Instruction> decl;
248}
249{
250    sel=child_selector() { selectors.add(sel); }
251    (
252        <COMMA> w()
253        sel=child_selector() { selectors.add(sel); }
254    )*
255    decl=declaration()
256    { return new MapCSSRule(selectors, decl); }
257}
258
259Selector child_selector() :
260{
261    boolean parentSelector = false;
262    Condition c;
263    List<Condition> conditions = new ArrayList<Condition>();
264    Selector selLeft;
265    LinkSelector selLink = null;
266    Selector selRight = null;
267}
268{
269    selLeft=selector() w()
270    (
271        ( <GREATER> { parentSelector = false; } | <LESS> { parentSelector = true; } )
272        ( ( c=condition(Context.LINK) | c=pseudoclass(Context.LINK) ) { conditions.add(c); } )*
273        { selLink = new LinkSelector(conditions); }
274        w()
275        selRight=selector() w()
276    )?
277    { return selRight != null ? new ChildOrParentSelector(selLeft, selLink, selRight, parentSelector) : selLeft; }
278}
279
280Selector selector() :
281{
282    Token base;
283    Condition c;
284    Pair<Integer, Integer> r = null;
285    List<Condition> conditions = new ArrayList<Condition>();
286    String sub = null;
287}
288{
289    ( base=<IDENT> | base=<STAR> )
290    ( r=zoom() )?
291    ( ( c=condition(Context.PRIMITIVE) | c=pseudoclass(Context.PRIMITIVE) ) { conditions.add(c); } )*
292    ( sub=subpart() )?
293    { return new GeneralSelector(base.image, r, conditions, sub); }
294}
295
296Pair<Integer, Integer> zoom() :
297{
298    Integer min = 0;
299    Integer max = Integer.MAX_VALUE;
300}
301{
302    <PIPE_Z>
303    (
304            <MINUS> max=uint()
305        |
306        LOOKAHEAD(2)
307            min=uint() <MINUS> ( max=uint() )?
308        |
309            min=uint() { max = min; }
310    )
311    { return new Pair<Integer, Integer>(min, max); }
312}
313
314Condition condition(Context context) :
315{
316    Condition c;
317    Expression e;
318}
319{
320    <LSQUARE> s()
321    (
322        LOOKAHEAD( simple_key_condition(context) s() <RSQUARE> )
323            c=simple_key_condition(context) s() <RSQUARE> { return c; }
324        |
325        LOOKAHEAD( simple_key_value_condition(context) s() <RSQUARE> )
326            c=simple_key_value_condition(context) s() <RSQUARE> { return c; }
327        |
328            e=expression() <RSQUARE> { return Condition.create(e, context); }
329    )
330}
331
332String tag_key() :
333{
334    String s;
335    Token t;
336}
337{
338        s=string() { return s; }
339    |
340        t=<IDENT> { s = t.image; } ( <COLON> t=<IDENT> { s += ':' + t.image; } )* { return s; }
341}
342
343Condition simple_key_condition(Context context) :
344{
345    boolean not = false;
346    boolean yes = false;
347    String key;
348}
349{
350    ( <EXCLAMATION> { not = true; } )?
351    key=tag_key()
352    ( <QUESTION> { yes = true; } )?
353    { return Condition.create(key, not, yes, context); }
354}
355
356Condition simple_key_value_condition(Context context) :
357{
358    String key;
359    String val;
360    float f;
361    int i;
362    Condition.Op op;
363}
364{
365    key=tag_key() s()
366    (
367        LOOKAHEAD(2)
368            <EQUAL> <TILDE> { op=Condition.Op.REGEX; } s() val=regex()
369        |
370        LOOKAHEAD(2)
371            <EXCLAMATION> <TILDE> { op=Condition.Op.NREGEX; } s() val=regex()
372        |
373            (
374                    <EXCLAMATION> <EQUAL> { op=Condition.Op.NEQ; }
375                |
376                    <EQUAL> { op=Condition.Op.EQ; }
377                |
378                    <TILDE> <EQUAL> { op=Condition.Op.ONE_OF; }
379                |
380                    <CARET> <EQUAL> { op=Condition.Op.BEGINS_WITH; }
381                |
382                    <DOLLAR> <EQUAL> { op=Condition.Op.ENDS_WITH; }
383                |
384                    <STAR> <EQUAL> { op=Condition.Op.CONTAINS; }
385            )
386            s()
387            (
388                LOOKAHEAD(2)
389                        i=int_() { val=Integer.toString(i); }
390                    |
391                        f=float_() { val=Float.toString(f); }
392                    |
393                        val=string_or_ident()
394            )
395        |
396            (
397                    <GREATER_EQUAL> { op=Condition.Op.GREATER_OR_EQUAL; }
398                |
399                    <GREATER> { op=Condition.Op.GREATER; }
400                |
401                    <LESS_EQUAL> { op=Condition.Op.LESS_OR_EQUAL; }
402                |
403                    <LESS> { op=Condition.Op.LESS; }
404            )
405            s()
406            f=float_() { val=Float.toString(f); }
407    )
408    { return Condition.create(key, val, op, context); }
409}
410
411Condition pseudoclass(Context context) :
412{
413    Token t;
414    boolean not = false;
415}
416{
417    ( <EXCLAMATION> { not = true; } )?
418    <COLON>
419    t=<IDENT>
420    { return Condition.create(t.image, not, context); }
421}
422
423String subpart() :
424{
425    Token t;
426}
427{
428    <DCOLON>
429    ( t=<IDENT> | t=<STAR> )
430    { return t.image; }
431}
432
433List<Instruction> declaration() :
434{
435    List<Instruction> ins = new ArrayList<Instruction>();
436    Instruction i;
437    Token key;
438    Object val;
439}
440{
441    <LBRACE> w()
442    (
443        key=<IDENT> w() <COLON> w()
444        (
445            LOOKAHEAD( float_array() w() ( <SEMICOLON> | <RBRACE> ) )
446                val=float_array()
447                { ins.add(new Instruction.AssignmentInstruction(key.image, val)); }
448                w()
449                ( <RBRACE> { return ins; } | <SEMICOLON> w() )
450            |
451            LOOKAHEAD( expression() ( <SEMICOLON> | <RBRACE> ) )
452                val=expression()
453                { ins.add(new Instruction.AssignmentInstruction(key.image, val)); }
454                ( <RBRACE> { return ins; } | <SEMICOLON> w() )
455            |
456                val=readRaw() w() { ins.add(new Instruction.AssignmentInstruction(key.image, val)); }
457        )
458    )*
459    <RBRACE>
460    { return ins; }
461}
462
463Expression expression():
464{
465    List<Expression> args = new ArrayList<Expression>();
466    Expression e;
467    String op = null;
468}
469{
470    (
471        <EXCLAMATION> { op = "not"; } w() e=primary() { args.add(e); } w()
472    |
473        <MINUS> { op = "minus"; } w() e=primary() { args.add(e); } w()
474    |
475
476        (
477            e=primary() { args.add(e); } w()
478            (
479                    ( <PLUS> { op = "plus"; } w() e=primary() { args.add(e); } w() )+
480                |
481                    ( <STAR> { op = "times"; } w() e=primary() { args.add(e); } w() )+
482                |
483                    ( <MINUS> { op = "minus"; } w() e=primary() { args.add(e); } w() )+
484                |
485                    ( <SLASH> { op = "divided_by"; } w() e=primary() { args.add(e); } w() )+
486                |
487                    <GREATER_EQUAL> { op = "greater_equal"; } w() e=primary() { args.add(e); } w()
488                |
489                    <LESS_EQUAL> { op = "less_equal"; } w() e=primary() { args.add(e); } w()
490                |
491                    <GREATER> { op = "greater"; } w() e=primary() { args.add(e); } w()
492                |
493                    <EQUAL> ( <EQUAL> )? { op = "equal"; } w() e=primary() { args.add(e); } w()
494                |
495                    <LESS> { op = "less"; } w() e=primary() { args.add(e); } w()
496                |
497                    <AMPERSAND> <AMPERSAND> { op = "and"; } w() e=primary() { args.add(e); } w()
498                |
499                    <PIPE> <PIPE> { op = "or"; } w() e=primary() { args.add(e); } w()
500                |
501                    <QUESTION> { op = "cond"; } w() e=primary() { args.add(e); } w() <COLON> w() e=primary() { args.add(e); } w()
502            )?
503        )
504    )
505    {
506        if (op == null)
507            return args.get(0);
508        return ExpressionFactory.createFunctionExpression(op, args);
509    }
510}
511
512Expression primary() :
513{
514    Expression nested;
515    Expression fn;
516    Object lit;
517}
518{
519    LOOKAHEAD(3) // both function and identifier start with an identifier (+ optional whitespace)
520        fn=function() { return fn; }
521    |
522        lit=literal() { return new LiteralExpression(lit); }
523    |
524        <LPAR> w() nested=expression() <RPAR> { return nested; }
525}
526
527Expression function() :
528{
529    Token tmp;
530    Expression arg;
531    String name;
532    List<Expression> args = new ArrayList<Expression>();
533}
534{
535    tmp=<IDENT> { name = tmp.image; } w()
536    <LPAR> w()
537    (
538        arg=expression() { args.add(arg); }
539        ( <COMMA> w() arg=expression() { args.add(arg); } )*
540    )?
541    <RPAR>
542    { return ExpressionFactory.createFunctionExpression(name, args); }
543}
544
545Object literal() :
546{
547    String val;
548    Token t;
549    float f;
550}
551{
552        t=<IDENT> { return new Keyword(t.image); }
553    |
554        val=string() { return val; }
555    |
556        <PLUS> f=ufloat() { return new Instruction.RelativeFloat(f); }
557    |
558        f=ufloat() { return f; }
559    |
560        t=<HEXCOLOR> { return Utils.hexToColor(t.image); }
561}
562
563JAVACODE
564void error_skipto(int kind, MapCSSException me) {
565    if (token.kind == EOF)
566        throw new ParseException("Reached end of file while parsing");
567       
568    Exception e = null;       
569    ParseException pe = generateParseException();
570
571    if (me != null) {
572        me.setLine(pe.currentToken.next.beginLine);
573        me.setColumn(pe.currentToken.next.beginColumn);
574        e = me;
575    } else {
576        e = new ParseException(pe.getMessage()); // prevent memory leak
577    }
578   
579    Main.error("Skipping to the next rule, because of an error:");
580    Main.error(e);
581    if (sheet != null) {
582        sheet.logError(e);
583    }
584    Token t;
585    do {
586        t = getNextToken();
587    } while (t.kind != kind && t.kind != EOF);
588    if (t.kind == EOF)
589        throw new ParseException("Reached end of file while parsing");
590}
591
592JAVACODE
593/**
594 * read everything to the next semicolon
595 */
596String readRaw() {
597    Token t;
598    StringBuilder s = new StringBuilder();
599    while (true) {
600        t = getNextToken();
601        if ((t.kind == S || t.kind == STRING || t.kind == UNEXPECTED_CHAR) &&
602                t.image.contains("\n")) {
603            ParseException e = new ParseException(String.format("Warning: end of line while reading an unquoted string at line %s column %s.", t.beginLine, t.beginColumn));
604            Main.error(e);
605            if (sheet != null) {
606                sheet.logError(e);
607            }
608        }
609        if (t.kind == SEMICOLON || t.kind == EOF)
610            break;
611        s.append(t.image);
612    }
613    if (t.kind == EOF)
614        throw new ParseException("Reached end of file while parsing");
615    return s.toString();
616}
617
Note: See TracBrowser for help on using the repository browser.