summaryrefslogtreecommitdiff
path: root/projects/hackc/classes.py
blob: ed69810db0846a602344f5165b8786ef83da716f (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
from .statements import StatementList
from .tokens import Token
from .utils import *

SCOPES = ["static", "field", "var"]
VAR_TYPES = ["int", "char", "boolean"]
RETURN_TYPES = ["int", "char", "boolean", "void"]
SUBROUTINE_CATS = ["constructor", "method", "function"]


class Class:
    def __init__(self, name: Token, variables: list, subroutines: list):
        self.name = name
        self.variables = variables
        self.subroutines = subroutines

    @classmethod
    def from_tokens(cls, tokens: list):
        """Construct a class from a list of tokens.

        In standard Jack, one file is exactly one class.

        Format:
        'class' <name> '{'
            <variable>*
            <subroutine>*
        '}'
        """
        tokens_total = len(tokens)
        if tokens_total < 4:
            return None
        if tokens[0] != "class":
            raise UnexpectedToken("class", tokens[0])

        name = tokens[1]
        if name.type != "identifier":
            raise JackSyntaxError(f"You cannot name a class `{name}`", name)

        if tokens[2] != LEFT_BRACE:
            raise UnexpectedToken(LEFT_BRACE, tokens[2])

        t = 3
        variables = []
        while t < tokens_total:
            variable, dt = Variable.from_tokens(tokens[t:], context="class")
            if variable is None:
                break
            variables.append(variable)
            t += dt

        subroutines = []
        while t < tokens_total:
            subroutine, dt = Subroutine.from_tokens(tokens[t:])
            if subroutine is None:
                break
            subroutines.append(subroutine)
            t += dt

        end = tokens[t]
        if end != RIGHT_BRACE:
            raise JackSyntaxError(
                f"Neither variable declaration nor subroutine: {end}", end
            )

        return Class(name, variables, subroutines)

    def print_verbose(self):
        print(f"Define class {self.name}")
        for variable in self.variables:
            variable.print_verbose()
        for subroutine in self.subroutines:
            subroutine.print_verbose()
        print(f"End of class {self.name}")


class Variable:
    def __init__(self, scope: Token, type: Token, names: list[Token]):
        self.scope = scope
        self.type = type
        self.names = names

    @classmethod
    def from_tokens(cls, tokens: list, context: str) -> tuple:
        """Construct variable declaration statement from a list of tokens.
        Return a tuple of an instance of Variable and number of tokens consumed.
        When `tokens` does not begin with a variable declaration, return (None, 0).

        context -- "class" (<scope> = static | field) or "subroutine" (<scope> = var)

        Format:
        <scope> <type> <name> (, <name>)* ;

        <scope> = static | field | var
        <type> = int | char | boolean | <class>
        """
        if len(tokens) < 4 or tokens[0] not in SCOPES:
            # not variable declaration
            return (None, 0)

        scope = tokens[0]
        if scope in ["static", "field"] and context != "class":
            raise JackSyntaxError(
                f"You cannot declare a {scope} variable in a subroutine", scope
            )
        if scope == "var" and context != "subroutine":
            raise JackSyntaxError(
                f"You cannot declare a local variable outside of a subroutine",
                scope,
            )

        type = tokens[1]
        if type not in VAR_TYPES and type.type != "identifier":
            raise UnexpectedToken("datatype", type)

        t = 2
        names = []  # names of variables
        expecting_identifier = True
        found_semicolon = False

        for token in tokens[2:]:
            t += 1
            if token.type == "identifier":
                if expecting_identifier:
                    names.append(token)
                    expecting_identifier = False
                else:
                    raise UnexpectedToken(",", token)
            elif token == ",":
                if not expecting_identifier:
                    expecting_identifier = True
                else:
                    raise UnexpectedToken("variable name", token)
            elif token == ";":
                if expecting_identifier:
                    raise UnexpectedToken("variable name", token)
                found_semicolon = True
                break
            else:
                expected = "variable name" if expecting_identifier else "`,` or `;`"
                raise UnexpectedToken(expected, token)

        if not found_semicolon:
            # TODO: print caret at end of token
            raise JackSyntaxError(f"Missing semicolon", token)

        return (Variable(scope, type, names), t)

    def print_verbose(self):
        print(f"Declare {len(self.names)} variable(s):")
        for name in self.names:
            print(self.scope, self.type, name)


class ParamList:
    def __init__(self, params: list[tuple]):
        self.params = params

    @classmethod
    def from_tokens(cls, tokens: list) -> tuple:
        """Construct parameter list of subroutine from tokens.

        Format:
        (<type> <name> (, <type> <name>)*)?

        <type> = int | char | boolean | <class>
        """
        if not tokens:
            return (None, 0)

        if tokens[0] == RIGHT_PAREN:
            # empty param list, i.e. '(' ')'
            return (ParamList([]), 0)

        t = 0
        params = []
        for type, name, delim in zip(tokens[0::3], tokens[1::3], tokens[2::3]):
            if type not in VAR_TYPES and type.type != "identifier":
                raise UnexpectedToken("datatype", type)
            if not name:
                # TODO: print caret at end of type
                raise JackSyntaxError("Expected variable name", type)
            if name.type != "identifier":
                raise UnexpectedToken("variable name", name)
            if not delim:
                raise UnexpectedToken(f"`,` or `{RIGHT_PAREN}`", name)
            if delim == ",":
                t += 3
                params.append((type, name))
                continue
            elif delim == RIGHT_PAREN:
                t += 2
                params.append((type, name))
                break
            else:
                raise UnexpectedToken(f"`,` or `{RIGHT_PAREN}`", delim)

        return (ParamList(params), t)

    def print_verbose(self):
        print(f"Subroutine takes {len(self.params)} parameter(s):")
        for param in self.params:
            print(param[0], param[1])


class Subroutine:
    def __init__(
        self,
        category: Token,
        type: Token,
        name: Token,
        params: ParamList,
        variables: list,
        statements: StatementList,
    ):
        self.category = category
        self.type = type
        self.name = name
        self.params = params
        self.variables = variables
        self.statements = statements

    @classmethod
    def from_tokens(cls, tokens: list) -> tuple:
        """Construct subroutine from tokens.

        Format:
        <category> <return type> <name> '(' <paramlist> ')' '{' <variable>* <statement>* '}'

        <category> = constructor | method | function
        <return type> = int | char | boolean | void | <class>
        """
        if len(tokens) < 7 or tokens[0] not in SUBROUTINE_CATS:
            # not a subroutine
            return (None, 0)
        category = tokens[0]

        return_type = tokens[1]
        if return_type not in RETURN_TYPES and return_type.type != "identifier":
            raise UnexpectedToken("datatype", return_type)

        name = tokens[2]
        if name.type != "identifier":
            raise UnexpectedToken(f"{category} name", name)

        if tokens[3] != LEFT_PAREN:
            raise UnexpectedToken(LEFT_PAREN, tokens[3])

        t = 4
        params, dt = ParamList.from_tokens(tokens[t:])
        if params is None:
            raise JackSyntaxError("Expected parameter list", tokens[t])
        # it can be safely assumed that the next token is ')'
        t += dt + 1

        # TODO: catch IndexError
        body_open = tokens[t]
        if body_open != LEFT_BRACE:
            raise UnexpectedToken(LEFT_BRACE, body_open)
        t += 1

        variables = []
        while t < len(tokens):
            variable, dt = Variable.from_tokens(tokens[t:], context="subroutine")
            if variable is None:
                break
            variables.append(variable)
            t += dt

        statements, dt = StatementList.from_tokens(tokens[t:])
        t += dt

        body_close = tokens[t]
        if body_close != RIGHT_BRACE:
            raise UnexpectedToken(RIGHT_BRACE, body_close)
        t += 1

        return (
            Subroutine(category, return_type, name, params, variables, statements),
            t,
        )

    def print_verbose(self):
        print(f"Define {self.category} {self.type} {self.name}")
        self.params.print_verbose()
        for variable in self.variables:
            variable.print_verbose()
        self.statements.print_verbose()
        print(f"End of {self.category} {self.name}")