In ANTLR how do I skip the value in a simple expression parser?

18 views
Skip to first unread message

Aravind Kumar

unread,
Mar 21, 2015, 3:42:00 PM3/21/15
to antlr-di...@googlegroups.com

Hi there I have been trying to write a simple expression parser, here is the grammar.

grammar extremelysimplgrammar ;

stat : expr ;
expr : sub ;
sub : add ( '-' add )* ;
add : VAL ( '+' VAL )* 
    | VAL
    ;  


VAL : [0-9]+ ;
[ \t\n\r]+ -> skip ;

It matches these expressions

1 + 1
0 + 3
4

But I do not want it to match single occurrence of VAL. I want it to match 1 + 1 but not 4. How do I do that ?

Mike Lischke

unread,
Mar 21, 2015, 4:58:58 PM3/21/15
to antlr-di...@googlegroups.com
When you define a rule that matches a single value then you should expect it to match a single value. From your very thin spec I'd say you want:

stat: VAL (('+' | '-') VAL)+;

Reply all
Reply to author
Forward
0 new messages