Operator Priority ANTLR

How is operator priority performed in ANTLR?

I am using the XText / Antlr package at the moment.

Edit:

I did what sepp2k suggested, and now the priority of the operators works, but now everything works like 3 + *. Operators basically “fall” through the tree.

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

Does anyone know what the problem is?

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

AndOp:
  'and'? ComparisonOp;

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

ConcatOp:
  '..'? AddSubOp;

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

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

ExpOp:
  '^'? expr=Expression;
+5
source share
2 answers

With ANTLR, you encode priority in grammar rules. How:

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

This will analyze "1 + 2 * 3 + (4 * 5 + 6)" as "(1 + (2 * 3)) + ((4 * 5) + 6)"

+9
source

Xtext, Xtext. :

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

. .

+2

All Articles