-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
84 lines (66 loc) · 1.48 KB
/
parser.go
File metadata and controls
84 lines (66 loc) · 1.48 KB
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
package main
// ASTNode represents a node in an abstract syntax tree
type ASTNode struct {
nodeType string // Node type (literal, call expression, program)
value interface{} // Node value (literal value, function name)
params []ASTNode // Slice of parameters to function call
body []ASTNode // Slice of nodes that make up a program
}
var walk func() ASTNode
// Parser converts a slice of tokens into an abstract syntax tree
func Parser(tokens []Token) ASTNode {
current := 0
walk = func() ASTNode {
token := tokens[current]
// Number literals
if token.tokenType == "number" {
current++
return ASTNode{
"NumberLiteral",
token.value,
nil,
nil,
}
}
// String literals
if token.tokenType == "string" {
current++
return ASTNode{
"StringLiteral",
token.value,
nil,
nil,
}
}
// Call expressions
if token.tokenType == "paren" && token.value == "(" {
current++
token = tokens[current]
node := ASTNode{
"CallExpression",
token.value,
make([]ASTNode, 0, 10),
nil,
}
current++
token = tokens[current]
for token.tokenType != "paren" || token.tokenType == "paren" && token.value != ")" {
node.params = append(node.params, walk())
token = tokens[current]
}
current++
return node
}
panic(token.tokenType)
}
ast := ASTNode{
"Program",
nil,
nil,
make([]ASTNode, 0, 10),
}
for current < len(tokens) {
ast.body = append(ast.body, walk())
}
return ast
}