[antlr-interest] Simple expression grammar
Maciej Bakalarz
shipmen at gmail.com
Wed May 14 05:26:17 PDT 2008
Hi again!
>> I need to parse expressions which are using nested parenthesis, like:
>> "( a>=3 || b<=4 ) && c>=4" or "((a>=3 || b<=4) && c>=4) || a>=3 )"
>>
> What happens if you change this:
>>
>> expression
>> : ALFANUM
>> ;
>
> to this:
>
> expression
> : ALFANUM | '(' prog ')'
It's good idea. I will try it for a moment. For now I used '('prog')'
but in other part of grammar.
I also used mentioned "backtrack=true; memoize=true;" option.
I added possibility to negate expressions too ...
It's not tested but seems to work fine.
Here is the final grammar:
grammar GuardCondition;
options {
output=AST;
ASTLabelType=CommonTree;
backtrack=true;
memoize=true;
}
prog:
logical_or_expression+
;
logical_or_expression:
logical_and_expression (OR_OP^ logical_and_expression)*
;
logical_and_expression
: rel_expression (AND_OP^ rel_expression)*
;
rel_expression
: expression (REL_OP^ expression)*
| LPAREN! prog RPAREN!
| NEG^ LPAREN! prog RPAREN!
;
expression
: ID | INT | NEG^ ID
;
NEG : '!';
LPAREN : '(';
RPAREN : ')';
REL_OP : '==' | '<' | '>' | '<=' | '>='|'!=';
OR_OP : '||';
AND_OP : '&&';
ID : ALFA ( ALFA | INT ) *;
ALFA : ('a'..'z'|'A'..'Z') ;
INT : '0'..'9'+;
WS : (' '|'\t')+ {skip();};
Thanks for help !
Maciek Bakalarz
More information about the antlr-interest
mailing list