summaryrefslogtreecommitdiff
path: root/projects/hackc/utils.py
diff options
context:
space:
mode:
Diffstat (limited to 'projects/hackc/utils.py')
-rw-r--r--projects/hackc/utils.py47
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)