260
|
1 |
package ast |
|
2 |
|
|
3 |
type Reference int |
|
4 |
|
|
5 |
const InvalidReference Reference = -1 |
|
6 |
|
|
7 |
func (r Reference) Valid() bool { |
|
8 |
return r != InvalidReference |
|
9 |
} |
|
10 |
|
|
11 |
type Builder struct { |
|
12 |
tree Root |
|
13 |
lastIdx int |
|
14 |
} |
|
15 |
|
|
16 |
func (b *Builder) Tree() *Root { |
|
17 |
return &b.tree |
|
18 |
} |
|
19 |
|
|
20 |
func (b *Builder) NodeAt(ref Reference) *Node { |
|
21 |
return b.tree.at(ref) |
|
22 |
} |
|
23 |
|
|
24 |
func (b *Builder) Reset() { |
|
25 |
b.tree.nodes = b.tree.nodes[:0] |
|
26 |
b.lastIdx = 0 |
|
27 |
} |
|
28 |
|
|
29 |
func (b *Builder) Push(n Node) Reference { |
|
30 |
b.lastIdx = len(b.tree.nodes) |
|
31 |
b.tree.nodes = append(b.tree.nodes, n) |
|
32 |
return Reference(b.lastIdx) |
|
33 |
} |
|
34 |
|
|
35 |
func (b *Builder) PushAndChain(n Node) Reference { |
|
36 |
newIdx := len(b.tree.nodes) |
|
37 |
b.tree.nodes = append(b.tree.nodes, n) |
|
38 |
if b.lastIdx >= 0 { |
|
39 |
b.tree.nodes[b.lastIdx].next = newIdx - b.lastIdx |
|
40 |
} |
|
41 |
b.lastIdx = newIdx |
|
42 |
return Reference(b.lastIdx) |
|
43 |
} |
|
44 |
|
|
45 |
func (b *Builder) AttachChild(parent Reference, child Reference) { |
|
46 |
b.tree.nodes[parent].child = int(child) - int(parent) |
|
47 |
} |
|
48 |
|
|
49 |
func (b *Builder) Chain(from Reference, to Reference) { |
|
50 |
b.tree.nodes[from].next = int(to) - int(from) |
|
51 |
} |