From b1794edb3d76db7c1a86fc14a60bc95b833bc7c7 Mon Sep 17 00:00:00 2001 From: Frederick Yin Date: Sat, 3 Sep 2022 11:22:20 +0800 Subject: hackc: more statements; UnexpectedToken --- projects/hackc/utils.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) (limited to 'projects/hackc/utils.py') diff --git a/projects/hackc/utils.py b/projects/hackc/utils.py index d375953..8756e46 100644 --- a/projects/hackc/utils.py +++ b/projects/hackc/utils.py @@ -1,5 +1,31 @@ from sys import stderr +KEYWORDS = [ + "class", + "constructor", + "function", + "method", + "field", + "static", + "var", + "int", + "char", + "boolean", + "void", + "true", + "false", + "null", + "this", + "let", + "do", + "if", + "else", + "while", + "return", +] + +SYMBOLS = "{}()[].,;+-*/&|<>=~" + EXIT_CODE_FILE_ERROR = 1 EXIT_CODE_INVALID_TOKEN = 2 EXIT_CODE_SYNTAX_ERROR = 4 @@ -13,6 +39,7 @@ RIGHT_BRACKET = "]" LEFT_PAREN = "(" RIGHT_PAREN = ")" + class JackSyntaxError(Exception): def __init__(self, msg, token): self.message = msg @@ -20,5 +47,25 @@ class JackSyntaxError(Exception): super().__init__(msg) +class UnexpectedToken(JackSyntaxError): + def __init__(self, expected, unexpected): + if str(expected) in KEYWORDS or str(expected) in SYMBOLS: + # wrap literal keyword/symbol in backticks + super().__init__( + f"Expected `{expected}`, got `{unexpected}` instead", unexpected + ) + else: + super().__init__( + f"Expected {expected}, got `{unexpected}` instead", unexpected + ) + + +class Unexpected(JackSyntaxError): + def __init__(self, expected, unexpected): + super().__init__( + f"Expected `{expected}`, got `{unexpected}` instead", unexpected + ) + + def print_err(msg): print(msg, file=stderr) -- cgit v1.2.3