diff --git a/src/errors/__init__.py b/src/errors/__init__.py new file mode 100644 index 0000000..13a1f1a --- /dev/null +++ b/src/errors/__init__.py @@ -0,0 +1,40 @@ + + +class BaseError(Exception): + def __init__(self, message): + super().__init__(message) + + @property + def traceback(self): + return self._traceback + + +class SyntaxError(BaseError): + def __init__(self, message, tokens, current): + self.tokens = tokens + self.current = current + super().__init__(message) + + def __str__(self): + string = '' + current_token = self.tokens[self.current] + current_line = current_token.line + + start_of_line = self.current + while start_of_line > 0 and self.tokens[start_of_line].line == current_line: + start_of_line -= 1 + + end_of_line = self.current + while end_of_line < len(self.tokens) and self.tokens[end_of_line].line == current_line: + end_of_line += 1 + + + for token, index in zip(self.tokens[start_of_line:end_of_line], range(start_of_line, end_of_line)): + if index == self.current: + string += '~~ ' + string += token.lexeme + ' ' + + if index == self.current: + string += '~~' + + return string diff --git a/src/pychart/runner.py b/src/pychart/runner.py index 89e990d..1e85ccd 100644 --- a/src/pychart/runner.py +++ b/src/pychart/runner.py @@ -1,24 +1,28 @@ from src.scanner import Scanner from src.pyparser import Parser +from src import errors def run(source: str): - scanner = Scanner(source) - tokens = scanner.get_tokens() - ast = Parser(tokens).parse() + try: + scanner = Scanner(source) + tokens = scanner.get_tokens() + ast = Parser(tokens).parse() - if ast is None: - return + if ast is None: + return - value = ast() + value = ast() - try: - value = int(value) - except: - pass + try: + value = int(value) + except: + pass - # print(f"AST: {ast}") - print(value) + # print(f"AST: {ast}") + print(value) + except errors.BaseError as e: + print(e) def run_prompt():