ANTLR: the problem of distinguishing between unary and binary operators (for example, a minus sign)

I use ANTLR (3.2) to parse a fairly simple grammar. Unfortunately, I ran into a little problem. Follow the following rule:

exp : NUM | '(' expression OPERATOR expression ')' -> expression+ | '(' (MINUS | '!') expression ')' -> expression ; 

The OPERATOR contains the same minus sign ('-') as for MINUS. Now ANTLR does not seem to cope with these two rules. If I delete one, everything will be fine.

Any ideas?

+7
binary operator-keyword antlr
source share
1 answer

Make a unary expression for those with the highest priority. I would also use a different token for unary - to make the difference between the minus better. Demonstration:

 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;} ; 

Quick test with source:

 3 * -4 + 7 / 6 * -(3 + -7 * (4 + !2)) 

produced the following AST:

alt text

+9
source share

All Articles