Get all Antlr parsing errors as list of string

antlr4, java, jvm, parsing

Solution

You need to provide an implementation of `ANTLRErrorListener` to gather information about the errors that occur. For example, the IntelliJ plugin uses its `SyntaxErrorListener` to track this information.

You can check `Parser.getNumberOfSyntaxErrors()` after the parse is complete to see if an error occurred. Note that this doesn't report errors from the lexer. The best way to make sure all errors are reported properly is to write your lexer in such a way that it can never encounter a syntax error itself, but instead passes invalid tokens on to the parser for handling.

Problem

- How can I get all parsing errors of Antlr in a list of strings? I use antlr as follows: ``` ANTLRInputStream input = new ANTLRInputStream(System.in); grLexer lexer = new grLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); grParser parser = new grParser(tokens); ParseTree tree = parser.formula(); System.out.println(tree.toStringTree(parser)); ``` For example ``` line 1:0 token recognition error at: '(' line 1:1 token recognition error at: ')' line 1:2 token recognition error at: '(' ``` - How can I find out that parsing is executed without an error? I would stop if there is only one parsing error. For example ``` if(tree.hasError()) // FOR EXAMPLE return; ```

Original source