From 43df98ea8f491b31b580fd909e92d5fea486599d Mon Sep 17 00:00:00 2001 From: Frederick Yin Date: Tue, 30 Aug 2022 15:21:25 +0800 Subject: hackc: print syntax error message --- projects/hackc/parser.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) (limited to 'projects/hackc/parser.py') 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) -- cgit v1.2.3