-
Notifications
You must be signed in to change notification settings - Fork 0
/
iter.go
95 lines (84 loc) · 1.83 KB
/
iter.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
package treesittergo
import (
"context"
"fmt"
"io"
)
type IterMode int
const (
DFSMode IterMode = iota
BFSMode
)
type Iterator struct {
named bool
mode IterMode
nodesToVisit []Node
}
func (t Treesitter) NewIterator(n Node, mode IterMode) Iterator {
return Iterator{
named: false,
mode: mode,
nodesToVisit: []Node{n},
}
}
func NewNamedIterator(n Node, mode IterMode) Iterator {
return Iterator{
named: true,
mode: mode,
nodesToVisit: []Node{n},
}
}
func (iter *Iterator) Next(ctx context.Context) (Node, error) {
if len(iter.nodesToVisit) == 0 {
return Node{}, io.EOF
}
var n Node
n, iter.nodesToVisit = iter.nodesToVisit[0], iter.nodesToVisit[1:]
var children []Node
if iter.named {
namedChildCount, err := n.NamedChildCount(ctx)
if err != nil {
return Node{}, fmt.Errorf("getting named child count: %w", err)
}
for i := uint64(0); i < namedChildCount; i++ {
c, err := n.NamedChild(ctx, i)
if err != nil {
return Node{}, fmt.Errorf("getting named child: %w", err)
}
children = append(children, c)
}
} else {
childCount, err := n.ChildCount(ctx)
if err != nil {
return Node{}, fmt.Errorf("getting child count: %w", err)
}
for i := uint64(0); i < childCount; i++ {
c, err := n.Child(ctx, i)
if err != nil {
return Node{}, fmt.Errorf("getting child: %w", err)
}
children = append(children, c)
}
}
switch iter.mode {
case DFSMode:
iter.nodesToVisit = append(children, iter.nodesToVisit...)
case BFSMode:
iter.nodesToVisit = append(iter.nodesToVisit, children...)
default:
panic("not implemented")
}
return n, nil
}
func (iter *Iterator) ForEach(ctx context.Context, fn func(Node) error) error {
for {
n, err := iter.Next(ctx)
if err != nil {
return err
}
err = fn(n)
if err != nil {
return err
}
}
}