ANTLRv4: How can I check efficiently whether a sentence satisfies a given grammar?

时间秒杀一切 提交于 2019-12-13 18:40:22

问题


This question is basic enough. If I have a sentence and a grammar how can I check efficiently whether this sentence is part of the grammar. By efficient way I mean a way which uses minimum amount of computations/resources. Here's what I did. I implemented a class ErrorListener which extends the already defined BaseErrorListener. This class ErrorListener has a single field boolean error which tells us whether a parse error was encountered during the parsing phase. At the start error is set to false and is updated to true when public void syntaxError(...) is called. Also before the parser's start state is invoked the statements

ErrorListener listener = new ErrorListener();
parser.removeErrorListeners();
parser.addErrorListener(listener);

are called. So after running some tests I stated to think that this approach might not the optimal one especially if this is formed as an query. So I was wondering is there another way of doing all this?


回答1:


The minimal resources would be consumed by starting with the following:

parser.removeErrorListeners();
parser.setErrorStrategy(new BailErrorStrategy());
try {
    parser.ruleName();
    System.out.println("The sentence was contained in the grammar.");
} catch (ParseCancellationException) {
    System.out.println("The sentence was not contained in the grammar.");
}

And then updating this to also use the two-stage parsing strategy descibed in the ANTLR 4 book.



来源:https://stackoverflow.com/questions/18664558/antlrv4-how-can-i-check-efficiently-whether-a-sentence-satisfies-a-given-gramma

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!