Debian Codegraph @

go/types/objectpath/objectpath_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 objectpath_test
6
7 import (
8 "bytes"
9 "fmt"
10 "go/ast"
11 "go/importer"
12 "go/parser"
13 "go/token"
14 "go/types"
15 "os"
16 "strings"
17 "testing"
18
19 "golang.org/x/tools/go/gcexportdata"
20 "golang.org/x/tools/go/packages"
21 "golang.org/x/tools/go/types/objectpath"
22 "golang.org/x/tools/internal/testenv"
23 "golang.org/x/tools/internal/testfiles"
24 "golang.org/x/tools/txtar"
25 )
26
27 func TestPaths(t *testing.T) {
28 const src = `
29 -- go.mod --
30 module x.io
31
32 -- b/b.go --
33 package b
34
35 import "x.io/a"
36
37 const C = a.Int(0)
38
39 func F(a, b, c int, d a.T)
40
41 type T struct{ A int; b int; a.T }
42
43 func (T) M() *interface{ f() }
44
45 type U T
46
47 type A = struct{ x int }
48
49 type unexported2 struct { z int }
50 type AN = unexported2 // alias of named
51
52 // type GA[T any] = T // see below
53
54 var V []*a.T
55
56 type M map[struct{x int}]struct{y int}
57
58 func unexportedFunc()
59 type unexportedType struct{}
60
61 func (unexportedType) F() {} // not reachable from package's public API (export data)
62
63 type S struct{t struct{x int}}
64 type R []struct{y int}
65 type Q [2]struct{z int}
66
67 type I interface {
68 M()
69 }
70
71 -- a/a.go --
72 package a
73
74 type Int int
75
76 type T struct{x, y int}
77
78 type Issue68046 interface { f(x int) interface{Issue68046} }
79 `
80
81 pkgmap := loadPackages(t, src, "./a", "./b")
82
83 paths := []pathTest{
84 // Good paths
85 {"b", "C", "const b.C a.Int", ""},
86 {"b", "F", "func b.F(a int, b int, c int, d a.T)", ""},
87 {"b", "F.PA0", "var a int", ""},
88 {"b", "F.PA1", "var b int", ""},
89 {"b", "F.PA2", "var c int", ""},
90 {"b", "F.PA3", "var d a.T", ""},
91 {"b", "T", "type b.T struct{A int; b int; a.T}", ""},
92 {"b", "T.O", "type b.T struct{A int; b int; a.T}", ""},
93 {"b", "T.UF0", "field A int", ""},
94 {"b", "T.UF1", "field b int", ""},
95 {"b", "T.UF2", "field T a.T", ""},
96 {"b", "U.UF2", "field T a.T", ""}, // U.U... are aliases for T.U...
97 {"b", "A", "type b.A = struct{x int}", ""}, // go1.22/alias=1: "type b.A = b.A"
98 {"b", "A.aF0", "field x int", ""},
99 {"b", "A.F0", "field x int", ""},
100 {"b", "AN", "type b.AN = b.unexported2", ""}, // go1.22/alias=1: "type b.AN = b.AN"
101 {"b", "AN.UF0", "field z int", ""},
102 {"b", "AN.aO", "type b.unexported2 struct{z int}", ""},
103 {"b", "AN.O", "type b.unexported2 struct{z int}", ""},
104 {"b", "AN.aUF0", "field z int", ""},
105 {"b", "AN.UF0", "field z int", ""},
106 // {"b", "GA", "type parameter b.GA = T", ""}, // TODO(adonovan): enable once GOEXPERIMENT=aliastypeparams has gone
107 {"b", "V", "var b.V []*a.T", ""},
108 {"b", "M", "type b.M map[struct{x int}]struct{y int}", ""},
109 {"b", "M.UKF0", "field x int", ""},
110 {"b", "M.UEF0", "field y int", ""},
111 {"b", "T.M0", "func (b.T).M() *interface{f()}", ""}, // concrete method
112 {"b", "T.M0.RA0", "var *interface{f()}", ""}, // parameter
113 {"b", "T.M0.RA0.EM0", "func (interface).f()", ""}, // interface method
114 {"b", "I.UM0", "func (b.I).M()", ""},
115 {"b", "unexportedType", "type b.unexportedType struct{}", ""},
116 {"b", "unexportedType.M0", "func (b.unexportedType).F()", ""},
117 {"b", "S.UF0.F0", "field x int", ""},
118 {"b", "R.UEF0", "field y int", ""},
119 {"b", "Q.UEF0", "field z int", ""},
120 {"a", "T", "type a.T struct{x int; y int}", ""},
121 {"a", "Issue68046.UM0", "func (a.Issue68046).f(x int) interface{a.Issue68046}", ""},
122 {"a", "Issue68046.UM0.PA0", "var x int", ""},
123
124 // Bad paths
125 {"b", "", "", "empty path"},
126 {"b", "missing", "", `package b does not contain "missing"`},
127 {"b", "F.U", "", "invalid path: ends with 'U', want [AFMO]"},
128 {"b", "F.PA3.O", "", "path denotes type a.T struct{x int; y int}, which belongs to a different package"},
129 {"b", "F.PA!", "", `invalid path: bad numeric operand "" for code 'A'`},
130 {"b", "F.PA3.UF0", "", "path denotes field x int, which belongs to a different package"},
131 {"b", "F.PA3.UF5", "", "field index 5 out of range [0-2)"},
132 {"b", "V.EE", "", "invalid path: ends with 'E', want [AFMO]"},
133 {"b", "F..O", "", "invalid path: unexpected '.' in type context"},
134 {"b", "T.OO", "", "invalid path: code 'O' in object context"},
135 {"b", "T.EO", "", "cannot apply 'E' to b.T (got *types.Named, want pointer, slice, array, chan or map)"},
136 {"b", "A.O", "", "cannot apply 'O' to struct{x int} (got *types.Struct, want named or type param)"},
137 {"b", "A.UF0", "", "cannot apply 'U' to struct{x int} (got *types.Struct, want named)"},
138 {"b", "M.UPO", "", "cannot apply 'P' to map[struct{x int}]struct{y int} (got *types.Map, want signature)"},
139 {"b", "C.O", "", "path denotes type a.Int int, which belongs to a different package"},
140 {"b", "T.M9", "", "method index 9 out of range [0-1)"},
141 {"b", "M.UF0", "", "cannot apply 'F' to map[struct{x int}]struct{y int} (got *types.Map, want struct)"},
142 {"b", "V.KO", "", "cannot apply 'K' to []*a.T (got *types.Slice, want map)"},
143 {"b", "V.A4", "", "cannot apply 'A' to []*a.T (got *types.Slice, want tuple)"},
144 {"b", "V.RA0", "", "cannot apply 'R' to []*a.T (got *types.Slice, want signature)"},
145 {"b", "F.PA4", "", "tuple index 4 out of range [0-4)"},
146 {"b", "F.XO", "", "invalid path: unknown code 'X'"},
147 }
148 for _, test := range paths {
149 if err := testPath(pkgmap, test); err != nil {
150 t.Error(err)
151 }
152 }
153
154 // bad objects
155 b := pkgmap["x.io/b"]
156 for _, test := range []struct {
157 obj types.Object
158 wantErr string
159 }{
160 {types.Universe.Lookup("nil"), "predeclared nil has no path"},
161 {types.Universe.Lookup("len"), "predeclared builtin len has no path"},
162 {types.Universe.Lookup("int"), "predeclared type int has no path"},
163 {b.TypesInfo.Implicits[b.Syntax[0].Imports[0]], "no path for package a (\"a\")"}, // import "a"
164 {b.Types.Scope().Lookup("unexportedFunc"), "no path for non-exported func b.unexportedFunc()"},
165 } {
166 path, err := objectpath.For(test.obj)
167 if err == nil {
168 t.Errorf("Object(%s) = %q, want error", test.obj, path)
169 continue
170 }
171 gotErr := strings.ReplaceAll(err.Error(), "x.io/", "")
172 if gotErr != test.wantErr {
173 t.Errorf("Object(%s) error was %q, want %q", test.obj, gotErr, test.wantErr)
174 continue
175 }
176 }
177 }
178
179 // loadPackages expands the archive and loads the package patterns relative to its root.
180 func loadPackages(t *testing.T, archive string, patterns ...string) map[string]*packages.Package {
181 // TODO(adonovan): ExtractTxtarToTmp (sans File) would be useful.
182 ar := txtar.Parse([]byte(archive))
183 pkgs := testfiles.LoadPackages(t, ar, patterns...)
184 m := make(map[string]*packages.Package)
185 packages.Visit(pkgs, nil, func(pkg *packages.Package) {
186 m[pkg.Types.Path()] = pkg
187 })
188 return m
189 }
190
191 type pathTest struct {
192 pkg string // sans "x.io/" module prefix
193 path objectpath.Path
194 wantobj string
195 wantErr string // after each "x.io/" replaced with ""
196 }
197
198 func testPath(pkgmap map[string]*packages.Package, test pathTest) error {
199 // We test objectpath by enumerating a set of paths
200 // and ensuring that Path(pkg, Object(pkg, path)) == path.
201 //
202 // It might seem more natural to invert the test:
203 // identify a set of objects and for each one,
204 // ensure that Object(pkg, Path(pkg, obj)) == obj.
205 // However, for most interesting test cases there is no
206 // easy way to identify the object short of applying
207 // a series of destructuring operations to pkg---which
208 // is essentially what objectpath.Object does.
209 // (We do a little of that when testing bad paths, below.)
210 //
211 // The downside is that the test depends on the path encoding.
212 // The upside is that the test exercises the encoding.
213 pkg := pkgmap["x.io/"+test.pkg].Types
214
215 // check path -> object
216 obj, err := objectpath.Object(pkg, test.path)
217 if (test.wantErr != "") != (err != nil) {
218 return fmt.Errorf("Object(%s, %q) returned error %q, want %q", pkg.Path(), test.path, err, test.wantErr)
219 }
220 if test.wantErr != "" {
221 gotErr := strings.ReplaceAll(err.Error(), "x.io/", "")
222 if gotErr != test.wantErr {
223 return fmt.Errorf("Object(%s, %q) error was %q, want %q",
224 pkg.Path(), test.path, gotErr, test.wantErr)
225 }
226 return nil
227 }
228 // Inv: err == nil
229
230 if objString := types.ObjectString(obj, (*types.Package).Name); objString != test.wantobj {
231 return fmt.Errorf("Object(%s, %q) = %s, want %s", pkg.Path(), test.path, objString, test.wantobj)
232 }
233 if obj.Pkg() != pkg {
234 return fmt.Errorf("Object(%s, %q) = %v, which belongs to package %s",
235 pkg.Path(), test.path, obj, obj.Pkg().Path())
236 }
237
238 // check object -> path
239 path2, err := objectpath.For(obj)
240 if err != nil {
241 return fmt.Errorf("For(%v) failed: %v, want %q", obj, err, test.path)
242 }
243 // We do not require that test.path == path2. Aliases are legal.
244 // But we do require that Object(path2) finds the same object.
245 obj2, err := objectpath.Object(pkg, path2)
246 if err != nil {
247 return fmt.Errorf("Object(%s, %q) failed: %v (roundtrip from %q)", pkg.Path(), path2, err, test.path)
248 }
249 if obj2 != obj {
250 return fmt.Errorf("Object(%s, For(obj)) != obj: got %s, obj is %s (path1=%q, path2=%q)", pkg.Path(), obj2, obj, test.path, path2)
251 }
252
253 // We also call [objectpath.Encoder.For] three times to ensure it
254 // gives consistent results with [objectpath.For] in all states:
255 // 1: searching for symbol without index
256 // 2: building index and looking up symbol
257 // 3: looking up symbol in existing index.
258 {
259 enc := new(objectpath.Encoder)
260
261 epath1, err := enc.For(obj)
262 if err != nil {
263 return fmt.Errorf("#1 Encoder.For(%v) failed: %v, want %q", obj, err, test.path)
264 }
265
266 epath2, err := enc.For(obj)
267 if err != nil {
268 return fmt.Errorf("#2 Encoder.For(%v) failed: %v, want %q", obj, err, test.path)
269 }
270
271 epath3, err := enc.For(obj)
272 if err != nil {
273 return fmt.Errorf("#3 Encoder.For(%v) failed: %v, want %q", obj, err, test.path)
274 }
275
276 if epath1 != path2 || epath2 != path2 || epath3 != path2 {
277 return fmt.Errorf("consistency error for %v: For path=%q, Encoder paths=(%q %q %q)",
278 obj, path2, epath1, epath2, epath3)
279 }
280 }
281
282 return nil
283 }
284
285 // TestSourceAndExportData uses objectpath to compute a correspondence
286 // of objects between two versions of the same package, one loaded from
287 // source, the other from export data.
288 func TestSourceAndExportData(t *testing.T) {
289 const src = `
290 package p
291
292 type I int
293
294 func (I) F() *struct{ X, Y int } {
295 return nil
296 }
297
298 type Foo interface {
299 Method() (string, func(int) struct{ X int })
300 }
301
302 var X chan struct{ Z int }
303 var Z map[string]struct{ A int }
304
305 var V unexported
306 type unexported struct{}
307 func (unexported) F() {} // reachable via V
308
309 // The name 'unreachable' has special meaning to the test.
310 type unreachable struct{}
311 func (unreachable) F() {} // not reachable in export data
312 `
313
314 // Parse source file and type-check it as a package, "src".
315 fset := token.NewFileSet()
316 f, err := parser.ParseFile(fset, "src.go", src, 0)
317 if err != nil {
318 t.Fatal(err)
319 }
320 conf := types.Config{Importer: importer.ForCompiler(token.NewFileSet(), "source", nil)}
321 info := &types.Info{
322 Defs: make(map[*ast.Ident]types.Object),
323 }
324 srcpkg, err := conf.Check("src/p", fset, []*ast.File{f}, info)
325 if err != nil {
326 t.Fatal(err)
327 }
328
329 // Export binary export data then reload it as a new package, "bin".
330 var buf bytes.Buffer
331 if err := gcexportdata.Write(&buf, fset, srcpkg); err != nil {
332 t.Fatal(err)
333 }
334
335 imports := make(map[string]*types.Package)
336 binpkg, err := gcexportdata.Read(&buf, fset, imports, "bin/p")
337 if err != nil {
338 t.Fatal(err)
339 }
340
341 // Now find the correspondences between them.
342 for _, srcobj := range info.Defs {
343 if srcobj == nil {
344 continue // e.g. package declaration
345 }
346 if _, ok := srcobj.(*types.PkgName); ok {
347 continue // PkgName has no objectpath
348 }
349
350 path, err := objectpath.For(srcobj)
351 if err != nil {
352 t.Errorf("For(%v): %v", srcobj, err)
353 continue
354 }
355
356 // Do we expect to find this object in the export data?
357 reachable := !strings.Contains(string(path), "unreachable")
358
359 binobj, err := objectpath.Object(binpkg, path)
360 if err != nil {
361 if reachable {
362 t.Errorf("Object(%s, %q): %v", binpkg.Path(), path, err)
363 }
364 continue
365 }
366 if !reachable {
367 t.Errorf("Object(%s, %q) = %v (unexpectedly reachable)", binpkg.Path(), path, binobj)
368 }
369
370 // Check the object strings match.
371 // (We can't check that types are identical because the
372 // objects belong to different type-checker realms.)
373 srcstr := objectString(srcobj)
374 binstr := objectString(binobj)
375 if srcstr != binstr {
376 t.Errorf("ObjectStrings do not match: Object(For(%q)) = %s, want %s",
377 path, srcstr, binstr)
378 continue
379 }
380 }
381 }
382
383 func objectString(obj types.Object) string {
384 s := types.ObjectString(obj, (*types.Package).Name)
385
386 // The printing of interface methods changed in go1.11.
387 // This work-around makes the specific test pass with earlier versions.
388 s = strings.Replace(s, "func (interface).Method", "func (p.Foo).Method", -1)
389
390 return s
391 }
392
393 // TestOrdering verifies that the compiler and go/types emit methods in the same order.
394 //
395 // See golang/go#78495.
396 func TestOrdering(t *testing.T) {
397 testenv.NeedsGoPackages(t)
398
399 const src = `-- go.mod --
400 module x.io
401
402 -- p/p.go --
403 package p
404
405 type T struct{ A int }
406
407 func (T) X() { }
408 func (T) Y() { }
409 func (T) M() { }
410 func (T) N() { }
411 `
412 fs, err := txtar.FS(txtar.Parse([]byte(src)))
413 if err != nil {
414 t.Fatal(err)
415 }
416 dir := testfiles.CopyToTmp(t, fs)
417
418 loadPackageWithMode := func(mode packages.LoadMode) *packages.Package {
419 cfg := &packages.Config{
420 Mode: mode,
421 Dir: dir,
422 Env: append(os.Environ(),
423 "GO111MODULES=on",
424 "GOPATH=",
425 "GOWORK=off",
426 "GOPROXY=off"),
427 }
428 pkgs, err := packages.Load(cfg, "x.io/p")
429 if err != nil {
430 t.Fatal(err)
431 }
432 if num := packages.PrintErrors(pkgs); num > 0 {
433 t.Fatalf("packages contained %d errors", num)
434 }
435 if len(pkgs) != 1 {
436 t.Fatalf("packages.Load returned %d packages, want 1", len(pkgs))
437 }
438 return pkgs[0]
439 }
440
441 // Load the package from compiler export data.
442 binpkg := loadPackageWithMode(packages.NeedExportFile | packages.NeedTypes)
443 // load the pacakge from typed syntax tree.
444 srcpkg := loadPackageWithMode(packages.LoadSyntax)
445
446 // objectpath encodes concrete methods by their go/types method index.
447 // Verify that paths produced from source-loaded types resolve to the same
448 // methods in compiler export data.
449 srcNamed := srcpkg.Types.Scope().Lookup("T").Type().(*types.Named)
450
451 for srcMethod := range srcNamed.Methods() {
452 path, err := objectpath.For(srcMethod)
453 if err != nil {
454 t.Fatalf("For(%s): %v", srcMethod.Name(), err)
455 }
456
457 binObj, err := objectpath.Object(binpkg.Types, path)
458 if err != nil {
459 t.Fatalf("Object(%q): %v", path, err)
460 }
461
462 if binObj.Name() != srcMethod.Name() {
463 t.Errorf("Object(%q) = %s, want %s", path, binObj.Name(), srcMethod.Name())
464 }
465 }
466
467 binNamed := binpkg.Types.Scope().Lookup("T").Type().(*types.Named)
468 for binMethod := range binNamed.Methods() {
469 path, err := objectpath.For(binMethod)
470 if err != nil {
471 t.Fatalf("For(%s): %v", binMethod.Name(), err)
472 }
473
474 srcObj, err := objectpath.Object(srcpkg.Types, path)
475 if err != nil {
476 t.Fatalf("Object(%q): %v", path, err)
477 }
478
479 if srcObj.Name() != binMethod.Name() {
480 t.Errorf("Object(%q) = %s, want %s", path, srcObj.Name(), binMethod.Name())
481 }
482 }
483 }
484
485 func TestIssue70418(t *testing.T) {
486 // This cyclic structure exhibited a bug (go.dev/issues/70418)
487 // with the seenMethods map that causes a lot of gopls crashes.
488 // objectpath would inspect the methods of I:
489 // - First we see I.A, which leads to Anon, to F, which is marked as seen.
490 // - Second we see I.F, embedded via alias Anon.
491 // Since we've already seen F, we break ouf the the interface method loop.
492 // - Third, we fail to visit I.Z.
493 // The solution is to skip only I.F, not the rest of the interface.
494
495 const src = `
496 -- go.mod --
497 module example.com
498
499 -- p/p.go --
500 package p
501
502 type Anon = interface{ F() }
503
504 type I interface {
505 A(Anon)
506 Z()
507 Anon
508 }
509 `
510 pkgmap := loadPackages(t, src, "./p")
511 pkg := pkgmap["example.com/p"].Types
512 Z, _ := types.LookupSelection(pkg.Scope().Lookup("I").Type(), false, pkg, "Z")
513 _, err := objectpath.For(Z.Obj())
514 if err != nil {
515 t.Fatalf("objectpath.For(Z) failed: %v", err)
516 }
517 }