diff options
author | Frederick Yin <fkfd@fkfd.me> | 2022-08-30 15:21:25 +0800 |
---|---|---|
committer | Frederick Yin <fkfd@fkfd.me> | 2022-08-30 15:21:25 +0800 |
commit | 43df98ea8f491b31b580fd909e92d5fea486599d (patch) | |
tree | 1358545301a13413428859bbbe67cf0c279e7e75 /projects/hackc/parser.py | |
parent | b439d663a3f3d4d275f07339c1c0e794808f67d9 (diff) |
hackc: print syntax error message
Diffstat (limited to 'projects/hackc/parser.py')
-rw-r--r-- | projects/hackc/parser.py | 22 |
1 files changed, 14 insertions, 8 deletions
diff --git a/projects/hackc/parser.py b/projects/hackc/parser.py index 9a927c6..2c34d1b 100644 --- a/projects/hackc/parser.py +++ b/projects/hackc/parser.py @@ -35,6 +35,12 @@ class Parser: self._extensions = extensions self.tokens = [] + # load source code + input_file = open(fp) + self.source = input_file.read() + self.lines = self.source.splitlines() + input_file.close() + def print_tokens(self): print("LINE\tCOL\tTYPE\tTOKEN") for token in self.tokens: @@ -42,16 +48,10 @@ class Parser: print(f"===== {len(self.tokens)} tokens =====") def tokenize(self): - # read file - input_file = open(self._fp) - source_code = input_file.read() - source_lines = source_code.splitlines() - input_file.close() - # tokenize code self.tokens = [] in_multicomment = False # True when inside /* */ - for line_no, line in enumerate(source_lines): + for line_no, line in enumerate(self.lines): pos = 0 # current position in line line_width = len(line) if in_multicomment: @@ -94,4 +94,10 @@ class Parser: exit(EXIT_CODE_INVALID_TOKEN) def parse(self): - syntax_tree = Class.from_tokens(self.tokens) + try: + syntax_tree = Class.from_tokens(self.tokens) + except JackSyntaxError as err: + print_err(f"{self._fp}:{err.token.line_no + 1}") + print_err(self.lines[err.token.line_no]) + print_err(" " * err.token.column + "^ " + err.message) + exit(EXIT_CODE_SYNTAX_ERROR) |