From faef67d7c44e156ff80292a69f57d82aef35efec Mon Sep 17 00:00:00 2001 From: Roman Lukash <2893931+RomanLukash340@users.noreply.github.com> Date: Thu, 3 Oct 2024 19:26:46 +0200 Subject: [PATCH] Fix lexer error handling --- .vscode/launch.json | 7 ++++++ simulator/src/jack/listener/error.listener.ts | 23 ++++++++++++++++--- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 6b93aff12..184dfbb0d 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -34,6 +34,13 @@ ], "outFiles": ["${workspaceFolder}/extension/build/test/**/*.js"], "preLaunchTask": "${defaultBuildTask}" + }, + { + "type": "chrome", + "request": "launch", + "name": "Test web ide", + "url": "http://localhost:3000/web-ide", + "webRoot": "${workspaceFolder}" } ] } diff --git a/simulator/src/jack/listener/error.listener.ts b/simulator/src/jack/listener/error.listener.ts index 63b6594a2..38a6c6da9 100644 --- a/simulator/src/jack/listener/error.listener.ts +++ b/simulator/src/jack/listener/error.listener.ts @@ -1,5 +1,8 @@ -import { ErrorListener, RecognitionException, Recognizer, Token } from "antlr4"; +import { ErrorListener, NoViableAltException, RecognitionException, Recognizer, Token } from "antlr4"; import { JackCompilerError, LexerOrParserError } from "../error.js"; +interface LexerNoViableAltException { + startIndex: number; +} export class CustomErrorListener extends ErrorListener { public errors: JackCompilerError[] = []; @@ -11,7 +14,21 @@ export class CustomErrorListener extends ErrorListener { msg: string, e: RecognitionException | undefined, ) => { - const t = offendingSymbol as Token; - this.errors.push(new LexerOrParserError(line, t.start, t.stop + 1, msg)); + if (offendingSymbol != null || e != null && e.offendingToken != null) { + const t = offendingSymbol ?? e!.offendingToken as Token; + this.errors.push(new LexerOrParserError(line, t.start, t.stop + 1, msg)); + } else if (e instanceof NoViableAltException) { + this.errors.push(new LexerOrParserError(line, e.startToken.start, e.startToken.stop + 1, msg)); + + } + //antlr doesn't provide a class for LexerNoViableAltException atm. Once https://github.com/antlr/antlr4/pull/4711 is release we can change it + else if (e != null && 'startIndex' in e) { + const err = e as LexerNoViableAltException; + this.errors.push(new LexerOrParserError(line, err.startIndex, err.startIndex + 1, msg)); + } else { + console.error("Don't know how to handle this error"); + throw new Error("Don't know how to handle this error"); + } }; } +