-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.js
366 lines (307 loc) · 9.26 KB
/
parser.js
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
const tokenizer = require('./tokenizer')
const {
Binary,
Unary,
Var,
Call,
Literal,
While,
Class,
Super,
Get,
Set,
This,
Grouping,
Return,
LoxFunction,
PrintStatement,
ExpressionStatement,
VarStatement,
Assignment,
Logical,
Block,
Condition
} = require('./types')
const { parseError: ParseError } = require('./errors')
const token = tokenizer.tokenEnum
const FUNCTION_TYPE = 'function'
const METHOD_TYPE = 'method'
const forLoopContext = 'forLoop'
class Parser {
constructor(tokens) {
this.tokens = tokens
this.current = 0
}
parse() {
let statements = []
while (!this.isAtEnd) {
statements.push(this.declaration())
}
return statements
}
declaration() {
if (this.match(token.FUN)) return this.fun(FUNCTION_TYPE)
if (this.match(token.CLASS)) return this.classDeclaration()
if (this.match(token.VAR)) return this.varDeclaration()
return this.statement()
}
classDeclaration() {
const name = this.consume(token.IDENTIFIER, `Expected class name`)
let superClass = null
if (this.match(token.LESS)) {
superClass = new Var(this.consume(token.IDENTIFIER, `Expected superclass name after "<"`))
}
this.consume(token.LEFT_BRACE, 'expected "{" before class body')
let methods = []
while (!this.check(token.RIGHT_BRACE)) {
methods.push(this.fun(METHOD_TYPE))
}
this.consume(token.RIGHT_BRACE, 'expected "}" after class body')
return new Class(name, methods, superClass)
}
fun(type) {
const name = this.consume(token.IDENTIFIER, `Expected ${type} name`)
let params = []
this.consume(token.LEFT_PAREN, `Expected paren after ${type} name`)
if (!this.check(token.RIGHT_PAREN)) {
do {
params.push(this.consume(token.IDENTIFIER, 'Expected identifier'))
} while (this.match(token.COMMA))
}
this.consume(token.RIGHT_PAREN, 'Expected paren after arguments')
this.consume(token.LEFT_BRACE, 'Expected left brace after argument list')
const body = this.block()
return new LoxFunction(name, params, body)
}
varDeclaration() {
const name = this.consume(token.IDENTIFIER, 'Expected variable name')
let initializer = null
if (this.match(token.EQUAL)) {
initializer = this.expression()
}
this.consume(token.SEMICOLON, 'Expect ; after value.')
return new VarStatement(name, initializer)
}
statement() {
if (this.match(token.IF)) return this.ifStatement()
if (this.match(token.FOR)) return this.forStatement()
if (this.match(token.WHILE)) return this.whileStatement()
if (this.match(token.RETURN)) return this.returnStatement()
if (this.match(token.PRINT)) return this.printStatement()
if (this.match(token.LEFT_BRACE)) return new Block(this.block())
return this.expressionStatement()
}
forStatement() {
this.consume(token.LEFT_PAREN, 'Expected "(" after "for"')
let init
if (this.match(token.SEMICOLON)) {
init = null
} else if (this.match(token.VAR)) {
init = this.varDeclaration()
} else {
init = this.expressionStatement()
}
let cond = null
if (!this.check(token.SEMICOLON)) {
cond = this.expression()
}
this.consume(token.SEMICOLON, 'Expected ";" after loop condition')
let inc = null
if (!this.check(token.RIGHT_PAREN)) {
inc = this.expression()
}
this.consume(token.RIGHT_PAREN, 'Expected ")" after for clause')
let body = this.statement()
if (inc) {
body = new Block([body, new ExpressionStatement(inc, forLoopContext)], forLoopContext)
}
if (!cond) cond = new Literal(true, forLoopContext)
body = new While(cond, body, forLoopContext)
if (init) body = new Block([init, body], forLoopContext)
return body
}
whileStatement() {
this.consume(token.LEFT_PAREN, 'Expected "(" after "while"')
const cond = this.expression()
this.consume(token.RIGHT_PAREN, 'Expected ")" after expression')
const body = this.statement()
return new While(cond, body)
}
ifStatement() {
this.consume(token.LEFT_PAREN, 'Expected "(" after "if"')
const cond = this.expression()
this.consume(token.RIGHT_PAREN, 'Expected ")" after expression')
const ifBranch = this.statement()
let elseBranch = null
if (this.match(token.ELSE)) elseBranch = this.statement()
return new Condition(cond, ifBranch, elseBranch)
}
block() {
let statements = []
while (!this.check(token.RIGHT_BRACE) && !this.isAtEnd) {
statements.push(this.declaration())
}
this.consume(token.RIGHT_BRACE, 'Missing closing brace. (Expect "}" after block)')
return statements
}
printStatement() {
const val = this.expression()
this.consume(token.SEMICOLON, 'Expect ; after value.')
return new PrintStatement(val)
}
returnStatement() {
const prev = this.previous()
let value = null
if (!this.check(token.SEMICOLON)) {
value = this.expression()
}
this.consume(token.SEMICOLON, 'Expected ";" after return value')
return new Return(prev, value)
}
expressionStatement() {
const val = this.expression()
this.consume(token.SEMICOLON, 'Expect ; after value.')
return new ExpressionStatement(val)
}
expression() {
return this.assignment()
}
assignment() {
const expr = this.or()
if (this.match(token.EQUAL)) {
const equalToken = this.previous()
const value = this.assignment()
if (expr instanceof Var) {
const nameToken = expr.name
return new Assignment(nameToken, value)
} else if (expr instanceof Get) {
return new Set(expr.object, expr.name, value)
}
throw ParseError('Expected Expression', equalToken)
}
return expr
}
or() {
return this.matchBinary('and', Logical, token.OR)
}
and() {
return this.matchBinary('equality', Logical, token.AND)
}
matchBinary(method, Class, ...operators) {
let expr = this[method]()
while (this.match(...operators)) {
const operator = this.previous()
const right = this[method]()
expr = new Class(expr, operator, right)
}
return expr
}
equality() {
return this.matchBinary('comparison', Binary, token.BANG_EQUAL, token.EQUAL_EQUAL)
}
comparison() {
return this.matchBinary(
'addition',
Binary,
token.GREATER,
token.GREATER_EQUAL,
token.LESS,
token.LESS_EQUAL
)
}
addition() {
return this.matchBinary('multiplication', Binary, token.MINUS, token.PLUS)
}
multiplication() {
return this.matchBinary('unary', Binary, token.SLASH, token.STAR)
}
unary() {
if (this.match(token.BANG, token.MINUS)) {
const operator = this.previous()
const right = this.unary()
return new Unary(operator, right)
}
return this.call()
}
call() {
let expr = this.primary()
//eslint-disable-next-line
while (true) {
if (this.match(token.LEFT_PAREN)) {
expr = this.finishCall(expr)
} else if (this.match(token.DOT)) {
const name = this.consume(token.IDENTIFIER, 'Expected property name after "."')
expr = new Get(expr, name)
} else {
break
}
}
return expr
}
finishCall(callee) {
let args = []
if (!this.check(token.RIGHT_PAREN)) {
do {
args.push(this.expression())
} while (this.match(token.COMMA))
}
const paren = this.consume(token.RIGHT_PAREN, 'Unfinished argument list')
return new Call(callee, paren, args)
}
primary() {
if (this.match(token.FALSE)) return new Literal(false)
if (this.match(token.TRUE)) return new Literal(true)
if (this.match(token.NIL)) return new Literal(null)
if (this.match(token.NUMBER, token.STRING)) return new Literal(this.previous().literal)
if (this.match(token.SUPER)) {
const keyword = this.previous()
this.consume(token.DOT, 'Expected "." after super statement')
const method = this.consume(token.IDENTIFIER, 'Expected superclass method name')
return new Super(keyword, method)
}
if (this.match(token.THIS)) return new This(this.previous())
if (this.match(token.IDENTIFIER)) return new Var(this.previous())
if (this.match(token.LEFT_PAREN)) {
const expr = this.expression()
this.consume(token.RIGHT_PAREN, `Expect ')' after expression.`)
return new Grouping(expr)
}
throw ParseError('Expected Expression', this.peek())
}
consume(type, err) {
if (this.check(type)) return this.advance()
throw ParseError(err, this.peek())
}
// Checks if current token is one of the following tokens and advances to next token
match(...tokens) {
for (let token of tokens) {
if (this.check(token)) {
this.advance()
return true
}
}
return false
}
// Verifies current token is equal to type
check(type) {
return !this.isAtEnd && this.peek().type === type
}
get isAtEnd() {
return this.peek().type === token.EOF
}
// Gets current token
peek() {
return this.tokens[this.current]
}
// Gets previous token
previous() {
if (this.current <= 0) throw ParseError('Expected previous but found nothing', this.peek())
return this.tokens[this.current - 1]
}
// Advances parser to the next token
advance() {
if (!this.isAtEnd) this.current++
return this.previous()
}
}
module.exports = Parser