1

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?

sve
  • 4,336
  • 1
  • 19
  • 30

1 Answers1

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.

Sam Harwell
  • 97,721
  • 20
  • 209
  • 280