ANTLR4 for Java. How to display errors in lexical analysis

青春壹個敷衍的年華 提交于 2021-02-05 09:45:47

问题


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].

The code I wrote:

private static String errorsOutput(String code) {
    Java8Lexer lexer = new Java8Lexer(new ANTLRInputStream(code));

    CommonTokenStream tokens = new CommonTokenStream(lexer);
    Java8Parser parser = new Java8Parser(tokens);

    return ""+lexer.getErrorListeners();
}

Main class:

String code = "public class Main {public static void main(String[] args) {System.out.println("Hello, world")}}";
System.out.println( errorsOutput(code) );

There is no sign in this example [;] and I need the program to display this error


回答1:


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 '}'



来源:https://stackoverflow.com/questions/64544255/antlr4-for-java-how-to-display-errors-in-lexical-analysis

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