-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
337 lines (307 loc) · 7.26 KB
/
parser.go
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
package main
import (
"errors"
"strconv"
"strings"
)
type Parser struct {
curToken Token
curValue string
scanner *Scanner
scope *Scope
}
func NewParser(s *Scanner) *Parser {
p := &Parser{
scanner: s,
scope: NewScope(),
}
p.advance()
return p
}
// advance retrieves the next token/value pair from the scanner. COMMENT tokens
// are skipped as whitespace.
func (p *Parser) advance() {
for {
p.curToken, p.curValue = p.scanner.Scan()
if p.curToken != TkComment {
return
}
}
}
// match returns bool indicating whether the current token matches one of the
// specified tokens.
func (p Parser) match(tokens ...Token) bool {
for _, t := range tokens {
if p.curToken == t {
return true
}
}
return false
}
// consume advances to the next token/value pair when the current token matches
// one in t, otherwise it panics.
func (p *Parser) consume(t Token) {
if !p.match(t) {
panic("unexpected lexeme " + p.curToken.String())
}
p.advance()
}
// Parse consumes the token stream and returns the parsed program as an AST
// (ProgramNode). err is nil for a successful parse.
func (p *Parser) Parse() (prog *AstProgramNode, err error) {
defer func() {
if e := recover(); e != nil {
err = errors.New(e.(string))
}
}()
prog = &AstProgramNode{Scope: p.scope}
for {
if p.curToken == TkEOF {
return prog, nil
}
prog.Stmts = append(prog.Stmts, p.stmt())
}
}
// expr = cmp-expr [log-op expr]
func (p *Parser) expr() AstNode {
node := p.cmpExpr()
switch p.curToken {
case TkAnd:
p.advance()
return &AstAndNode{Left: node, Right: p.expr()}
case TkOr:
p.advance()
return &AstOrNode{Left: node, Right: p.expr()}
}
return node
}
// cmp-expr = add-expr [cmp-op cmp-expr]
func (p *Parser) cmpExpr() AstNode {
node := p.addExpr()
switch p.curToken {
case TkEqual:
p.advance()
return &AstEqualNode{Left: node, Right: p.cmpExpr()}
case TkNotEqual:
p.advance()
return &AstNotEqualNode{Left: node, Right: p.cmpExpr()}
case TkGreater:
p.advance()
return &AstGreaterNode{Left: node, Right: p.cmpExpr()}
case TkGreaterEq:
p.advance()
return &AstGreaterEqualNode{Left: node, Right: p.cmpExpr()}
case TkLess:
p.advance()
return &AstLessNode{Left: node, Right: p.cmpExpr()}
case TkLessEq:
p.advance()
return &AstLessEqualNode{Left: node, Right: p.cmpExpr()}
}
return node
}
// add-expr = mul-expr [add-op add-expr]
func (p *Parser) addExpr() AstNode {
node := p.mulExpr()
switch p.curToken {
case TkAdd:
p.advance()
return &AstAddNode{Left: node, Right: p.addExpr()}
case TkSubtract:
p.advance()
return &AstSubtractNode{Left: node, Right: p.addExpr()}
}
return node
}
// mul-expr = cast-expr [mul-op mul-expr]
func (p *Parser) mulExpr() AstNode {
node := p.castExpr()
switch p.curToken {
case TkMultiply:
p.advance()
return &AstMultiplyNode{Left: node, Right: p.mulExpr()}
case TkDivide:
p.advance()
return &AstDivideNode{Left: node, Right: p.mulExpr()}
case TkModulo:
p.advance()
return &AstModuloNode{Left: node, Right: p.mulExpr()}
}
return node
}
// cast-expr = term [":" ident]
func (p *Parser) castExpr() AstNode {
node := p.term()
if p.curToken == TkColon {
p.advance()
return &AstCastNode{Cast: p.ident(), Term: node}
}
return node
}
// term = "(" expr ")" / ("+" / "-" / "~") term / boolean / number / string /
// func-call / ident
func (p *Parser) term() AstNode {
switch p.curToken {
case TkLParen:
p.advance()
node := p.expr()
p.consume(TkRParen)
return node
case TkAdd:
p.advance()
return &AstPositiveNode{p.term()}
case TkSubtract:
p.advance()
return &AstNegativeNode{p.term()}
case TkIf:
p.advance()
return &AstNotNode{p.term()}
case TkBool:
node := &AstBoolNode{strings.ToLower(p.curValue) == "true"}
p.advance()
return node
case TkNumber:
val, _ := strconv.ParseFloat(p.curValue, 64)
node := &AstNumberNode{val}
p.advance()
return node
case TkString:
node := &AstStringNode{p.curValue}
p.advance()
return node
case TkIdentifier:
name := p.ident()
if p.match(TkLParen) {
return &AstFuncCallNode{Name: name, Args: p.parenExprList()}
}
return &AstVariableNode{Name: name}
}
panic("whoops?")
}
// paren-expr-list = "(" [expr *("," expr)] ")"
func (p *Parser) parenExprList() []AstNode {
defer p.consume(TkRParen)
p.consume(TkLParen)
var list []AstNode
if p.match(TkRParen) {
return list
}
for {
list = append(list, p.expr())
if !p.match(TkComma) {
return list
}
p.advance()
}
}
// stmt = if-stmt / while-stmt / func-def / return-stmt / assign-stmt /
// func-call
func (p *Parser) stmt() (node AstNode) {
switch p.curToken {
case TkIf:
return p.ifStmt()
case TkWhile:
return p.whileStmt()
case TkFunc:
return p.funcDef()
case TkReturn:
return p.returnStmt()
case TkIdentifier:
return p.assignStmtOrFuncCall()
}
panic("unexpected lexeme " + p.curToken.String())
}
// if-stmt = "if" expr brace-stmt-list [else-clause]
func (p *Parser) ifStmt() *AstIfNode {
p.consume(TkIf)
node := &AstIfNode{Cond: p.expr(), Body: p.braceStmtList()}
if p.match(TkElse) {
p.advance()
if p.match(TkLBrace) {
node.Else = p.braceStmtList()
} else {
node.Else = append(node.Else, p.elseClause())
}
}
return node
}
// brace-stmt-list = "{" *stmt "}"
func (p *Parser) braceStmtList() (list []AstNode) {
p.consume(TkLBrace)
for {
if !(p.curToken.IsStmtKeyword() || p.match(TkIdentifier)) {
break
}
list = append(list, p.stmt())
}
p.consume(TkRBrace)
return list
}
// else-clause = "else" (brace-stmt-list / expr brace-stmt-list else-clause)
// Note: an else with an expression becomes an if-stmt within a default else
// clause.
func (p *Parser) elseClause() *AstIfNode {
node := &AstIfNode{Cond: p.expr(), Body: p.braceStmtList()}
if p.match(TkElse) {
p.advance()
if p.match(TkLBrace) {
node.Else = p.braceStmtList()
} else {
node.Else = append(node.Else, p.elseClause())
}
}
return node
}
// while-stmt = "while" expr brace-stmt-list
func (p *Parser) whileStmt() *AstWhileNode {
p.consume(TkWhile)
return &AstWhileNode{Cond: p.expr(), Body: p.braceStmtList()}
}
// func-def = "func" ident *ident brace-stmt-list
func (p *Parser) funcDef() *AstFuncDefNode {
p.consume(TkFunc)
node := &AstFuncDefNode{
Name: p.ident(),
}
p.scope.SetFunc(node.Name, ScopeEntry{TypFunc, node})
node.Scope = NewScopeWithParent(p.scope)
p.scope = node.Scope
if !p.match(TkLBrace) {
var list []string
for p.match(TkIdentifier) {
list = append(list, p.ident())
}
node.Args = list
}
node.Body = p.braceStmtList()
p.scope = node.Scope.parent
return node
}
// return-stmt = "return" [expr]
func (p *Parser) returnStmt() *AstReturnNode {
p.consume(TkReturn)
node := &AstReturnNode{}
if p.match(TkLParen, TkAdd, TkSubtract, TkIf, TkBool, TkNumber, TkString,
TkIdentifier) {
node.Expr = p.expr()
}
return node
}
// assign-stmt = ident ":=" expr
// func-call = ident paren-expr-list
func (p *Parser) assignStmtOrFuncCall() AstNode {
name := p.ident()
if p.match(TkAssign) {
p.advance()
return &AstAssignNode{Name: name, Expr: p.expr()}
}
if p.match(TkLParen) {
return &AstFuncCallNode{Name: name, Args: p.parenExprList()}
}
panic("unexpected " + p.curToken.String())
}
// identifier returns the lexeme value of the current identifier.
func (p *Parser) ident() string {
defer p.consume(TkIdentifier)
return p.curValue
}