-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
104 lines (91 loc) · 1.78 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
package main
import "fmt"
type NodeType uint8
const (
LoopNode = iota
AddNode
SubNode
MoveLeftNode
MoveRightNode
InputNode
OutputNode
)
type Node struct {
Children []Node
Type NodeType
}
type Parser struct {
Content string
Line int
Col int
Index int
Nodes []Node
Brackets int
Error error
}
func NewParser(content string) *Parser {
return &Parser{
Content: content,
Line: 1,
Col: 1,
Index: 0,
}
}
func (p *Parser) Advance() {
p.Index++
p.Col++
}
func (p *Parser) Parse(start int, brackets int) []Node {
nodes := []Node{}
for p.Index < len(p.Content) {
c := p.Content[p.Index]
switch c {
case '+':
nodes = append(nodes, Node{Type: AddNode, Children: nil})
p.Advance()
case '-':
nodes = append(nodes, Node{Type: SubNode, Children: nil})
p.Advance()
case '>':
nodes = append(nodes, Node{Type: MoveRightNode, Children: nil})
p.Advance()
case '<':
nodes = append(nodes, Node{Type: MoveLeftNode, Children: nil})
p.Advance()
case '.':
nodes = append(nodes, Node{Type: OutputNode, Children: nil})
p.Advance()
case ',':
nodes = append(nodes, Node{Type: InputNode, Children: nil})
p.Advance()
case '[':
p.Brackets++
p.Advance()
nodes = append(nodes, p.MakeLoop())
case ']':
if p.Brackets == 0 {
p.Error = fmt.Errorf("unexpected ']' at line %d, col %d", p.Line, p.Col)
return nil
}
p.Brackets--
p.Advance()
if p.Brackets == brackets-1 {
return nodes
}
case '\n':
p.Line++
p.Col = 1
p.Advance()
}
}
if p.Brackets != 0 {
p.Error = fmt.Errorf("expected ']' at line %d, col %d", p.Line, p.Col-1)
return nil
}
return nodes
}
func (p *Parser) MakeLoop() Node {
node := Node{Type: LoopNode}
node.Children = p.Parse(p.Index, p.Brackets)
return node
}