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 | '!') e开发者_如何学Cxpression ')' -> 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:
- image created using http://graph.gafol.net/
精彩评论