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