Debian Codegraph @

internal/gcimporter/gcimporter_test.go

raw symbols SCIP
1 // Copyright 2011 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 // This file is a copy of $GOROOT/src/go/internal/gcimporter/gcimporter_test.go,
6 // adjusted to make it build with code from (std lib) internal/testenv copied.
7
8 package gcimporter_test
9
10 import (
11 "bytes"
12 "fmt"
13 "go/ast"
14 "go/constant"
15 goimporter "go/importer"
16 goparser "go/parser"
17 "go/token"
18 "go/types"
19 "os"
20 "os/exec"
21 "path"
22 "path/filepath"
23 "runtime"
24 "sort"
25 "strings"
26 "sync"
27 "testing"
28 "time"
29
30 "golang.org/x/tools/internal/gcimporter"
31 "golang.org/x/tools/internal/goroot"
32 "golang.org/x/tools/internal/testenv"
33 )
34
35 func TestMain(m *testing.M) {
36 testenv.ExitIfSmallMachine()
37 os.Exit(m.Run())
38 }
39
40 // ----------------------------------------------------------------------------
41
42 func needsCompiler(t *testing.T, compiler string) {
43 if runtime.Compiler == compiler {
44 return
45 }
46 switch compiler {
47 case "gc":
48 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
49 }
50 }
51
52 // compile runs the compiler on filename, with dirname as the working directory,
53 // and writes the output file to outdirname.
54 // compile gives the resulting package a packagepath of p.
55 func compile(t *testing.T, dirname, filename, outdirname string, packagefiles map[string]string) string {
56 return compilePkg(t, dirname, filename, outdirname, packagefiles, "p")
57 }
58
59 func compilePkg(t *testing.T, dirname, filename, outdirname string, packagefiles map[string]string, pkg string) string {
60 testenv.NeedsGoBuild(t)
61
62 // filename must end with ".go"
63 basename := strings.TrimSuffix(filepath.Base(filename), ".go")
64 ok := filename != basename
65 if !ok {
66 t.Fatalf("filename doesn't end in .go: %s", filename)
67 }
68 objname := basename + ".o"
69 outname := filepath.Join(outdirname, objname)
70
71 importcfgfile := os.DevNull
72 if len(packagefiles) > 0 {
73 importcfgfile = filepath.Join(outdirname, basename) + ".importcfg"
74 importcfg := new(bytes.Buffer)
75 fmt.Fprintf(importcfg, "# import config")
76 for k, v := range packagefiles {
77 fmt.Fprintf(importcfg, "\npackagefile %s=%s\n", k, v)
78 }
79 if err := os.WriteFile(importcfgfile, importcfg.Bytes(), 0655); err != nil {
80 t.Fatal(err)
81 }
82 }
83
84 importreldir := strings.ReplaceAll(outdirname, string(os.PathSeparator), "/")
85 cmd := exec.Command("go", "tool", "compile", "-p", pkg, "-D", importreldir, "-importcfg", importcfgfile, "-o", outname, filename)
86 cmd.Dir = dirname
87 if out, err := cmd.CombinedOutput(); err != nil {
88 t.Logf("%s", out)
89 t.Fatalf("go tool compile %s failed: %s", filename, err)
90 }
91 return outname
92 }
93
94 func testPath(t *testing.T, path, srcDir string) *types.Package {
95 t0 := time.Now()
96 pkg, err := gcimporter.Import(token.NewFileSet(), make(map[string]*types.Package), path, srcDir, nil)
97 if err != nil {
98 t.Errorf("testPath(%s): %s", path, err)
99 return nil
100 }
101 t.Logf("testPath(%s): %v", path, time.Since(t0))
102 return pkg
103 }
104
105 func mktmpdir(t *testing.T) string {
106 tmpdir, err := os.MkdirTemp("", "gcimporter_test")
107 if err != nil {
108 t.Fatal("mktmpdir:", err)
109 }
110 if err := os.Mkdir(filepath.Join(tmpdir, "testdata"), 0700); err != nil {
111 os.RemoveAll(tmpdir)
112 t.Fatal("mktmpdir:", err)
113 }
114 return tmpdir
115 }
116
117 const testfile = "exports.go"
118
119 func TestImportTestdata(t *testing.T) {
120 needsCompiler(t, "gc")
121 testenv.NeedsGoBuild(t) // to find stdlib export data in the build cache
122
123 tmpdir := mktmpdir(t)
124 defer os.RemoveAll(tmpdir)
125
126 packageFiles := map[string]string{}
127 for _, pkg := range []string{"go/ast", "go/token"} {
128 export, _, err := gcimporter.FindPkg(pkg, "testdata")
129 if export == "" {
130 t.Fatalf("no export data found for %s: %s", pkg, err)
131 }
132 packageFiles[pkg] = export
133 }
134
135 compile(t, "testdata", testfile, filepath.Join(tmpdir, "testdata"), packageFiles)
136
137 // filename should end with ".go"
138 filename := testfile[:len(testfile)-3]
139 if pkg := testPath(t, "./testdata/"+filename, tmpdir); pkg != nil {
140 // The package's Imports list must include all packages
141 // explicitly imported by testfile, plus all packages
142 // referenced indirectly via exported objects in testfile.
143 // With the textual export format (when run against Go1.6),
144 // the list may also include additional packages that are
145 // not strictly required for import processing alone (they
146 // are exported to err "on the safe side").
147 // For now, we just test the presence of a few packages
148 // that we know are there for sure.
149 got := fmt.Sprint(pkg.Imports())
150 wants := []string{"go/ast", "go/token", "go/ast"}
151 for _, want := range wants {
152 if !strings.Contains(got, want) {
153 t.Errorf(`Package("exports").Imports() = %s, does not contain %s`, got, want)
154 }
155 }
156 }
157 }
158
159 func TestImportTypeparamTests(t *testing.T) {
160 if testing.Short() {
161 t.Skipf("in short mode, skipping test that requires export data for all of std")
162 }
163
164 testenv.NeedsGoBuild(t) // to find stdlib export data in the build cache
165 testenv.NeedsGOROOTDir(t, "test")
166
167 // This package only handles gc export data.
168 if runtime.Compiler != "gc" {
169 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
170 }
171
172 tmpdir := mktmpdir(t)
173 defer os.RemoveAll(tmpdir)
174
175 // Check go files in test/typeparam, except those that fail for a known
176 // reason.
177 rootDir := filepath.Join(runtime.GOROOT(), "test", "typeparam")
178 list, err := os.ReadDir(rootDir)
179 if err != nil {
180 t.Fatal(err)
181 }
182
183 for _, entry := range list {
184 if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") {
185 // For now, only consider standalone go files.
186 continue
187 }
188
189 t.Run(entry.Name(), func(t *testing.T) {
190 filename := filepath.Join(rootDir, entry.Name())
191 src, err := os.ReadFile(filename)
192 if err != nil {
193 t.Fatal(err)
194 }
195 if !bytes.HasPrefix(src, []byte("// run")) && !bytes.HasPrefix(src, []byte("// compile")) {
196 // We're bypassing the logic of run.go here, so be conservative about
197 // the files we consider in an attempt to make this test more robust to
198 // changes in test/typeparams.
199 t.Skipf("not detected as a run test")
200 }
201
202 // Compile and import, and compare the resulting package with the package
203 // that was type-checked directly.
204 pkgFiles, err := goroot.PkgfileMap()
205 if err != nil {
206 t.Fatal(err)
207 }
208 compile(t, rootDir, entry.Name(), filepath.Join(tmpdir, "testdata"), pkgFiles)
209 pkgName := strings.TrimSuffix(entry.Name(), ".go")
210 imported := importPkg(t, "./testdata/"+pkgName, tmpdir)
211 checked := checkFile(t, filename, src)
212
213 seen := make(map[string]bool)
214 for _, name := range imported.Scope().Names() {
215 if !token.IsExported(name) {
216 continue // ignore synthetic names like .inittask and .dict.*
217 }
218 seen[name] = true
219
220 importedObj := imported.Scope().Lookup(name)
221 got := types.ObjectString(importedObj, types.RelativeTo(imported))
222
223 checkedObj := checked.Scope().Lookup(name)
224 if checkedObj == nil {
225 t.Fatalf("imported object %q was not type-checked", name)
226 }
227 want := types.ObjectString(checkedObj, types.RelativeTo(checked))
228
229 if got != want {
230 t.Errorf("imported %q as %q, want %q", name, got, want)
231 }
232 }
233
234 for _, name := range checked.Scope().Names() {
235 if !token.IsExported(name) || seen[name] {
236 continue
237 }
238 t.Errorf("did not import object %q", name)
239 }
240 })
241 }
242 }
243
244 func checkFile(t *testing.T, filename string, src []byte) *types.Package {
245 fset := token.NewFileSet()
246 f, err := goparser.ParseFile(fset, filename, src, 0)
247 if err != nil {
248 t.Fatal(err)
249 }
250 config := types.Config{
251 Importer: goimporter.Default(),
252 }
253 pkg, err := config.Check("", fset, []*ast.File{f}, nil)
254 if err != nil {
255 t.Fatal(err)
256 }
257 return pkg
258 }
259
260 func TestVersionHandling(t *testing.T) {
261 // This package only handles gc export data.
262 needsCompiler(t, "gc")
263
264 const dir = "./testdata/versions"
265 list, err := os.ReadDir(dir)
266 if err != nil {
267 t.Fatal(err)
268 }
269
270 tmpdir := mktmpdir(t)
271 defer os.RemoveAll(tmpdir)
272 corruptdir := filepath.Join(tmpdir, "testdata", "versions")
273 if err := os.Mkdir(corruptdir, 0700); err != nil {
274 t.Fatal(err)
275 }
276
277 for _, f := range list {
278 name := f.Name()
279 if !strings.HasSuffix(name, ".a") {
280 continue // not a package file
281 }
282 if strings.Contains(name, "corrupted") {
283 continue // don't process a leftover corrupted file
284 }
285 pkgpath := "./" + name[:len(name)-2]
286
287 if testing.Verbose() {
288 t.Logf("importing %s", name)
289 }
290
291 // test that export data can be imported
292 _, err := gcimporter.Import(token.NewFileSet(), make(map[string]*types.Package), pkgpath, dir, nil)
293 if err != nil {
294 t.Errorf("import %q failed: %v", pkgpath, err)
295 continue
296 }
297
298 // create file with corrupted export data
299 // 1) read file
300 data, err := os.ReadFile(filepath.Join(dir, name))
301 if err != nil {
302 t.Fatal(err)
303 }
304 // 2) find export data
305 // Index is an incorrect but 'good enough for tests' way to find the end of the export data.
306 i := bytes.Index(data, []byte("\n$$B\n")) + 5
307 j := bytes.Index(data[i:], []byte("\n$$\n")) + i
308 if i < 0 || j < 0 || i > j {
309 t.Fatalf("export data section not found (i = %d, j = %d)", i, j)
310 }
311 // 3) corrupt the data (increment every 7th byte)
312 for k := j - 13; k >= i; k -= 7 {
313 data[k]++
314 }
315 // 4) write the file
316 pkgpath += "_corrupted"
317 filename := filepath.Join(corruptdir, pkgpath) + ".a"
318 os.WriteFile(filename, data, 0666)
319
320 // test that importing the corrupted file results in an error
321 _, err = gcimporter.Import(token.NewFileSet(), make(map[string]*types.Package), pkgpath, corruptdir, nil)
322 if err == nil {
323 t.Errorf("import corrupted %q succeeded", pkgpath)
324 } else if msg := err.Error(); !strings.Contains(msg, "internal error") {
325 t.Errorf("import %q error incorrect (%s)", pkgpath, msg)
326 }
327 }
328 }
329
330 func TestImportStdLib(t *testing.T) {
331 if testing.Short() {
332 t.Skip("the imports can be expensive, and this test is especially slow when the build cache is empty")
333 }
334 // This package only handles gc export data.
335 needsCompiler(t, "gc")
336 testenv.NeedsGoBuild(t) // to find stdlib export data in the build cache
337
338 // Get list of packages in stdlib. Filter out test-only packages with {{if .GoFiles}} check.
339 var stderr bytes.Buffer
340 cmd := exec.Command("go", "list", "-f", "{{if .GoFiles}}{{.ImportPath}}{{end}}", "std")
341 cmd.Stderr = &stderr
342 out, err := cmd.Output()
343 if err != nil {
344 t.Fatalf("failed to run go list to determine stdlib packages: %v\nstderr:\n%v", err, stderr.String())
345 }
346 pkgs := strings.Fields(string(out))
347
348 var nimports int
349 for _, pkg := range pkgs {
350 t.Run(pkg, func(t *testing.T) {
351 if testPath(t, pkg, filepath.Join(testenv.GOROOT(t), "src", path.Dir(pkg))) != nil {
352 nimports++
353 }
354 })
355 }
356 const minPkgs = 225 // 'GOOS=plan9 go1.18 list std | wc -l' reports 228; most other platforms have more.
357 if len(pkgs) < minPkgs {
358 t.Fatalf("too few packages (%d) were imported", nimports)
359 }
360
361 t.Logf("tested %d imports", nimports)
362 }
363
364 var importedObjectTests = []struct {
365 name string
366 want string
367 }{
368 // non-interfaces
369 {"crypto.Hash", "type Hash uint"},
370 {"go/ast.ObjKind", "type ObjKind int"},
371 {"go/types.Qualifier", "type Qualifier func(*Package) string"},
372 {"go/types.Comparable", "func Comparable(T Type) bool"},
373 {"math.Pi", "const Pi untyped float"},
374 {"math.Sin", "func Sin(x float64) float64"},
375 {"go/ast.NotNilFilter", "func NotNilFilter(_ string, v reflect.Value) bool"},
376
377 // interfaces
378 {"context.Context", "type Context interface{Deadline() (deadline time.Time, ok bool); Done() <-chan struct{}; Err() error; Value(key any) any}"},
379 {"crypto.Decrypter", "type Decrypter interface{Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error); Public() PublicKey}"},
380 {"encoding.BinaryMarshaler", "type BinaryMarshaler interface{MarshalBinary() (data []byte, err error)}"},
381 {"io.Reader", "type Reader interface{Read(p []byte) (n int, err error)}"},
382 {"io.ReadWriter", "type ReadWriter interface{Reader; Writer}"},
383 {"go/ast.Node", "type Node interface{End() go/token.Pos; Pos() go/token.Pos}"},
384 {"go/types.Type", "type Type interface{String() string; Underlying() Type}"},
385 }
386
387 func TestImportedTypes(t *testing.T) {
388 // This package only handles gc export data.
389 needsCompiler(t, "gc")
390 testenv.NeedsGoBuild(t) // to find stdlib export data in the build cache
391
392 for _, test := range importedObjectTests {
393 obj := importObject(t, test.name)
394 if obj == nil {
395 continue // error reported elsewhere
396 }
397 got := types.ObjectString(obj, types.RelativeTo(obj.Pkg()))
398
399 // TODO(rsc): Delete this block once go.dev/cl/368254 lands.
400 if got != test.want && test.want == strings.ReplaceAll(got, "interface{}", "any") {
401 got = test.want
402 }
403
404 if got != test.want {
405 t.Errorf("%s: got %q; want %q", test.name, got, test.want)
406 }
407
408 if named, _ := types.Unalias(obj.Type()).(*types.Named); named != nil {
409 verifyInterfaceMethodRecvs(t, named, 0)
410 }
411 }
412 }
413
414 func TestImportedConsts(t *testing.T) {
415 testenv.NeedsGoBuild(t) // to find stdlib export data in the build cache
416
417 tests := []struct {
418 name string
419 want constant.Kind
420 }{
421 {"math.Pi", constant.Float},
422 {"math.MaxFloat64", constant.Float},
423 {"math.MaxInt64", constant.Int},
424 }
425
426 for _, test := range tests {
427 obj := importObject(t, test.name)
428 if got := obj.(*types.Const).Val().Kind(); got != test.want {
429 t.Errorf("%s: imported as constant.Kind(%v), want constant.Kind(%v)", test.name, got, test.want)
430 }
431 }
432 }
433
434 // importObject imports the object specified by a name of the form
435 // <import path>.<object name>, e.g. go/types.Type.
436 //
437 // If any errors occur they are reported via t and the resulting object will
438 // be nil.
439 func importObject(t *testing.T, name string) types.Object {
440 s := strings.Split(name, ".")
441 if len(s) != 2 {
442 t.Fatal("inconsistent test data")
443 }
444 importPath := s[0]
445 objName := s[1]
446
447 pkg, err := gcimporter.Import(token.NewFileSet(), make(map[string]*types.Package), importPath, ".", nil)
448 if err != nil {
449 t.Error(err)
450 return nil
451 }
452
453 obj := pkg.Scope().Lookup(objName)
454 if obj == nil {
455 t.Errorf("%s: object not found", name)
456 return nil
457 }
458 return obj
459 }
460
461 // verifyInterfaceMethodRecvs verifies that method receiver types
462 // are named if the methods belong to a named interface type.
463 func verifyInterfaceMethodRecvs(t *testing.T, named *types.Named, level int) {
464 // avoid endless recursion in case of an embedding bug that lead to a cycle
465 if level > 10 {
466 t.Errorf("%s: embeds itself", named)
467 return
468 }
469
470 iface, _ := named.Underlying().(*types.Interface)
471 if iface == nil {
472 return // not an interface
473 }
474
475 // check explicitly declared methods
476 for m := range iface.ExplicitMethods() {
477 recv := m.Type().(*types.Signature).Recv()
478 if recv == nil {
479 t.Errorf("%s: missing receiver type", m)
480 continue
481 }
482 if recv.Type() != named {
483 t.Errorf("%s: got recv type %s; want %s", m, recv.Type(), named)
484 }
485 }
486
487 // check embedded interfaces (if they are named, too)
488 for etyp := range iface.EmbeddedTypes() {
489 // embedding of interfaces cannot have cycles; recursion will terminate
490 if etype, _ := types.Unalias(etyp).(*types.Named); etype != nil {
491 verifyInterfaceMethodRecvs(t, etype, level+1)
492 }
493 }
494 }
495
496 func TestIssue5815(t *testing.T) {
497 // This package only handles gc export data.
498 needsCompiler(t, "gc")
499 testenv.NeedsGoBuild(t) // to find stdlib export data in the build cache
500
501 pkg := importPkg(t, "strings", ".")
502
503 scope := pkg.Scope()
504 for _, name := range scope.Names() {
505 obj := scope.Lookup(name)
506 if obj.Pkg() == nil {
507 t.Errorf("no pkg for %s", obj)
508 }
509 if tname, _ := obj.(*types.TypeName); tname != nil {
510 named := types.Unalias(tname.Type()).(*types.Named)
511 for m := range named.Methods() {
512 if m.Pkg() == nil {
513 t.Errorf("no pkg for %s", m)
514 }
515 }
516 }
517 }
518 }
519
520 // Smoke test to ensure that imported methods get the correct package.
521 func TestCorrectMethodPackage(t *testing.T) {
522 // This package only handles gc export data.
523 needsCompiler(t, "gc")
524 testenv.NeedsGoBuild(t) // to find stdlib export data in the build cache
525
526 imports := make(map[string]*types.Package)
527 _, err := gcimporter.Import(token.NewFileSet(), imports, "net/http", ".", nil)
528 if err != nil {
529 t.Fatal(err)
530 }
531
532 mutex := imports["sync"].Scope().Lookup("Mutex").(*types.TypeName).Type()
533 mset := types.NewMethodSet(types.NewPointer(mutex)) // methods of *sync.Mutex
534 sel := mset.Lookup(nil, "Lock")
535 lock := sel.Obj().(*types.Func)
536 if got, want := lock.Pkg().Path(), "sync"; got != want {
537 t.Errorf("got package path %q; want %q", got, want)
538 }
539 }
540
541 func TestIssue13566(t *testing.T) {
542 // This package only handles gc export data.
543 needsCompiler(t, "gc")
544 testenv.NeedsGoBuild(t) // to find stdlib export data in the build cache
545 skipWindows(t)
546
547 tmpdir := mktmpdir(t)
548 defer os.RemoveAll(tmpdir)
549 testoutdir := filepath.Join(tmpdir, "testdata")
550
551 // b.go needs to be compiled from the output directory so that the compiler can
552 // find the compiled package a. We pass the full path to compile() so that we
553 // don't have to copy the file to that directory.
554 bpath, err := filepath.Abs(filepath.Join("testdata", "b.go"))
555 if err != nil {
556 t.Fatal(err)
557 }
558
559 jsonExport, _, err := gcimporter.FindPkg("encoding/json", "testdata")
560 if jsonExport == "" {
561 t.Fatalf("no export data found for encoding/json: %s", err)
562 }
563
564 compilePkg(t, "testdata", "a.go", testoutdir, map[string]string{"encoding/json": jsonExport}, apkg(testoutdir))
565 compile(t, testoutdir, bpath, testoutdir, map[string]string{apkg(testoutdir): filepath.Join(testoutdir, "a.o")})
566
567 // import must succeed (test for issue at hand)
568 pkg := importPkg(t, "./testdata/b", tmpdir)
569
570 // make sure all indirectly imported packages have names
571 for _, imp := range pkg.Imports() {
572 if imp.Name() == "" {
573 t.Errorf("no name for %s package", imp.Path())
574 }
575 }
576 }
577
578 func TestIssue13898(t *testing.T) {
579 // This package only handles gc export data.
580 needsCompiler(t, "gc")
581 testenv.NeedsGoBuild(t) // to find stdlib export data in the build cache
582
583 // import go/internal/gcimporter which imports go/types partially
584 imports := make(map[string]*types.Package)
585 _, err := gcimporter.Import(token.NewFileSet(), imports, "go/internal/gcimporter", ".", nil)
586 if err != nil {
587 t.Fatal(err)
588 }
589
590 // look for go/types package
591 var goTypesPkg *types.Package
592 for path, pkg := range imports {
593 if path == "go/types" {
594 goTypesPkg = pkg
595 break
596 }
597 }
598 if goTypesPkg == nil {
599 t.Fatal("go/types not found")
600 }
601
602 // look for go/types.Object type
603 obj := lookupObj(t, goTypesPkg.Scope(), "Object")
604 typ, ok := types.Unalias(obj.Type()).(*types.Named)
605 if !ok {
606 t.Fatalf("go/types.Object type is %v; wanted named type", typ)
607 }
608
609 // lookup go/types.Object.Pkg method
610 m, index, indirect := types.LookupFieldOrMethod(typ, false, nil, "Pkg")
611 if m == nil {
612 t.Fatalf("go/types.Object.Pkg not found (index = %v, indirect = %v)", index, indirect)
613 }
614
615 // the method must belong to go/types
616 if m.Pkg().Path() != "go/types" {
617 t.Fatalf("found %v; want go/types", m.Pkg())
618 }
619 }
620
621 func TestIssue15517(t *testing.T) {
622 // This package only handles gc export data.
623 needsCompiler(t, "gc")
624 skipWindows(t)
625
626 tmpdir := mktmpdir(t)
627 defer os.RemoveAll(tmpdir)
628
629 compile(t, "testdata", "p.go", filepath.Join(tmpdir, "testdata"), nil)
630
631 // Multiple imports of p must succeed without redeclaration errors.
632 // We use an import path that's not cleaned up so that the eventual
633 // file path for the package is different from the package path; this
634 // will expose the error if it is present.
635 //
636 // (Issue: Both the textual and the binary importer used the file path
637 // of the package to be imported as key into the shared packages map.
638 // However, the binary importer then used the package path to identify
639 // the imported package to mark it as complete; effectively marking the
640 // wrong package as complete. By using an "unclean" package path, the
641 // file and package path are different, exposing the problem if present.
642 // The same issue occurs with vendoring.)
643 imports := make(map[string]*types.Package)
644 for range 3 {
645 if _, err := gcimporter.Import(token.NewFileSet(), imports, "./././testdata/p", tmpdir, nil); err != nil {
646 t.Fatal(err)
647 }
648 }
649 }
650
651 func TestIssue15920(t *testing.T) {
652 // This package only handles gc export data.
653 needsCompiler(t, "gc")
654 skipWindows(t)
655
656 compileAndImportPkg(t, "issue15920")
657 }
658
659 func TestIssue20046(t *testing.T) {
660 // This package only handles gc export data.
661 needsCompiler(t, "gc")
662 skipWindows(t)
663
664 // "./issue20046".V.M must exist
665 pkg := compileAndImportPkg(t, "issue20046")
666 obj := lookupObj(t, pkg.Scope(), "V")
667 if m, index, indirect := types.LookupFieldOrMethod(obj.Type(), false, nil, "M"); m == nil {
668 t.Fatalf("V.M not found (index = %v, indirect = %v)", index, indirect)
669 }
670 }
671
672 func TestIssue25301(t *testing.T) {
673 // This package only handles gc export data.
674 needsCompiler(t, "gc")
675 skipWindows(t)
676
677 compileAndImportPkg(t, "issue25301")
678 }
679
680 func TestIssue51836(t *testing.T) {
681 // This package only handles gc export data.
682 needsCompiler(t, "gc")
683 skipWindows(t)
684
685 tmpdir := mktmpdir(t)
686 defer os.RemoveAll(tmpdir)
687 testoutdir := filepath.Join(tmpdir, "testdata")
688
689 dir := filepath.Join("testdata", "issue51836")
690 // Following the pattern of TestIssue13898, aa.go needs to be compiled from
691 // the output directory. We pass the full path to compile() so that we don't
692 // have to copy the file to that directory.
693 aapath, err := filepath.Abs(filepath.Join(dir, "aa.go"))
694 if err != nil {
695 t.Fatal(err)
696 }
697 compilePkg(t, dir, "a.go", testoutdir, nil, apkg(testoutdir))
698 compile(t, testoutdir, aapath, testoutdir, map[string]string{apkg(testoutdir): filepath.Join(testoutdir, "a.o")})
699
700 // import must succeed (test for issue at hand)
701 _ = importPkg(t, "./testdata/aa", tmpdir)
702 }
703
704 func TestIssue61561(t *testing.T) {
705 const src = `package p
706
707 type I[P any] interface {
708 m(P)
709 n() P
710 }
711
712 type J = I[int]
713
714 type StillBad[P any] *interface{b(P)}
715
716 type K = StillBad[string]
717 `
718 fset := token.NewFileSet()
719 f, err := goparser.ParseFile(fset, "p.go", src, 0)
720 if f == nil {
721 // Some test cases may have parse errors, but we must always have a
722 // file.
723 t.Fatalf("ParseFile returned nil file. Err: %v", err)
724 }
725
726 config := &types.Config{}
727 pkg1, err := config.Check("p", fset, []*ast.File{f}, nil)
728 if err != nil {
729 t.Fatal(err)
730 }
731
732 // Export it. (Shallowness isn't important here.)
733 data, err := gcimporter.IExportShallow(fset, pkg1, nil)
734 if err != nil {
735 t.Fatalf("export: %v", err) // any failure to export is a bug
736 }
737
738 // Re-import it.
739 imports := make(map[string]*types.Package)
740 pkg2, err := gcimporter.IImportShallow(fset, gcimporter.GetPackagesFromMap(imports), data, "p", nil)
741 if err != nil {
742 t.Fatalf("import: %v", err) // any failure of IExport+IImport is a bug.
743 }
744
745 insts := []types.Type{
746 pkg2.Scope().Lookup("J").Type(),
747 // This test is still racy, because the incomplete interface is contained
748 // within a nested type expression.
749 //
750 // Uncomment this once golang/go#61561 is fixed.
751 // pkg2.Scope().Lookup("K").Type().Underlying().(*types.Pointer).Elem(),
752 }
753
754 // Use the interface instances concurrently.
755 for _, inst := range insts {
756 var wg sync.WaitGroup
757 for range 2 {
758 wg.Go(func() {
759 _ = types.NewMethodSet(inst)
760 })
761 }
762 wg.Wait()
763 }
764 }
765
766 func TestIssue57015(t *testing.T) {
767 // This package only handles gc export data.
768 needsCompiler(t, "gc")
769 skipWindows(t)
770
771 compileAndImportPkg(t, "issue57015")
772 }
773
774 // This is a regression test for a failure to export a package
775 // containing type errors.
776 //
777 // Though the issues and tests are specific, they may be representatives of a
778 // class of exporter bugs on ill-typed code that we have yet to flush out.
779 //
780 // TODO(adonovan): systematize our search for similar problems using
781 // fuzz testing.
782 func TestExportInvalid(t *testing.T) {
783
784 tests := []struct {
785 name string
786 src string
787 objName string
788 }{
789 // The lack of a receiver causes Recv.Type=Invalid.
790 // (The type checker then treats Foo as a package-level
791 // function, inserting it into the package scope.)
792 // The exporter needs to apply the same treatment.
793 {"issue 57729", `package p; func () Foo() {}`, "Foo"},
794
795 // It must be possible to export a constant with unknown kind, even if its
796 // type is known.
797 {"issue 60605", `package p; const EPSILON float64 = 1e-`, "EPSILON"},
798
799 // We must not crash when exporting a struct with unknown package.
800 {"issue 60891", `package p; type I[P any] int; const C I[struct{}] = 42`, "C"},
801 }
802
803 for _, test := range tests {
804 t.Run(test.name, func(t *testing.T) {
805 // Parse the ill-typed input.
806 fset := token.NewFileSet()
807
808 f, err := goparser.ParseFile(fset, "p.go", test.src, 0)
809 if f == nil {
810 // Some test cases may have parse errors, but we must always have a
811 // file.
812 t.Fatalf("ParseFile returned nil file. Err: %v", err)
813 }
814
815 // Type check it, expecting errors.
816 config := &types.Config{
817 Error: func(err error) { t.Log(err) }, // don't abort at first error
818 }
819 pkg1, _ := config.Check("p", fset, []*ast.File{f}, nil)
820
821 // Export it.
822 // (Shallowness isn't important here.)
823 data, err := gcimporter.IExportShallow(fset, pkg1, nil)
824 if err != nil {
825 t.Fatalf("export: %v", err) // any failure to export is a bug
826 }
827
828 // Re-import it.
829 imports := make(map[string]*types.Package)
830 pkg2, err := gcimporter.IImportShallow(fset, gcimporter.GetPackagesFromMap(imports), data, "p", nil)
831 if err != nil {
832 t.Fatalf("import: %v", err) // any failure of IExport+IImport is a bug.
833 }
834
835 // Check that the expected object is present in both packages.
836 // We can't assert the type hasn't changed: it may have, in some cases.
837 hasObj1 := pkg1.Scope().Lookup(test.objName) != nil
838 hasObj2 := pkg2.Scope().Lookup(test.objName) != nil
839 if hasObj1 != hasObj2 {
840 t.Errorf("export+import changed Lookup(%q)!=nil: was %t, became %t", test.objName, hasObj1, hasObj2)
841 }
842 })
843 }
844 }
845
846 func TestIssue58296(t *testing.T) {
847 // Compiles packages c, b, and a where c imports b and b imports a,
848 // then imports c with stub *types.Packages for b and a, and checks that
849 // both a and b are in the Imports() of c.
850 //
851 // This is how go/packages can read the exportdata when NeedDeps is off.
852
853 // This package only handles gc export data.
854 needsCompiler(t, "gc")
855 testenv.NeedsGoBuild(t) // to find stdlib export data in the build cache
856 skipWindows(t)
857
858 tmpdir := mktmpdir(t)
859 defer os.RemoveAll(tmpdir)
860 testoutdir := filepath.Join(tmpdir, "testdata")
861
862 apkg := filepath.Join(testoutdir, "a")
863 bpkg := filepath.Join(testoutdir, "b")
864 cpkg := filepath.Join(testoutdir, "c")
865
866 srcdir := filepath.Join("testdata", "issue58296")
867 compilePkg(t, filepath.Join(srcdir, "a"), "a.go", testoutdir, nil, apkg)
868 compilePkg(t, filepath.Join(srcdir, "b"), "b.go", testoutdir, map[string]string{apkg: filepath.Join(testoutdir, "a.o")}, bpkg)
869 compilePkg(t, filepath.Join(srcdir, "c"), "c.go", testoutdir, map[string]string{bpkg: filepath.Join(testoutdir, "b.o")}, cpkg)
870
871 // The export data reader for c cannot rely on Package.Imports
872 // being populated for a or b. (For the imports {a,b} it is unset.)
873 imports := map[string]*types.Package{
874 apkg: types.NewPackage(apkg, "a"),
875 bpkg: types.NewPackage(bpkg, "b"),
876 }
877
878 // make sure a and b are both imported by c.
879 pkg, err := gcimporter.Import(token.NewFileSet(), imports, "./c", testoutdir, nil)
880 if err != nil {
881 t.Fatal(err)
882 }
883
884 var names []string
885 for _, imp := range pkg.Imports() {
886 names = append(names, imp.Name())
887 }
888 sort.Strings(names)
889
890 if got, want := strings.Join(names, ","), "a,b"; got != want {
891 t.Errorf("got imports %v for package c. wanted %v", names, want)
892 }
893 }
894
895 func TestIssueAliases(t *testing.T) {
896 // This package only handles gc export data.
897 testenv.NeedsGo1Point(t, 24)
898 needsCompiler(t, "gc")
899 testenv.NeedsGoBuild(t) // to find stdlib export data in the build cache
900 skipWindows(t)
901
902 tmpdir := mktmpdir(t)
903 defer os.RemoveAll(tmpdir)
904 testoutdir := filepath.Join(tmpdir, "testdata")
905
906 apkg := filepath.Join(testoutdir, "a")
907 bpkg := filepath.Join(testoutdir, "b")
908 cpkg := filepath.Join(testoutdir, "c")
909
910 // compile a, b and c into gc export data.
911 srcdir := filepath.Join("testdata", "aliases")
912 compilePkg(t, filepath.Join(srcdir, "a"), "a.go", testoutdir, nil, apkg)
913 compilePkg(t, filepath.Join(srcdir, "b"), "b.go", testoutdir, map[string]string{apkg: filepath.Join(testoutdir, "a.o")}, bpkg)
914 compilePkg(t, filepath.Join(srcdir, "c"), "c.go", testoutdir,
915 map[string]string{apkg: filepath.Join(testoutdir, "a.o"), bpkg: filepath.Join(testoutdir, "b.o")},
916 cpkg,
917 )
918
919 // import c from gc export data using a and b.
920 pkg, err := gcimporter.Import(token.NewFileSet(), map[string]*types.Package{
921 apkg: types.NewPackage(apkg, "a"),
922 bpkg: types.NewPackage(bpkg, "b"),
923 }, "./c", testoutdir, nil)
924 if err != nil {
925 t.Fatal(err)
926 }
927
928 // Check c's objects and types.
929 var objs []string
930 for _, imp := range pkg.Scope().Names() {
931 obj := pkg.Scope().Lookup(imp)
932 s := fmt.Sprintf("%s : %s", obj.Name(), obj.Type())
933 s = strings.ReplaceAll(s, testoutdir, "testdata")
934 objs = append(objs, s)
935 }
936 sort.Strings(objs)
937
938 want := strings.Join([]string{
939 "S : struct{F int}",
940 "T : struct{F int}",
941 "U : testdata/a.A[string]",
942 "V : testdata/a.A[int]",
943 "W : testdata/b.B[string]",
944 "X : testdata/b.B[int]",
945 "Y : testdata/c.c[string]",
946 "Z : testdata/c.c[int]",
947 "c : testdata/c.c[V any]",
948 }, ",")
949 if got := strings.Join(objs, ","); got != want {
950 t.Errorf("got imports %v for package c. wanted %v", objs, want)
951 }
952 }
953
954 // apkg returns the package "a" prefixed by (as a package) testoutdir
955 func apkg(testoutdir string) string {
956 apkg := testoutdir + "/a"
957 if os.PathSeparator != '/' {
958 apkg = strings.ReplaceAll(apkg, string(os.PathSeparator), "/")
959 }
960 return apkg
961 }
962
963 func importPkg(t *testing.T, path, srcDir string) *types.Package {
964 pkg, err := gcimporter.Import(token.NewFileSet(), make(map[string]*types.Package), path, srcDir, nil)
965 if err != nil {
966 t.Fatal(err)
967 }
968 return pkg
969 }
970
971 func compileAndImportPkg(t *testing.T, name string) *types.Package {
972 tmpdir := mktmpdir(t)
973 defer os.RemoveAll(tmpdir)
974 compile(t, "testdata", name+".go", filepath.Join(tmpdir, "testdata"), nil)
975 return importPkg(t, "./testdata/"+name, tmpdir)
976 }
977
978 func lookupObj(t *testing.T, scope *types.Scope, name string) types.Object {
979 if obj := scope.Lookup(name); obj != nil {
980 return obj
981 }
982 t.Fatalf("%s not found", name)
983 return nil
984 }
985
986 // skipWindows skips the test on windows.
987 //
988 // On windows, we have to set the -D option for the compiler to avoid having a drive
989 // letter and an illegal ':' in the import path - just skip it (see also issue #3483).
990 func skipWindows(t *testing.T) {
991 if runtime.GOOS == "windows" {
992 t.Skip("avoid dealing with relative paths/drive letters on windows")
993 }
994 }
995
996 type importMap map[string]*types.Package
997
998 func (m importMap) Import(path string) (*types.Package, error) { return m[path], nil }
999
1000 func TestIssue69912(t *testing.T) {
1001 fset := token.NewFileSet()
1002
1003 check := func(pkgname, src string, imports importMap) (*types.Package, error) {
1004 f, err := goparser.ParseFile(fset, "a.go", src, 0)
1005 if err != nil {
1006 return nil, err
1007 }
1008 config := &types.Config{
1009 Importer: imports,
1010 }
1011 return config.Check(pkgname, fset, []*ast.File{f}, nil)
1012 }
1013
1014 const libSrc = `package lib
1015
1016 type T int
1017 `
1018
1019 lib, err := check("lib", libSrc, nil)
1020 if err != nil {
1021 t.Fatalf("Checking lib: %v", err)
1022 }
1023
1024 // Export it.
1025 var out bytes.Buffer
1026 if err := gcimporter.IExportData(&out, fset, lib); err != nil {
1027 t.Fatalf("export: %v", err) // any failure to export is a bug
1028 }
1029
1030 // Re-import it.
1031 imports := make(map[string]*types.Package)
1032 _, lib2, err := gcimporter.IImportData(fset, imports, out.Bytes(), "lib")
1033 if err != nil {
1034 t.Fatalf("import: %v", err) // any failure of export+import is a bug.
1035 }
1036
1037 // Use the resulting package concurrently, via dot-imports.
1038
1039 const pSrc = `package p
1040
1041 import . "lib"
1042
1043 type S struct {
1044 f T
1045 }
1046 `
1047 importer := importMap{
1048 "lib": lib2,
1049 }
1050 var wg sync.WaitGroup
1051 for range 10 {
1052 wg.Go(func() {
1053 _, err := check("p", pSrc, importer)
1054 if err != nil {
1055 t.Errorf("check failed: %v", err)
1056 }
1057 })
1058 }
1059 wg.Wait()
1060 }
1061
1062 func TestGenericMethods(t *testing.T) {
1063 t.SkipNow() // TODO(mark): Turn on with UIR V4.
1064 // This package only handles gc export data.
1065 needsCompiler(t, "gc")
1066 skipWindows(t)
1067
1068 tmpdir := mktmpdir(t)
1069 defer os.RemoveAll(tmpdir)
1070 testoutdir := filepath.Join(tmpdir, "testdata")
1071
1072 // Following the pattern of TestIssue13898, b.go needs to be compiled from
1073 // the output directory. We pass the full path to compile() so that we don't
1074 // have to copy the file to that directory.
1075 srcdir := filepath.Join("testdata", "genmeth")
1076 bpath, err := filepath.Abs(filepath.Join(srcdir, "b.go"))
1077 if err != nil {
1078 t.Fatal(err)
1079 }
1080
1081 compilePkg(t, srcdir, "a.go", testoutdir, nil, apkg(testoutdir))
1082 compile(t, testoutdir, bpath, testoutdir, map[string]string{apkg(testoutdir): filepath.Join(testoutdir, "a.o")})
1083 }