| 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/txtar" |
| 19 |
"honnef.co/go/tools/internal/xtools-internal/testenv" |
| 20 |
"honnef.co/go/tools/internal/xtools-internal/testfiles" |
| 21 |
"honnef.co/go/tools/internal/xtools-internal/typesinternal/typeindex" |
| 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 |
t.Skip("Debian: fails in sbuild because packages.Load cannot find package foo (no network, package not resolvable in chroot)") |
| 264 |
testenv.NeedsGoPackages(t) |
| 265 |
const file = `-- go.mod -- |
| 266 |
module foo |
| 267 |
|
| 268 |
go 1.24 |
| 269 |
|
| 270 |
-- pkg/pkg.go -- |
| 271 |
package pkg |
| 272 |
|
| 273 |
type Bar struct {} |
| 274 |
|
| 275 |
func (f Bar) Method() {} |
| 276 |
|
| 277 |
var Foo Bar |
| 278 |
-- test.go -- |
| 279 |
package foo |
| 280 |
|
| 281 |
import "foo/pkg" |
| 282 |
|
| 283 |
func foo() {} |
| 284 |
|
| 285 |
func _() { |
| 286 |
foo() |
| 287 |
(foo)() |
| 288 |
((foo))() |
| 289 |
} |
| 290 |
|
| 291 |
func fooGeneric[T any]() {} |
| 292 |
|
| 293 |
func _() { |
| 294 |
fooGeneric[int]() |
| 295 |
(fooGeneric[int])() |
| 296 |
((fooGeneric[int]))() |
| 297 |
} |
| 298 |
|
| 299 |
func fooGeneric2[T, T2 any]() {} |
| 300 |
|
| 301 |
func _() { |
| 302 |
fooGeneric2[int, int]() |
| 303 |
(fooGeneric2[int, int])() |
| 304 |
((fooGeneric2[int, int]))() |
| 305 |
} |
| 306 |
|
| 307 |
func _() { |
| 308 |
var foo pkg.Bar |
| 309 |
(foo.Method)() |
| 310 |
((foo).Method)() |
| 311 |
(foo).Method() |
| 312 |
pkg.Bar.Method(pkg.Bar{}) |
| 313 |
(pkg.Bar).Method(pkg.Bar{}) |
| 314 |
((pkg.Bar).Method)(pkg.Bar{}) |
| 315 |
|
| 316 |
var bar struct { field pkg.Bar } |
| 317 |
bar.field.Method() |
| 318 |
} |
| 319 |
|
| 320 |
func _() { |
| 321 |
pkg.Foo.Method() |
| 322 |
(pkg.Foo).Method() |
| 323 |
((pkg.Foo).Method)() |
| 324 |
(pkg.Foo.Method)() |
| 325 |
} |
| 326 |
` |
| 327 |
fs, err := txtar.FS(txtar.Parse([]byte(file))) |
| 328 |
if err != nil { |
| 329 |
t.Fatal(err) |
| 330 |
} |
| 331 |
dir := testfiles.CopyToTmp(t, fs) |
| 332 |
|
| 333 |
fset := token.NewFileSet() |
| 334 |
cfg := packages.Config{Mode: packages.LoadAllSyntax, Fset: fset, Dir: dir} |
| 335 |
pkgs, err := packages.Load(&cfg, "foo") |
| 336 |
if err != nil { |
| 337 |
t.Fatal(err) |
| 338 |
} |
| 339 |
if packages.PrintErrors(pkgs) > 0 { |
| 340 |
t.Fatal("Load: there were errors") |
| 341 |
} |
| 342 |
|
| 343 |
var ( |
| 344 |
pkg = pkgs[0] |
| 345 |
inspect = inspector.New(pkg.Syntax) |
| 346 |
index = typeindex.New(inspect, pkg.Types, pkg.TypesInfo) |
| 347 |
) |
| 348 |
|
| 349 |
// Emulate index.Calls with a tree walk. |
| 350 |
objToCall := make(map[types.Object][]token.Pos) |
| 351 |
for call := range inspector.All[*ast.CallExpr](inspect) { |
| 352 |
obj := typeutil.Callee(pkg.TypesInfo, call) |
| 353 |
if obj != nil { |
| 354 |
objToCall[obj] = append(objToCall[obj], call.Pos()) |
| 355 |
} |
| 356 |
} |
| 357 |
|
| 358 |
// Assert index.Calls returns the same results, as the slow version (above). |
| 359 |
for obj, wantCalls := range objToCall { |
| 360 |
var gotCalls []token.Pos |
| 361 |
for call := range index.Calls(obj) { |
| 362 |
gotCalls = append(gotCalls, call.Node().Pos()) |
| 363 |
} |
| 364 |
if !slices.Equal(gotCalls, wantCalls) { |
| 365 |
t.Errorf("%v: got calls: %v; want: %v", obj.Name(), gotCalls, wantCalls) |
| 366 |
} |
| 367 |
} |
| 368 |
} |