-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast.go
87 lines (74 loc) · 1.68 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
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
package main
import (
"io"
"log"
"strings"
)
type astNode struct {
left, right *astNode
token Token
depth int // depth in the ast, helps in stringify
evalr evaluator
}
type parserFn func(*parser) *astNode
var nilASTNode *astNode = nil
func newASTNode(token Token, left, right *astNode, evalr evaluator) *astNode {
return &astNode{left, right, token, 0, evalr}
}
type parser struct {
tokens []Token
processedToken int
lastErr error
}
func (ast *astNode) String() string {
marginStr := ""
var out strings.Builder
for leftMargin := ast.depth; leftMargin > 0; leftMargin-- {
marginStr += "\t"
}
out.WriteString("\n")
out.WriteString(marginStr)
out.WriteString("Token: ")
out.WriteString(ast.token.String())
if ast.left != nilASTNode {
ast.left.depth = ast.depth + 1
out.WriteString("\n")
out.WriteString(marginStr)
out.WriteString("Left: ")
out.WriteString(ast.left.String())
}
if ast.right != nilASTNode {
ast.right.depth = ast.depth + 1
out.WriteString("\n")
out.WriteString(marginStr)
out.WriteString("Right: ")
out.WriteString(ast.right.String())
}
return out.String()
}
func (p *parser) next() Token {
if p.processedToken < len(p.tokens) {
token := p.tokens[p.processedToken]
p.processedToken++
return token
}
p.lastErr = io.EOF
return Token{}
}
func (p *parser) peek() Token {
if p.processedToken < len(p.tokens) {
return p.tokens[p.processedToken]
}
p.lastErr = io.EOF
return Token{}
}
func (p *parser) eof() bool {
defer log.Print("LastError: ", p.lastErr)
return p.lastErr == io.EOF
}
func parseTokens(tokens []Token, prsFn parserFn) *astNode {
par := parser{
tokens: tokens,
}
return prsFn(&par)
}