1

In the following example, the order matters in terms of precedence:

grammar Precedence;
root: expr EOF;

expr
    : expr ('+'|'-') expr
    | expr ('*' | '/') expr
    | Atom
    ;

Atom: [0-9]+;
WHITESPACE: [ \t\r\n] -> skip;

For example, on the expression 1+1*2 the above would produce the following parse tree which would evaluate to (1+1)*2=4:

enter image description here

Whereas if I changed the first and second alternations in the expr I would then get the following parse tree which would evaluate to 1+(1*2)=3:

enter image description here

What are the 'rules' then for when it actually matters where the ordering in an alternation occurs? Is this only relevant if it one of the 'edges' of the alternation recursively calls the expr? For example, something like ~ expr or expr + expr would matter, but something like func_call '(' expr ')' or Atom would not. Or, when is it important to order things for precedence?

David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

2

If ANTLR did not have the rule to give precedence to the first alternative that could match, then either of those trees would be valid interpretations of your input (and means the grammar is technically ambiguous).

However, when there are two alternatives that could be used to match your input, then ANTLR will use the first alternative to resolve the ambiguity, in this case establishing operator precedence, so typically you would put the multiplication/division operator before the addition/subtraction, since that would be the traditional order of operations:

grammar Precedence;
root: expr EOF;

expr
    : expr ('+'|'-') expr
    | expr ('*' | '/') expr
    | Atom
    ;

Atom: [0-9]+;
WHITESPACE: [ \t\r\n] -> skip;

Most grammar authors will just put them in precedence order, but things like Atoms or parenthesized exprs won’t really care about the order since there’s only a single alternative that could be used.

Mike Cargal
  • 6,610
  • 3
  • 21
  • 27
  • exactly, what I meant is actually the last part of your answer -- `Most grammar authors will just put them in precedence order, but things like Atoms or parenthesized exprs won’t really care about the order since there’s only a single alternative that could be used.` <-- when does this not matter, is it when there is not an `expr` on the edge of the rule? – David542 Aug 30 '22 at 03:27
  • 2
    No it’s just how ANTLR resolves ambiguities (you see the same rule taking affect in your previous question here: https://stackoverflow.com/questions/73508143/how-to-disambiguate-a-subselect-from-a-parenthesized-expression). It just so happens that it’s more clearly useful when it settles the precedence of alternatives where `expr` is at the edge of the rules. – Mike Cargal Aug 30 '22 at 12:22