Reputation: 83
In ANTLR 4 error/exception handling can be extended by implementing ANTLRErrorListener. It's events will be fired only when I traverse tree which is created using lexer and parser. e.g.
parser.removeErrorListeners();
parser.addErrorListener(new MyTryDSLErrorListener());
ParseTreeWalker walker = new ParseTreeWalker();
MyTryDSLListener listener = new MyTryDSLListener(); // Can be replaced by default Base listener(empty implementation)
walker.walk(listener, parser.test()); // At this line tree will be traversed and if any error then MyTryDSLErrorListener's callback will be called.
I want to know if is there any clean way to get errors from input string without invoking listener/visitor.
NOTE: Though there is a way to handle this by replacing listener with default implementations. And then again traverse tree with own implemented listeners, like as below:
walker.walk(new TryDSLBaseListener(), parser.test()); // Find if has any errors.
walker.walk(new MyTryDSLListener(), parser.test()); // Actual use case.
Upvotes: 0
Views: 2302
Reputation: 6001
The ANTLRErrorListener
only reports errors encountered by the Parser in-line during parsing. That is, the listener reports syntax errors encountered as a result of the Parser's execution of a grammar's start rule.
The listener has no participation with parse-tree walk operations.
Update
parser.removeErrorListeners();
parser.addErrorListener(new MyTryDSLErrorListener());
ParseTree tree = parser.test();
Calling parser.test()
initiates parser execution to create the parse tree. During execution, if and as the parser encounters an error, the parser reports the error through the ANTLRErrorListener
s registered with the parser. All such errors will have been reported when parser.test()
returns.
At this point a parse tree has been constructed. Walking is entirely separate from tree construction. The parser registered ANTLRErrorListener
s will not be called.
ParseTreeWalker walker = new ParseTreeWalker();
MyTryDSLListener listener = new MyTryDSLListener();
walker.walk(listener, tree);
Upvotes: 1