...
The beauty of this is that it would automatically know how to build ASTs (or with a little bit of help from you for the complicated ones like method calls and array indexing). Further, the precedence specified as usual by the order of the alternatives. Anything that starts and stops with e
is considered a binary (or possibly trinary) operator. Any other alternative that starts with e
is a suffix operation. Any other alternative that ends with e
is a unitary operation. Alts that are simply rule references identify groups of operations at the same level such as the suffix rule.
The first thing I would need to do is to identify the various kinds of operationsPerhaps as Gavin Lambert oointed out, we simply need to do associativity with an option:
No Format |
---|
e : primary | primaryexponent '^' e // right associative | e '*' e | unary('++'|'-') e | e ('+'|'-') e | suffix_e '.' ID // higher |than array/method call suffix | ; suffix :| e '[++' e ']' ; |exponent options {associativity e '(' e (',' e)* ')' | e '++'= right;} : e '^' e ; unary_suffix : '++' e | '-'[' e ']' ; | suffix_ e '(' e : e(',' e)* '.)' ID ; primary : '(' e ')' | INT | ID ; |
Once I had identified these elements, The one funny thing about all this is that we like to see usually things in order from lowest to highest precedence for these kinds of expression rules, but ANTLR assumes everything is highest to lowest precedence.
I could generate something like the following:
...