如何在 antlr4 中报告语法歧义 [英] how to report grammar ambiguity in antlr4
问题描述
根据antlr4 book(第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 :
语法歧义;
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屋!