...
1 package nodes
2
3 import (
4 "github.com/pkg/errors"
5 )
6
7 type Visitor interface {
8 Visit(node Node) (Visitor, error)
9 }
10
11
12
13
14
15
16
17
18
19 func Walk(v Visitor, node Node) error {
20 v, err := v.Visit(node)
21 if err != nil {
22 return err
23 }
24 if v == nil {
25 return nil
26 }
27
28 switch n := node.(type) {
29 case *Template:
30 for _, node := range n.Nodes {
31 if err := Walk(v, node); err != nil {
32 return err
33 }
34 }
35 case *Wrapper:
36 for _, node := range n.Nodes {
37 if err := Walk(v, node); err != nil {
38 return err
39 }
40 }
41
42
43
44
45 default:
46 return errors.Errorf("Unkown type %T", n)
47 }
48 return nil
49 }
50
51 type Inspector func(Node) bool
52
53 func (f Inspector) Visit(node Node) (Visitor, error) {
54 if f(node) {
55 return f, nil
56 }
57 return nil, nil
58 }
59
60
61
62
63
64
65 func Inspect(node Node, f func(Node) bool) {
66 Walk(Inspector(f), node)
67 }
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
View as plain text