Debian Codegraph @

go/ast/inspector/inspector_test.go

raw symbols SCIP
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package inspector_test
6
7 import (
8 "go/ast"
9 "go/build"
10 "go/parser"
11 "go/token"
12 "log"
13 "path/filepath"
14 "reflect"
15 "strconv"
16 "strings"
17 "testing"
18
19 "golang.org/x/tools/go/ast/inspector"
20 )
21
22 // net/http package
23 var (
24 netFset = token.NewFileSet()
25 netFiles []*ast.File
26 netInspect *inspector.Inspector
27 )
28
29 func init() {
30 files, err := parseNetFiles()
31 if err != nil {
32 log.Fatal(err)
33 }
34 netFiles = files
35 netInspect = inspector.New(netFiles)
36 }
37
38 func parseNetFiles() ([]*ast.File, error) {
39 pkg, err := build.Default.Import("net", "", 0)
40 if err != nil {
41 return nil, err
42 }
43 var files []*ast.File
44 for _, filename := range pkg.GoFiles {
45 filename = filepath.Join(pkg.Dir, filename)
46 f, err := parser.ParseFile(netFset, filename, nil, 0)
47 if err != nil {
48 return nil, err
49 }
50 files = append(files, f)
51 }
52 return files, nil
53 }
54
55 // TestInspectAllNodes compares Inspector against ast.Inspect.
56 func TestInspectAllNodes(t *testing.T) {
57 inspect := inspector.New(netFiles)
58
59 var nodesA []ast.Node
60 inspect.Nodes(nil, func(n ast.Node, push bool) bool {
61 if push {
62 nodesA = append(nodesA, n)
63 }
64 return true
65 })
66 var nodesB []ast.Node
67 for _, f := range netFiles {
68 ast.Inspect(f, func(n ast.Node) bool {
69 if n != nil {
70 nodesB = append(nodesB, n)
71 }
72 return true
73 })
74 }
75 compare(t, nodesA, nodesB)
76 }
77
78 func TestInspectGenericNodes(t *testing.T) {
79 // src is using the 16 identifiers i0, i1, ... i15 so
80 // we can easily verify that we've found all of them.
81 const src = `package a
82
83 type I interface { ~i0|i1 }
84
85 type T[i2, i3 interface{ ~i4 }] struct {}
86
87 func f[i5, i6 any]() {
88 _ = f[i7, i8]
89 var x T[i9, i10]
90 }
91
92 func (*T[i11, i12]) m()
93
94 var _ i13[i14, i15]
95 `
96 fset := token.NewFileSet()
97 f, _ := parser.ParseFile(fset, "a.go", src, 0)
98 inspect := inspector.New([]*ast.File{f})
99 found := make([]bool, 16)
100
101 indexListExprs := make(map[*ast.IndexListExpr]bool)
102
103 // Verify that we reach all i* identifiers, and collect IndexListExpr nodes.
104 inspect.Preorder(nil, func(n ast.Node) {
105 switch n := n.(type) {
106 case *ast.Ident:
107 if n.Name[0] == 'i' {
108 index, err := strconv.Atoi(n.Name[1:])
109 if err != nil {
110 t.Fatal(err)
111 }
112 found[index] = true
113 }
114 case *ast.IndexListExpr:
115 indexListExprs[n] = false
116 }
117 })
118 for i, v := range found {
119 if !v {
120 t.Errorf("missed identifier i%d", i)
121 }
122 }
123
124 // Verify that we can filter to IndexListExprs that we found in the first
125 // step.
126 if len(indexListExprs) == 0 {
127 t.Fatal("no index list exprs found")
128 }
129 inspect.Preorder([]ast.Node{&ast.IndexListExpr{}}, func(n ast.Node) {
130 ix := n.(*ast.IndexListExpr)
131 indexListExprs[ix] = true
132 })
133 for ix, v := range indexListExprs {
134 if !v {
135 t.Errorf("inspected node %v not filtered", ix)
136 }
137 }
138 }
139
140 // TestInspectPruning compares Inspector against ast.Inspect,
141 // pruning descent within ast.CallExpr nodes.
142 func TestInspectPruning(t *testing.T) {
143 inspect := inspector.New(netFiles)
144
145 var nodesA []ast.Node
146 inspect.Nodes(nil, func(n ast.Node, push bool) bool {
147 if push {
148 nodesA = append(nodesA, n)
149 _, isCall := n.(*ast.CallExpr)
150 return !isCall // don't descend into function calls
151 }
152 return false
153 })
154 var nodesB []ast.Node
155 for _, f := range netFiles {
156 ast.Inspect(f, func(n ast.Node) bool {
157 if n != nil {
158 nodesB = append(nodesB, n)
159 _, isCall := n.(*ast.CallExpr)
160 return !isCall // don't descend into function calls
161 }
162 return false
163 })
164 }
165 compare(t, nodesA, nodesB)
166 }
167
168 // compare calls t.Error if !slices.Equal(nodesA, nodesB).
169 func compare[N comparable](t *testing.T, nodesA, nodesB []N) {
170 if len(nodesA) != len(nodesB) {
171 t.Errorf("inconsistent node lists: %d vs %d", len(nodesA), len(nodesB))
172 } else {
173 for i := range nodesA {
174 if a, b := nodesA[i], nodesB[i]; a != b {
175 t.Errorf("node %d is inconsistent: %T, %T", i, a, b)
176 }
177 }
178 }
179 }
180
181 func TestTypeFiltering(t *testing.T) {
182 const src = `package a
183 func f() {
184 print("hi")
185 panic("oops")
186 }
187 `
188 fset := token.NewFileSet()
189 f, _ := parser.ParseFile(fset, "a.go", src, 0)
190 inspect := inspector.New([]*ast.File{f})
191
192 var got []string
193 fn := func(n ast.Node, push bool) bool {
194 if push {
195 got = append(got, typeOf(n))
196 }
197 return true
198 }
199
200 // no type filtering
201 inspect.Nodes(nil, fn)
202 if want := strings.Fields("File Ident FuncDecl Ident FuncType FieldList BlockStmt ExprStmt CallExpr Ident BasicLit ExprStmt CallExpr Ident BasicLit"); !reflect.DeepEqual(got, want) {
203 t.Errorf("inspect: got %s, want %s", got, want)
204 }
205
206 // type filtering
207 nodeTypes := []ast.Node{
208 (*ast.BasicLit)(nil),
209 (*ast.CallExpr)(nil),
210 }
211 got = nil
212 inspect.Nodes(nodeTypes, fn)
213 if want := strings.Fields("CallExpr BasicLit CallExpr BasicLit"); !reflect.DeepEqual(got, want) {
214 t.Errorf("inspect: got %s, want %s", got, want)
215 }
216
217 // inspect with stack
218 got = nil
219 inspect.WithStack(nodeTypes, func(n ast.Node, push bool, stack []ast.Node) bool {
220 if push {
221 var line []string
222 for _, n := range stack {
223 line = append(line, typeOf(n))
224 }
225 got = append(got, strings.Join(line, " "))
226 }
227 return true
228 })
229 want := []string{
230 "File FuncDecl BlockStmt ExprStmt CallExpr",
231 "File FuncDecl BlockStmt ExprStmt CallExpr BasicLit",
232 "File FuncDecl BlockStmt ExprStmt CallExpr",
233 "File FuncDecl BlockStmt ExprStmt CallExpr BasicLit",
234 }
235 if !reflect.DeepEqual(got, want) {
236 t.Errorf("inspect: got %s, want %s", got, want)
237 }
238 }
239
240 func typeOf(n ast.Node) string {
241 return strings.TrimPrefix(reflect.TypeOf(n).String(), "*ast.")
242 }
243
244 // The numbers show a marginal improvement (ASTInspect/Inspect) of 3.5x,
245 // but a break-even point (NewInspector/(ASTInspect-Inspect)) of about 5
246 // traversals.
247 //
248 // BenchmarkASTInspect 1.0 ms
249 // BenchmarkNewInspector 2.2 ms
250 // BenchmarkInspect 0.39ms
251 // BenchmarkInspectFilter 0.01ms
252 // BenchmarkInspectCalls 0.14ms
253
254 func BenchmarkNewInspector(b *testing.B) {
255 // Measure one-time construction overhead.
256 for b.Loop() {
257 inspector.New(netFiles)
258 }
259 }
260
261 func BenchmarkInspect(b *testing.B) {
262
263 inspect := inspector.New(netFiles)
264
265 // Measure marginal cost of traversal.
266 var ndecls, nlits int
267 for b.Loop() {
268 inspect.Preorder(nil, func(n ast.Node) {
269 switch n.(type) {
270 case *ast.FuncDecl:
271 ndecls++
272 case *ast.FuncLit:
273 nlits++
274 }
275 })
276 }
277 }
278
279 func BenchmarkInspectFilter(b *testing.B) {
280
281 inspect := inspector.New(netFiles)
282
283 // Measure marginal cost of traversal.
284 nodeFilter := []ast.Node{(*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)}
285 var ndecls, nlits int
286 for b.Loop() {
287 inspect.Preorder(nodeFilter, func(n ast.Node) {
288 switch n.(type) {
289 case *ast.FuncDecl:
290 ndecls++
291 case *ast.FuncLit:
292 nlits++
293 }
294 })
295 }
296 }
297
298 func BenchmarkASTInspect(b *testing.B) {
299 var ndecls, nlits int
300 for b.Loop() {
301 for _, f := range netFiles {
302 ast.Inspect(f, func(n ast.Node) bool {
303 switch n.(type) {
304 case *ast.FuncDecl:
305 ndecls++
306 case *ast.FuncLit:
307 nlits++
308 }
309 return true
310 })
311 }
312 }
313 }