-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.py
229 lines (185 loc) · 6.61 KB
/
parser.py
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
from typing import List
from expr import *
from stmt import *
from tokens import Token, TokenType, TokenType as tt
class ParseError(Exception):
def __init__(self, token: Token, message: str):
self.token = token
self.message = message
def report(self):
if self.token.type == tt.EOF:
return f'[line {self.token.line}] Error at end: {self.message}'
else:
where = self.token.lexeme
return f"[line {self.token.line}] Error at '{where}': {self.message}"
class Parser:
"""
program = declaration* eof ;
declaration = varDecl
| statement ;
varDecl = "var" IDENTIFIER ( "=" expression )? ";" ;
statement = exprStmt
| printStmt
| block ;
block = "{" declaration* "}" ;
exprStmt = expression ";" ;
printStmt = "print" expression ";" ;
expression = assignment ;
assignment = identifier ( "=" assignment )?
| equality ;
equality → comparison ( ( "!=" | "==" ) comparison )*
comparison → term ( ( ">" | ">=" | "<" | "<=" ) term )*
term → factor ( ( "-" | "+" ) factor )*
factor → unary ( ( "/" | "*" ) unary )*
unary → ( "!" | "-" ) unary
| primary
primary → NUMBER | STRING | "false" | "true" | "nil"
| "(" expression ")"
| IDENTIFIER ;
"""
def __init__(self, tokens: List[Token]):
self.tokens = tokens
self.errors = []
self.current = 0
def parse(self):
statements = []
while not self.is_at_end():
statements.append(self.declaration())
return statements
def expression(self):
return self.assignment()
def declaration(self):
try:
if self.match(tt.VAR):
return self.var_declaration();
return self.statement();
except ParseError:
self.synchronize()
return None
def statement(self):
if self.match(tt.PRINT): return self.printStatement()
if self.match(tt.LEFT_BRACE): return Block(self.block())
return self.expressionStatement()
def printStatement(self):
value = self.expression()
self.consume(tt.SEMICOLON, "Expect ';' after value.")
return Print(value)
def var_declaration(self):
name = self.consume(tt.IDENTIFIER, 'Expect variable name.')
if self.match(tt.EQUAL):
initializer = self.expression()
else:
initializer = None
self.consume(tt.SEMICOLON, "Expect ';' after variable declaration.")
return Var(name, initializer)
def expressionStatement(self):
expr = self.expression()
self.consume(tt.SEMICOLON, "Expect ';' after expression.")
return Expression(expr)
def block(self):
statements = []
while not self.check(tt.RIGHT_BRACE) and not self.is_at_end():
statements.append(self.declaration())
self.consume(tt.RIGHT_BRACE, "Expect '}' after block.")
return statements
def assignment(self):
expr = self.equality()
if self.match(tt.EQUAL):
equals = self.previous()
value = self.assignment()
if isinstance(expr, Variable):
name = expr.name
return Assign(name, value)
self.error(equals, 'Invalid assignment target.')
return expr
def equality(self):
expr = self.comparison()
while self.match(tt.BANG_EQUAL, tt.EQUAL_EQUAL):
operator = self.previous()
right = self.comparison()
expr = Binary(expr, operator, right)
return expr
def comparison(self):
expr = self.term()
while self.match(tt.GREATER, tt.GREATER_EQUAL, tt.LESS, tt.LESS_EQUAL):
operator = self.previous()
right = self.term()
expr = Binary(expr, operator, right)
return expr
def term(self):
expr = self.factor()
while self.match(tt.MINUS, tt.PLUS):
operator = self.previous()
right = self.factor()
expr = Binary(expr, operator, right)
return expr
def factor(self):
expr = self.unary()
while self.match(tt.SLASH, tt.STAR):
operator = self.previous()
right = self.unary()
expr = Binary(expr, operator, right)
return expr
def unary(self):
if self.match(tt.BANG, tt.MINUS):
operator = self.previous()
right = self.unary()
return Unary(operator, right)
return self.primary()
def primary(self):
if self.match(tt.FALSE): return Literal(False)
elif self.match(tt.TRUE): return Literal(True)
elif self.match(tt.NIL): return Literal(None)
elif self.match(tt.NUMBER,
tt.STRING): return Literal(self.previous().literal)
elif self.match(tt.IDENTIFIER):
return Variable(self.previous())
elif self.match(tt.LEFT_PAREN):
expr = self.expression()
self.consume(tt.RIGHT_PAREN, "Expect ')' after expression")
return Grouping(expr)
raise self.error(self.peek(), 'Expect expression')
def match(self, *types: List[TokenType]):
for type in types:
if self.check(type):
self.advance()
return True
return False
def consume(self, type: TokenType, message: str):
if self.check(type):
return self.advance()
def check(self, type: TokenType):
if self.is_at_end():
return False
return self.peek().type == type
def advance(self):
if not self.is_at_end():
self.current += 1
return self.previous()
def is_at_end(self):
return self.peek().type == tt.EOF
def peek(self):
return self.tokens[self.current]
def previous(self):
return self.tokens[self.current - 1]
def error(self, token: Token, message: str):
err = ParseError(token, message)
self.errors.append(err)
return err
def synchronize(self):
self.advance()
while not self.is_at_end():
if self.previous().type == tt.SEMICOLON:
return
if self.peek().type in {
tt.CLASS,
tt.FUN,
tt.VAR,
tt.FOR,
tt.IF,
tt.WHILE,
tt.PRINT,
tt.RETURN,
}:
return
self.advance()