问题
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