From 245dc147ec951663bf224765ac8d6dc9d4e0b409 Mon Sep 17 00:00:00 2001 From: Boolean-true Date: Sun, 30 Jun 2024 22:38:20 +0200 Subject: [PATCH] add custom error listener --- src/main/java/de/maishai/Compiler.java | 10 ++++++++++ .../java/de/maishai/ThrowingErrorListener.java | 17 +++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 src/main/java/de/maishai/ThrowingErrorListener.java diff --git a/src/main/java/de/maishai/Compiler.java b/src/main/java/de/maishai/Compiler.java index 79e5355..749afb5 100644 --- a/src/main/java/de/maishai/Compiler.java +++ b/src/main/java/de/maishai/Compiler.java @@ -25,9 +25,19 @@ public class Compiler { List classes = new ArrayList<>(); for (String fromSource : fromSources) { CharStream input = CharStreams.fromString(fromSource); + DecafLexer lexer = new DecafLexer(input); + //add custom error listener + lexer.removeErrorListeners(); + lexer.addErrorListener(ThrowingErrorListener.INSTANCE); + CommonTokenStream tokens = new CommonTokenStream(lexer); + DecafParser parser = new DecafParser(tokens); + //add custom error listener + parser.removeErrorListeners(); + parser.addErrorListener(ThrowingErrorListener.INSTANCE); + DecafParser.ClassContext tree = parser.class_(); //Parsen classes.add(ASTGenerator.generateAST(tree)); } diff --git a/src/main/java/de/maishai/ThrowingErrorListener.java b/src/main/java/de/maishai/ThrowingErrorListener.java new file mode 100644 index 0000000..7cbbdee --- /dev/null +++ b/src/main/java/de/maishai/ThrowingErrorListener.java @@ -0,0 +1,17 @@ +package de.maishai; + +import org.antlr.v4.runtime.BaseErrorListener; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Recognizer; +import org.antlr.v4.runtime.misc.ParseCancellationException; + +public class ThrowingErrorListener extends BaseErrorListener { + + public static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener(); + + @Override + public void syntaxError(Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) + throws ParseCancellationException { + throw new ParseCancellationException("Error in line " + line + ":" + charPositionInLine + " " + msg); + } +}