Debian Codegraph @

internal/typesinternal/typeindex/typeindex_test.go

raw symbols SCIP
1 // Copyright 2025 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 typeindex_test
6
7 import (
8 "go/ast"
9 "go/parser"
10 "go/token"
11 "go/types"
12 "slices"
13 "testing"
14
15 "golang.org/x/tools/go/ast/inspector"
16 "golang.org/x/tools/go/packages"
17 "golang.org/x/tools/go/types/typeutil"
18 "golang.org/x/tools/internal/testenv"
19 "golang.org/x/tools/internal/testfiles"
20 "golang.org/x/tools/internal/typesinternal/typeindex"
21 "golang.org/x/tools/txtar"
22 )
23
24 func TestIndex(t *testing.T) {
25 testenv.NeedsGoPackages(t)
26 var (
27 pkg = loadNetHTTP(t)
28 inspect = inspector.New(pkg.Syntax)
29 index = typeindex.New(inspect, pkg.Types, pkg.TypesInfo)
30 fmtSprintf = index.Object("fmt", "Sprintf")
31 )
32
33 // Gather calls and uses of fmt.Sprintf in net/http.
34 var (
35 wantUses []*ast.Ident
36 wantCalls []*ast.CallExpr
37 )
38 for n := range inspect.PreorderSeq((*ast.CallExpr)(nil), (*ast.Ident)(nil)) {
39 switch n := n.(type) {
40 case *ast.CallExpr:
41 if typeutil.Callee(pkg.TypesInfo, n) == fmtSprintf {
42 wantCalls = append(wantCalls, n)
43 }
44 case *ast.Ident:
45 if pkg.TypesInfo.Uses[n] == fmtSprintf {
46 wantUses = append(wantUses, n)
47 }
48 }
49 }
50 // sanity check (expect about 60 of each)
51 if wantUses == nil || wantCalls == nil {
52 t.Fatalf("no calls or uses of fmt.Sprintf in net/http")
53 }
54
55 var (
56 gotUses []*ast.Ident
57 gotCalls []*ast.CallExpr
58 )
59 for curId := range index.Uses(fmtSprintf) {
60 gotUses = append(gotUses, curId.Node().(*ast.Ident))
61 }
62 for curCall := range index.Calls(fmtSprintf) {
63 gotCalls = append(gotCalls, curCall.Node().(*ast.CallExpr))
64 }
65
66 if !slices.Equal(gotUses, wantUses) {
67 t.Errorf("index.Uses(fmt.Sprintf) = %v, want %v", gotUses, wantUses)
68 }
69 if !slices.Equal(gotCalls, wantCalls) {
70 t.Errorf("index.Calls(fmt.Sprintf) = %v, want %v", gotCalls, wantCalls)
71 }
72 }
73
74 func loadNetHTTP(tb testing.TB) *packages.Package {
75 cfg := &packages.Config{Mode: packages.LoadSyntax}
76 pkgs, err := packages.Load(cfg, "net/http")
77 if err != nil {
78 tb.Fatal(err)
79 }
80 return pkgs[0]
81 }
82
83 func BenchmarkIndex(b *testing.B) {
84 testenv.NeedsGoPackages(b)
85 // Load net/http, a large package, and find calls to net.Dial.
86 //
87 // There is currently exactly one, which provides an extreme
88 // demonstration of the performance advantage of the Index.
89 //
90 // Index construction costs approximately 7x the cursor
91 // traversal, so it breaks even when it replaces 7 passes.
92 // The cost of index lookup is approximately zero.
93 pkg := loadNetHTTP(b)
94
95 // Build the Inspector (~2.8ms).
96 var inspect *inspector.Inspector
97 b.Run("inspector.New", func(b *testing.B) {
98 for b.Loop() {
99 inspect = inspector.New(pkg.Syntax)
100 }
101 })
102
103 // Build the Index (~6.6ms).
104 var index *typeindex.Index
105 b.Run("typeindex.New", func(b *testing.B) {
106 b.ReportAllocs() // 2.48MB/op
107 for b.Loop() {
108 index = typeindex.New(inspect, pkg.Types, pkg.TypesInfo)
109 }
110 })
111
112 target := index.Object("net", "Dial")
113
114 var countA, countB, countC int
115
116 // unoptimized inspect implementation (~1.6ms, 1x)
117 b.Run("inspect", func(b *testing.B) {
118 for b.Loop() {
119 countA = 0
120 for _, file := range pkg.Syntax {
121 ast.Inspect(file, func(n ast.Node) bool {
122 if call, ok := n.(*ast.CallExpr); ok {
123 if typeutil.Callee(pkg.TypesInfo, call) == target {
124 countA++
125 }
126 }
127 return true
128 })
129 }
130 }
131 })
132 if countA == 0 {
133 b.Errorf("target %v not found", target)
134 }
135
136 // unoptimized cursor implementation (~390us, 4x faster)
137 b.Run("cursor", func(b *testing.B) {
138 for b.Loop() {
139 countB = 0
140 for curCall := range inspect.Root().Preorder((*ast.CallExpr)(nil)) {
141 call := curCall.Node().(*ast.CallExpr)
142 if typeutil.Callee(pkg.TypesInfo, call) == target {
143 countB++
144 }
145 }
146 }
147 })
148
149 // indexed implementation (~120ns, >10,000x faster)
150 b.Run("index", func(b *testing.B) {
151 for b.Loop() {
152 countC = 0
153 for range index.Calls(target) {
154 countC++
155 }
156 }
157 })
158
159 if countA != countB || countA != countC {
160 b.Fatalf("inconsistent results (inspect=%d, cursor=%d, index=%d)", countA, countB, countC)
161 }
162 }
163
164 // TestOrigin checks that index.Uses on field or method of a generic
165 // type reports references to its instantiations.
166 // Lexical references (to functions, types, and aliases) always
167 // resolve to the generic; there is no Origin distinction.
168 func TestOrigin(t *testing.T) {
169 // Each nonblank declared name must have at least one use.
170 for _, src := range []string{
171 `
172 package alias
173 type A[T any] = *T
174 var _ A[int]`,
175 `
176 package localalias
177 func _[T any]() {
178 type A[U any] = *U
179 var _ A[T]
180 }`,
181 `
182 package named
183 type Named[_ any] int
184 var _ Named[int]`,
185 `
186 package localnamed
187 func _[T any]() {
188 type N[U any] struct { f U }
189 _ = N[T]{}.f
190 }`,
191 `
192 package field
193 type Named[T any] struct { field T }
194 var _ = Named[int]{}.field`,
195 `
196 package function
197 func F[T any](T) {}
198 var _ = F[int]`,
199 `
200 package method
201 type Named[_ any] int
202 func (Named[T]) method(T) {}
203 var _ = Named[int].method`,
204 `
205 package uninstantiatedmethod
206 type Named[_ any] int
207 func (Named[_]) f() {}
208 func (Named[T]) g() { Named[T](0).f() }
209 func (n Named[_]) _() { n.g() }`,
210 } {
211 // parse
212 fset := token.NewFileSet()
213 f, _ := parser.ParseFile(fset, "", src, parser.PackageClauseOnly)
214 t.Run(f.Name.Name, func(t *testing.T) {
215 f, _ := parser.ParseFile(fset, "", src, 0)
216 files := []*ast.File{f}
217
218 // typecheck
219 info := &types.Info{
220 Defs: make(map[*ast.Ident]types.Object),
221 Uses: make(map[*ast.Ident]types.Object),
222 }
223 pkg, err := new(types.Config).Check(f.Name.Name, fset, files, info)
224 if err != nil {
225 t.Fatal(err)
226 }
227
228 // index
229 var (
230 inspect = inspector.New(files)
231 index = typeindex.New(inspect, pkg, info)
232 )
233
234 // check Def/Uses of all objects
235 for id := range inspect.PreorderSeq((*ast.Ident)(nil)) {
236 id := id.(*ast.Ident)
237 if obj := info.Defs[id]; obj != nil && id.Name != "_" {
238 t.Logf("%T %s @ %s", obj, id.Name, fset.Position(id.Pos()))
239
240 // check Def
241 if curDef, ok := index.Def(obj); !ok {
242 t.Errorf("- index.Def missing")
243 } else if curDef.Node() != id {
244 t.Errorf("- index.Def wrong: @%s", fset.Position(curDef.Node().Pos()))
245 }
246
247 // check Uses is nonempty
248 ok := false
249 for use := range index.Uses(obj) {
250 t.Logf("- index.Use at %s", fset.Position(use.Node().Pos()))
251 ok = true
252 }
253 if !ok {
254 t.Errorf("- no index.Uses")
255 }
256 }
257 }
258 })
259 }
260 }
261
262 func TestCalls(t *testing.T) {
263 testenv.NeedsGoPackages(t)
264 const file = `-- go.mod --
265 module foo
266
267 go 1.24
268
269 -- pkg/pkg.go --
270 package pkg
271
272 type Bar struct {}
273
274 func (f Bar) Method() {}
275
276 var Foo Bar
277 -- test.go --
278 package foo
279
280 import "foo/pkg"
281
282 func foo() {}
283
284 func _() {
285 foo()
286 (foo)()
287 ((foo))()
288 }
289
290 func fooGeneric[T any]() {}
291
292 func _() {
293 fooGeneric[int]()
294 (fooGeneric[int])()
295 ((fooGeneric[int]))()
296 }
297
298 func fooGeneric2[T, T2 any]() {}
299
300 func _() {
301 fooGeneric2[int, int]()
302 (fooGeneric2[int, int])()
303 ((fooGeneric2[int, int]))()
304 }
305
306 func _() {
307 var foo pkg.Bar
308 (foo.Method)()
309 ((foo).Method)()
310 (foo).Method()
311 pkg.Bar.Method(pkg.Bar{})
312 (pkg.Bar).Method(pkg.Bar{})
313 ((pkg.Bar).Method)(pkg.Bar{})
314
315 var bar struct { field pkg.Bar }
316 bar.field.Method()
317 }
318
319 func _() {
320 pkg.Foo.Method()
321 (pkg.Foo).Method()
322 ((pkg.Foo).Method)()
323 (pkg.Foo.Method)()
324 }
325 `
326 fs, err := txtar.FS(txtar.Parse([]byte(file)))
327 if err != nil {
328 t.Fatal(err)
329 }
330 dir := testfiles.CopyToTmp(t, fs)
331
332 fset := token.NewFileSet()
333 cfg := packages.Config{Mode: packages.LoadAllSyntax, Fset: fset, Dir: dir}
334 pkgs, err := packages.Load(&cfg, "foo")
335 if err != nil {
336 t.Fatal(err)
337 }
338 if packages.PrintErrors(pkgs) > 0 {
339 t.Fatal("Load: there were errors")
340 }
341
342 var (
343 pkg = pkgs[0]
344 inspect = inspector.New(pkg.Syntax)
345 index = typeindex.New(inspect, pkg.Types, pkg.TypesInfo)
346 )
347
348 // Emulate index.Calls with a tree walk.
349 objToCall := make(map[types.Object][]token.Pos)
350 for call := range inspector.All[*ast.CallExpr](inspect) {
351 obj := typeutil.Callee(pkg.TypesInfo, call)
352 if obj != nil {
353 objToCall[obj] = append(objToCall[obj], call.Pos())
354 }
355 }
356
357 // Assert index.Calls returns the same results, as the slow version (above).
358 for obj, wantCalls := range objToCall {
359 var gotCalls []token.Pos
360 for call := range index.Calls(obj) {
361 gotCalls = append(gotCalls, call.Node().Pos())
362 }
363 if !slices.Equal(gotCalls, wantCalls) {
364 t.Errorf("%v: got calls: %v; want: %v", obj.Name(), gotCalls, wantCalls)
365 }
366 }
367 }