views:

27

answers:

2

Hi guys,

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?

A: 

What is the specific error message you are getting? It helps if you're using the ANTLR plugin for Eclipse; that would tell me more about the error. It would also be helpful if you could post the grammar itself, as that might have something to do with it as well.

jyaworski
A: 

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

Bart Kiers
wow, great work, thank you very much!
Christian
@Christian, you're welcome.
Bart Kiers