how to get ambiguity report for antlr4

237 views
Skip to first unread message

roge...@gmail.com

unread,
Oct 17, 2016, 1:32:49 AM10/17/16
to antlr-discussion, Roger Goodman
Hi, I had posted a question on stackoverflow several weeks ago, but did not get a suitable response, so I am asking the question here again.

I have a large grammar file, and want to make sure that I have not inadvertently created some ambiguity in it. Hence I would like an ambiguity report for each testcase that I have.

The full question is at http://stackoverflow.com/questions/39827313

The summary is given below:

According to the antlr4 book (page 159), and using the grammar Ambig.g4, grammar ambiguity can be reported by:

      grun Ambig stat -diagnostics

or equivalently, in code form:

parser.removeErrorListeners();
parser.addErrorListener(new DiagnosticErrorListener());
parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);

The grun command reports the ambiguity properly for me, using antlr-4.5.3. But when I use the code form, I dont get the ambiguity report. Here is the command trace:

$ antlr4 Ambig.g4   # see the book's page.159 for the grammar
$ javac Ambig*.java
$ grun Ambig stat -diagnostics < 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 < in1.txt   # exits silently

The TestA_Listener.java code is the following:

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();
    }
}

Can somebody please point out how the above java code should be modified, to print the ambiguity report?


Reply all
Reply to author
Forward
0 new messages