Debian Codegraph @

go/ir/builder_test.go

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright 2013 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 ir_test
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "go/ast"
12 "go/importer"
13 "go/parser"
14 "go/token"
15 "go/types"
16 "io/fs"
17 "os"
18 "os/exec"
19 "path/filepath"
20 "reflect"
21 "runtime"
22 "sort"
23 "strings"
24 "testing"
25
26 "honnef.co/go/tools/go/ir"
27 "honnef.co/go/tools/go/ir/irutil"
28 "honnef.co/go/tools/internal/xtools-internal/expect"
29 "honnef.co/go/tools/internal/xtools-internal/testenv"
30
31 "golang.org/x/sync/errgroup"
32 "golang.org/x/tools/go/analysis/analysistest"
33 "golang.org/x/tools/go/packages"
34 )
35
36 func isEmpty(f *ir.Function) bool { return f.Blocks == nil }
37
38 // Tests that programs partially loaded from gc object files contain
39 // functions with no code for the external portions, but are otherwise ok.
40 func TestBuildPackage(t *testing.T) {
41 testenv.NeedsGoBuild(t) // for importer.Default()
42
43 input := `
44 package main
45
46 import (
47 "bytes"
48 "io"
49 "testing"
50 )
51
52 func main() {
53 var t testing.T
54 t.Parallel() // static call to external declared method
55 t.Fail() // static call to promoted external declared method
56 testing.Short() // static call to external package-level function
57
58 var w io.Writer = new(bytes.Buffer)
59 w.Write(nil) // interface invoke of external declared method
60 }
61 `
62
63 // Parse the file.
64 fset := token.NewFileSet()
65 f, err := parser.ParseFile(fset, "input.go", input, parser.SkipObjectResolution)
66 if err != nil {
67 t.Error(err)
68 return
69 }
70
71 // Build an IR program from the parsed file.
72 // Load its dependencies from gc binary export data.
73 mainPkg, _, err := irutil.BuildPackage(&types.Config{Importer: importer.Default()}, fset,
74 types.NewPackage("main", ""), []*ast.File{f}, ir.SanityCheckFunctions)
75 if err != nil {
76 t.Error(err)
77 return
78 }
79
80 // The main package, its direct and indirect dependencies are loaded.
81 deps := []string{
82 // directly imported dependencies:
83 "bytes", "io", "testing",
84 // indirect dependencies mentioned by
85 // the direct imports' export data
86 "sync", "unicode", "time",
87 }
88
89 prog := mainPkg.Prog
90 all := prog.AllPackages()
91 if len(all) <= len(deps) {
92 t.Errorf("unexpected set of loaded packages: %q", all)
93 }
94 for _, path := range deps {
95 pkg := prog.ImportedPackage(path)
96 if pkg == nil {
97 t.Errorf("package not loaded: %q", path)
98 continue
99 }
100
101 // External packages should have no function bodies (except for wrappers).
102 isExt := pkg != mainPkg
103
104 // init()
105 if isExt && !isEmpty(pkg.Func("init")) {
106 t.Errorf("external package %s has non-empty init", pkg)
107 } else if !isExt && isEmpty(pkg.Func("init")) {
108 t.Errorf("main package %s has empty init", pkg)
109 }
110
111 for _, mem := range pkg.Members {
112 switch mem := mem.(type) {
113 case *ir.Function:
114 // Functions at package level.
115 if isExt && !isEmpty(mem) {
116 t.Errorf("external function %s is non-empty", mem)
117 } else if !isExt && isEmpty(mem) {
118 t.Errorf("function %s is empty", mem)
119 }
120
121 case *ir.Type:
122 // Methods of named types T.
123 // (In this test, all exported methods belong to *T not T.)
124 if !isExt {
125 t.Fatalf("unexpected name type in main package: %s", mem)
126 }
127 mset := prog.MethodSets.MethodSet(types.NewPointer(mem.Type()))
128 for i, n := 0, mset.Len(); i < n; i++ {
129 m := prog.MethodValue(mset.At(i))
130 // For external types, only synthetic wrappers have code.
131 expExt := !strings.Contains(m.Synthetic, "wrapper")
132 if expExt && !isEmpty(m) {
133 t.Errorf("external method %s is non-empty: %s",
134 m, m.Synthetic)
135 } else if !expExt && isEmpty(m) {
136 t.Errorf("method function %s is empty: %s",
137 m, m.Synthetic)
138 }
139 }
140 }
141 }
142 }
143
144 expectedCallee := []string{
145 "(*testing.T).Parallel",
146 "(*testing.common).Fail",
147 "testing.Short",
148 "N/A",
149 }
150 callNum := 0
151 for _, b := range mainPkg.Func("main").Blocks {
152 for _, instr := range b.Instrs {
153 switch instr := instr.(type) {
154 case ir.CallInstruction:
155 call := instr.Common()
156 if want := expectedCallee[callNum]; want != "N/A" {
157 got := call.StaticCallee().String()
158 if want != got {
159 t.Errorf("call #%d from main.main: got callee %s, want %s",
160 callNum, got, want)
161 }
162 }
163 callNum++
164 }
165 }
166 }
167 if callNum != 4 {
168 t.Errorf("in main.main: got %d calls, want %d", callNum, 4)
169 }
170 }
171
172 // Tests that methods from indirect dependencies not subject to
173 // CreatePackage are created as needed.
174 func TestNoIndirectCreatePackage(t *testing.T) {
175 testenv.NeedsGoBuild(t) // for go/packages
176
177 fs := openTxtar(t, filepath.Join(analysistest.TestData(), "indirect.txtar"))
178 pkgs := loadPackages(t, fs, "testdata/a")
179 a := pkgs[0]
180
181 // Create a from syntax, its direct deps b from types, but not indirect deps c.
182 prog := ir.NewProgram(a.Fset, ir.SanityCheckFunctions|ir.PrintFunctions)
183 aSSA := prog.CreatePackage(a.Types, a.Syntax, a.TypesInfo, false)
184 for _, p := range a.Types.Imports() {
185 prog.CreatePackage(p, nil, nil, true)
186 }
187
188 // Build SSA for package a.
189 aSSA.Build()
190
191 // Find the function in the sole call in the sole block of function a.A.
192 var got string
193 for _, instr := range aSSA.Members["A"].(*ir.Function).Blocks[0].Instrs {
194 if call, ok := instr.(*ir.Call); ok {
195 f := call.Call.Value.(*ir.Function)
196 got = fmt.Sprintf("%v # %s", f, f.Synthetic)
197 break
198 }
199 }
200 want := "(testdata/c.C).F # from type information (on demand)"
201 if got != want {
202 t.Errorf("for sole call in a.A, got: <<%s>>, want <<%s>>", got, want)
203 }
204 }
205
206 // TestRuntimeTypes tests that (*Program).RuntimeTypes() includes all necessary types.
207 func TestRuntimeTypes(t *testing.T) {
208 testenv.NeedsGoBuild(t) // for importer.Default()
209
210 // TODO(adonovan): these test cases don't really make logical
211 // sense any more. Rethink.
212
213 tests := []struct {
214 input string
215 want []string
216 }{
217 // A package-level type is needed.
218 {`package A; type T struct{}; func (T) f() {}; var x any = T{}`,
219 []string{"*p.T", "p.T"},
220 },
221 // An unexported package-level type is not needed.
222 {`package B; type t struct{}; func (t) f() {}`,
223 nil,
224 },
225 // Subcomponents of type of exported package-level var are needed.
226 {`package C; import "bytes"; var V struct {*bytes.Buffer}; var x any = &V`,
227 []string{"*bytes.Buffer", "*struct{*bytes.Buffer}", "struct{*bytes.Buffer}"},
228 },
229 // Subcomponents of type of unexported package-level var are not needed.
230 {`package D; import "bytes"; var v struct {*bytes.Buffer}; var x any = v`,
231 []string{"*bytes.Buffer", "struct{*bytes.Buffer}"},
232 },
233 // Subcomponents of type of exported package-level function are needed.
234 {`package E; import "bytes"; func F(struct {*bytes.Buffer}) {}; var v any = F`,
235 []string{"*bytes.Buffer", "struct{*bytes.Buffer}"},
236 },
237 // Subcomponents of type of unexported package-level function are not needed.
238 {`package F; import "bytes"; func f(struct {*bytes.Buffer}) {}; var v any = f`,
239 []string{"*bytes.Buffer", "struct{*bytes.Buffer}"},
240 },
241 // Subcomponents of type of exported method of uninstantiated unexported type are not needed.
242 {`package G; import "bytes"; type x struct{}; func (x) G(struct {*bytes.Buffer}) {}; var v x`,
243 nil,
244 },
245 // ...unless used by MakeInterface.
246 {`package G2; import "bytes"; type x struct{}; func (x) G(struct {*bytes.Buffer}) {}; var v interface{} = x{}`,
247 []string{"*bytes.Buffer", "*p.x", "p.x", "struct{*bytes.Buffer}"},
248 },
249 // Subcomponents of type of unexported method are not needed.
250 {`package I; import "bytes"; type X struct{}; func (X) G(struct {*bytes.Buffer}) {}; var x any = X{}`,
251 []string{"*bytes.Buffer", "*p.X", "p.X", "struct{*bytes.Buffer}"},
252 },
253 // Local types aren't needed.
254 {`package J; import "bytes"; func f() { type T struct {*bytes.Buffer}; var t T; _ = t }`,
255 nil,
256 },
257 // ...unless used by MakeInterface.
258 {`package K; import "bytes"; func f() { type T struct {*bytes.Buffer}; _ = interface{}(T{}) }`,
259 []string{"*bytes.Buffer", "*p.T", "p.T"},
260 },
261 // Types used as operand of MakeInterface are needed.
262 {`package L; import "bytes"; func f() { _ = interface{}(struct{*bytes.Buffer}{}) }`,
263 []string{"*bytes.Buffer", "struct{*bytes.Buffer}"},
264 },
265 // MakeInterface is optimized away when storing to a blank.
266 {`package M; import "bytes"; var _ interface{} = struct{*bytes.Buffer}{}`,
267 nil,
268 },
269 // MakeInterface does not create runtime type for parameterized types.
270 {
271 `package N; var g interface{}; func f[S any]() { var v []S; g = v }; `,
272 nil,
273 },
274 // ...including a parameterized type boxed by a closure in the body of a method of a generic type (go.dev/issue/80055).
275 {`package O; type box[N any] struct{ n N }; type holder[N any] struct{}; func (h *holder[N]) get() any { f := func() any { return &box[N]{} }; return f() }`,
276 nil,
277 },
278 // The type []T within generic F[T] is parameterized, so not a RuntimeType.
279 // But []T within instance f[T=C] is a ground type, so a RuntimeType.
280 {`package P
281 var _ = G[C]
282 func G[U any]() { F[U]() }
283 func F[T any]() any { return []T{} }
284 type C struct{}
285 func (C) f()
286 `,
287 []string{"*p.C", "p.C"},
288 },
289 }
290 for _, test := range tests {
291 // Parse the file.
292 fset := token.NewFileSet()
293 f, err := parser.ParseFile(fset, "input.go", test.input, 0)
294 if err != nil {
295 t.Errorf("test %q: %s", test.input[:15], err)
296 continue
297 }
298
299 // Create a single-file main package.
300 // Load dependencies from gc binary export data.
301 irpkg, _, err := irutil.BuildPackage(&types.Config{Importer: importer.Default()}, fset,
302 types.NewPackage("p", ""), []*ast.File{f}, ir.SanityCheckFunctions|ir.InstantiateGenerics)
303 if err != nil {
304 t.Errorf("test %q: %s", test.input[:15], err)
305 continue
306 }
307
308 var typstrs []string
309 for _, T := range irpkg.Prog.RuntimeTypes() {
310 if types.IsInterface(T) || types.NewMethodSet(T).Len() == 0 {
311 continue // skip interfaces and types without methods
312 }
313 typstrs = append(typstrs, T.String())
314 }
315 sort.Strings(typstrs)
316
317 if !reflect.DeepEqual(typstrs, test.want) {
318 t.Errorf("test 'package %s': got %q, want %q",
319 f.Name.Name, typstrs, test.want)
320 }
321 }
322 }
323
324 // TestInit tests that synthesized init functions are correctly formed.
325 // Bare init functions omit calls to dependent init functions and the use of
326 // an init guard. They are useful in cases where the client uses a different
327 // calling convention for init functions, or cases where it is easier for a
328 // client to analyze bare init functions. Both of these aspects are used by
329 // the llgo compiler for simpler integration with gccgo's runtime library,
330 // and to simplify the analysis whereby it deduces which stores to globals
331 // can be lowered to global initializers.
332 func TestInit(t *testing.T) {
333 tests := []struct {
334 mode ir.BuilderMode
335 input, want string
336 }{
337 {0, `package A; import _ "errors"; var i int = 42`,
338 `# Name: A.init
339 # Package: A
340 # Synthetic: package initializer
341 func init():
342 0: entry P:0 S:2
343 t1 = *init$guard bool
344 if t1 goto 2 else 1
345 1: init.start P:1 S:1 idom:0
346 *init$guard = true:bool
347 t4 = errors.init() ()
348 *i = 42:int
349 jump 2
350 2: init.done P:2 S:0 idom:0
351 return
352
353 `},
354 }
355 for _, test := range tests {
356 // Create a single-file main package.
357 mainPkg, _ := buildPackage(t, test.input, test.mode)
358 name := mainPkg.Pkg.Name()
359 initFunc := mainPkg.Func("init")
360 if initFunc == nil {
361 t.Errorf("test 'package %s': no init function", name)
362 continue
363 }
364
365 var initbuf bytes.Buffer
366 _, err := initFunc.WriteTo(&initbuf)
367 if err != nil {
368 t.Errorf("test 'package %s': WriteTo: %s", name, err)
369 continue
370 }
371
372 if initbuf.String() != test.want {
373 t.Errorf("test 'package %s': got %s, want %s", name, initbuf.String(), test.want)
374 }
375 }
376 }
377
378 // TestSyntheticFuncs checks that the expected synthetic functions are
379 // created, reachable, and not duplicated.
380 func TestSyntheticFuncs(t *testing.T) {
381 const input = `package P
382 type T int
383 func (T) f() int
384 func (*T) g() int
385 var (
386 // thunks
387 a = T.f
388 b = T.f
389 c = (struct{T}).f
390 d = (struct{T}).f
391 e = (*T).g
392 f = (*T).g
393 g = (struct{*T}).g
394 h = (struct{*T}).g
395
396 // bounds
397 i = T(0).f
398 j = T(0).f
399 k = new(T).g
400 l = new(T).g
401
402 // wrappers
403 m interface{} = struct{T}{}
404 n interface{} = struct{T}{}
405 o interface{} = struct{*T}{}
406 p interface{} = struct{*T}{}
407 q interface{} = new(struct{T})
408 r interface{} = new(struct{T})
409 s interface{} = new(struct{*T})
410 t interface{} = new(struct{*T})
411 )
412 `
413 pkg, _ := buildPackage(t, input, ir.BuilderMode(0))
414
415 // Enumerate reachable synthetic functions
416 want := map[string]string{
417 "(*P.T).g$bound": "bound method wrapper for func (*P.T).g() int",
418 "(P.T).f$bound": "bound method wrapper for func (P.T).f() int",
419
420 "(*P.T).g$thunk": "thunk for func (*P.T).g() int",
421 "(P.T).f$thunk": "thunk for func (P.T).f() int",
422 "(struct{*P.T}).g$thunk": "thunk for func (*P.T).g() int",
423 "(struct{P.T}).f$thunk": "thunk for func (P.T).f() int",
424
425 "(*P.T).f": "wrapper for func (P.T).f() int",
426 "(*struct{*P.T}).f": "wrapper for func (P.T).f() int",
427 "(*struct{*P.T}).g": "wrapper for func (*P.T).g() int",
428 "(*struct{P.T}).f": "wrapper for func (P.T).f() int",
429 "(*struct{P.T}).g": "wrapper for func (*P.T).g() int",
430 "(struct{*P.T}).f": "wrapper for func (P.T).f() int",
431 "(struct{*P.T}).g": "wrapper for func (*P.T).g() int",
432 "(struct{P.T}).f": "wrapper for func (P.T).f() int",
433
434 "P.init": "package initializer",
435 }
436 var seen []string // may contain dups
437 for fn := range irutil.AllFunctions(pkg.Prog) {
438 if fn.Synthetic == "" {
439 continue
440 }
441 name := fn.String()
442 wantDescr, ok := want[name]
443 if !ok {
444 t.Errorf("got unexpected/duplicate func: %q: %q", name, fn.Synthetic)
445 continue
446 }
447 seen = append(seen, name)
448
449 if wantDescr != fn.Synthetic {
450 t.Errorf("(%s).Synthetic = %q, want %q", name, fn.Synthetic, wantDescr)
451 }
452 }
453
454 for _, name := range seen {
455 delete(want, name)
456 }
457 for fn, descr := range want {
458 t.Errorf("want func: %q: %q", fn, descr)
459 }
460 }
461
462 // TestPhiElimination ensures that dead phis, including those that
463 // participate in a cycle, are properly eliminated.
464 func TestPhiElimination(t *testing.T) {
465 const input = `
466 package p
467
468 func f() error
469
470 func g(slice []int) {
471 for {
472 for range slice {
473 // e should not be lifted to a dead φ-node.
474 e := f()
475 h(e)
476 }
477 }
478 }
479
480 func h(error)
481 `
482 // The IR code for this function should look something like this:
483 // 0:
484 // jump 1
485 // 1:
486 // t0 = len(slice)
487 // jump 2
488 // 2:
489 // t1 = phi [1: -1:int, 3: t2]
490 // t2 = t1 + 1:int
491 // t3 = t2 < t0
492 // if t3 goto 3 else 1
493 // 3:
494 // t4 = f()
495 // t5 = h(t4)
496 // jump 2
497 //
498 // But earlier versions of the IR construction algorithm would
499 // additionally generate this cycle of dead phis:
500 //
501 // 1:
502 // t7 = phi [0: nil:error, 2: t8] #e
503 // ...
504 // 2:
505 // t8 = phi [1: t7, 3: t4] #e
506 // ...
507
508 p, _ := buildPackage(t, input, ir.BuilderMode(0))
509 g := p.Func("g")
510
511 phis := 0
512 for _, b := range g.Blocks {
513 for _, instr := range b.Instrs {
514 if _, ok := instr.(*ir.Phi); ok {
515 phis++
516 }
517 }
518 }
519 if phis != 1 {
520 g.WriteTo(os.Stderr)
521 t.Errorf("expected a single Phi (for the range index), got %d", phis)
522 }
523 }
524
525 // TestGenericDecls ensures that *unused* generic types, methods and functions
526 // signatures can be built.
527 //
528 // TODO(taking): Add calls from non-generic functions to instantiations of generic functions.
529 // TODO(taking): Add globals with types that are instantiations of generic functions.
530 func TestGenericDecls(t *testing.T) {
531 const input = `
532 package p
533
534 import "unsafe"
535
536 type Pointer[T any] struct {
537 v unsafe.Pointer
538 }
539
540 func (x *Pointer[T]) Load() *T {
541 return (*T)(LoadPointer(&x.v))
542 }
543
544 func Load[T any](x *Pointer[T]) *T {
545 return x.Load()
546 }
547
548 func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer)
549 `
550 // The SSA members for this package should look something like this:
551 // func LoadPointer func(addr *unsafe.Pointer) (val unsafe.Pointer)
552 // type Pointer struct{v unsafe.Pointer}
553 // method (*Pointer[T any]) Load() *T
554 // func init func()
555 // var init$guard bool
556
557 p, _ := buildPackage(t, input, ir.BuilderMode(0))
558
559 if load := p.Func("Load"); load.Signature.TypeParams().Len() != 1 {
560 t.Errorf("expected a single type param T for Load got %q", load.Signature)
561 }
562 if ptr := p.Type("Pointer"); ptr.Type().(*types.Named).TypeParams().Len() != 1 {
563 t.Errorf("expected a single type param T for Pointer got %q", ptr.Type())
564 }
565 }
566
567 func TestGenericWrappers(t *testing.T) {
568 const input = `
569 package p
570
571 type S[T any] struct {
572 t *T
573 }
574
575 func (x S[T]) M() T {
576 return *(x.t)
577 }
578
579 var thunk = S[int].M
580
581 var g S[int]
582 var bound = g.M
583
584 type R[T any] struct{ S[T] }
585
586 var indirect = R[int].M
587 `
588 // The relevant SSA members for this package should look something like this:
589 // var bound func() int
590 // var thunk func(S[int]) int
591 // var wrapper func(R[int]) int
592
593 for _, mode := range []ir.BuilderMode{ir.BuilderMode(0), ir.InstantiateGenerics} {
594 p, _ := buildPackage(t, input, mode)
595
596 for _, entry := range []struct {
597 name string // name of the package variable
598 typ string // type of the package variable
599 wrapper string // wrapper function to which the package variable is set
600 callee string // callee within the wrapper function
601 }{
602 {
603 "bound",
604 "*func() int",
605 "(p.S[int]).M$bound",
606 "(p.S[int]).M",
607 },
608 {
609 "thunk",
610 "*func(p.S[int]) int",
611 "(p.S[int]).M$thunk",
612 "(p.S[int]).M",
613 },
614 {
615 "indirect",
616 "*func(p.R[int]) int",
617 "(p.R[int]).M$thunk",
618 "(p.S[int]).M",
619 },
620 } {
621 t.Run(entry.name, func(t *testing.T) {
622 v := p.Var(entry.name)
623 if v == nil {
624 t.Fatalf("Did not find variable for %q in %s", entry.name, p.String())
625 }
626 if v.Type().String() != entry.typ {
627 t.Errorf("Expected type for variable %s: %q. got %q", v, entry.typ, v.Type())
628 }
629
630 // Find the wrapper for v. This is stored exactly once in init.
631 var wrapper *ir.Function
632 for _, bb := range p.Func("init").Blocks {
633 for _, i := range bb.Instrs {
634 if store, ok := i.(*ir.Store); ok && v == store.Addr {
635 switch val := store.Val.(type) {
636 case *ir.Function:
637 wrapper = val
638 case *ir.MakeClosure:
639 wrapper = val.Fn.(*ir.Function)
640 }
641 }
642 }
643 }
644 if wrapper == nil {
645 t.Fatalf("failed to find wrapper function for %s", entry.name)
646 }
647 if wrapper.String() != entry.wrapper {
648 t.Errorf("Expected wrapper function %q. got %q", wrapper, entry.wrapper)
649 }
650
651 // Find the callee within the wrapper. There should be exactly one call.
652 var callee *ir.Function
653 for _, bb := range wrapper.Blocks {
654 for _, i := range bb.Instrs {
655 if call, ok := i.(*ir.Call); ok {
656 callee = call.Call.StaticCallee()
657 }
658 }
659 }
660 if callee == nil {
661 t.Fatalf("failed to find callee within wrapper %s", wrapper)
662 }
663 if callee.String() != entry.callee {
664 t.Errorf("Expected callee in wrapper %q is %q. got %q", v, entry.callee, callee)
665 }
666 })
667 }
668 }
669 }
670
671 // TestTypeparamTest builds SSA over compilable examples in $GOROOT/test/typeparam/*.go.
672
673 func TestTypeparamTest(t *testing.T) {
674 testenv.NeedsGOROOTDir(t, "test")
675
676 // Tests use a fake goroot to stub out standard libraries with declarations in
677 // testdata/src. Decreases runtime from ~80s to ~1s.
678
679 if runtime.GOARCH == "wasm" {
680 // Consistent flakes on wasm (#64726, #69409, #69410).
681 // Needs more investigation, but more likely a wasm issue
682 // Disabling for now.
683 t.Skip("Consistent flakes on wasm (e.g. https://go.dev/issues/64726)")
684 }
685
686 // located GOROOT based on the relative path of errors in $GOROOT/src/errors
687 stdPkgs, err := packages.Load(&packages.Config{
688 Mode: packages.NeedFiles,
689 }, "errors")
690 if err != nil {
691 t.Fatalf("Failed to load errors package from std: %s", err)
692 }
693 goroot := filepath.Dir(filepath.Dir(filepath.Dir(stdPkgs[0].GoFiles[0])))
694 dir := filepath.Join(goroot, "test", "typeparam")
695 if _, err = os.Stat(dir); errors.Is(err, os.ErrNotExist) {
696 t.Skipf("test/typeparam doesn't exist under GOROOT %s", goroot)
697 }
698
699 // Collect all of the .go files in
700 fsys := os.DirFS(dir)
701 entries, err := fs.ReadDir(fsys, ".")
702 if err != nil {
703 t.Fatal(err)
704 }
705
706 // Each call to buildPackage calls package.Load, which invokes "go list",
707 // and with over 300 subtests this can be very slow (minutes, or tens
708 // on some platforms). So, we use an overlay to map each test file to a
709 // distinct single-file package and load them all at once.
710 overlay := map[string][]byte{
711 "go.mod": goMod("example.com", -1),
712 }
713 for _, entry := range entries {
714 if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") {
715 continue // Consider standalone go files.
716 }
717 src, err := fs.ReadFile(fsys, entry.Name())
718 if err != nil {
719 t.Fatal(err)
720 }
721 // Only build test files that can be compiled, or compiled and run.
722 if !bytes.HasPrefix(src, []byte("// run")) && !bytes.HasPrefix(src, []byte("// compile")) {
723 t.Logf("%s: not detected as a run test", entry.Name())
724 continue
725 }
726
727 filename := fmt.Sprintf("%s/main.go", entry.Name())
728 overlay[filename] = src
729 }
730
731 // load all packages inside the overlay so 'go list' will be triggered only once.
732 pkgs := loadPackages(t, overlayFS(overlay), "./...")
733 for _, p := range pkgs {
734 originFilename := filepath.Base(filepath.Dir(p.GoFiles[0]))
735 t.Run(originFilename, func(t *testing.T) {
736 t.Parallel()
737 prog, _ := irutil.Packages([]*packages.Package{p}, ir.SanityCheckFunctions|ir.InstantiateGenerics)
738 prog.Package(p.Types).Build()
739 })
740 }
741 }
742
743 // TestOrderOfOperations ensures order of operations are as intended.
744 func TestOrderOfOperations(t *testing.T) {
745 // Testing for the order of operations within an expression is done
746 // by collecting the sequence of direct function calls within a *Function.
747 // Callees are all external functions so they cannot be safely re-ordered by ssa.
748 const input = `
749 package p
750
751 func a() int
752 func b() int
753 func c() int
754
755 func slice(s []int) []int { return s[a():b()] }
756 func sliceMax(s []int) []int { return s[a():b():c()] }
757
758 `
759
760 p, _ := buildPackage(t, input, ir.BuilderMode(0))
761
762 for _, item := range []struct {
763 fn string
764 want string // sequence of calls within the function.
765 }{
766 {"sliceMax", "[a() b() c()]"},
767 {"slice", "[a() b()]"},
768 } {
769 fn := p.Func(item.fn)
770 want := item.want
771 t.Run(item.fn, func(t *testing.T) {
772 t.Parallel()
773
774 var calls []string
775 for _, b := range fn.Blocks {
776 for _, instr := range b.Instrs {
777 if call, ok := instr.(ir.CallInstruction); ok {
778 calls = append(calls, call.String())
779 }
780 }
781 }
782 if got := fmt.Sprint(calls); got != want {
783 fn.WriteTo(os.Stderr)
784 t.Errorf("Expected sequence of function calls in %s was %s. got %s", fn, want, got)
785 }
786 })
787 }
788 }
789
790 // TestGenericFunctionSelector ensures generic functions from other packages can be selected.
791 func TestGenericFunctionSelector(t *testing.T) {
792 fsys := overlayFS(map[string][]byte{
793 "go.mod": goMod("example.com", -1),
794 "main.go": []byte(`package main; import "example.com/a"; func main() { a.F[int](); a.G[int,string](); a.H(0) }`),
795 "a/a.go": []byte(`package a; func F[T any](){}; func G[S, T any](){}; func H[T any](a T){} `),
796 })
797
798 for _, mode := range []ir.BuilderMode{
799 ir.SanityCheckFunctions,
800 ir.SanityCheckFunctions | ir.InstantiateGenerics,
801 } {
802
803 pkgs := loadPackages(t, fsys, "example.com") // package main
804 if len(pkgs) != 1 {
805 t.Fatalf("Expected 1 root package but got %d", len(pkgs))
806 }
807 prog, _ := irutil.Packages(pkgs, mode)
808 p := prog.Package(pkgs[0].Types)
809 p.Build()
810
811 if p.Pkg.Name() != "main" {
812 t.Fatalf("Expected the second package is main but got %s", p.Pkg.Name())
813 }
814 p.Build()
815
816 var callees []string // callees of the CallInstruction.String() in main().
817 for _, b := range p.Func("main").Blocks {
818 for _, i := range b.Instrs {
819 if call, ok := i.(ir.CallInstruction); ok {
820 if callee := call.Common().StaticCallee(); call != nil {
821 callees = append(callees, callee.String())
822 } else {
823 t.Errorf("CallInstruction without StaticCallee() %q", call)
824 }
825 }
826 }
827 }
828 sort.Strings(callees) // ignore the order in the code.
829
830 want := "[example.com/a.F[int] example.com/a.G[int, string] example.com/a.H[int]]"
831 if got := fmt.Sprint(callees); got != want {
832 t.Errorf("Expected main() to contain calls %v. got %v", want, got)
833 }
834 }
835 }
836
837 func TestIssue58491(t *testing.T) {
838 // Test that a local type reaches type param in instantiation.
839 src := `
840 package p
841
842 func foo[T any](blocking func() (T, error)) error {
843 type result struct {
844 res T
845 error // ensure the method set of result is non-empty
846 }
847
848 res := make(chan result, 1)
849 go func() {
850 var r result
851 r.res, r.error = blocking()
852 res <- r
853 }()
854 r := <-res
855 err := r // require the rtype for result when instantiated
856 return err
857 }
858 var Inst = foo[int]
859 `
860 fset := token.NewFileSet()
861 f, err := parser.ParseFile(fset, "p.go", src, 0)
862 if err != nil {
863 t.Fatal(err)
864 }
865 files := []*ast.File{f}
866
867 pkg := types.NewPackage("p", "")
868 conf := &types.Config{}
869 p, _, err := irutil.BuildPackage(conf, fset, pkg, files, ir.SanityCheckFunctions|ir.InstantiateGenerics)
870 if err != nil {
871 t.Fatalf("unexpected error: %v", err)
872 }
873
874 // Find the local type result instantiated with int.
875 var found bool
876 for _, rt := range p.Prog.RuntimeTypes() {
877 if n, ok := rt.(*types.Named); ok {
878 if u, ok := n.Underlying().(*types.Struct); ok {
879 found = true
880 if got, want := n.String(), "p.result"; got != want {
881 t.Errorf("Expected the name %s got: %s", want, got)
882 }
883 if got, want := u.String(), "struct{res int; error}"; got != want {
884 t.Errorf("Expected the underlying type of %s to be %s. got %s", n, want, got)
885 }
886 }
887 }
888 }
889 if !found {
890 t.Error("Failed to find any Named to struct types")
891 }
892 }
893
894 func TestIssue58491Rec(t *testing.T) {
895 // Roughly the same as TestIssue58491 but with a recursive type.
896 src := `
897 package p
898
899 func foo[T any]() error {
900 type result struct {
901 res T
902 next *result
903 error // ensure the method set of result is non-empty
904 }
905
906 r := &result{}
907 err := r // require the rtype for result when instantiated
908 return err
909 }
910 var Inst = foo[int]
911 `
912 fset := token.NewFileSet()
913 f, err := parser.ParseFile(fset, "p.go", src, 0)
914 if err != nil {
915 t.Fatal(err)
916 }
917 files := []*ast.File{f}
918
919 pkg := types.NewPackage("p", "")
920 conf := &types.Config{}
921 p, _, err := irutil.BuildPackage(conf, fset, pkg, files, ir.SanityCheckFunctions|ir.InstantiateGenerics)
922 if err != nil {
923 t.Fatalf("unexpected error: %v", err)
924 }
925
926 // Find the local type result instantiated with int.
927 var found bool
928 for _, rt := range p.Prog.RuntimeTypes() {
929 if n, ok := types.Unalias(rt).(*types.Named); ok {
930 if u, ok := n.Underlying().(*types.Struct); ok {
931 found = true
932 if got, want := n.String(), "p.result"; got != want {
933 t.Errorf("Expected the name %s got: %s", want, got)
934 }
935 if got, want := u.String(), "struct{res int; next *p.result; error}"; got != want {
936 t.Errorf("Expected the underlying type of %s to be %s. got %s", n, want, got)
937 }
938 }
939 }
940 }
941 if !found {
942 t.Error("Failed to find any Named to struct types")
943 }
944 }
945
946 // TestSyntax ensures that a function's Syntax is available.
947 func TestSyntax(t *testing.T) {
•948 t.Skip("Debian: requires github.com/google/go-cmp/cmp which is not available in the build environment")
949 const input = `package p
950
951 type P int
952 func (x *P) g() *P { return x }
953
954 func F[T ~int]() *T {
955 type S1 *T
956 type S2 *T
957 type S3 *T
958 f1 := func() S1 {
959 f2 := func() S2 {
960 return S2(nil)
961 }
962 return S1(f2())
963 }
964 f3 := func() S3 {
965 return S3(f1())
966 }
967 return (*T)(f3())
968 }
969 var g = F[int]
970 `
971
972 p, _ := buildPackage(t, input, ir.InstantiateGenerics)
973 prog := p.Prog
974
975 // Collect syntax information for all of the functions.
976 got := make(map[string]string)
977 for fn := range irutil.AllFunctions(prog) {
978 if fn.Name() == "init" {
979 continue
980 }
981 syntax := fn.Syntax()
982 if got[fn.Name()] != "" {
983 t.Error("dup")
984 }
985 got[fn.Name()] = fmt.Sprintf("%T : %s @ %d", syntax, fn.Signature, prog.Fset.Position(syntax.Pos()).Line)
986 }
987
988 // go/ssa also tests that 'var _ = F[P]' does not add F[P] and its
989 // anonymous functions because it's strictly speaking unreferenced. But in
990 // go/ir, assignment to the blank identifier is visible in the IR and it
991 // would be referenced.
992 want := map[string]string{
993 "g": "*ast.FuncDecl : func() *p.P @ 4",
994 "F": "*ast.FuncDecl : func[T ~int]() *T @ 6",
995 "F$1": "*ast.FuncLit : func() p.S1 @ 10",
996 "F$1$1": "*ast.FuncLit : func() p.S2 @ 11",
997 "F$2": "*ast.FuncLit : func() p.S3 @ 16",
998 "F[int]": "*ast.FuncDecl : func() *int @ 6",
999 "F[int]$1": "*ast.FuncLit : func() p.S1 @ 10",
1000 "F[int]$1$1": "*ast.FuncLit : func() p.S2 @ 11",
1001 "F[int]$2": "*ast.FuncLit : func() p.S3 @ 16",
1002 // ...but no F[P] etc as they are unreferenced.
1003 // (NB: GlobalDebug mode would cause them to be referenced.)
1004 }
•1005 if !reflect.DeepEqual(want, got) {
1006 t.Errorf("unexpected function signatures:\nwant: %v\ngot: %v", want, got)
1007 }
1008 }
1009
1010 func TestGo117Builtins(t *testing.T) {
1011 tests := []struct {
1012 name string
1013 src string
1014 importer types.Importer
1015 }{
1016 {"slice to array pointer", "package p; var s []byte; var _ = (*[4]byte)(s)", nil},
1017 {"unsafe slice", `package p; import "unsafe"; var _ = unsafe.Add(nil, 0)`, importer.Default()},
1018 {"unsafe add", `package p; import "unsafe"; var _ = unsafe.Slice((*int)(nil), 0)`, importer.Default()},
1019 }
1020
1021 for _, tc := range tests {
1022 t.Run(tc.name, func(t *testing.T) {
1023 t.Parallel()
1024 fset := token.NewFileSet()
1025 f, err := parser.ParseFile(fset, "p.go", tc.src, parser.ParseComments)
1026 if err != nil {
1027 t.Error(err)
1028 }
1029 files := []*ast.File{f}
1030
1031 pkg := types.NewPackage("p", "")
1032 conf := &types.Config{Importer: tc.importer}
1033 if _, _, err := irutil.BuildPackage(conf, fset, pkg, files, ir.SanityCheckFunctions); err != nil {
1034 t.Error(err)
1035 }
1036 })
1037 }
1038 }
1039
1040 // TestLabels just tests that anonymous labels are handled.
1041 func TestLabels(t *testing.T) {
1042 tests := []string{
1043 `package main
1044 func main() { _:println(1) }`,
1045 `package main
1046 func main() { _:println(1); _:println(2)}`,
1047 }
1048 for _, test := range tests {
1049 buildPackage(t, test, ir.BuilderMode(0))
1050 }
1051 }
1052
1053 func TestFixedBugs(t *testing.T) {
1054 for _, name := range []string{
1055 "issue66783a",
1056 "issue66783b",
1057 "issue73594",
1058 "issue78110",
1059 "issue73871",
1060 } {
1061 t.Run(name, func(t *testing.T) {
1062 base := name + ".go"
1063 path := filepath.Join(analysistest.TestData(), "fixedbugs", base)
1064 fset := token.NewFileSet()
1065 f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
1066 if err != nil {
1067 t.Fatal(err)
1068 }
1069 files := []*ast.File{f}
1070 pkg := types.NewPackage(name, name)
1071 mode := ir.SanityCheckFunctions | ir.InstantiateGenerics
1072 // mode |= ir.PrintFunctions // debug mode
1073 if _, _, err := irutil.BuildPackage(&types.Config{}, fset, pkg, files, mode); err != nil {
1074 t.Error(err)
1075 }
1076 })
1077 }
1078 }
1079
1080 func TestIssue67079(t *testing.T) {
1081 // This test reproduced a race in the SSA builder nearly 100% of the time.
1082
1083 // Load the package.
1084 const src = `package p; type T int; func (T) f() {}; var _ = (*T).f`
1085 spkg, ppkg := buildPackage(t, src, ir.BuilderMode(0))
1086 prog := spkg.Prog
1087 var g errgroup.Group
1088
1089 // Access bodies of all functions.
1090 g.Go(func() error {
1091 for fn := range irutil.AllFunctions(prog) {
1092 for _, b := range fn.Blocks {
1093 for _, instr := range b.Instrs {
1094 if call, ok := instr.(*ir.Call); ok {
1095 call.Common().StaticCallee() // access call.Value
1096 }
1097 }
1098 }
1099 }
1100 return nil
1101 })
1102
1103 // Force building of wrappers.
1104 g.Go(func() error {
1105 ptrT := types.NewPointer(ppkg.Types.Scope().Lookup("T").Type())
1106 ptrTf := types.NewMethodSet(ptrT).At(0) // (*T).f symbol
1107 prog.MethodValue(ptrTf)
1108 return nil
1109 })
1110
1111 g.Wait() // ignore error
1112 }
1113
1114 func TestGenericAliases(t *testing.T) {
1115 testenv.NeedsGo1Point(t, 23)
1116
1117 if os.Getenv("GENERICALIASTEST_CHILD") == "1" {
1118 testGenericAliases(t)
1119 return
1120 }
1121
1122 testenv.NeedsExec(t)
1123 testenv.NeedsTool(t, "go")
1124
1125 cmd := exec.Command(os.Args[0], "-test.run=TestGenericAliases")
1126 cmd.Env = append(os.Environ(), "GENERICALIASTEST_CHILD=1")
1127 if testenv.Go1Point() == 23 {
1128 cmd.Env = append(cmd.Env, "GOEXPERIMENT=aliastypeparams")
1129 }
1130 out, err := cmd.CombinedOutput()
1131 if len(out) > 0 {
1132 t.Logf("out=<<%s>>", out)
1133 }
1134 var exitcode int
1135 if err, ok := err.(*exec.ExitError); ok {
1136 exitcode = err.ExitCode()
1137 }
1138 const want = 0
1139 if exitcode != want {
1140 t.Errorf("exited %d, want %d", exitcode, want)
1141 }
1142 }
1143
1144 func testGenericAliases(t *testing.T) {
1145 testenv.NeedsGoExperiment(t, "aliastypeparams")
1146
1147 const source = `
1148 package p
1149
1150 type A = uint8
1151 type B[T any] = [4]T
1152
1153 var F = f[string]
1154
1155 func f[S any]() {
1156 // Two copies of f are made: p.f[S] and p.f[string]
1157
1158 var v A // application of A that is declared outside of f without no type arguments
1159 print("p.f", "String", "p.A", v)
1160 print("p.f", "==", v, uint8(0))
1161 print("p.f[string]", "String", "p.A", v)
1162 print("p.f[string]", "==", v, uint8(0))
1163
1164
1165 var u B[S] // application of B that is declared outside declared outside of f with type arguments
1166 print("p.f", "String", "p.B[S]", u)
1167 print("p.f", "==", u, [4]S{})
1168 print("p.f[string]", "String", "p.B[string]", u)
1169 print("p.f[string]", "==", u, [4]string{})
1170
1171 type C[T any] = struct{ s S; ap *B[T]} // declaration within f with type params
1172 var w C[int] // application of C with type arguments
1173 print("p.f", "String", "p.C[int]", w)
1174 print("p.f", "==", w, struct{ s S; ap *[4]int}{})
1175 print("p.f[string]", "String", "p.C[int]", w)
1176 print("p.f[string]", "==", w, struct{ s string; ap *[4]int}{})
1177 }
1178 `
1179
1180 p, _ := buildPackage(t, source, ir.InstantiateGenerics)
1181
1182 probes := callsTo(irutil.AllFunctions(p.Prog), "print")
1183 if got, want := len(probes), 3*4*2; got != want {
1184 t.Errorf("Found %v probes, expected %v", got, want)
1185 }
1186
1187 const debug = false // enable to debug skips
1188 skipped := 0
1189 for probe, fn := range probes {
1190 // Each probe is of the form:
1191 // print("within", "test", head, tail)
1192 // The probe only matches within a function whose fn.String() is within.
1193 // This allows for different instantiations of fn to match different probes.
1194 // On a match, it applies the test named "test" to head::tail.
1195 if len(probe.Args) < 3 {
1196 t.Fatalf("probe %v did not have enough arguments", probe)
1197 }
1198 within, test, head, tail := constString(probe.Args[0]), probe.Args[1], probe.Args[2], probe.Args[3:]
1199 if within != fn.String() {
1200 skipped++
1201 if debug {
1202 t.Logf("Skipping %q within %q", within, fn.String())
1203 }
1204 continue // does not match function
1205 }
1206
1207 switch test := constString(test); test {
1208 case "==": // All of the values are types.Identical.
1209 for _, v := range tail {
1210 if !types.Identical(head.Type(), v.Type()) {
1211 t.Errorf("Expected %v and %v to have identical types", head, v)
1212 }
1213 }
1214 case "String": // head is a string constant that all values in tail must match Type().String()
1215 want := constString(head)
1216 for _, v := range tail {
1217 if got := v.Type().String(); got != want {
1218 t.Errorf("%s: %v had the Type().String()=%q. expected %q", within, v, got, want)
1219 }
1220 }
1221 default:
1222 t.Errorf("%q is not a test subcommand", test)
1223 }
1224 }
1225 if want := 3 * 4; skipped != want {
1226 t.Errorf("Skipped %d probes, expected to skip %d", skipped, want)
1227 }
1228 }
1229
1230 // constString returns the value of a string constant
1231 // or "<not a constant string>" if the value is not a string constant.
1232 func constString(v ir.Value) string {
1233 if c, ok := v.(*ir.Const); ok {
1234 str := c.Value.String()
1235 return strings.Trim(str, `"`)
1236 }
1237 return "<not a constant string>"
1238 }
1239
1240 // TestMultipleGoversions tests that globals initialized to equivalent
1241 // function literals are compiled based on the different GoVersion in each file.
1242 func TestMultipleGoversions(t *testing.T) {
1243 contents := map[string]string{
1244 "post.go": `
1245 //go:build go1.22
1246 package p
1247
1248 var distinct = func(l []int) {
1249 for i := range l {
1250 print(&i)
1251 }
1252 }
1253 `,
1254 "pre.go": `
1255 package p
1256
1257 var same = func(l []int) {
1258 for i := range l {
1259 print(&i)
1260 }
1261 }
1262 `,
1263 }
1264
1265 fset := token.NewFileSet()
1266 var files []*ast.File
1267 for _, fname := range []string{"post.go", "pre.go"} {
1268 file, err := parser.ParseFile(fset, fname, contents[fname], 0)
1269 if err != nil {
1270 t.Fatal(err)
1271 }
1272 files = append(files, file)
1273 }
1274
1275 pkg := types.NewPackage("p", "")
1276 conf := &types.Config{Importer: nil, GoVersion: "go1.21"}
1277 p, _, err := irutil.BuildPackage(conf, fset, pkg, files, ir.SanityCheckFunctions)
1278 if err != nil {
1279 t.Fatal(err)
1280 }
1281
1282 // Test that global is initialized to a function literal that was
1283 // compiled to have the expected for loop range variable lifetime for i.
1284 for _, test := range []struct {
1285 global *ir.Global
1286 want string // basic block to []*ir.Alloc.
1287 }{
1288 {p.Var("same"), "map[entry:[new int (i)]]"}, // i is allocated in the entry block.
1289 {p.Var("distinct"), "map[rangeindex.body:[new int (i)]]"}, // i is allocated in the body block.
1290 } {
1291 // Find the function the test.name global is initialized to.
1292 var fn *ir.Function
1293 for _, b := range p.Func("init").Blocks {
1294 for _, instr := range b.Instrs {
1295 if s, ok := instr.(*ir.Store); ok && s.Addr == test.global {
1296 fn, _ = s.Val.(*ir.Function)
1297 }
1298 }
1299 }
1300 if fn == nil {
1301 t.Fatalf("Failed to find *ir.Function for initial value of global %s", test.global)
1302 }
1303
1304 allocs := make(map[string][]string) // block comments -> []Alloc
1305 for _, b := range fn.Blocks {
1306 for _, instr := range b.Instrs {
1307 if a, ok := instr.(*ir.Alloc); ok {
1308 allocs[b.Comment] = append(allocs[b.Comment], a.String())
1309 }
1310 }
1311 }
1312 if got := fmt.Sprint(allocs); got != test.want {
1313 t.Errorf("[%s:=%s] expected the allocations to be in the basic blocks %q, got %q", test.global, fn, test.want, got)
1314 }
1315 }
1316 }
1317
1318 // TestRangeOverInt tests that, in a range-over-int (#61405),
1319 // the type of each range var v (identified by print(v) calls)
1320 // has the expected type.
1321 func TestRangeOverInt(t *testing.T) {
1322 const rangeOverIntSrc = `
1323 package p
1324
1325 type I uint8
1326
1327 func noKey(x int) {
1328 for range x {
1329 // does not crash
1330 }
1331 }
1332
1333 func untypedConstantOperand() {
1334 for i := range 10 {
1335 print(i) /*@ types("int")*/
1336 }
1337 }
1338
1339 func unsignedOperand(x uint64) {
1340 for i := range x {
1341 print(i) /*@ types("uint64")*/
1342 }
1343 }
1344
1345 func namedOperand(x I) {
1346 for i := range x {
1347 print(i) /*@ types("p.I")*/
1348 }
1349 }
1350
1351 func typeparamOperand[T int](x T) {
1352 for i := range x {
1353 print(i) /*@ types("T")*/
1354 }
1355 }
1356
1357 func assignment(x I) {
1358 var k I
1359 for k = range x {
1360 print(k) /*@ types("p.I")*/
1361 }
1362 }
1363 `
1364
1365 fset := token.NewFileSet()
1366 f, err := parser.ParseFile(fset, "p.go", rangeOverIntSrc, parser.ParseComments)
1367 if err != nil {
1368 t.Fatal(err)
1369 }
1370
1371 pkg := types.NewPackage("p", "")
1372 conf := &types.Config{}
1373 p, _, err := irutil.BuildPackage(conf, fset, pkg, []*ast.File{f}, ir.SanityCheckFunctions)
1374 if err != nil {
1375 t.Fatal(err)
1376 }
1377
1378 // Collect all notes in f, i.e. comments starting with "//@ types".
1379 notes, err := expect.ExtractGo(fset.File(f.Pos()), f)
1380 if err != nil {
1381 t.Fatal(err)
1382 }
1383
1384 // Collect calls to the built-in print function.
1385 fns := make(map[*ir.Function]bool)
1386 for _, mem := range p.Members {
1387 if fn, ok := mem.(*ir.Function); ok {
1388 fns[fn] = true
1389 }
1390 }
1391 probes := callsTo(fns, "print")
1392 expectations := matchNotes(fset, notes, probes)
1393
1394 for call := range probes {
1395 if expectations[call] == nil {
1396 t.Errorf("Unmatched call: %v @ %s", call, fset.Position(call.Pos()))
1397 }
1398 }
1399
1400 // Check each expectation.
1401 for call, note := range expectations {
1402 var args []string
1403 for _, a := range call.Args {
1404 args = append(args, a.Type().String())
1405 }
1406 if got, want := fmt.Sprint(args), fmt.Sprint(note.Args); got != want {
1407 at := fset.Position(call.Pos())
1408 t.Errorf("%s: arguments to print had types %s, want %s", at, got, want)
1409 logFunction(t, probes[call])
1410 }
1411 }
1412 }
1413
1414 func TestBuildPackageGo120(t *testing.T) {
1415 tests := []struct {
1416 name string
1417 src string
1418 importer types.Importer
1419 }{
1420 {"slice to array", "package p; var s []byte; var _ = ([4]byte)(s)", nil},
1421 {"slice to zero length array", "package p; var s []byte; var _ = ([0]byte)(s)", nil},
1422 {"slice to zero length array type parameter", "package p; var s []byte; func f[T ~[0]byte]() { tmp := (T)(s); var z T; _ = tmp == z}", nil},
1423 {"slice to non-zero length array type parameter", "package p; var s []byte; func h[T ~[1]byte | [4]byte]() { tmp := T(s); var z T; _ = tmp == z}", nil},
1424 {"slice to maybe-zero length array type parameter", "package p; var s []byte; func g[T ~[0]byte | [4]byte]() { tmp := T(s); var z T; _ = tmp == z}", nil},
1425 {
1426 "rune sequence to sequence cast patterns", `
1427 package p
1428 // Each of fXX functions describes a 1.20 legal cast between sequences of runes
1429 // as []rune, pointers to rune arrays, rune arrays, or strings.
1430 //
1431 // Comments listed given the current emitted instructions [approximately].
1432 // If multiple conversions are needed, these are separated by |.
1433 // rune was selected as it leads to string casts (byte is similar).
1434 // The length 2 is not significant.
1435 // Multiple array lengths may occur in a cast in practice (including 0).
1436 func f00[S string, D string](s S) { _ = D(s) } // ChangeType
1437 func f01[S string, D []rune](s S) { _ = D(s) } // Convert
1438 func f02[S string, D []rune | string](s S) { _ = D(s) } // ChangeType | Convert
1439 func f03[S [2]rune, D [2]rune](s S) { _ = D(s) } // ChangeType
1440 func f04[S *[2]rune, D *[2]rune](s S) { _ = D(s) } // ChangeType
1441 func f05[S []rune, D string](s S) { _ = D(s) } // Convert
1442 func f06[S []rune, D [2]rune](s S) { _ = D(s) } // SliceToArray
1443 func f07[S []rune, D [2]rune | string](s S) { _ = D(s) } // SliceToArray | Convert
1444 func f08[S []rune, D *[2]rune](s S) { _ = D(s) } // SliceToArrayPointer
1445 func f09[S []rune, D *[2]rune | string](s S) { _ = D(s) } // SliceToArray | Convert
1446 func f10[S []rune, D *[2]rune | [2]rune](s S) { _ = D(s) } // SliceToArrayPointer | SliceToArray
1447 func f11[S []rune, D *[2]rune | [2]rune | string](s S) { _ = D(s) } // SliceToArrayPointer | SliceToArray | Convert
1448 func f12[S []rune, D []rune](s S) { _ = D(s) } // ChangeType
1449 func f13[S []rune, D []rune | string](s S) { _ = D(s) } // Convert | ChangeType
1450 func f14[S []rune, D []rune | [2]rune](s S) { _ = D(s) } // ChangeType | SliceToArray
1451 func f15[S []rune, D []rune | [2]rune | string](s S) { _ = D(s) } // ChangeType | SliceToArray | Convert
1452 func f16[S []rune, D []rune | *[2]rune](s S) { _ = D(s) } // ChangeType | SliceToArrayPointer
1453 func f17[S []rune, D []rune | *[2]rune | string](s S) { _ = D(s) } // ChangeType | SliceToArrayPointer | Convert
1454 func f18[S []rune, D []rune | *[2]rune | [2]rune](s S) { _ = D(s) } // ChangeType | SliceToArrayPointer | SliceToArray
1455 func f19[S []rune, D []rune | *[2]rune | [2]rune | string](s S) { _ = D(s) } // ChangeType | SliceToArrayPointer | SliceToArray | Convert
1456 func f20[S []rune | string, D string](s S) { _ = D(s) } // Convert | ChangeType
1457 func f21[S []rune | string, D []rune](s S) { _ = D(s) } // Convert | ChangeType
1458 func f22[S []rune | string, D []rune | string](s S) { _ = D(s) } // ChangeType | Convert | Convert | ChangeType
1459 func f23[S []rune | [2]rune, D [2]rune](s S) { _ = D(s) } // SliceToArray | ChangeType
1460 func f24[S []rune | *[2]rune, D *[2]rune](s S) { _ = D(s) } // SliceToArrayPointer | ChangeType
1461 `, nil,
1462 },
1463 {
1464 "matching named and underlying types", `
1465 package p
1466 type a string
1467 type b string
1468 func g0[S []rune | a | b, D []rune | a | b](s S) { _ = D(s) }
1469 func g1[S []rune | ~string, D []rune | a | b](s S) { _ = D(s) }
1470 func g2[S []rune | a | b, D []rune | ~string](s S) { _ = D(s) }
1471 func g3[S []rune | ~string, D []rune |~string](s S) { _ = D(s) }
1472 `, nil,
1473 },
1474 }
1475
1476 for _, tc := range tests {
1477 t.Run(tc.name, func(t *testing.T) {
1478 t.Parallel()
1479 fset := token.NewFileSet()
1480 f, err := parser.ParseFile(fset, "p.go", tc.src, 0)
1481 if err != nil {
1482 t.Error(err)
1483 }
1484 files := []*ast.File{f}
1485
1486 pkg := types.NewPackage("p", "")
1487 conf := &types.Config{Importer: tc.importer}
1488 _, _, err = irutil.BuildPackage(conf, fset, pkg, files, ir.SanityCheckFunctions)
1489 if err != nil {
1490 t.Errorf("unexpected error: %v", err)
1491 }
1492 })
1493 }
1494 }