summaryrefslogtreecommitdiff
path: root/projects/hackc/utils.py
blob: 8756e4618154f11f6dbec91e091e2e03caacd4fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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
EXIT_CODE_EOF = 7

# vim autoindent misbehaves if I type these verbatim in strings
LEFT_BRACE = "{"
RIGHT_BRACE = "}"
LEFT_BRACKET = "["
RIGHT_BRACKET = "]"
LEFT_PAREN = "("
RIGHT_PAREN = ")"


class JackSyntaxError(Exception):
    def __init__(self, msg, token):
        self.message = msg
        self.token = token
        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)