Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANTLR Operator Precedence

How is operator precedence implemented in ANTLR?

I'm using the XText/Antlr package at the moment.

Edit:

I did what sepp2k suggested, and operator precedence works now, but stuff like 3 +* also work now. The operators are basically "falling through" the tree.

Also, I tried the C grammar on ANTLR's website and the same thing happened in ANTLRworks.

Anyone know what the issue is?

BinaryExpression:
  'or'? AndOp; //or op

AndOp:
  'and'? ComparisonOp;

ComparisonOp:
  ('>'|'<'|'>='|'<='|'=='|'~=')? ConcatOp;

ConcatOp:
  '..'? AddSubOp;

AddSubOp:
  ('+' | '-')? MultDivOp;

MultDivOp:
  ('*' | '/')? ExpOp;

ExpOp:
  '^'? expr=Expression;
like image 432
jameszhao00 Avatar asked Sep 20 '09 18:09

jameszhao00


1 Answers

With Xtext / ANTLR 3 you encode the precedence in the grammar rules like this:

Expr:  mult ('+' mult)* ;
Mult:  atom ('*' atom)* ;
Atom:  INT | '(' expr ')' ;

This would parse "1 + 2 * 3 + ( 4 * 5 + 6)" as "(1 + (2 * 3)) + ((4 * 5) + 6)"

like image 161
sepp2k Avatar answered Oct 03 '22 08:10

sepp2k