diff options
author | Frederick Yin <fkfd@fkfd.me> | 2022-09-03 11:22:20 +0800 |
---|---|---|
committer | Frederick Yin <fkfd@fkfd.me> | 2022-09-03 11:22:20 +0800 |
commit | b1794edb3d76db7c1a86fc14a60bc95b833bc7c7 (patch) | |
tree | 582288c1618a74405d3c183410d7525b8d6aa31f /projects/hackc/utils.py | |
parent | bed429a1d17b43678a70bc286aac12a0bd6e387d (diff) |
hackc: more statements; UnexpectedToken
Diffstat (limited to 'projects/hackc/utils.py')
-rw-r--r-- | projects/hackc/utils.py | 47 |
1 files changed, 47 insertions, 0 deletions
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) |