如何在antlr4中报告语法歧义 [英] how to report grammar ambiguity in antlr4
问题描述
根据antlr4书(第159页),并使用语法Ambig.g4,可以通过以下方式报告语法歧义:
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);
grun命令使用 antlr-4.5.3 为我正确报告了歧义.但是,当我使用代码形式时,我没有得到歧义报告.这是命令跟踪:
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
TestA_Listener.java代码如下:
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();
}
}
有人可以指出如何修改上面的Java代码以打印歧义报告吗?
Can somebody please point out how the above java code should be modified, to print the ambiguity report?
为完整起见,这是代码Ambig.g4:
For completeness, here is the code Ambig.g4 :
语法Ambig;
stat: expr ';' // expression statement
| ID '(' ')' ';' // function call statement
;
expr: ID '(' ')'
| INT
;
INT : [0-9]+ ;
ID : [a-zA-Z]+ ;
WS : [ \t\r\n]+ -> skip ;
这是in1.txt的输入文件:
And here is the input file in1.txt :
f();
推荐答案
我等了几天,以待其他人发布他们的答案.经过几轮试验,终于找到了答案:
I waited for several days for other people to post their answers. Finally after several rounds of experimenting, I found an answer:
下面的行应从上面的代码中删除.然后我们得到与grun相同的歧义报告.
The following line should be deleted from the above code. Then we get the same ambiguity report as given by grun.
parser.removeErrorListeners(); // remove ConsoleErrorListener
这篇关于如何在antlr4中报告语法歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!