Linear array storage for AST

This commit is contained in:
Thomas Pelletier
2021-03-25 19:56:02 -04:00
parent 8a8d1233bb
commit 1bae751a45
7 changed files with 659 additions and 460 deletions
+58
View File
@@ -0,0 +1,58 @@
package ast
type Builder struct {
nodes []Node
lastIdx int
}
type Reference struct {
idx int
set bool
}
func (r Reference) Valid() bool {
return r.set
}
func (b *Builder) Finish() *Root {
r := &Root{
nodes: b.nodes,
}
b.nodes = nil
for i := range r.nodes {
r.nodes[i].root = r
}
return r
}
func (b *Builder) Push(n Node) Reference {
b.lastIdx = len(b.nodes)
b.nodes = append(b.nodes, n)
return Reference{
idx: b.lastIdx,
set: true,
}
}
func (b *Builder) PushAndChain(n Node) Reference {
newIdx := len(b.nodes)
b.nodes = append(b.nodes, n)
if b.lastIdx >= 0 {
b.nodes[b.lastIdx].next = newIdx
}
b.lastIdx = newIdx
return Reference{
idx: b.lastIdx,
set: true,
}
}
func (b *Builder) AttachChild(parent Reference, child Reference) {
b.nodes[parent.idx].child = child.idx
}
func (b *Builder) Chain(from Reference, to Reference) {
b.nodes[from.idx].next = to.idx
}