In grammars that have a large number of operator precedence levels for binary expressions, the time spent in the standard ANTLR recursive approach to expression parsing can have a noticeable impact on the overall speed of the grammar. One option to consider in writing the binary expression parser is embedding an operator precedence parser for binary expressions between the 'expression' (or similar) rule and the unary expression rule(s). For the time being, I don't have an example implementation for additionally handling ternary and unary expressions, but those can be written in the same recursive manner as usual, since they are the minority of the time spent recursing the expression rules.
Benefits:
- When the binary expression rules don't use predicates, this can be an order of magnitude faster than the common recursive method.
- Operator associativity (left to right / right to left) is handled in a concise and clear way.
- Operator precedence is clear and concise, and properly handles multiple operators at the same level, such as * and / in C++
Downsides:
- Requires some implementation in the target language.
Here is a very simple example grammar that implements this method. The methods are written in Java here (which I tested), but I use C# for my production grammars and the code (minor changes of course) runs great there too.