Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANTLR: problem differntiating unary and binary operators (e.g. minus sign)

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?

like image 231
Christian Avatar asked Oct 25 '10 23:10

Christian


1 Answers

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:

alt text

  • image created using http://graph.gafol.net/
like image 172
Bart Kiers Avatar answered Sep 19 '22 15:09

Bart Kiers