title: ANTLR4 different precedence in two seemingly equivalent grammars
body: <p>The following test grammars differ only in that the first alternative of the rule 'expr' is either specified inline or refers to another rule 'notExpression' with just the same definition. But this grammars produce different trees parsing this: '! a &amp; b'. Why?</p>
  
  <p>I really want the grammar to produce the first result (with NOT associated with identifier, not with AND expression) but still need to have 'expr' to reference 'notExpression' in my real grammar. What do I have to change?</p>
  
  <pre><code>grammar test;
  s: expr ';' &lt;EOF&gt;;
  expr:
      NOT expr
      | left=expr AND right=expr
      | identifier
      ;
  identifier: LETTER (LETTER)*;
  WS  :  ' '+ -&gt;skip;
  NOT: '!';
  AND: '&amp;';
  LETTER: 'A'..'z';
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/U19sf.png" rel="nofollow noreferrer">Tree one</a></p>
  
  <pre><code>grammar test;
  s: expr ';' &lt;EOF&gt;;
  expr:
      notExpression
      | left=expr AND right=expr
      | identifier
      ;
  notExpression:  NOT expr;
  identifier: LETTER (LETTER)*;
  WS  :  ' '+ -&gt;skip;
  NOT: '!';
  AND: '&amp;';
  LETTER: 'A'..'z';
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/2i9ff.png" rel="nofollow noreferrer">Tree two</a></p>