i'm using ANTLR (3.2) to parse some rather simple grammar. Unfortunately, I came across a little problem. Take the follwoing rule:
exp
: NUM
| '(' expression OPERATOR expression ')' -> expression+
| '(' (MINUS | '!') expression ')' -> expression
;
OPERATOR contains the same minus sign ('-') as is defined with MINUS. Now ANTLR seems to be unable to deal with these two rules. If I remove either one, everything works fine.
Anyone ideas?
Make the unary expression the one with the highest precedence. I'd also use a different token for the unary -
to make the distinction between the minus better. A demo:
grammar Exp;
options {
output=AST;
}
tokens {
UNARY;
}
parse
: exp EOF
;
exp
: additionExp
;
additionExp
: multiplyExp ('+'^ multiplyExp | '-'^ multiplyExp)*
;
multiplyExp
: unaryExp ('*'^ unaryExp | '/'^ unaryExp)*
;
unaryExp
: '-' atom -> ^(UNARY atom)
| '!' atom -> ^('!' atom)
| atom
;
atom
: '(' exp ')' -> exp
| Number -> Number
;
Number : ('0'..'9')+ ('.' ('0'..'9')+)? ;
Spaces : (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;} ;
A quick test with the source:
3 * -4 + 7 / 6 * -(3 + -7 * (4 + !2))
produced the following AST:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With