Debian Codegraph @

go/ast/inspector/iter_test.go

raw symbols SCIP
1 // Copyright 2024 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 "iter"
10 "slices"
11 "testing"
12
13 "golang.org/x/tools/go/ast/inspector"
14 )
15
16 // TestPreorderSeq checks PreorderSeq against Preorder.
17 func TestPreorderSeq(t *testing.T) {
18 inspect := inspector.New(netFiles)
19
20 nodeFilter := []ast.Node{(*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)}
21
22 // reference implementation
23 var want []ast.Node
24 inspect.Preorder(nodeFilter, func(n ast.Node) {
25 want = append(want, n)
26 })
27
28 // Check entire sequence.
29 got := slices.Collect(inspect.PreorderSeq(nodeFilter...))
30 compare(t, got, want)
31
32 // Check that break works.
33 got = firstN(10, inspect.PreorderSeq(nodeFilter...))
34 compare(t, got, want[:10])
35 }
36
37 // TestAll checks All against Preorder.
38 func TestAll(t *testing.T) {
39 inspect := inspector.New(netFiles)
40
41 // reference implementation
42 var want []*ast.CallExpr
43 inspect.Preorder([]ast.Node{(*ast.CallExpr)(nil)}, func(n ast.Node) {
44 want = append(want, n.(*ast.CallExpr))
45 })
46
47 // Check entire sequence.
48 got := slices.Collect(inspector.All[*ast.CallExpr](inspect))
49 compare(t, got, want)
50
51 // Check that break works.
52 got = firstN(10, inspector.All[*ast.CallExpr](inspect))
53 compare(t, got, want[:10])
54 }
55
56 // firstN(n, seq), returns a slice of up to n elements of seq.
57 func firstN[T any](n int, seq iter.Seq[T]) (res []T) {
58 for x := range seq {
59 res = append(res, x)
60 if len(res) == n {
61 break
62 }
63 }
64 return res
65 }
66
67 // BenchmarkAllCalls is like BenchmarkInspectCalls,
68 // but using the single-type filtering iterator, All.
69 // (The iterator adds about 5-15%.)
70 func BenchmarkAllCalls(b *testing.B) {
71 inspect := inspector.New(netFiles)
72
73 // Measure marginal cost of traversal.
74 var ncalls int
75 for b.Loop() {
76 for range inspector.All[*ast.CallExpr](inspect) {
77 ncalls++
78 }
79 }
80 }