Debian Codegraph @

go/ir/builder_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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 "github.com/google/go-cmp/cmp"
32 "golang.org/x/sync/errgroup"
33 "golang.org/x/tools/go/analysis/analysistest"
34 "golang.org/x/tools/go/packages"
35 )
36
37 func isEmpty(f *ir.Function) bool { return f.Blocks == nil }
38
39 // Tests that programs partially loaded from gc object files contain
40 // functions with no code for the external portions, but are otherwise ok.
41 func TestBuildPackage(t *testing.T) {
42 testenv.NeedsGoBuild(t) // for importer.Default()
43
44 input := `
45 package main
46
47 import (
48 "bytes"
49 "io"
50 "testing"
51 )
52
53 func main() {
54 var t testing.T
55 t.Parallel() // static call to external declared method
56 t.Fail() // static call to promoted external declared method
57 testing.Short() // static call to external package-level function
58
59 var w io.Writer = new(bytes.Buffer)
60 w.Write(nil) // interface invoke of external declared method
61 }
62 `
63
64 // Parse the file.
65 fset := token.NewFileSet()
66 f, err := parser.ParseFile(fset, "input.go", input, parser.SkipObjectResolution)
67 if err != nil {
68 t.Error(err)
69 return
70 }
71
72 // Build an IR program from the parsed file.
73 // Load its dependencies from gc binary export data.
74 mainPkg, _, err := irutil.BuildPackage(&types.Config{Importer: importer.Default()}, fset,
75 types.NewPackage("main", ""), []*ast.File{f}, ir.SanityCheckFunctions)
76 if err != nil {
77 t.Error(err)
78 return
79 }
80
81 // The main package, its direct and indirect dependencies are loaded.
82 deps := []string{
83 // directly imported dependencies:
84 "bytes", "io", "testing",
85 // indirect dependencies mentioned by
86 // the direct imports' export data
87 "sync", "unicode", "time",
88 }
89
90 prog := mainPkg.Prog
91 all := prog.AllPackages()
92 if len(all) <= len(deps) {
93 t.Errorf("unexpected set of loaded packages: %q", all)
94 }
95 for _, path := range deps {
96 pkg := prog.ImportedPackage(path)
97 if pkg == nil {
98 t.Errorf("package not loaded: %q", path)
99 continue
100 }
101
102 // External packages should have no function bodies (except for wrappers).
103 isExt := pkg != mainPkg
104
105 // init()
106 if isExt && !isEmpty(pkg.Func("init")) {
107 t.Errorf("external package %s has non-empty init", pkg)
108 } else if !isExt && isEmpty(pkg.Func("init")) {
109 t.Errorf("main package %s has empty init", pkg)
110 }
111
112 for _, mem := range pkg.Members {
113 switch mem := mem.(type) {
114 case *ir.Function:
115 // Functions at package level.
116 if isExt && !isEmpty(mem) {
117 t.Errorf("external function %s is non-empty", mem)
118 } else if !isExt && isEmpty(mem) {
119 t.Errorf("function %s is empty", mem)
120 }
121
122 case *ir.Type:
123 // Methods of named types T.
124 // (In this test, all exported methods belong to *T not T.)
125 if !isExt {
126 t.Fatalf("unexpected name type in main package: %s", mem)
127 }
128 mset := prog.MethodSets.MethodSet(types.NewPointer(mem.Type()))
129 for i, n := 0, mset.Len(); i < n; i++ {
130 m := prog.MethodValue(mset.At(i))
131 // For external types, only synthetic wrappers have code.
132 expExt := !strings.Contains(m.Synthetic, "wrapper")
133 if expExt && !isEmpty(m) {
134 t.Errorf("external method %s is non-empty: %s",
135 m, m.Synthetic)
136 } else if !expExt && isEmpty(m) {
137 t.Errorf("method function %s is empty: %s",
138 m, m.Synthetic)
139 }
140 }
141 }
142 }
143 }
144
145 expectedCallee := []string{
146 "(*testing.T).Parallel",
147 "(*testing.common).Fail",
148 "testing.Short",
149 "N/A",
150 }
151 callNum := 0
152 for _, b := range mainPkg.Func("main").Blocks {
153 for _, instr := range b.Instrs {
154 switch instr := instr.(type) {
155 case ir.CallInstruction:
156 call := instr.Common()
157 if want := expectedCallee[callNum]; want != "N/A" {
158 got := call.StaticCallee().String()
159 if want != got {
160 t.Errorf("call #%d from main.main: got callee %s, want %s",
161 callNum, got, want)
162 }
163 }
164 callNum++
165 }
166 }
167 }
168 if callNum != 4 {
169 t.Errorf("in main.main: got %d calls, want %d", callNum, 4)
170 }
171 }
172
173 // Tests that methods from indirect dependencies not subject to
174 // CreatePackage are created as needed.
175 func TestNoIndirectCreatePackage(t *testing.T) {
176 testenv.NeedsGoBuild(t) // for go/packages
177
178 fs := openTxtar(t, filepath.Join(analysistest.TestData(), "indirect.txtar"))
179 pkgs := loadPackages(t, fs, "testdata/a")
180 a := pkgs[0]
181
182 // Create a from syntax, its direct deps b from types, but not indirect deps c.
183 prog := ir.NewProgram(a.Fset, ir.SanityCheckFunctions|ir.PrintFunctions)
184 aSSA := prog.CreatePackage(a.Types, a.Syntax, a.TypesInfo, false)
185 for _, p := range a.Types.Imports() {
186 prog.CreatePackage(p, nil, nil, true)
187 }
188
189 // Build SSA for package a.
190 aSSA.Build()
191
192 // Find the function in the sole call in the sole block of function a.A.
193 var got string
194 for _, instr := range aSSA.Members["A"].(*ir.Function).Blocks[0].Instrs {
195 if call, ok := instr.(*ir.Call); ok {
196 f := call.Call.Value.(*ir.Function)
197 got = fmt.Sprintf("%v # %s", f, f.Synthetic)
198 break
199 }
200 }
201 want := "(testdata/c.C).F # from type information (on demand)"
202 if got != want {
203 t.Errorf("for sole call in a.A, got: <<%s>>, want <<%s>>", got, want)
204 }
205 }
206
207 // TestRuntimeTypes tests that (*Program).RuntimeTypes() includes all necessary types.
208 func TestRuntimeTypes(t *testing.T) {
209 testenv.NeedsGoBuild(t) // for importer.Default()
210
211 // TODO(adonovan): these test cases don't really make logical
212 // sense any more. Rethink.
213
214 tests := []struct {
215 input string
216 want []string
217 }{
218 // A package-level type is needed.
219 {`package A; type T struct{}; func (T) f() {}; var x any = T{}`,
220 []string{"*p.T", "p.T"},
221 },
222 // An unexported package-level type is not needed.
223 {`package B; type t struct{}; func (t) f() {}`,
224 nil,
225 },
226 // Subcomponents of type of exported package-level var are needed.
227 {`package C; import "bytes"; var V struct {*bytes.Buffer}; var x any = &V`,
228 []string{"*bytes.Buffer", "*struct{*bytes.Buffer}", "struct{*bytes.Buffer}"},
229 },
230 // Subcomponents of type of unexported package-level var are not needed.
231 {`package D; import "bytes"; var v struct {*bytes.Buffer}; var x any = v`,
232 []string{"*bytes.Buffer", "struct{*bytes.Buffer}"},
233 },
234 // Subcomponents of type of exported package-level function are needed.
235 {`package E; import "bytes"; func F(struct {*bytes.Buffer}) {}; var v any = F`,
236 []string{"*bytes.Buffer", "struct{*bytes.Buffer}"},
237 },
238 // Subcomponents of type of unexported package-level function are not needed.
239 {`package F; import "bytes"; func f(struct {*bytes.Buffer}) {}; var v any = f`,
240 []string{"*bytes.Buffer", "struct{*bytes.Buffer}"},
241 },
242 // Subcomponents of type of exported method of uninstantiated unexported type are not needed.
243 {`package G; import "bytes"; type x struct{}; func (x) G(struct {*bytes.Buffer}) {}; var v x`,
244 nil,
245 },
246 // ...unless used by MakeInterface.
247 {`package G2; import "bytes"; type x struct{}; func (x) G(struct {*bytes.Buffer}) {}; var v interface{} = x{}`,
248 []string{"*bytes.Buffer", "*p.x", "p.x", "struct{*bytes.Buffer}"},
249 },
250 // Subcomponents of type of unexported method are not needed.
251 {`package I; import "bytes"; type X struct{}; func (X) G(struct {*bytes.Buffer}) {}; var x any = X{}`,
252 []string{"*bytes.Buffer", "*p.X", "p.X", "struct{*bytes.Buffer}"},
253 },
254 // Local types aren't needed.
255 {`package J; import "bytes"; func f() { type T struct {*bytes.Buffer}; var t T; _ = t }`,
256 nil,
257 },
258 // ...unless used by MakeInterface.
259 {`package K; import "bytes"; func f() { type T struct {*bytes.Buffer}; _ = interface{}(T{}) }`,
260 []string{"*bytes.Buffer", "*p.T", "p.T"},
261 },
262 // Types used as operand of MakeInterface are needed.
263 {`package L; import "bytes"; func f() { _ = interface{}(struct{*bytes.Buffer}{}) }`,
264 []string{"*bytes.Buffer", "struct{*bytes.Buffer}"},
265 },
266 // MakeInterface is optimized away when storing to a blank.
267 {`package M; import "bytes"; var _ interface{} = struct{*bytes.Buffer}{}`,
268 nil,
269 },
270 // MakeInterface does not create runtime type for parameterized types.
271 {
272 `package N; var g interface{}; func f[S any]() { var v []S; g = v }; `,
273 nil,
274 },
275 // ...including a parameterized type boxed by a closure in the body of a method of a generic type (go.dev/issue/80055).
276 {`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() }`,
277 nil,
278 },
279 // The type []T within generic F[T] is parameterized, so not a RuntimeType.
280 // But []T within instance f[T=C] is a ground type, so a RuntimeType.
281 {`package P
282 var _ = G[C]
283 func G[U any]() { F[U]() }
284 func F[T any]() any { return []T{} }
285 type C struct{}
286 func (C) f()
287 `,
288 []string{"*p.C", "p.C"},
289 },
290 }
291 for _, test := range tests {
292 // Parse the file.
293 fset := token.NewFileSet()
294 f, err := parser.ParseFile(fset, "input.go", test.input, 0)
295 if err != nil {
296 t.Errorf("test %q: %s", test.input[:15], err)
297 continue
298 }
299
300 // Create a single-file main package.
301 // Load dependencies from gc binary export data.
302 irpkg, _, err := irutil.BuildPackage(&types.Config{Importer: importer.Default()}, fset,
303 types.NewPackage("p", ""), []*ast.File{f}, ir.SanityCheckFunctions|ir.InstantiateGenerics)
304 if err != nil {
305 t.Errorf("test %q: %s", test.input[:15], err)
306 continue
307 }
308
309 var typstrs []string
310 for _, T := range irpkg.Prog.RuntimeTypes() {
311 if types.IsInterface(T) || types.NewMethodSet(T).Len() == 0 {
312 continue // skip interfaces and types without methods
313 }
314 typstrs = append(typstrs, T.String())
315 }
316 sort.Strings(typstrs)
317
318 if !reflect.DeepEqual(typstrs, test.want) {
319 t.Errorf("test 'package %s': got %q, want %q",
320 f.Name.Name, typstrs, test.want)
321 }
322 }
323 }
324
325 // TestInit tests that synthesized init functions are correctly formed.
326 // Bare init functions omit calls to dependent init functions and the use of
327 // an init guard. They are useful in cases where the client uses a different
328 // calling convention for init functions, or cases where it is easier for a
329 // client to analyze bare init functions. Both of these aspects are used by
330 // the llgo compiler for simpler integration with gccgo's runtime library,
331 // and to simplify the analysis whereby it deduces which stores to globals
332 // can be lowered to global initializers.
333 func TestInit(t *testing.T) {
334 tests := []struct {
335 mode ir.BuilderMode
336 input, want string
337 }{
338 {0, `package A; import _ "errors"; var i int = 42`,
339 `# Name: A.init
340 # Package: A
341 # Synthetic: package initializer
342 func init():
343 0: entry P:0 S:2
344 t1 = *init$guard bool
345 if t1 goto 2 else 1
346 1: init.start P:1 S:1 idom:0
347 *init$guard = true:bool
348 t4 = errors.init() ()
349 *i = 42:int
350 jump 2
351 2: init.done P:2 S:0 idom:0
352 return
353
354 `},
355 }
356 for _, test := range tests {
357 // Create a single-file main package.
358 mainPkg, _ := buildPackage(t, test.input, test.mode)
359 name := mainPkg.Pkg.Name()
360 initFunc := mainPkg.Func("init")
361 if initFunc == nil {
362 t.Errorf("test 'package %s': no init function", name)
363 continue
364 }
365
366 var initbuf bytes.Buffer
367 _, err := initFunc.WriteTo(&initbuf)
368 if err != nil {
369 t.Errorf("test 'package %s': WriteTo: %s", name, err)
370 continue
371 }
372
373 if initbuf.String() != test.want {
374 t.Errorf("test 'package %s': got %s, want %s", name, initbuf.String(), test.want)
375 }
376 }
377 }
378
379 // TestSyntheticFuncs checks that the expected synthetic functions are
380 // created, reachable, and not duplicated.
381 func TestSyntheticFuncs(t *testing.T) {
382 const input = `package P
383 type T int
384 func (T) f() int
385 func (*T) g() int
386 var (
387 // thunks
388 a = T.f
389 b = T.f
390 c = (struct{T}).f
391 d = (struct{T}).f
392 e = (*T).g
393 f = (*T).g
394 g = (struct{*T}).g
395 h = (struct{*T}).g
396
397 // bounds
398 i = T(0).f
399 j = T(0).f
400 k = new(T).g
401 l = new(T).g
402
403 // wrappers
404 m interface{} = struct{T}{}
405 n interface{} = struct{T}{}
406 o interface{} = struct{*T}{}
407 p interface{} = struct{*T}{}
408 q interface{} = new(struct{T})
409 r interface{} = new(struct{T})
410 s interface{} = new(struct{*T})
411 t interface{} = new(struct{*T})
412 )
413 `
414 pkg, _ := buildPackage(t, input, ir.BuilderMode(0))
415
416 // Enumerate reachable synthetic functions
417 want := map[string]string{
418 "(*P.T).g$bound": "bound method wrapper for func (*P.T).g() int",
419 "(P.T).f$bound": "bound method wrapper for func (P.T).f() int",
420
421 "(*P.T).g$thunk": "thunk for func (*P.T).g() int",
422 "(P.T).f$thunk": "thunk for func (P.T).f() int",
423 "(struct{*P.T}).g$thunk": "thunk for func (*P.T).g() int",
424 "(struct{P.T}).f$thunk": "thunk for func (P.T).f() int",
425
426 "(*P.T).f": "wrapper for func (P.T).f() int",
427 "(*struct{*P.T}).f": "wrapper for func (P.T).f() int",
428 "(*struct{*P.T}).g": "wrapper for func (*P.T).g() int",
429 "(*struct{P.T}).f": "wrapper for func (P.T).f() int",
430 "(*struct{P.T}).g": "wrapper for func (*P.T).g() int",
431 "(struct{*P.T}).f": "wrapper for func (P.T).f() int",
432 "(struct{*P.T}).g": "wrapper for func (*P.T).g() int",
433 "(struct{P.T}).f": "wrapper for func (P.T).f() int",
434
435 "P.init": "package initializer",
436 }
437 var seen []string // may contain dups
438 for fn := range irutil.AllFunctions(pkg.Prog) {
439 if fn.Synthetic == "" {
440 continue
441 }
442 name := fn.String()
443 wantDescr, ok := want[name]
444 if !ok {
445 t.Errorf("got unexpected/duplicate func: %q: %q", name, fn.Synthetic)
446 continue
447 }
448 seen = append(seen, name)
449
450 if wantDescr != fn.Synthetic {
451 t.Errorf("(%s).Synthetic = %q, want %q", name, fn.Synthetic, wantDescr)
452 }
453 }
454
455 for _, name := range seen {
456 delete(want, name)
457 }
458 for fn, descr := range want {
459 t.Errorf("want func: %q: %q", fn, descr)
460 }
461 }
462
463 // TestPhiElimination ensures that dead phis, including those that
464 // participate in a cycle, are properly eliminated.
465 func TestPhiElimination(t *testing.T) {
466 const input = `
467 package p
468
469 func f() error
470
471 func g(slice []int) {
472 for {
473 for range slice {
474 // e should not be lifted to a dead φ-node.
475 e := f()
476 h(e)
477 }
478 }
479 }
480
481 func h(error)
482 `
483 // The IR code for this function should look something like this:
484 // 0:
485 // jump 1
486 // 1:
487 // t0 = len(slice)
488 // jump 2
489 // 2:
490 // t1 = phi [1: -1:int, 3: t2]
491 // t2 = t1 + 1:int
492 // t3 = t2 < t0
493 // if t3 goto 3 else 1
494 // 3:
495 // t4 = f()
496 // t5 = h(t4)
497 // jump 2
498 //
499 // But earlier versions of the IR construction algorithm would
500 // additionally generate this cycle of dead phis:
501 //
502 // 1:
503 // t7 = phi [0: nil:error, 2: t8] #e
504 // ...
505 // 2:
506 // t8 = phi [1: t7, 3: t4] #e
507 // ...
508
509 p, _ := buildPackage(t, input, ir.BuilderMode(0))
510 g := p.Func("g")
511
512 phis := 0
513 for _, b := range g.Blocks {
514 for _, instr := range b.Instrs {
515 if _, ok := instr.(*ir.Phi); ok {
516 phis++
517 }
518 }
519 }
520 if phis != 1 {
521 g.WriteTo(os.Stderr)
522 t.Errorf("expected a single Phi (for the range index), got %d", phis)
523 }
524 }
525
526 // TestGenericDecls ensures that *unused* generic types, methods and functions
527 // signatures can be built.
528 //
529 // TODO(taking): Add calls from non-generic functions to instantiations of generic functions.
530 // TODO(taking): Add globals with types that are instantiations of generic functions.
531 func TestGenericDecls(t *testing.T) {
532 const input = `
533 package p
534
535 import "unsafe"
536
537 type Pointer[T any] struct {
538 v unsafe.Pointer
539 }
540
541 func (x *Pointer[T]) Load() *T {
542 return (*T)(LoadPointer(&x.v))
543 }
544
545 func Load[T any](x *Pointer[T]) *T {
546 return x.Load()
547 }
548
549 func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer)
550 `
551 // The SSA members for this package should look something like this:
552 // func LoadPointer func(addr *unsafe.Pointer) (val unsafe.Pointer)
553 // type Pointer struct{v unsafe.Pointer}
554 // method (*Pointer[T any]) Load() *T
555 // func init func()
556 // var init$guard bool
557
558 p, _ := buildPackage(t, input, ir.BuilderMode(0))
559
560 if load := p.Func("Load"); load.Signature.TypeParams().Len() != 1 {
561 t.Errorf("expected a single type param T for Load got %q", load.Signature)
562 }
563 if ptr := p.Type("Pointer"); ptr.Type().(*types.Named).TypeParams().Len() != 1 {
564 t.Errorf("expected a single type param T for Pointer got %q", ptr.Type())
565 }
566 }
567
568 func TestGenericWrappers(t *testing.T) {
569 const input = `
570 package p
571
572 type S[T any] struct {
573 t *T
574 }
575
576 func (x S[T]) M() T {
577 return *(x.t)
578 }
579
580 var thunk = S[int].M
581
582 var g S[int]
583 var bound = g.M
584
585 type R[T any] struct{ S[T] }
586
587 var indirect = R[int].M
588 `
589 // The relevant SSA members for this package should look something like this:
590 // var bound func() int
591 // var thunk func(S[int]) int
592 // var wrapper func(R[int]) int
593
594 for _, mode := range []ir.BuilderMode{ir.BuilderMode(0), ir.InstantiateGenerics} {
595 p, _ := buildPackage(t, input, mode)
596
597 for _, entry := range []struct {
598 name string // name of the package variable
599 typ string // type of the package variable
600 wrapper string // wrapper function to which the package variable is set
601 callee string // callee within the wrapper function
602 }{
603 {
604 "bound",
605 "*func() int",
606 "(p.S[int]).M$bound",
607 "(p.S[int]).M",
608 },
609 {
610 "thunk",
611 "*func(p.S[int]) int",
612 "(p.S[int]).M$thunk",
613 "(p.S[int]).M",
614 },
615 {
616 "indirect",
617 "*func(p.R[int]) int",
618 "(p.R[int]).M$thunk",
619 "(p.S[int]).M",
620 },
621 } {
622 t.Run(entry.name, func(t *testing.T) {
623 v := p.Var(entry.name)
624 if v == nil {
625 t.Fatalf("Did not find variable for %q in %s", entry.name, p.String())
626 }
627 if v.Type().String() != entry.typ {
628 t.Errorf("Expected type for variable %s: %q. got %q", v, entry.typ, v.Type())
629 }
630
631 // Find the wrapper for v. This is stored exactly once in init.
632 var wrapper *ir.Function
633 for _, bb := range p.Func("init").Blocks {
634 for _, i := range bb.Instrs {
635 if store, ok := i.(*ir.Store); ok && v == store.Addr {
636 switch val := store.Val.(type) {
637 case *ir.Function:
638 wrapper = val
639 case *ir.MakeClosure:
640 wrapper = val.Fn.(*ir.Function)
641 }
642 }
643 }
644 }
645 if wrapper == nil {
646 t.Fatalf("failed to find wrapper function for %s", entry.name)
647 }
648 if wrapper.String() != entry.wrapper {
649 t.Errorf("Expected wrapper function %q. got %q", wrapper, entry.wrapper)
650 }
651
652 // Find the callee within the wrapper. There should be exactly one call.
653 var callee *ir.Function
654 for _, bb := range wrapper.Blocks {
655 for _, i := range bb.Instrs {
656 if call, ok := i.(*ir.Call); ok {
657 callee = call.Call.StaticCallee()
658 }
659 }
660 }
661 if callee == nil {
662 t.Fatalf("failed to find callee within wrapper %s", wrapper)
663 }
664 if callee.String() != entry.callee {
665 t.Errorf("Expected callee in wrapper %q is %q. got %q", v, entry.callee, callee)
666 }
667 })
668 }
669 }
670 }
671
672 // TestTypeparamTest builds SSA over compilable examples in $GOROOT/test/typeparam/*.go.
673
674 func TestTypeparamTest(t *testing.T) {
675 testenv.NeedsGOROOTDir(t, "test")
676
677 // Tests use a fake goroot to stub out standard libraries with declarations in
678 // testdata/src. Decreases runtime from ~80s to ~1s.
679
680 if runtime.GOARCH == "wasm" {
681 // Consistent flakes on wasm (#64726, #69409, #69410).
682 // Needs more investigation, but more likely a wasm issue
683 // Disabling for now.
684 t.Skip("Consistent flakes on wasm (e.g. https://go.dev/issues/64726)")
685 }
686
687 // located GOROOT based on the relative path of errors in $GOROOT/src/errors
688 stdPkgs, err := packages.Load(&packages.Config{
689 Mode: packages.NeedFiles,
690 }, "errors")
691 if err != nil {
692 t.Fatalf("Failed to load errors package from std: %s", err)
693 }
694 goroot := filepath.Dir(filepath.Dir(filepath.Dir(stdPkgs[0].GoFiles[0])))
695 dir := filepath.Join(goroot, "test", "typeparam")
696 if _, err = os.Stat(dir); errors.Is(err, os.ErrNotExist) {
697 t.Skipf("test/typeparam doesn't exist under GOROOT %s", goroot)
698 }
699
700 // Collect all of the .go files in
701 fsys := os.DirFS(dir)
702 entries, err := fs.ReadDir(fsys, ".")
703 if err != nil {
704 t.Fatal(err)
705 }
706
707 // Each call to buildPackage calls package.Load, which invokes "go list",
708 // and with over 300 subtests this can be very slow (minutes, or tens
709 // on some platforms). So, we use an overlay to map each test file to a
710 // distinct single-file package and load them all at once.
711 overlay := map[string][]byte{
712 "go.mod": goMod("example.com", -1),
713 }
714 for _, entry := range entries {
715 if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") {
716 continue // Consider standalone go files.
717 }
718 src, err := fs.ReadFile(fsys, entry.Name())
719 if err != nil {
720 t.Fatal(err)
721 }
722 // Only build test files that can be compiled, or compiled and run.
723 if !bytes.HasPrefix(src, []byte("// run")) && !bytes.HasPrefix(src, []byte("// compile")) {
724 t.Logf("%s: not detected as a run test", entry.Name())
725 continue
726 }
727
728 filename := fmt.Sprintf("%s/main.go", entry.Name())
729 overlay[filename] = src
730 }
731
732 // load all packages inside the overlay so 'go list' will be triggered only once.
733 pkgs := loadPackages(t, overlayFS(overlay), "./...")
734 for _, p := range pkgs {
735 originFilename := filepath.Base(filepath.Dir(p.GoFiles[0]))
736 t.Run(originFilename, func(t *testing.T) {
737 t.Parallel()
738 prog, _ := irutil.Packages([]*packages.Package{p}, ir.SanityCheckFunctions|ir.InstantiateGenerics)
739 prog.Package(p.Types).Build()
740 })
741 }
742 }
743
744 // TestOrderOfOperations ensures order of operations are as intended.
745 func TestOrderOfOperations(t *testing.T) {
746 // Testing for the order of operations within an expression is done
747 // by collecting the sequence of direct function calls within a *Function.
748 // Callees are all external functions so they cannot be safely re-ordered by ssa.
749 const input = `
750 package p
751
752 func a() int
753 func b() int
754 func c() int
755
756 func slice(s []int) []int { return s[a():b()] }
757 func sliceMax(s []int) []int { return s[a():b():c()] }
758
759 `
760
761 p, _ := buildPackage(t, input, ir.BuilderMode(0))
762
763 for _, item := range []struct {
764 fn string
765 want string // sequence of calls within the function.
766 }{
767 {"sliceMax", "[a() b() c()]"},
768 {"slice", "[a() b()]"},
769 } {
770 fn := p.Func(item.fn)
771 want := item.want
772 t.Run(item.fn, func(t *testing.T) {
773 t.Parallel()
774
775 var calls []string
776 for _, b := range fn.Blocks {
777 for _, instr := range b.Instrs {
778 if call, ok := instr.(ir.CallInstruction); ok {
779 calls = append(calls, call.String())
780 }
781 }
782 }
783 if got := fmt.Sprint(calls); got != want {
784 fn.WriteTo(os.Stderr)
785 t.Errorf("Expected sequence of function calls in %s was %s. got %s", fn, want, got)
786 }
787 })
788 }
789 }
790
791 // TestGenericFunctionSelector ensures generic functions from other packages can be selected.
792 func TestGenericFunctionSelector(t *testing.T) {
793 fsys := overlayFS(map[string][]byte{
794 "go.mod": goMod("example.com", -1),
795 "main.go": []byte(`package main; import "example.com/a"; func main() { a.F[int](); a.G[int,string](); a.H(0) }`),
796 "a/a.go": []byte(`package a; func F[T any](){}; func G[S, T any](){}; func H[T any](a T){} `),
797 })
798
799 for _, mode := range []ir.BuilderMode{
800 ir.SanityCheckFunctions,
801 ir.SanityCheckFunctions | ir.InstantiateGenerics,
802 } {
803
804 pkgs := loadPackages(t, fsys, "example.com") // package main
805 if len(pkgs) != 1 {
806 t.Fatalf("Expected 1 root package but got %d", len(pkgs))
807 }
808 prog, _ := irutil.Packages(pkgs, mode)
809 p := prog.Package(pkgs[0].Types)
810 p.Build()
811
812 if p.Pkg.Name() != "main" {
813 t.Fatalf("Expected the second package is main but got %s", p.Pkg.Name())
814 }
815 p.Build()
816
817 var callees []string // callees of the CallInstruction.String() in main().
818 for _, b := range p.Func("main").Blocks {
819 for _, i := range b.Instrs {
820 if call, ok := i.(ir.CallInstruction); ok {
821 if callee := call.Common().StaticCallee(); call != nil {
822 callees = append(callees, callee.String())
823 } else {
824 t.Errorf("CallInstruction without StaticCallee() %q", call)
825 }
826 }
827 }
828 }
829 sort.Strings(callees) // ignore the order in the code.
830
831 want := "[example.com/a.F[int] example.com/a.G[int, string] example.com/a.H[int]]"
832 if got := fmt.Sprint(callees); got != want {
833 t.Errorf("Expected main() to contain calls %v. got %v", want, got)
834 }
835 }
836 }
837
838 func TestIssue58491(t *testing.T) {
839 // Test that a local type reaches type param in instantiation.
840 src := `
841 package p
842
843 func foo[T any](blocking func() (T, error)) error {
844 type result struct {
845 res T
846 error // ensure the method set of result is non-empty
847 }
848
849 res := make(chan result, 1)
850 go func() {
851 var r result
852 r.res, r.error = blocking()
853 res <- r
854 }()
855 r := <-res
856 err := r // require the rtype for result when instantiated
857 return err
858 }
859 var Inst = foo[int]
860 `
861 fset := token.NewFileSet()
862 f, err := parser.ParseFile(fset, "p.go", src, 0)
863 if err != nil {
864 t.Fatal(err)
865 }
866 files := []*ast.File{f}
867
868 pkg := types.NewPackage("p", "")
869 conf := &types.Config{}
870 p, _, err := irutil.BuildPackage(conf, fset, pkg, files, ir.SanityCheckFunctions|ir.InstantiateGenerics)
871 if err != nil {
872 t.Fatalf("unexpected error: %v", err)
873 }
874
875 // Find the local type result instantiated with int.
876 var found bool
877 for _, rt := range p.Prog.RuntimeTypes() {
878 if n, ok := rt.(*types.Named); ok {
879 if u, ok := n.Underlying().(*types.Struct); ok {
880 found = true
881 if got, want := n.String(), "p.result"; got != want {
882 t.Errorf("Expected the name %s got: %s", want, got)
883 }
884 if got, want := u.String(), "struct{res int; error}"; got != want {
885 t.Errorf("Expected the underlying type of %s to be %s. got %s", n, want, got)
886 }
887 }
888 }
889 }
890 if !found {
891 t.Error("Failed to find any Named to struct types")
892 }
893 }
894
895 func TestIssue58491Rec(t *testing.T) {
896 // Roughly the same as TestIssue58491 but with a recursive type.
897 src := `
898 package p
899
900 func foo[T any]() error {
901 type result struct {
902 res T
903 next *result
904 error // ensure the method set of result is non-empty
905 }
906
907 r := &result{}
908 err := r // require the rtype for result when instantiated
909 return err
910 }
911 var Inst = foo[int]
912 `
913 fset := token.NewFileSet()
914 f, err := parser.ParseFile(fset, "p.go", src, 0)
915 if err != nil {
916 t.Fatal(err)
917 }
918 files := []*ast.File{f}
919
920 pkg := types.NewPackage("p", "")
921 conf := &types.Config{}
922 p, _, err := irutil.BuildPackage(conf, fset, pkg, files, ir.SanityCheckFunctions|ir.InstantiateGenerics)
923 if err != nil {
924 t.Fatalf("unexpected error: %v", err)
925 }
926
927 // Find the local type result instantiated with int.
928 var found bool
929 for _, rt := range p.Prog.RuntimeTypes() {
930 if n, ok := types.Unalias(rt).(*types.Named); ok {
931 if u, ok := n.Underlying().(*types.Struct); ok {
932 found = true
933 if got, want := n.String(), "p.result"; got != want {
934 t.Errorf("Expected the name %s got: %s", want, got)
935 }
936 if got, want := u.String(), "struct{res int; next *p.result; error}"; got != want {
937 t.Errorf("Expected the underlying type of %s to be %s. got %s", n, want, got)
938 }
939 }
940 }
941 }
942 if !found {
943 t.Error("Failed to find any Named to struct types")
944 }
945 }
946
947 // TestSyntax ensures that a function's Syntax is available.
948 func TestSyntax(t *testing.T) {
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 d := cmp.Diff(want, got); d != "" {
1006 t.Errorf("unexpected function signatures:\n%s", d)
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 }