ANTLR4 for Java. How to display errors in lexical analysis

前端 未结 1 634
忘了有多久
忘了有多久 2021-01-28 09:04

How can you display a list of errors (if any) during lexical analysis. I tried the following method, but my output is [org.antlr.v4.runtime.ConsoleErrorListener@1026c84c].

<
相关标签:
1条回答
  • 2021-01-28 09:42

    What you're describing is not lexical analysis, but syntactic analysis.

    This is how you add a custom error listener and collect messages:

    String source = "public class Main {\n" +
            "    public static void main(String[] args) {\n" +
            "        System.out.println(\"Hello, world\")\n" +
            "    }\n" +
            "}";
    
    Java8Lexer lexer = new Java8Lexer(CharStreams.fromString(source));
    Java8Parser parser = new Java8Parser(new CommonTokenStream(lexer));
    
    parser.removeErrorListeners();
    
    final List<String> errorMessages = new ArrayList<>();
    
    parser.addErrorListener(new BaseErrorListener(){
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
            errorMessages.add(msg);
        }
    });
    
    parser.compilationUnit();
    
    System.out.println("errorMessages: " + errorMessages);
    

    Note that the snippet above will display the message mismatched input '(' expecting '.' because at this location:

    System.out.println(
    //                ^
    //                |
    //                '-- here
    

    it cannot match a println statement because of the missing ; so it then tries to match another . to complete a methodInvocation, which also fails. That is just how the grammar is structured, not much to do about that (besides rewriting large parts of it).

    If you parse this:

    String source = "public class Main {\n" +
            "    public static void main(String[] args) {\n" +
            "        foo()\n" +
            "    }\n" +
            "}";
    

    then you do get the message: missing ';' at '}'

    0 讨论(0)
提交回复
热议问题