Question

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;
Was it helpful?

Solution

With ANTLR you encode the precedence in the grammar rules. Like:

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)"

OTHER TIPS

Since you use Xtext, I'd recommend to use the action concept of Xtext. That is, a simple expression grammar would typically look similar to this one:

Sum: Product ({Sum.left=current} operator=('+'|'-') right=Product)*;
Product: Atom ({Product.left=current} operator=('+'|'-') right=Atom)*;
Atom: Number | Paren;
Paren: '(' Sum ')';
Number: value=INT;

Please have a look at the docs for details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top