title: how to report grammar ambiguity in antlr4
body: <p>According to the antlr4 book (page 159), and using the grammar Ambig.g4, grammar ambiguity can be reported by:</p>
  
  <pre><code>grun Ambig stat -diagnostics
  </code></pre>
  
  <p>or equivalently, in code form:</p>
  
  <pre><code>parser.removeErrorListeners();
  parser.addErrorListener(new DiagnosticErrorListener());
  parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);
  </code></pre>
  
  <p>The grun command reports the ambiguity properly for me, using <strong>antlr-4.5.3</strong>. But when I use the code form, I dont get the ambiguity report. Here is the command trace:</p>
  
  <pre><code>$ antlr4 Ambig.g4   # see the book's page.159 for the grammar
  $ javac Ambig*.java
  $ grun Ambig stat -diagnostics &lt; in1.txt # in1.txt is as shown on page.159
      line 1:3 reportAttemptingFullContext d=0 (stat), input='f();'
      line 1:3 reportAmbiguity d=0 (stat): ambigAlts={1, 2}, input='f();'
  $ javac TestA_Listener.java
  $ java TestA_Listener &lt; in1.txt   # exits silently
  </code></pre>
  
  <p>The TestA_Listener.java code is the following:</p>
  
  <pre><code>import org.antlr.v4.runtime.*;
  import org.antlr.v4.runtime.atn.*; // for PredictionMode
  import java.util.*;
  public class TestA_Listener {
      public static void main(String[] args) throws Exception {
          ANTLRInputStream input = new ANTLRInputStream(System.in);
          AmbigLexer lexer = new AmbigLexer(input);
          CommonTokenStream tokens = new CommonTokenStream(lexer);
          AmbigParser parser = new AmbigParser(tokens);
          parser.removeErrorListeners(); // remove ConsoleErrorListener
          parser.addErrorListener(new DiagnosticErrorListener());
          parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);
          parser.stat();
      }
  }
  </code></pre>
  
  <p>Can somebody please point out how the above java code should be modified, to print the ambiguity report?</p>
  
  <p>For completeness, here is the code Ambig.g4 :</p>
  
  <p>grammar Ambig;</p>
  
  <pre><code>stat: expr ';'        // expression statement
      | ID '(' ')' ';'  // function call statement
      ;
  
  expr: ID '(' ')'
      | INT
      ;
  
  INT :   [0-9]+ ;
  ID  :   [a-zA-Z]+ ;
  WS  :   [ \t\r\n]+ -&gt; skip ;
  </code></pre>
  
  <p>And here is the input file in1.txt :</p>
  
  <pre><code>f();
  </code></pre>