-
Notifications
You must be signed in to change notification settings - Fork 1
/
ast.go
52 lines (48 loc) · 1.01 KB
/
ast.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
package rule
import(
"errors"
)
// astNode 是抽象语法树的节点
type astNode struct {
child *astNode
// 列表用链表形式存储
next *astNode
token *token
}
// appendChild 给当前节点增加一个子节点
func (node *astNode) appendChild(anotherNode *astNode) {
if node.child == nil {
node.child = anotherNode
return
}
current := node.child
for current.next != nil {
current = current.next
}
current.next = anotherNode
}
// buildAST 递归构造抽象语法树
func buildAST(tks *tokens) (*astNode, error) {
if tks.length() == 0{
return nil, errors.New("unexpected eof")
}
current := tks.peak()
if current.tokenType == leftParenthesisToken {
node := new(astNode)
node.token = current
for tks.shift(); tks.peak().tokenType != rightParenthesisToken; {
newNode, err := buildAST(tks)
if err != nil{
return nil ,err
}
node.appendChild(newNode)
}
// 弹出右括号
tks.shift()
return node, nil
}
tks.shift()
return &astNode{
token: current,
}, nil
}