api_test.go raw

   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 types_test
   6  
   7  import (
   8  	"errors"
   9  	"fmt"
  10  	"go/ast"
  11  	"go/importer"
  12  	"go/parser"
  13  	"go/token"
  14  	"internal/goversion"
  15  	"internal/testenv"
  16  	"slices"
  17  	"sort"
  18  	"strings"
  19  	"sync"
  20  	"testing"
  21  
  22  	. "go/types"
  23  	"runtime"
  24  )
  25  
  26  // nopos indicates an unknown position
  27  var nopos token.Pos
  28  
  29  func defaultImporter(fset *token.FileSet) Importer {
  30  	return importer.ForCompiler(fset, runtime.Compiler, nil)
  31  }
  32  
  33  func mustParse(fset *token.FileSet, src string) *ast.File {
  34  	f, err := parser.ParseFile(fset, pkgName(src), src, parser.ParseComments)
  35  	if err != nil {
  36  		panic(err) // so we don't need to pass *testing.T
  37  	}
  38  	return f
  39  }
  40  
  41  func typecheck(src string, conf *Config, info *Info) (*Package, error) {
  42  	// TODO(adonovan): plumb this from caller.
  43  	fset := token.NewFileSet()
  44  	f := mustParse(fset, src)
  45  	if conf == nil {
  46  		conf = &Config{
  47  			Error:    func(err error) {}, // collect all errors
  48  			Importer: defaultImporter(fset),
  49  		}
  50  	}
  51  	return conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
  52  }
  53  
  54  func mustTypecheck(src string, conf *Config, info *Info) *Package {
  55  	pkg, err := typecheck(src, conf, info)
  56  	if err != nil {
  57  		panic(err) // so we don't need to pass *testing.T
  58  	}
  59  	return pkg
  60  }
  61  
  62  // pkgName extracts the package name from src, which must contain a package header.
  63  func pkgName(src string) string {
  64  	const kw = "package "
  65  	if i := strings.Index(src, kw); i >= 0 {
  66  		after := src[i+len(kw):]
  67  		n := len(after)
  68  		if i := strings.IndexAny(after, "\n\t ;/"); i >= 0 {
  69  			n = i
  70  		}
  71  		return after[:n]
  72  	}
  73  	panic("missing package header: " + src)
  74  }
  75  
  76  func TestValuesInfo(t *testing.T) {
  77  	var tests = []struct {
  78  		src  string
  79  		expr string // constant expression
  80  		typ  string // constant type
  81  		val  string // constant value
  82  	}{
  83  		{`package a0; const _ = false`, `false`, `untyped bool`, `false`},
  84  		{`package a1; const _ = 0`, `0`, `untyped int`, `0`},
  85  		{`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
  86  		{`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
  87  		{`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
  88  		{`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
  89  
  90  		{`package b0; var _ = false`, `false`, `bool`, `false`},
  91  		{`package b1; var _ = 0`, `0`, `int`, `0`},
  92  		{`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
  93  		{`package b3; var _ = 0.`, `0.`, `float64`, `0`},
  94  		{`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
  95  		{`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
  96  
  97  		{`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
  98  		{`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
  99  		{`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
 100  
 101  		{`package c1a; var _ = int(0)`, `0`, `int`, `0`},
 102  		{`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
 103  		{`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
 104  
 105  		{`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
 106  		{`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
 107  		{`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
 108  
 109  		{`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
 110  		{`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
 111  		{`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
 112  
 113  		{`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
 114  		{`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
 115  		{`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
 116  
 117  		{`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
 118  		{`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
 119  		{`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
 120  		{`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
 121  		{`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
 122  		{`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
 123  
 124  		{`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
 125  		{`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
 126  		{`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
 127  		{`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
 128  
 129  		{`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
 130  		{`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
 131  		{`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
 132  		{`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
 133  		{`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
 134  		{`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
 135  		{`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
 136  		{`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
 137  
 138  		{`package f0 ; var _ float32 =  1e-200`, `1e-200`, `float32`, `0`},
 139  		{`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
 140  		{`package f2a; var _ float64 =  1e-2000`, `1e-2000`, `float64`, `0`},
 141  		{`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
 142  		{`package f2b; var _         =  1e-2000`, `1e-2000`, `float64`, `0`},
 143  		{`package f3b; var _         = -1e-2000`, `-1e-2000`, `float64`, `0`},
 144  		{`package f4 ; var _ complex64  =  1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
 145  		{`package f5 ; var _ complex64  = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
 146  		{`package f6a; var _ complex128 =  1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
 147  		{`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
 148  		{`package f6b; var _            =  1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
 149  		{`package f7b; var _            = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
 150  
 151  		{`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // go.dev/issue/22341
 152  		{`package g1; var(j int32; s int; n = 1.0<<s == j)`, `1.0`, `int32`, `1`},        // go.dev/issue/48422
 153  	}
 154  
 155  	for _, test := range tests {
 156  		info := Info{
 157  			Types: make(map[ast.Expr]TypeAndValue),
 158  		}
 159  		name := mustTypecheck(test.src, nil, &info).Name()
 160  
 161  		// look for expression
 162  		var expr ast.Expr
 163  		for e := range info.Types {
 164  			if ExprString(e) == test.expr {
 165  				expr = e
 166  				break
 167  			}
 168  		}
 169  		if expr == nil {
 170  			t.Errorf("package %s: no expression found for %s", name, test.expr)
 171  			continue
 172  		}
 173  		tv := info.Types[expr]
 174  
 175  		// check that type is correct
 176  		if got := tv.Type.String(); got != test.typ {
 177  			t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
 178  			continue
 179  		}
 180  
 181  		// if we have a constant, check that value is correct
 182  		if tv.Value != nil {
 183  			if got := tv.Value.ExactString(); got != test.val {
 184  				t.Errorf("package %s: got value %s; want %s", name, got, test.val)
 185  			}
 186  		} else {
 187  			if test.val != "" {
 188  				t.Errorf("package %s: no constant found; want %s", name, test.val)
 189  			}
 190  		}
 191  	}
 192  }
 193  
 194  func TestTypesInfo(t *testing.T) {
 195  	// Test sources that are not expected to typecheck must start with the broken prefix.
 196  	const broken = "package broken_"
 197  
 198  	var tests = []struct {
 199  		src  string
 200  		expr string // expression
 201  		typ  string // value type
 202  	}{
 203  		// single-valued expressions of untyped constants
 204  		{`package b0; var x interface{} = false`, `false`, `bool`},
 205  		{`package b1; var x interface{} = 0`, `0`, `int`},
 206  		{`package b2; var x interface{} = 0.`, `0.`, `float64`},
 207  		{`package b3; var x interface{} = 0i`, `0i`, `complex128`},
 208  		{`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
 209  
 210  		// uses of nil
 211  		{`package n0; var _ *int = nil`, `nil`, `untyped nil`},
 212  		{`package n1; var _ func() = nil`, `nil`, `untyped nil`},
 213  		{`package n2; var _ []byte = nil`, `nil`, `untyped nil`},
 214  		{`package n3; var _ map[int]int = nil`, `nil`, `untyped nil`},
 215  		{`package n4; var _ chan int = nil`, `nil`, `untyped nil`},
 216  		{`package n5; var _ interface{} = nil`, `nil`, `untyped nil`},
 217  		{`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `untyped nil`},
 218  
 219  		{`package n10; var (x *int; _ = x == nil)`, `nil`, `untyped nil`},
 220  		{`package n11; var (x func(); _ = x == nil)`, `nil`, `untyped nil`},
 221  		{`package n12; var (x []byte; _ = x == nil)`, `nil`, `untyped nil`},
 222  		{`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `untyped nil`},
 223  		{`package n14; var (x chan int; _ = x == nil)`, `nil`, `untyped nil`},
 224  		{`package n15; var (x interface{}; _ = x == nil)`, `nil`, `untyped nil`},
 225  		{`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `untyped nil`},
 226  
 227  		{`package n20; var _ = (*int)(nil)`, `nil`, `untyped nil`},
 228  		{`package n21; var _ = (func())(nil)`, `nil`, `untyped nil`},
 229  		{`package n22; var _ = ([]byte)(nil)`, `nil`, `untyped nil`},
 230  		{`package n23; var _ = (map[int]int)(nil)`, `nil`, `untyped nil`},
 231  		{`package n24; var _ = (chan int)(nil)`, `nil`, `untyped nil`},
 232  		{`package n25; var _ = (interface{})(nil)`, `nil`, `untyped nil`},
 233  		{`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `untyped nil`},
 234  
 235  		{`package n30; func f(*int) { f(nil) }`, `nil`, `untyped nil`},
 236  		{`package n31; func f(func()) { f(nil) }`, `nil`, `untyped nil`},
 237  		{`package n32; func f([]byte) { f(nil) }`, `nil`, `untyped nil`},
 238  		{`package n33; func f(map[int]int) { f(nil) }`, `nil`, `untyped nil`},
 239  		{`package n34; func f(chan int) { f(nil) }`, `nil`, `untyped nil`},
 240  		{`package n35; func f(interface{}) { f(nil) }`, `nil`, `untyped nil`},
 241  		{`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `untyped nil`},
 242  
 243  		// comma-ok expressions
 244  		{`package p0; var x interface{}; var _, _ = x.(int)`,
 245  			`x.(int)`,
 246  			`(int, bool)`,
 247  		},
 248  		{`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
 249  			`x.(int)`,
 250  			`(int, bool)`,
 251  		},
 252  		{`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
 253  			`m["foo"]`,
 254  			`(complex128, p2a.mybool)`,
 255  		},
 256  		{`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
 257  			`m["foo"]`,
 258  			`(complex128, bool)`,
 259  		},
 260  		{`package p3; var c chan string; var _, _ = <-c`,
 261  			`<-c`,
 262  			`(string, bool)`,
 263  		},
 264  
 265  		// go.dev/issue/6796
 266  		{`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
 267  			`x.(int)`,
 268  			`(int, bool)`,
 269  		},
 270  		{`package issue6796_b; var c chan string; var _, _ = (<-c)`,
 271  			`(<-c)`,
 272  			`(string, bool)`,
 273  		},
 274  		{`package issue6796_c; var c chan string; var _, _ = (<-c)`,
 275  			`<-c`,
 276  			`(string, bool)`,
 277  		},
 278  		{`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
 279  			`(<-c)`,
 280  			`(string, bool)`,
 281  		},
 282  		{`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
 283  			`(<-c)`,
 284  			`(string, bool)`,
 285  		},
 286  
 287  		// go.dev/issue/7060
 288  		{`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
 289  			`m[0]`,
 290  			`(string, bool)`,
 291  		},
 292  		{`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
 293  			`m[0]`,
 294  			`(string, bool)`,
 295  		},
 296  		{`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
 297  			`m[0]`,
 298  			`(string, bool)`,
 299  		},
 300  		{`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
 301  			`<-ch`,
 302  			`(string, bool)`,
 303  		},
 304  		{`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
 305  			`<-ch`,
 306  			`(string, bool)`,
 307  		},
 308  		{`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
 309  			`<-ch`,
 310  			`(string, bool)`,
 311  		},
 312  
 313  		// go.dev/issue/28277
 314  		{`package issue28277_a; func f(...int)`,
 315  			`...int`,
 316  			`[]int`,
 317  		},
 318  		{`package issue28277_b; func f(a, b int, c ...[]struct{})`,
 319  			`...[]struct{}`,
 320  			`[][]struct{}`,
 321  		},
 322  
 323  		// go.dev/issue/47243
 324  		{`package issue47243_a; var x int32; var _ = x << 3`, `3`, `untyped int`},
 325  		{`package issue47243_b; var x int32; var _ = x << 3.`, `3.`, `untyped float`},
 326  		{`package issue47243_c; var x int32; var _ = 1 << x`, `1 << x`, `int`},
 327  		{`package issue47243_d; var x int32; var _ = 1 << x`, `1`, `int`},
 328  		{`package issue47243_e; var x int32; var _ = 1 << 2`, `1`, `untyped int`},
 329  		{`package issue47243_f; var x int32; var _ = 1 << 2`, `2`, `untyped int`},
 330  		{`package issue47243_g; var x int32; var _ = int(1) << 2`, `2`, `untyped int`},
 331  		{`package issue47243_h; var x int32; var _ = 1 << (2 << x)`, `1`, `int`},
 332  		{`package issue47243_i; var x int32; var _ = 1 << (2 << x)`, `(2 << x)`, `untyped int`},
 333  		{`package issue47243_j; var x int32; var _ = 1 << (2 << x)`, `2`, `untyped int`},
 334  
 335  		// tests for broken code that doesn't type-check
 336  		{broken + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
 337  		{broken + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
 338  		{broken + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a, f: b,}}`, `b`, `string`},
 339  		{broken + `x3; var x = panic("");`, `panic`, `func(interface{})`},
 340  		{`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
 341  		{broken + `x5; func _() { var x map[string][...]int; x = map[string][...]int{"": {1,2,3}} }`, `x`, `map[string]invalid type`},
 342  
 343  		// parameterized functions
 344  		{`package p0; func f[T any](T) {}; var _ = f[int]`, `f`, `func[T any](T)`},
 345  		{`package p1; func f[T any](T) {}; var _ = f[int]`, `f[int]`, `func(int)`},
 346  		{`package p2; func f[T any](T) {}; func _() { f(42) }`, `f`, `func(int)`},
 347  		{`package p3; func f[T any](T) {}; func _() { f[int](42) }`, `f[int]`, `func(int)`},
 348  		{`package p4; func f[T any](T) {}; func _() { f[int](42) }`, `f`, `func[T any](T)`},
 349  		{`package p5; func f[T any](T) {}; func _() { f(42) }`, `f(42)`, `()`},
 350  
 351  		// type parameters
 352  		{`package t0; type t[] int; var _ t`, `t`, `t0.t`}, // t[] is a syntax error that is ignored in this test in favor of t
 353  		{`package t1; type t[P any] int; var _ t[int]`, `t`, `t1.t[P any]`},
 354  		{`package t2; type t[P interface{}] int; var _ t[int]`, `t`, `t2.t[P interface{}]`},
 355  		{`package t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `t3.t[P, Q interface{}]`},
 356  		{broken + `t4; type t[P, Q interface{ m() }] int; var _ t[int, int]`, `t`, `broken_t4.t[P, Q interface{m()}]`},
 357  
 358  		// instantiated types must be sanitized
 359  		{`package g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `g0.t[int]`},
 360  
 361  		// go.dev/issue/45096
 362  		{`package issue45096; func _[T interface{ ~int8 | ~int16 | ~int32  }](x T) { _ = x < 0 }`, `0`, `T`},
 363  
 364  		// go.dev/issue/47895
 365  		{`package p; import "unsafe"; type S struct { f int }; var s S; var _ = unsafe.Offsetof(s.f)`, `s.f`, `int`},
 366  
 367  		// go.dev/issue/74303. Note that interface field types are synthetic, so
 368  		// even though `func()` doesn't appear in the source, it appears in the
 369  		// syntax tree.
 370  		{`package p; type T interface { M(int) }`, `func(int)`, `func(int)`},
 371  
 372  		// go.dev/issue/50093
 373  		{`package u0a; func _[_ interface{int}]() {}`, `int`, `int`},
 374  		{`package u1a; func _[_ interface{~int}]() {}`, `~int`, `~int`},
 375  		{`package u2a; func _[_ interface{int | string}]() {}`, `int | string`, `int | string`},
 376  		{`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `int | string | ~bool`, `int | string | ~bool`},
 377  		{`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `int | string`, `int | string`},
 378  		{`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `~bool`, `~bool`},
 379  		{`package u3a; func _[_ interface{int | string | ~float64|~bool}]() {}`, `int | string | ~float64`, `int | string | ~float64`},
 380  
 381  		{`package u0b; func _[_ int]() {}`, `int`, `int`},
 382  		{`package u1b; func _[_ ~int]() {}`, `~int`, `~int`},
 383  		{`package u2b; func _[_ int | string]() {}`, `int | string`, `int | string`},
 384  		{`package u3b; func _[_ int | string | ~bool]() {}`, `int | string | ~bool`, `int | string | ~bool`},
 385  		{`package u3b; func _[_ int | string | ~bool]() {}`, `int | string`, `int | string`},
 386  		{`package u3b; func _[_ int | string | ~bool]() {}`, `~bool`, `~bool`},
 387  		{`package u3b; func _[_ int | string | ~float64|~bool]() {}`, `int | string | ~float64`, `int | string | ~float64`},
 388  
 389  		{`package u0c; type _ interface{int}`, `int`, `int`},
 390  		{`package u1c; type _ interface{~int}`, `~int`, `~int`},
 391  		{`package u2c; type _ interface{int | string}`, `int | string`, `int | string`},
 392  		{`package u3c; type _ interface{int | string | ~bool}`, `int | string | ~bool`, `int | string | ~bool`},
 393  		{`package u3c; type _ interface{int | string | ~bool}`, `int | string`, `int | string`},
 394  		{`package u3c; type _ interface{int | string | ~bool}`, `~bool`, `~bool`},
 395  		{`package u3c; type _ interface{int | string | ~float64|~bool}`, `int | string | ~float64`, `int | string | ~float64`},
 396  
 397  		// reverse type inference
 398  		{`package r1; var _ func(int) = g; func g[P any](P) {}`, `g`, `func(int)`},
 399  		{`package r2; var _ func(int) = g[int]; func g[P any](P) {}`, `g`, `func[P any](P)`}, // go.dev/issues/60212
 400  		{`package r3; var _ func(int) = g[int]; func g[P any](P) {}`, `g[int]`, `func(int)`},
 401  		{`package r4; var _ func(int, string) = g; func g[P, Q any](P, Q) {}`, `g`, `func(int, string)`},
 402  		{`package r5; var _ func(int, string) = g[int]; func g[P, Q any](P, Q) {}`, `g`, `func[P, Q any](P, Q)`}, // go.dev/issues/60212
 403  		{`package r6; var _ func(int, string) = g[int]; func g[P, Q any](P, Q) {}`, `g[int]`, `func(int, string)`},
 404  
 405  		{`package s1; func _() { f(g) }; func f(func(int)) {}; func g[P any](P) {}`, `g`, `func(int)`},
 406  		{`package s2; func _() { f(g[int]) }; func f(func(int)) {}; func g[P any](P) {}`, `g`, `func[P any](P)`}, // go.dev/issues/60212
 407  		{`package s3; func _() { f(g[int]) }; func f(func(int)) {}; func g[P any](P) {}`, `g[int]`, `func(int)`},
 408  		{`package s4; func _() { f(g) }; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}`, `g`, `func(int, string)`},
 409  		{`package s5; func _() { f(g[int]) }; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}`, `g`, `func[P, Q any](P, Q)`}, // go.dev/issues/60212
 410  		{`package s6; func _() { f(g[int]) }; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}`, `g[int]`, `func(int, string)`},
 411  
 412  		{`package s7; func _() { f(g, h) }; func f[P any](func(int, P), func(P, string)) {}; func g[P any](P, P) {}; func h[P, Q any](P, Q) {}`, `g`, `func(int, int)`},
 413  		{`package s8; func _() { f(g, h) }; func f[P any](func(int, P), func(P, string)) {}; func g[P any](P, P) {}; func h[P, Q any](P, Q) {}`, `h`, `func(int, string)`},
 414  		{`package s9; func _() { f(g, h[int]) }; func f[P any](func(int, P), func(P, string)) {}; func g[P any](P, P) {}; func h[P, Q any](P, Q) {}`, `h`, `func[P, Q any](P, Q)`}, // go.dev/issues/60212
 415  		{`package s10; func _() { f(g, h[int]) }; func f[P any](func(int, P), func(P, string)) {}; func g[P any](P, P) {}; func h[P, Q any](P, Q) {}`, `h[int]`, `func(int, string)`},
 416  
 417  		// go.dev/issue/68639
 418  		// parenthesized and pointer type expressions in various positions
 419  		// - as variable type, not generic
 420  		{`package qa1; type T int; var x T`, `T`, `qa1.T`},
 421  		{`package qa2; type T int; var x (T)`, `T`, `qa2.T`},
 422  		{`package qa3; type T int; var x (T)`, `(T)`, `qa3.T`},
 423  		{`package qa4; type T int; var x ((T))`, `T`, `qa4.T`},
 424  		{`package qa5; type T int; var x ((T))`, `(T)`, `qa5.T`},
 425  		{`package qa6; type T int; var x ((T))`, `((T))`, `qa6.T`},
 426  		{`package qa7; type T int; var x *T`, `T`, `qa7.T`},
 427  		{`package qa8; type T int; var x *T`, `*T`, `*qa8.T`},
 428  		{`package qa9; type T int; var x (*T)`, `T`, `qa9.T`},
 429  		{`package qa10; type T int; var x (*T)`, `*T`, `*qa10.T`},
 430  		{`package qa11; type T int; var x *(T)`, `T`, `qa11.T`},
 431  		{`package qa12; type T int; var x *(T)`, `(T)`, `qa12.T`},
 432  		{`package qa13; type T int; var x *(T)`, `*(T)`, `*qa13.T`},
 433  		{`package qa14; type T int; var x (*(T))`, `(T)`, `qa14.T`},
 434  		{`package qa15; type T int; var x (*(T))`, `*(T)`, `*qa15.T`},
 435  		{`package qa16; type T int; var x (*(T))`, `(*(T))`, `*qa16.T`},
 436  
 437  		// - as ordinary function parameter, not generic
 438  		{`package qb1; type T int; func _(T)`, `T`, `qb1.T`},
 439  		{`package qb2; type T int; func _((T))`, `T`, `qb2.T`},
 440  		{`package qb3; type T int; func _((T))`, `(T)`, `qb3.T`},
 441  		{`package qb4; type T int; func _(((T)))`, `T`, `qb4.T`},
 442  		{`package qb5; type T int; func _(((T)))`, `(T)`, `qb5.T`},
 443  		{`package qb6; type T int; func _(((T)))`, `((T))`, `qb6.T`},
 444  		{`package qb7; type T int; func _(*T)`, `T`, `qb7.T`},
 445  		{`package qb8; type T int; func _(*T)`, `*T`, `*qb8.T`},
 446  		{`package qb9; type T int; func _((*T))`, `T`, `qb9.T`},
 447  		{`package qb10; type T int; func _((*T))`, `*T`, `*qb10.T`},
 448  		{`package qb11; type T int; func _(*(T))`, `T`, `qb11.T`},
 449  		{`package qb12; type T int; func _(*(T))`, `(T)`, `qb12.T`},
 450  		{`package qb13; type T int; func _(*(T))`, `*(T)`, `*qb13.T`},
 451  		{`package qb14; type T int; func _((*(T)))`, `(T)`, `qb14.T`},
 452  		{`package qb15; type T int; func _((*(T)))`, `*(T)`, `*qb15.T`},
 453  		{`package qb16; type T int; func _((*(T)))`, `(*(T))`, `*qb16.T`},
 454  
 455  		// - as method receiver, not generic
 456  		{`package qc1; type T int; func (T) _() {}`, `T`, `qc1.T`},
 457  		{`package qc2; type T int; func ((T)) _() {}`, `T`, `qc2.T`},
 458  		{`package qc3; type T int; func ((T)) _() {}`, `(T)`, `qc3.T`},
 459  		{`package qc4; type T int; func (((T))) _() {}`, `T`, `qc4.T`},
 460  		{`package qc5; type T int; func (((T))) _() {}`, `(T)`, `qc5.T`},
 461  		{`package qc6; type T int; func (((T))) _() {}`, `((T))`, `qc6.T`},
 462  		{`package qc7; type T int; func (*T) _() {}`, `T`, `qc7.T`},
 463  		{`package qc8; type T int; func (*T) _() {}`, `*T`, `*qc8.T`},
 464  		{`package qc9; type T int; func ((*T)) _() {}`, `T`, `qc9.T`},
 465  		{`package qc10; type T int; func ((*T)) _() {}`, `*T`, `*qc10.T`},
 466  		{`package qc11; type T int; func (*(T)) _() {}`, `T`, `qc11.T`},
 467  		{`package qc12; type T int; func (*(T)) _() {}`, `(T)`, `qc12.T`},
 468  		{`package qc13; type T int; func (*(T)) _() {}`, `*(T)`, `*qc13.T`},
 469  		{`package qc14; type T int; func ((*(T))) _() {}`, `(T)`, `qc14.T`},
 470  		{`package qc15; type T int; func ((*(T))) _() {}`, `*(T)`, `*qc15.T`},
 471  		{`package qc16; type T int; func ((*(T))) _() {}`, `(*(T))`, `*qc16.T`},
 472  
 473  		// - as variable type, generic
 474  		{`package qd1; type T[_ any] int; var x T[int]`, `T`, `qd1.T[_ any]`},
 475  		{`package qd2; type T[_ any] int; var x (T[int])`, `T[int]`, `qd2.T[int]`},
 476  		{`package qd3; type T[_ any] int; var x (T[int])`, `(T[int])`, `qd3.T[int]`},
 477  		{`package qd4; type T[_ any] int; var x ((T[int]))`, `T`, `qd4.T[_ any]`},
 478  		{`package qd5; type T[_ any] int; var x ((T[int]))`, `(T[int])`, `qd5.T[int]`},
 479  		{`package qd6; type T[_ any] int; var x ((T[int]))`, `((T[int]))`, `qd6.T[int]`},
 480  		{`package qd7; type T[_ any] int; var x *T[int]`, `T`, `qd7.T[_ any]`},
 481  		{`package qd8; type T[_ any] int; var x *T[int]`, `*T[int]`, `*qd8.T[int]`},
 482  		{`package qd9; type T[_ any] int; var x (*T[int])`, `T`, `qd9.T[_ any]`},
 483  		{`package qd10; type T[_ any] int; var x (*T[int])`, `*T[int]`, `*qd10.T[int]`},
 484  		{`package qd11; type T[_ any] int; var x *(T[int])`, `T[int]`, `qd11.T[int]`},
 485  		{`package qd12; type T[_ any] int; var x *(T[int])`, `(T[int])`, `qd12.T[int]`},
 486  		{`package qd13; type T[_ any] int; var x *(T[int])`, `*(T[int])`, `*qd13.T[int]`},
 487  		{`package qd14; type T[_ any] int; var x (*(T[int]))`, `(T[int])`, `qd14.T[int]`},
 488  		{`package qd15; type T[_ any] int; var x (*(T[int]))`, `*(T[int])`, `*qd15.T[int]`},
 489  		{`package qd16; type T[_ any] int; var x (*(T[int]))`, `(*(T[int]))`, `*qd16.T[int]`},
 490  
 491  		// - as ordinary function parameter, generic
 492  		{`package qe1; type T[_ any] int; func _(T[int])`, `T`, `qe1.T[_ any]`},
 493  		{`package qe2; type T[_ any] int; func _((T[int]))`, `T[int]`, `qe2.T[int]`},
 494  		{`package qe3; type T[_ any] int; func _((T[int]))`, `(T[int])`, `qe3.T[int]`},
 495  		{`package qe4; type T[_ any] int; func _(((T[int])))`, `T`, `qe4.T[_ any]`},
 496  		{`package qe5; type T[_ any] int; func _(((T[int])))`, `(T[int])`, `qe5.T[int]`},
 497  		{`package qe6; type T[_ any] int; func _(((T[int])))`, `((T[int]))`, `qe6.T[int]`},
 498  		{`package qe7; type T[_ any] int; func _(*T[int])`, `T`, `qe7.T[_ any]`},
 499  		{`package qe8; type T[_ any] int; func _(*T[int])`, `*T[int]`, `*qe8.T[int]`},
 500  		{`package qe9; type T[_ any] int; func _((*T[int]))`, `T`, `qe9.T[_ any]`},
 501  		{`package qe10; type T[_ any] int; func _((*T[int]))`, `*T[int]`, `*qe10.T[int]`},
 502  		{`package qe11; type T[_ any] int; func _(*(T[int]))`, `T[int]`, `qe11.T[int]`},
 503  		{`package qe12; type T[_ any] int; func _(*(T[int]))`, `(T[int])`, `qe12.T[int]`},
 504  		{`package qe13; type T[_ any] int; func _(*(T[int]))`, `*(T[int])`, `*qe13.T[int]`},
 505  		{`package qe14; type T[_ any] int; func _((*(T[int])))`, `(T[int])`, `qe14.T[int]`},
 506  		{`package qe15; type T[_ any] int; func _((*(T[int])))`, `*(T[int])`, `*qe15.T[int]`},
 507  		{`package qe16; type T[_ any] int; func _((*(T[int])))`, `(*(T[int]))`, `*qe16.T[int]`},
 508  
 509  		// - as method receiver, generic
 510  		{`package qf1; type T[_ any] int; func (T[_]) _() {}`, `T`, `qf1.T[_ any]`},
 511  		{`package qf2; type T[_ any] int; func ((T[_])) _() {}`, `T[_]`, `qf2.T[_]`},
 512  		{`package qf3; type T[_ any] int; func ((T[_])) _() {}`, `(T[_])`, `qf3.T[_]`},
 513  		{`package qf4; type T[_ any] int; func (((T[_]))) _() {}`, `T`, `qf4.T[_ any]`},
 514  		{`package qf5; type T[_ any] int; func (((T[_]))) _() {}`, `(T[_])`, `qf5.T[_]`},
 515  		{`package qf6; type T[_ any] int; func (((T[_]))) _() {}`, `((T[_]))`, `qf6.T[_]`},
 516  		{`package qf7; type T[_ any] int; func (*T[_]) _() {}`, `T`, `qf7.T[_ any]`},
 517  		{`package qf8; type T[_ any] int; func (*T[_]) _() {}`, `*T[_]`, `*qf8.T[_]`},
 518  		{`package qf9; type T[_ any] int; func ((*T[_])) _() {}`, `T`, `qf9.T[_ any]`},
 519  		{`package qf10; type T[_ any] int; func ((*T[_])) _() {}`, `*T[_]`, `*qf10.T[_]`},
 520  		{`package qf11; type T[_ any] int; func (*(T[_])) _() {}`, `T[_]`, `qf11.T[_]`},
 521  		{`package qf12; type T[_ any] int; func (*(T[_])) _() {}`, `(T[_])`, `qf12.T[_]`},
 522  		{`package qf13; type T[_ any] int; func (*(T[_])) _() {}`, `*(T[_])`, `*qf13.T[_]`},
 523  		{`package qf14; type T[_ any] int; func ((*(T[_]))) _() {}`, `(T[_])`, `qf14.T[_]`},
 524  		{`package qf15; type T[_ any] int; func ((*(T[_]))) _() {}`, `*(T[_])`, `*qf15.T[_]`},
 525  		{`package qf16; type T[_ any] int; func ((*(T[_]))) _() {}`, `(*(T[_]))`, `*qf16.T[_]`},
 526  
 527  		// For historic reasons, type parameters in receiver type expressions
 528  		// are considered both definitions and uses and thus also show up in
 529  		// the Info.Types map (see go.dev/issue/68670).
 530  		{`package t1; type T[_ any] int; func (T[P]) _() {}`, `P`, `P`},
 531  		{`package t2; type T[_, _ any] int; func (T[P, Q]) _() {}`, `P`, `P`},
 532  		{`package t3; type T[_, _ any] int; func (T[P, Q]) _() {}`, `Q`, `Q`},
 533  	}
 534  
 535  	for _, test := range tests {
 536  		info := Info{Types: make(map[ast.Expr]TypeAndValue)}
 537  		var name string
 538  		if strings.HasPrefix(test.src, broken) {
 539  			pkg, err := typecheck(test.src, nil, &info)
 540  			if err == nil {
 541  				t.Errorf("package %s: expected to fail but passed", pkg.Name())
 542  				continue
 543  			}
 544  			if pkg != nil {
 545  				name = pkg.Name()
 546  			}
 547  		} else {
 548  			name = mustTypecheck(test.src, nil, &info).Name()
 549  		}
 550  
 551  		// look for expression type
 552  		var typ Type
 553  		for e, tv := range info.Types {
 554  			if ExprString(e) == test.expr {
 555  				typ = tv.Type
 556  				break
 557  			}
 558  		}
 559  		if typ == nil {
 560  			t.Errorf("package %s: no type found for %s", name, test.expr)
 561  			continue
 562  		}
 563  
 564  		// check that type is correct
 565  		if got := typ.String(); got != test.typ {
 566  			t.Errorf("package %s: expr = %s: got %s; want %s", name, test.expr, got, test.typ)
 567  		}
 568  	}
 569  }
 570  
 571  func TestInstanceInfo(t *testing.T) {
 572  	const lib = `package lib
 573  
 574  func F[P any](P) {}
 575  
 576  type T[P any] []P
 577  `
 578  
 579  	type testInst struct {
 580  		name  string
 581  		targs []string
 582  		typ   string
 583  	}
 584  
 585  	var tests = []struct {
 586  		src       string
 587  		instances []testInst // recorded instances in source order
 588  	}{
 589  		{`package p0; func f[T any](T) {}; func _() { f(42) }`,
 590  			[]testInst{{`f`, []string{`int`}, `func(int)`}},
 591  		},
 592  		{`package p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
 593  			[]testInst{{`f`, []string{`rune`}, `func(rune) rune`}},
 594  		},
 595  		{`package p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
 596  			[]testInst{{`f`, []string{`complex128`}, `func(...complex128) complex128`}},
 597  		},
 598  		{`package p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
 599  			[]testInst{{`f`, []string{`float64`, `string`, `byte`}, `func(float64, *string, []byte)`}},
 600  		},
 601  		{`package p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
 602  			[]testInst{{`f`, []string{`float64`, `byte`}, `func(float64, *byte, ...[]byte)`}},
 603  		},
 604  
 605  		{`package s1; func f[T any, P interface{*T}](x T) {}; func _(x string) { f(x) }`,
 606  			[]testInst{{`f`, []string{`string`, `*string`}, `func(x string)`}},
 607  		},
 608  		{`package s2; func f[T any, P interface{*T}](x []T) {}; func _(x []int) { f(x) }`,
 609  			[]testInst{{`f`, []string{`int`, `*int`}, `func(x []int)`}},
 610  		},
 611  		{`package s3; type C[T any] interface{chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
 612  			[]testInst{
 613  				{`C`, []string{`T`}, `interface{chan<- T}`},
 614  				{`f`, []string{`int`, `chan<- int`}, `func(x []int)`},
 615  			},
 616  		},
 617  		{`package s4; type C[T any] interface{chan<- T}; func f[T any, P C[T], Q C[[]*P]](x []T) {}; func _(x []int) { f(x) }`,
 618  			[]testInst{
 619  				{`C`, []string{`T`}, `interface{chan<- T}`},
 620  				{`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
 621  				{`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func(x []int)`},
 622  			},
 623  		},
 624  
 625  		{`package t1; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = f[string] }`,
 626  			[]testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
 627  		},
 628  		{`package t2; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = (f[string]) }`,
 629  			[]testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
 630  		},
 631  		{`package t3; type C[T any] interface{chan<- T}; func f[T any, P C[T], Q C[[]*P]]() []T { return nil }; func _() { _ = f[int] }`,
 632  			[]testInst{
 633  				{`C`, []string{`T`}, `interface{chan<- T}`},
 634  				{`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
 635  				{`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
 636  			},
 637  		},
 638  		{`package t4; type C[T any] interface{chan<- T}; func f[T any, P C[T], Q C[[]*P]]() []T { return nil }; func _() { _ = (f[int]) }`,
 639  			[]testInst{
 640  				{`C`, []string{`T`}, `interface{chan<- T}`},
 641  				{`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
 642  				{`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
 643  			},
 644  		},
 645  		{`package i0; import "lib"; func _() { lib.F(42) }`,
 646  			[]testInst{{`F`, []string{`int`}, `func(int)`}},
 647  		},
 648  
 649  		{`package duplfunc0; func f[T any](T) {}; func _() { f(42); f("foo"); f[int](3) }`,
 650  			[]testInst{
 651  				{`f`, []string{`int`}, `func(int)`},
 652  				{`f`, []string{`string`}, `func(string)`},
 653  				{`f`, []string{`int`}, `func(int)`},
 654  			},
 655  		},
 656  		{`package duplfunc1; import "lib"; func _() { lib.F(42); lib.F("foo"); lib.F(3) }`,
 657  			[]testInst{
 658  				{`F`, []string{`int`}, `func(int)`},
 659  				{`F`, []string{`string`}, `func(string)`},
 660  				{`F`, []string{`int`}, `func(int)`},
 661  			},
 662  		},
 663  
 664  		{`package type0; type T[P interface{~int}] struct{ x P }; var _ T[int]`,
 665  			[]testInst{{`T`, []string{`int`}, `struct{x int}`}},
 666  		},
 667  		{`package type1; type T[P interface{~int}] struct{ x P }; var _ (T[int])`,
 668  			[]testInst{{`T`, []string{`int`}, `struct{x int}`}},
 669  		},
 670  		{`package type2; type T[P interface{~int}] struct{ x P }; var _ T[(int)]`,
 671  			[]testInst{{`T`, []string{`int`}, `struct{x int}`}},
 672  		},
 673  		{`package type3; type T[P1 interface{~[]P2}, P2 any] struct{ x P1; y P2 }; var _ T[[]int, int]`,
 674  			[]testInst{{`T`, []string{`[]int`, `int`}, `struct{x []int; y int}`}},
 675  		},
 676  		{`package type4; import "lib"; var _ lib.T[int]`,
 677  			[]testInst{{`T`, []string{`int`}, `[]int`}},
 678  		},
 679  
 680  		{`package dupltype0; type T[P interface{~int}] struct{ x P }; var x T[int]; var y T[int]`,
 681  			[]testInst{
 682  				{`T`, []string{`int`}, `struct{x int}`},
 683  				{`T`, []string{`int`}, `struct{x int}`},
 684  			},
 685  		},
 686  		{`package dupltype1; type T[P ~int] struct{ x P }; func (r *T[Q]) add(z T[Q]) { r.x += z.x }`,
 687  			[]testInst{
 688  				{`T`, []string{`Q`}, `struct{x Q}`},
 689  				{`T`, []string{`Q`}, `struct{x Q}`},
 690  			},
 691  		},
 692  		{`package dupltype1; import "lib"; var x lib.T[int]; var y lib.T[int]; var z lib.T[string]`,
 693  			[]testInst{
 694  				{`T`, []string{`int`}, `[]int`},
 695  				{`T`, []string{`int`}, `[]int`},
 696  				{`T`, []string{`string`}, `[]string`},
 697  			},
 698  		},
 699  		{`package issue51803; func foo[T any](T) {}; func _() { foo[int]( /* leave arg away on purpose */ ) }`,
 700  			[]testInst{{`foo`, []string{`int`}, `func(int)`}},
 701  		},
 702  
 703  		// reverse type inference
 704  		{`package reverse1a; var f func(int) = g; func g[P any](P) {}`,
 705  			[]testInst{{`g`, []string{`int`}, `func(int)`}},
 706  		},
 707  		{`package reverse1b; func f(func(int)) {}; func g[P any](P) {}; func _() { f(g) }`,
 708  			[]testInst{{`g`, []string{`int`}, `func(int)`}},
 709  		},
 710  		{`package reverse2a; var f func(int, string) = g; func g[P, Q any](P, Q) {}`,
 711  			[]testInst{{`g`, []string{`int`, `string`}, `func(int, string)`}},
 712  		},
 713  		{`package reverse2b; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}; func _() { f(g) }`,
 714  			[]testInst{{`g`, []string{`int`, `string`}, `func(int, string)`}},
 715  		},
 716  		{`package reverse2c; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}; func _() { f(g[int]) }`,
 717  			[]testInst{{`g`, []string{`int`, `string`}, `func(int, string)`}},
 718  		},
 719  		// reverse3a not possible (cannot assign to generic function outside of argument passing)
 720  		{`package reverse3b; func f[R any](func(int) R) {}; func g[P any](P) string { return "" }; func _() { f(g) }`,
 721  			[]testInst{
 722  				{`f`, []string{`string`}, `func(func(int) string)`},
 723  				{`g`, []string{`int`}, `func(int) string`},
 724  			},
 725  		},
 726  		{`package reverse4a; var _, _ func([]int, *float32) = g, h; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}`,
 727  			[]testInst{
 728  				{`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
 729  				{`h`, []string{`int`}, `func([]int, *float32)`},
 730  			},
 731  		},
 732  		{`package reverse4b; func f(_, _ func([]int, *float32)) {}; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}; func _() { f(g, h) }`,
 733  			[]testInst{
 734  				{`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
 735  				{`h`, []string{`int`}, `func([]int, *float32)`},
 736  			},
 737  		},
 738  		{`package issue59956; func f(func(int), func(string), func(bool)) {}; func g[P any](P) {}; func _() { f(g, g, g) }`,
 739  			[]testInst{
 740  				{`g`, []string{`int`}, `func(int)`},
 741  				{`g`, []string{`string`}, `func(string)`},
 742  				{`g`, []string{`bool`}, `func(bool)`},
 743  			},
 744  		},
 745  	}
 746  
 747  	for _, test := range tests {
 748  		imports := make(testImporter)
 749  		conf := Config{Importer: imports}
 750  		instMap := make(map[*ast.Ident]Instance)
 751  		useMap := make(map[*ast.Ident]Object)
 752  		makePkg := func(src string) *Package {
 753  			pkg, err := typecheck(src, &conf, &Info{Instances: instMap, Uses: useMap})
 754  			// allow error for issue51803
 755  			if err != nil && (pkg == nil || pkg.Name() != "issue51803") {
 756  				t.Fatal(err)
 757  			}
 758  			imports[pkg.Name()] = pkg
 759  			return pkg
 760  		}
 761  		makePkg(lib)
 762  		pkg := makePkg(test.src)
 763  
 764  		t.Run(pkg.Name(), func(t *testing.T) {
 765  			// Sort instances in source order for stability.
 766  			instances := sortedInstances(instMap)
 767  			if got, want := len(instances), len(test.instances); got != want {
 768  				t.Fatalf("got %d instances, want %d", got, want)
 769  			}
 770  
 771  			// Pairwise compare with the expected instances.
 772  			for ii, inst := range instances {
 773  				var targs []Type
 774  				for i := 0; i < inst.Inst.TypeArgs.Len(); i++ {
 775  					targs = append(targs, inst.Inst.TypeArgs.At(i))
 776  				}
 777  				typ := inst.Inst.Type
 778  
 779  				testInst := test.instances[ii]
 780  				if got := inst.Ident.Name; got != testInst.name {
 781  					t.Fatalf("got name %s, want %s", got, testInst.name)
 782  				}
 783  				if len(targs) != len(testInst.targs) {
 784  					t.Fatalf("got %d type arguments; want %d", len(targs), len(testInst.targs))
 785  				}
 786  				for i, targ := range targs {
 787  					if got := targ.String(); got != testInst.targs[i] {
 788  						t.Errorf("type argument %d: got %s; want %s", i, got, testInst.targs[i])
 789  					}
 790  				}
 791  				if got := typ.Underlying().String(); got != testInst.typ {
 792  					t.Errorf("package %s: got %s; want %s", pkg.Name(), got, testInst.typ)
 793  				}
 794  
 795  				// Verify the invariant that re-instantiating the corresponding generic
 796  				// type with TypeArgs results in an identical instance.
 797  				ptype := useMap[inst.Ident].Type()
 798  				lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
 799  				if lister == nil || lister.TypeParams().Len() == 0 {
 800  					t.Fatalf("info.Types[%v] = %v, want parameterized type", inst.Ident, ptype)
 801  				}
 802  				inst2, err := Instantiate(nil, ptype, targs, true)
 803  				if err != nil {
 804  					t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
 805  				}
 806  				if !Identical(inst.Inst.Type, inst2) {
 807  					t.Errorf("%v and %v are not identical", inst.Inst.Type, inst2)
 808  				}
 809  			}
 810  		})
 811  	}
 812  }
 813  
 814  type recordedInstance struct {
 815  	Ident *ast.Ident
 816  	Inst  Instance
 817  }
 818  
 819  func sortedInstances(m map[*ast.Ident]Instance) (instances []recordedInstance) {
 820  	for id, inst := range m {
 821  		instances = append(instances, recordedInstance{id, inst})
 822  	}
 823  	slices.SortFunc(instances, func(a, b recordedInstance) int {
 824  		return CmpPos(a.Ident.Pos(), b.Ident.Pos())
 825  	})
 826  	return instances
 827  }
 828  
 829  func TestDefsInfo(t *testing.T) {
 830  	var tests = []struct {
 831  		src  string
 832  		obj  string
 833  		want string
 834  	}{
 835  		{`package p0; const x = 42`, `x`, `const p0.x untyped int`},
 836  		{`package p1; const x int = 42`, `x`, `const p1.x int`},
 837  		{`package p2; var x int`, `x`, `var p2.x int`},
 838  		{`package p3; type x int`, `x`, `type p3.x int`},
 839  		{`package p4; func f()`, `f`, `func p4.f()`},
 840  		{`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
 841  
 842  		// Tests using generics.
 843  		{`package g0; type x[T any] int`, `x`, `type g0.x[T any] int`},
 844  		{`package g1; func f[T any]() {}`, `f`, `func g1.f[T any]()`},
 845  		{`package g2; type x[T any] int; func (*x[_]) m() {}`, `m`, `func (*g2.x[_]).m()`},
 846  
 847  		// Type parameters in receiver type expressions are definitions.
 848  		{`package r0; type T[_ any] int; func (T[P]) _() {}`, `P`, `type parameter P any`},
 849  		{`package r1; type T[_, _ any] int; func (T[P, Q]) _() {}`, `P`, `type parameter P any`},
 850  		{`package r2; type T[_, _ any] int; func (T[P, Q]) _() {}`, `Q`, `type parameter Q any`},
 851  	}
 852  
 853  	for _, test := range tests {
 854  		info := Info{
 855  			Defs: make(map[*ast.Ident]Object),
 856  		}
 857  		name := mustTypecheck(test.src, nil, &info).Name()
 858  
 859  		// find object
 860  		var def Object
 861  		for id, obj := range info.Defs {
 862  			if id.Name == test.obj {
 863  				def = obj
 864  				break
 865  			}
 866  		}
 867  		if def == nil {
 868  			t.Errorf("package %s: %s not found", name, test.obj)
 869  			continue
 870  		}
 871  
 872  		if got := def.String(); got != test.want {
 873  			t.Errorf("package %s: got %s; want %s", name, got, test.want)
 874  		}
 875  	}
 876  }
 877  
 878  func TestUsesInfo(t *testing.T) {
 879  	var tests = []struct {
 880  		src  string
 881  		obj  string
 882  		want string
 883  	}{
 884  		{`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
 885  		{`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
 886  		{`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
 887  		{`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
 888  		{`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
 889  
 890  		// Tests using generics.
 891  		{`package g0; func _[T any]() { _ = x }; const x = 42`, `x`, `const g0.x untyped int`},
 892  		{`package g1; func _[T any](x T) { }`, `T`, `type parameter T any`},
 893  		{`package g2; type N[A any] int; var _ N[int]`, `N`, `type g2.N[A any] int`},
 894  		{`package g3; type N[A any] int; func (N[_]) m() {}`, `N`, `type g3.N[A any] int`},
 895  
 896  		// Uses of fields are instantiated.
 897  		{`package s1; type N[A any] struct{ a A }; var f = N[int]{}.a`, `a`, `field a int`},
 898  		{`package s2; type N[A any] struct{ a A }; func (r N[B]) m(b B) { r.a = b }`, `a`, `field a B`},
 899  
 900  		// Uses of methods are uses of the instantiated method.
 901  		{`package m0; type N[A any] int; func (r N[B]) m() { r.n() }; func (N[C]) n() {}`, `n`, `func (m0.N[B]).n()`},
 902  		{`package m1; type N[A any] int; func (r N[B]) m() { }; var f = N[int].m`, `m`, `func (m1.N[int]).m()`},
 903  		{`package m2; func _[A any](v interface{ m() A }) { v.m() }`, `m`, `func (interface).m() A`},
 904  		{`package m3; func f[A any]() interface{ m() A } { return nil }; var _ = f[int]().m()`, `m`, `func (interface).m() int`},
 905  		{`package m4; type T[A any] func() interface{ m() A }; var x T[int]; var y = x().m`, `m`, `func (interface).m() int`},
 906  		{`package m5; type T[A any] interface{ m() A }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m5.T[B]).m() B`},
 907  		{`package m6; type T[A any] interface{ m() }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m6.T[B]).m()`},
 908  		{`package m7; type T[A any] interface{ m() A }; func _(t T[int]) { t.m() }`, `m`, `func (m7.T[int]).m() int`},
 909  		{`package m8; type T[A any] interface{ m() }; func _(t T[int]) { t.m() }`, `m`, `func (m8.T[int]).m()`},
 910  		{`package m9; type T[A any] interface{ m() }; func _(t T[int]) { _ = t.m }`, `m`, `func (m9.T[int]).m()`},
 911  		{
 912  			`package m10; type E[A any] interface{ m() }; type T[B any] interface{ E[B]; n() }; func _(t T[int]) { t.m() }`,
 913  			`m`,
 914  			`func (m10.E[int]).m()`,
 915  		},
 916  		{`package m11; type T[A any] interface{ m(); n() }; func _(t1 T[int], t2 T[string]) { t1.m(); t2.n() }`, `m`, `func (m11.T[int]).m()`},
 917  		{`package m12; type T[A any] interface{ m(); n() }; func _(t1 T[int], t2 T[string]) { t1.m(); t2.n() }`, `n`, `func (m12.T[string]).n()`},
 918  
 919  		// For historic reasons, type parameters in receiver type expressions
 920  		// are considered both definitions and uses (see go.dev/issue/68670).
 921  		{`package r0; type T[_ any] int; func (T[P]) _() {}`, `P`, `type parameter P any`},
 922  		{`package r1; type T[_, _ any] int; func (T[P, Q]) _() {}`, `P`, `type parameter P any`},
 923  		{`package r2; type T[_, _ any] int; func (T[P, Q]) _() {}`, `Q`, `type parameter Q any`},
 924  	}
 925  
 926  	for _, test := range tests {
 927  		info := Info{
 928  			Uses: make(map[*ast.Ident]Object),
 929  		}
 930  		name := mustTypecheck(test.src, nil, &info).Name()
 931  
 932  		// find object
 933  		var use Object
 934  		for id, obj := range info.Uses {
 935  			if id.Name == test.obj {
 936  				if use != nil {
 937  					panic(fmt.Sprintf("multiple uses of %q", id.Name))
 938  				}
 939  				use = obj
 940  			}
 941  		}
 942  		if use == nil {
 943  			t.Errorf("package %s: %s not found", name, test.obj)
 944  			continue
 945  		}
 946  
 947  		if got := use.String(); got != test.want {
 948  			t.Errorf("package %s: got %s; want %s", name, got, test.want)
 949  		}
 950  	}
 951  }
 952  
 953  func TestGenericMethodInfo(t *testing.T) {
 954  	src := `package p
 955  
 956  type N[A any] int
 957  
 958  func (r N[B]) m() { r.m(); r.n() }
 959  
 960  func (r *N[C]) n() {  }
 961  `
 962  	fset := token.NewFileSet()
 963  	f := mustParse(fset, src)
 964  	info := Info{
 965  		Defs:       make(map[*ast.Ident]Object),
 966  		Uses:       make(map[*ast.Ident]Object),
 967  		Selections: make(map[*ast.SelectorExpr]*Selection),
 968  	}
 969  	var conf Config
 970  	pkg, err := conf.Check("p", fset, []*ast.File{f}, &info)
 971  	if err != nil {
 972  		t.Fatal(err)
 973  	}
 974  
 975  	N := pkg.Scope().Lookup("N").Type().(*Named)
 976  
 977  	// Find the generic methods stored on N.
 978  	gm, gn := N.Method(0), N.Method(1)
 979  	if gm.Name() == "n" {
 980  		gm, gn = gn, gm
 981  	}
 982  
 983  	// Collect objects from info.
 984  	var dm, dn *Func   // the declared methods
 985  	var dmm, dmn *Func // the methods used in the body of m
 986  	for _, decl := range f.Decls {
 987  		fdecl, ok := decl.(*ast.FuncDecl)
 988  		if !ok {
 989  			continue
 990  		}
 991  		def := info.Defs[fdecl.Name].(*Func)
 992  		switch fdecl.Name.Name {
 993  		case "m":
 994  			dm = def
 995  			ast.Inspect(fdecl.Body, func(n ast.Node) bool {
 996  				if call, ok := n.(*ast.CallExpr); ok {
 997  					sel := call.Fun.(*ast.SelectorExpr)
 998  					use := info.Uses[sel.Sel].(*Func)
 999  					selection := info.Selections[sel]
1000  					if selection.Kind() != MethodVal {
1001  						t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
1002  					}
1003  					if selection.Obj() != use {
1004  						t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
1005  					}
1006  					switch sel.Sel.Name {
1007  					case "m":
1008  						dmm = use
1009  					case "n":
1010  						dmn = use
1011  					}
1012  				}
1013  				return true
1014  			})
1015  		case "n":
1016  			dn = def
1017  		}
1018  	}
1019  
1020  	if gm != dm {
1021  		t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
1022  	}
1023  	if gn != dn {
1024  		t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
1025  	}
1026  	if dmm != dm {
1027  		t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
1028  	}
1029  	if dmn == dn {
1030  		t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
1031  	}
1032  }
1033  
1034  func TestImplicitsInfo(t *testing.T) {
1035  	testenv.MustHaveGoBuild(t)
1036  
1037  	var tests = []struct {
1038  		src  string
1039  		want string
1040  	}{
1041  		{`package p2; import . "fmt"; var _ = Println`, ""},           // no Implicits entry
1042  		{`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
1043  		{`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
1044  
1045  		{`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
1046  		{`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
1047  		{`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
1048  		{`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
1049  
1050  		{`package p7; func f(x int) {}`, ""}, // no Implicits entry
1051  		{`package p8; func f(int) {}`, "field: var  int"},
1052  		{`package p9; func f() (complex64) { return 0 }`, "field: var  complex64"},
1053  		{`package p10; type T struct{}; func (*T) f() {}`, "field: var  *p10.T"},
1054  
1055  		// Tests using generics.
1056  		{`package f0; func f[T any](x int) {}`, ""}, // no Implicits entry
1057  		{`package f1; func f[T any](int) {}`, "field: var  int"},
1058  		{`package f2; func f[T any](T) {}`, "field: var  T"},
1059  		{`package f3; func f[T any]() (complex64) { return 0 }`, "field: var  complex64"},
1060  		{`package f4; func f[T any](t T) (T) { return t }`, "field: var  T"},
1061  		{`package t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var  *t0.T[_]"},
1062  		{`package t1; type T[A any] struct{}; func _(x interface{}) { switch t := x.(type) { case T[int]: _ = t } }`, "caseClause: var t t1.T[int]"},
1063  		{`package t2; type T[A any] struct{}; func _[P any](x interface{}) { switch t := x.(type) { case T[P]: _ = t } }`, "caseClause: var t t2.T[P]"},
1064  		{`package t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
1065  	}
1066  
1067  	for _, test := range tests {
1068  		info := Info{
1069  			Implicits: make(map[ast.Node]Object),
1070  		}
1071  		name := mustTypecheck(test.src, nil, &info).Name()
1072  
1073  		// the test cases expect at most one Implicits entry
1074  		if len(info.Implicits) > 1 {
1075  			t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
1076  			continue
1077  		}
1078  
1079  		// extract Implicits entry, if any
1080  		var got string
1081  		for n, obj := range info.Implicits {
1082  			switch x := n.(type) {
1083  			case *ast.ImportSpec:
1084  				got = "importSpec"
1085  			case *ast.CaseClause:
1086  				got = "caseClause"
1087  			case *ast.Field:
1088  				got = "field"
1089  			default:
1090  				t.Fatalf("package %s: unexpected %T", name, x)
1091  			}
1092  			got += ": " + obj.String()
1093  		}
1094  
1095  		// verify entry
1096  		if got != test.want {
1097  			t.Errorf("package %s: got %q; want %q", name, got, test.want)
1098  		}
1099  	}
1100  }
1101  
1102  func TestPkgNameOf(t *testing.T) {
1103  	testenv.MustHaveGoBuild(t)
1104  
1105  	const src = `
1106  package p
1107  
1108  import (
1109  	. "os"
1110  	_ "io"
1111  	"math"
1112  	"path/filepath"
1113  	snort "sort"
1114  )
1115  
1116  // avoid imported and not used errors
1117  var (
1118  	_ = Open // os.Open
1119  	_ = math.Sin
1120  	_ = filepath.Abs
1121  	_ = snort.Ints
1122  )
1123  `
1124  
1125  	var tests = []struct {
1126  		path string // path string enclosed in "'s
1127  		want string
1128  	}{
1129  		{`"os"`, "."},
1130  		{`"io"`, "_"},
1131  		{`"math"`, "math"},
1132  		{`"path/filepath"`, "filepath"},
1133  		{`"sort"`, "snort"},
1134  	}
1135  
1136  	fset := token.NewFileSet()
1137  	f := mustParse(fset, src)
1138  	info := Info{
1139  		Defs:      make(map[*ast.Ident]Object),
1140  		Implicits: make(map[ast.Node]Object),
1141  	}
1142  	var conf Config
1143  	conf.Importer = defaultImporter(fset)
1144  	_, err := conf.Check("p", fset, []*ast.File{f}, &info)
1145  	if err != nil {
1146  		t.Fatal(err)
1147  	}
1148  
1149  	// map import paths to importDecl
1150  	imports := make(map[string]*ast.ImportSpec)
1151  	for _, s := range f.Decls[0].(*ast.GenDecl).Specs {
1152  		if imp, _ := s.(*ast.ImportSpec); imp != nil {
1153  			imports[imp.Path.Value] = imp
1154  		}
1155  	}
1156  
1157  	for _, test := range tests {
1158  		imp := imports[test.path]
1159  		if imp == nil {
1160  			t.Fatalf("invalid test case: import path %s not found", test.path)
1161  		}
1162  		got := info.PkgNameOf(imp)
1163  		if got == nil {
1164  			t.Fatalf("import %s: package name not found", test.path)
1165  		}
1166  		if got.Name() != test.want {
1167  			t.Errorf("import %s: got %s; want %s", test.path, got.Name(), test.want)
1168  		}
1169  	}
1170  
1171  	// test non-existing importDecl
1172  	if got := info.PkgNameOf(new(ast.ImportSpec)); got != nil {
1173  		t.Errorf("got %s for non-existing import declaration", got.Name())
1174  	}
1175  }
1176  
1177  func predString(tv TypeAndValue) string {
1178  	var buf strings.Builder
1179  	pred := func(b bool, s string) {
1180  		if b {
1181  			if buf.Len() > 0 {
1182  				buf.WriteString(", ")
1183  			}
1184  			buf.WriteString(s)
1185  		}
1186  	}
1187  
1188  	pred(tv.IsVoid(), "void")
1189  	pred(tv.IsType(), "type")
1190  	pred(tv.IsBuiltin(), "builtin")
1191  	pred(tv.IsValue() && tv.Value != nil, "const")
1192  	pred(tv.IsValue() && tv.Value == nil, "value")
1193  	pred(tv.IsNil(), "nil")
1194  	pred(tv.Addressable(), "addressable")
1195  	pred(tv.Assignable(), "assignable")
1196  	pred(tv.HasOk(), "hasOk")
1197  
1198  	if buf.Len() == 0 {
1199  		return "invalid"
1200  	}
1201  	return buf.String()
1202  }
1203  
1204  func TestPredicatesInfo(t *testing.T) {
1205  	testenv.MustHaveGoBuild(t)
1206  
1207  	var tests = []struct {
1208  		src  string
1209  		expr string
1210  		pred string
1211  	}{
1212  		// void
1213  		{`package n0; func f() { f() }`, `f()`, `void`},
1214  
1215  		// types
1216  		{`package t0; type _ int`, `int`, `type`},
1217  		{`package t1; type _ []int`, `[]int`, `type`},
1218  		{`package t2; type _ func()`, `func()`, `type`},
1219  		{`package t3; type _ func(int)`, `int`, `type`},
1220  		{`package t3; type _ func(...int)`, `...int`, `type`},
1221  
1222  		// built-ins
1223  		{`package b0; var _ = len("")`, `len`, `builtin`},
1224  		{`package b1; var _ = (len)("")`, `(len)`, `builtin`},
1225  
1226  		// constants
1227  		{`package c0; var _ = 42`, `42`, `const`},
1228  		{`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
1229  		{`package c2; const (i = 1i; _ = i)`, `i`, `const`},
1230  
1231  		// values
1232  		{`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
1233  		{`package v1; var _ = &[]int{1}`, `[]int{…}`, `value`},
1234  		{`package v2; var _ = func(){}`, `(func() literal)`, `value`},
1235  		{`package v4; func f() { _ = f }`, `f`, `value`},
1236  		{`package v3; var _ *int = nil`, `nil`, `value, nil`},
1237  		{`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
1238  
1239  		// addressable (and thus assignable) operands
1240  		{`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
1241  		{`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
1242  		{`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
1243  		{`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
1244  		{`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
1245  		{`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
1246  		{`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
1247  		{`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
1248  		// composite literals are not addressable
1249  
1250  		// assignable but not addressable values
1251  		{`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1252  		{`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1253  
1254  		// hasOk expressions
1255  		{`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
1256  		{`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
1257  
1258  		// missing entries
1259  		// - package names are collected in the Uses map
1260  		// - identifiers being declared are collected in the Defs map
1261  		{`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
1262  		{`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
1263  		{`package m2; const c = 0`, `c`, `<missing>`},
1264  		{`package m3; type T int`, `T`, `<missing>`},
1265  		{`package m4; var v int`, `v`, `<missing>`},
1266  		{`package m5; func f() {}`, `f`, `<missing>`},
1267  		{`package m6; func _(x int) {}`, `x`, `<missing>`},
1268  		{`package m6; func _()(x int) { return }`, `x`, `<missing>`},
1269  		{`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
1270  	}
1271  
1272  	for _, test := range tests {
1273  		info := Info{Types: make(map[ast.Expr]TypeAndValue)}
1274  		name := mustTypecheck(test.src, nil, &info).Name()
1275  
1276  		// look for expression predicates
1277  		got := "<missing>"
1278  		for e, tv := range info.Types {
1279  			//println(name, ExprString(e))
1280  			if ExprString(e) == test.expr {
1281  				got = predString(tv)
1282  				break
1283  			}
1284  		}
1285  
1286  		if got != test.pred {
1287  			t.Errorf("package %s: got %s; want %s", name, got, test.pred)
1288  		}
1289  	}
1290  }
1291  
1292  func TestScopesInfo(t *testing.T) {
1293  	testenv.MustHaveGoBuild(t)
1294  
1295  	var tests = []struct {
1296  		src    string
1297  		scopes []string // list of scope descriptors of the form kind:varlist
1298  	}{
1299  		{`package p0`, []string{
1300  			"file:",
1301  		}},
1302  		{`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
1303  			"file:fmt m",
1304  		}},
1305  		{`package p2; func _() {}`, []string{
1306  			"file:", "func:",
1307  		}},
1308  		{`package p3; func _(x, y int) {}`, []string{
1309  			"file:", "func:x y",
1310  		}},
1311  		{`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
1312  			"file:", "func:x y z", // redeclaration of x
1313  		}},
1314  		{`package p5; func _(x, y int) (u, _ int) { return }`, []string{
1315  			"file:", "func:u x y",
1316  		}},
1317  		{`package p6; func _() { { var x int; _ = x } }`, []string{
1318  			"file:", "func:", "block:x",
1319  		}},
1320  		{`package p7; func _() { if true {} }`, []string{
1321  			"file:", "func:", "if:", "block:",
1322  		}},
1323  		{`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
1324  			"file:", "func:", "if:x", "block:y",
1325  		}},
1326  		{`package p9; func _() { switch x := 0; x {} }`, []string{
1327  			"file:", "func:", "switch:x",
1328  		}},
1329  		{`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
1330  			"file:", "func:", "switch:x", "case:y", "case:",
1331  		}},
1332  		{`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
1333  			"file:", "func:t", "type switch:",
1334  		}},
1335  		{`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
1336  			"file:", "func:t", "type switch:t",
1337  		}},
1338  		{`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
1339  			"file:", "func:t", "type switch:", "case:x", // x implicitly declared
1340  		}},
1341  		{`package p14; func _() { select{} }`, []string{
1342  			"file:", "func:",
1343  		}},
1344  		{`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
1345  			"file:", "func:c", "comm:",
1346  		}},
1347  		{`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
1348  			"file:", "func:c", "comm:i x",
1349  		}},
1350  		{`package p17; func _() { for{} }`, []string{
1351  			"file:", "func:", "for:", "block:",
1352  		}},
1353  		{`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
1354  			"file:", "func:n", "for:i", "block:",
1355  		}},
1356  		{`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
1357  			"file:", "func:a", "range:i", "block:",
1358  		}},
1359  		{`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
1360  			"file:", "func:a", "range:i x", "block:",
1361  		}},
1362  	}
1363  
1364  	for _, test := range tests {
1365  		info := Info{Scopes: make(map[ast.Node]*Scope)}
1366  		name := mustTypecheck(test.src, nil, &info).Name()
1367  
1368  		// number of scopes must match
1369  		if len(info.Scopes) != len(test.scopes) {
1370  			t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
1371  		}
1372  
1373  		// scope descriptions must match
1374  		for node, scope := range info.Scopes {
1375  			kind := "<unknown node kind>"
1376  			switch node.(type) {
1377  			case *ast.File:
1378  				kind = "file"
1379  			case *ast.FuncType:
1380  				kind = "func"
1381  			case *ast.BlockStmt:
1382  				kind = "block"
1383  			case *ast.IfStmt:
1384  				kind = "if"
1385  			case *ast.SwitchStmt:
1386  				kind = "switch"
1387  			case *ast.TypeSwitchStmt:
1388  				kind = "type switch"
1389  			case *ast.CaseClause:
1390  				kind = "case"
1391  			case *ast.CommClause:
1392  				kind = "comm"
1393  			case *ast.ForStmt:
1394  				kind = "for"
1395  			case *ast.RangeStmt:
1396  				kind = "range"
1397  			}
1398  
1399  			// look for matching scope description
1400  			desc := kind + ":" + strings.Join(scope.Names(), " ")
1401  			if !slices.Contains(test.scopes, desc) {
1402  				t.Errorf("package %s: no matching scope found for %s", name, desc)
1403  			}
1404  		}
1405  	}
1406  }
1407  
1408  func TestInitOrderInfo(t *testing.T) {
1409  	var tests = []struct {
1410  		src   string
1411  		inits []string
1412  	}{
1413  		{`package p0; var (x = 1; y = x)`, []string{
1414  			"x = 1", "y = x",
1415  		}},
1416  		{`package p1; var (a = 1; b = 2; c = 3)`, []string{
1417  			"a = 1", "b = 2", "c = 3",
1418  		}},
1419  		{`package p2; var (a, b, c = 1, 2, 3)`, []string{
1420  			"a = 1", "b = 2", "c = 3",
1421  		}},
1422  		{`package p3; var _ = f(); func f() int { return 1 }`, []string{
1423  			"_ = f()", // blank var
1424  		}},
1425  		{`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
1426  			"a = 0", "z = 0", "y = z", "x = y",
1427  		}},
1428  		{`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
1429  			"a, _ = m[0]", // blank var
1430  		}},
1431  		{`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
1432  			"z = 0", "a, b = f()",
1433  		}},
1434  		{`package p7; var (a = func() int { return b }(); b = 1)`, []string{
1435  			"b = 1", "a = (func() int literal)()",
1436  		}},
1437  		{`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
1438  			"c = 1", "a, b = (func() (_, _ int) literal)()",
1439  		}},
1440  		{`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1441  			"y = 1", "x = T.m",
1442  		}},
1443  		{`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1444  			"a = 0", "b = 0", "c = 0", "d = c + b",
1445  		}},
1446  		{`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
1447  			"c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
1448  		}},
1449  		// emit an initializer for n:1 initializations only once (not for each node
1450  		// on the lhs which may appear in different order in the dependency graph)
1451  		{`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
1452  			"b = 0", "x, y = m[0]", "a = x",
1453  		}},
1454  		// test case from spec section on package initialization
1455  		{`package p12
1456  
1457  		var (
1458  			a = c + b
1459  			b = f()
1460  			c = f()
1461  			d = 3
1462  		)
1463  
1464  		func f() int {
1465  			d++
1466  			return d
1467  		}`, []string{
1468  			"d = 3", "b = f()", "c = f()", "a = c + b",
1469  		}},
1470  		// test case for go.dev/issue/7131
1471  		{`package main
1472  
1473  		var counter int
1474  		func next() int { counter++; return counter }
1475  
1476  		var _ = makeOrder()
1477  		func makeOrder() []int { return []int{f, b, d, e, c, a} }
1478  
1479  		var a       = next()
1480  		var b, c    = next(), next()
1481  		var d, e, f = next(), next(), next()
1482  		`, []string{
1483  			"a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1484  		}},
1485  		// test case for go.dev/issue/10709
1486  		{`package p13
1487  
1488  		var (
1489  		    v = t.m()
1490  		    t = makeT(0)
1491  		)
1492  
1493  		type T struct{}
1494  
1495  		func (T) m() int { return 0 }
1496  
1497  		func makeT(n int) T {
1498  		    if n > 0 {
1499  		        return makeT(n-1)
1500  		    }
1501  		    return T{}
1502  		}`, []string{
1503  			"t = makeT(0)", "v = t.m()",
1504  		}},
1505  		// test case for go.dev/issue/10709: same as test before, but variable decls swapped
1506  		{`package p14
1507  
1508  		var (
1509  		    t = makeT(0)
1510  		    v = t.m()
1511  		)
1512  
1513  		type T struct{}
1514  
1515  		func (T) m() int { return 0 }
1516  
1517  		func makeT(n int) T {
1518  		    if n > 0 {
1519  		        return makeT(n-1)
1520  		    }
1521  		    return T{}
1522  		}`, []string{
1523  			"t = makeT(0)", "v = t.m()",
1524  		}},
1525  		// another candidate possibly causing problems with go.dev/issue/10709
1526  		{`package p15
1527  
1528  		var y1 = f1()
1529  
1530  		func f1() int { return g1() }
1531  		func g1() int { f1(); return x1 }
1532  
1533  		var x1 = 0
1534  
1535  		var y2 = f2()
1536  
1537  		func f2() int { return g2() }
1538  		func g2() int { return x2 }
1539  
1540  		var x2 = 0`, []string{
1541  			"x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1542  		}},
1543  	}
1544  
1545  	for _, test := range tests {
1546  		info := Info{}
1547  		name := mustTypecheck(test.src, nil, &info).Name()
1548  
1549  		// number of initializers must match
1550  		if len(info.InitOrder) != len(test.inits) {
1551  			t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1552  			continue
1553  		}
1554  
1555  		// initializers must match
1556  		for i, want := range test.inits {
1557  			got := info.InitOrder[i].String()
1558  			if got != want {
1559  				t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1560  				continue
1561  			}
1562  		}
1563  	}
1564  }
1565  
1566  func TestMultiFileInitOrder(t *testing.T) {
1567  	fset := token.NewFileSet()
1568  	fileA := mustParse(fset, `package main; var a = 1`)
1569  	fileB := mustParse(fset, `package main; var b = 2`)
1570  
1571  	// The initialization order must not depend on the parse
1572  	// order of the files, only on the presentation order to
1573  	// the type-checker.
1574  	for _, test := range []struct {
1575  		files []*ast.File
1576  		want  string
1577  	}{
1578  		{[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
1579  		{[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
1580  	} {
1581  		var info Info
1582  		if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
1583  			t.Fatal(err)
1584  		}
1585  		if got := fmt.Sprint(info.InitOrder); got != test.want {
1586  			t.Fatalf("got %s; want %s", got, test.want)
1587  		}
1588  	}
1589  }
1590  
1591  func TestFiles(t *testing.T) {
1592  	var sources = []string{
1593  		"package p; type T struct{}; func (T) m1() {}",
1594  		"package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1595  		"package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1596  		"package p",
1597  	}
1598  
1599  	var conf Config
1600  	fset := token.NewFileSet()
1601  	pkg := NewPackage("p", "p")
1602  	var info Info
1603  	check := NewChecker(&conf, fset, pkg, &info)
1604  
1605  	for _, src := range sources {
1606  		if err := check.Files([]*ast.File{mustParse(fset, src)}); err != nil {
1607  			t.Error(err)
1608  		}
1609  	}
1610  
1611  	// check InitOrder is [x y]
1612  	var vars []string
1613  	for _, init := range info.InitOrder {
1614  		for _, v := range init.Lhs {
1615  			vars = append(vars, v.Name())
1616  		}
1617  	}
1618  	if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1619  		t.Errorf("InitOrder == %s, want %s", got, want)
1620  	}
1621  }
1622  
1623  type testImporter map[string]*Package
1624  
1625  func (m testImporter) Import(path string) (*Package, error) {
1626  	if pkg := m[path]; pkg != nil {
1627  		return pkg, nil
1628  	}
1629  	return nil, fmt.Errorf("package %q not found", path)
1630  }
1631  
1632  func TestSelection(t *testing.T) {
1633  	selections := make(map[*ast.SelectorExpr]*Selection)
1634  
1635  	// We need a specific fileset in this test below for positions.
1636  	// Cannot use typecheck helper.
1637  	fset := token.NewFileSet()
1638  	imports := make(testImporter)
1639  	conf := Config{Importer: imports}
1640  	makePkg := func(path, src string) {
1641  		pkg, err := conf.Check(path, fset, []*ast.File{mustParse(fset, src)}, &Info{Selections: selections})
1642  		if err != nil {
1643  			t.Fatal(err)
1644  		}
1645  		imports[path] = pkg
1646  	}
1647  
1648  	const libSrc = `
1649  package lib
1650  type T float64
1651  const C T = 3
1652  var V T
1653  func F() {}
1654  func (T) M() {}
1655  `
1656  	const mainSrc = `
1657  package main
1658  import "lib"
1659  
1660  type A struct {
1661  	*B
1662  	C
1663  }
1664  
1665  type B struct {
1666  	b int
1667  }
1668  
1669  func (B) f(int)
1670  
1671  type C struct {
1672  	c int
1673  }
1674  
1675  type G[P any] struct {
1676  	p P
1677  }
1678  
1679  func (G[P]) m(P) {}
1680  
1681  var Inst G[int]
1682  
1683  func (C) g()
1684  func (*C) h()
1685  
1686  func main() {
1687  	// qualified identifiers
1688  	var _ lib.T
1689  	_ = lib.C
1690  	_ = lib.F
1691  	_ = lib.V
1692  	_ = lib.T.M
1693  
1694  	// fields
1695  	_ = A{}.B
1696  	_ = new(A).B
1697  
1698  	_ = A{}.C
1699  	_ = new(A).C
1700  
1701  	_ = A{}.b
1702  	_ = new(A).b
1703  
1704  	_ = A{}.c
1705  	_ = new(A).c
1706  
1707  	_ = Inst.p
1708  	_ = G[string]{}.p
1709  
1710  	// methods
1711  	_ = A{}.f
1712  	_ = new(A).f
1713  	_ = A{}.g
1714  	_ = new(A).g
1715  	_ = new(A).h
1716  
1717  	_ = B{}.f
1718  	_ = new(B).f
1719  
1720  	_ = C{}.g
1721  	_ = new(C).g
1722  	_ = new(C).h
1723  	_ = Inst.m
1724  
1725  	// method expressions
1726  	_ = A.f
1727  	_ = (*A).f
1728  	_ = B.f
1729  	_ = (*B).f
1730  	_ = G[string].m
1731  }`
1732  
1733  	wantOut := map[string][2]string{
1734  		"lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1735  
1736  		"A{}.B":    {"field (main.A) B *main.B", ".[0]"},
1737  		"new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1738  		"A{}.C":    {"field (main.A) C main.C", ".[1]"},
1739  		"new(A).C": {"field (*main.A) C main.C", "->[1]"},
1740  		"A{}.b":    {"field (main.A) b int", "->[0 0]"},
1741  		"new(A).b": {"field (*main.A) b int", "->[0 0]"},
1742  		"A{}.c":    {"field (main.A) c int", ".[1 0]"},
1743  		"new(A).c": {"field (*main.A) c int", "->[1 0]"},
1744  		"Inst.p":   {"field (main.G[int]) p int", ".[0]"},
1745  
1746  		"A{}.f":    {"method (main.A) f(int)", "->[0 0]"},
1747  		"new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1748  		"A{}.g":    {"method (main.A) g()", ".[1 0]"},
1749  		"new(A).g": {"method (*main.A) g()", "->[1 0]"},
1750  		"new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1751  		"B{}.f":    {"method (main.B) f(int)", ".[0]"},
1752  		"new(B).f": {"method (*main.B) f(int)", "->[0]"},
1753  		"C{}.g":    {"method (main.C) g()", ".[0]"},
1754  		"new(C).g": {"method (*main.C) g()", "->[0]"},
1755  		"new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1756  		"Inst.m":   {"method (main.G[int]) m(int)", ".[0]"},
1757  
1758  		"A.f":           {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1759  		"(*A).f":        {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1760  		"B.f":           {"method expr (main.B) f(main.B, int)", ".[0]"},
1761  		"(*B).f":        {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1762  		"G[string].m":   {"method expr (main.G[string]) m(main.G[string], string)", ".[0]"},
1763  		"G[string]{}.p": {"field (main.G[string]) p string", ".[0]"},
1764  	}
1765  
1766  	makePkg("lib", libSrc)
1767  	makePkg("main", mainSrc)
1768  
1769  	for e, sel := range selections {
1770  		_ = sel.String() // assertion: must not panic
1771  
1772  		start := fset.Position(e.Pos()).Offset
1773  		end := fset.Position(e.End()).Offset
1774  		syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1775  
1776  		direct := "."
1777  		if sel.Indirect() {
1778  			direct = "->"
1779  		}
1780  		got := [2]string{
1781  			sel.String(),
1782  			fmt.Sprintf("%s%v", direct, sel.Index()),
1783  		}
1784  		want := wantOut[syntax]
1785  		if want != got {
1786  			t.Errorf("%s: got %q; want %q", syntax, got, want)
1787  		}
1788  		delete(wantOut, syntax)
1789  
1790  		// We must explicitly assert properties of the
1791  		// Signature's receiver since it doesn't participate
1792  		// in Identical() or String().
1793  		sig, _ := sel.Type().(*Signature)
1794  		if sel.Kind() == MethodVal {
1795  			got := sig.Recv().Type()
1796  			want := sel.Recv()
1797  			if !Identical(got, want) {
1798  				t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
1799  			}
1800  		} else if sig != nil && sig.Recv() != nil {
1801  			t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1802  		}
1803  	}
1804  	// Assert that all wantOut entries were used exactly once.
1805  	for syntax := range wantOut {
1806  		t.Errorf("no ast.Selection found with syntax %q", syntax)
1807  	}
1808  }
1809  
1810  func TestIssue8518(t *testing.T) {
1811  	fset := token.NewFileSet()
1812  	imports := make(testImporter)
1813  	conf := Config{
1814  		Error:    func(err error) { t.Log(err) }, // don't exit after first error
1815  		Importer: imports,
1816  	}
1817  	makePkg := func(path, src string) {
1818  		imports[path], _ = conf.Check(path, fset, []*ast.File{mustParse(fset, src)}, nil) // errors logged via conf.Error
1819  	}
1820  
1821  	const libSrc = `
1822  package a
1823  import "missing"
1824  const C1 = foo
1825  const C2 = missing.C
1826  `
1827  
1828  	const mainSrc = `
1829  package main
1830  import "a"
1831  var _ = a.C1
1832  var _ = a.C2
1833  `
1834  
1835  	makePkg("a", libSrc)
1836  	makePkg("main", mainSrc) // don't crash when type-checking this package
1837  }
1838  
1839  func TestIssue59603(t *testing.T) {
1840  	fset := token.NewFileSet()
1841  	imports := make(testImporter)
1842  	conf := Config{
1843  		Error:    func(err error) { t.Log(err) }, // don't exit after first error
1844  		Importer: imports,
1845  	}
1846  	makePkg := func(path, src string) {
1847  		imports[path], _ = conf.Check(path, fset, []*ast.File{mustParse(fset, src)}, nil) // errors logged via conf.Error
1848  	}
1849  
1850  	const libSrc = `
1851  package a
1852  const C = foo
1853  `
1854  
1855  	const mainSrc = `
1856  package main
1857  import "a"
1858  const _ = a.C
1859  `
1860  
1861  	makePkg("a", libSrc)
1862  	makePkg("main", mainSrc) // don't crash when type-checking this package
1863  }
1864  
1865  func TestLookupFieldOrMethodOnNil(t *testing.T) {
1866  	// LookupFieldOrMethod on a nil type is expected to produce a run-time panic.
1867  	defer func() {
1868  		const want = "LookupFieldOrMethod on nil type"
1869  		p := recover()
1870  		if s, ok := p.(string); !ok || s != want {
1871  			t.Fatalf("got %v, want %s", p, want)
1872  		}
1873  	}()
1874  	LookupFieldOrMethod(nil, false, nil, "")
1875  }
1876  
1877  func TestLookupFieldOrMethod(t *testing.T) {
1878  	// Test cases assume a lookup of the form a.f or x.f, where a stands for an
1879  	// addressable value, and x for a non-addressable value (even though a variable
1880  	// for ease of test case writing).
1881  	//
1882  	// Should be kept in sync with TestMethodSet.
1883  	var tests = []struct {
1884  		src      string
1885  		found    bool
1886  		index    []int
1887  		indirect bool
1888  	}{
1889  		// field lookups
1890  		{"var x T; type T struct{}", false, nil, false},
1891  		{"var x T; type T struct{ f int }", true, []int{0}, false},
1892  		{"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1893  
1894  		// field lookups on a generic type
1895  		{"var x T[int]; type T[P any] struct{}", false, nil, false},
1896  		{"var x T[int]; type T[P any] struct{ f P }", true, []int{0}, false},
1897  		{"var x T[int]; type T[P any] struct{ a, b, f, c P }", true, []int{2}, false},
1898  
1899  		// method lookups
1900  		{"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1901  		{"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1902  		{"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1903  		{"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1904  
1905  		// method lookups on a generic type
1906  		{"var a T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, false},
1907  		{"var a *T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, true},
1908  		{"var a T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, false},
1909  		{"var a *T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1910  
1911  		// collisions
1912  		{"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1913  		{"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1914  
1915  		// collisions on a generic type
1916  		{"type ( E1[P any] struct{ f P }; E2[P any] struct{ f P }; x struct{ E1[int]; *E2[int] })", false, []int{1, 0}, false},
1917  		{"type ( E1[P any] struct{ f P }; E2[P any] struct{}; x struct{ E1[int]; *E2[int] }); func (E2[P]) f() {}", false, []int{1, 0}, false},
1918  
1919  		// outside methodset
1920  		// (*T).f method exists, but value of type T is not addressable
1921  		{"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1922  
1923  		// outside method set of a generic type
1924  		{"var x T[int]; type T[P any] struct{}; func (*T[P]) f() {}", false, nil, true},
1925  
1926  		// recursive generic types; see go.dev/issue/52715
1927  		{"var a T[int]; type ( T[P any] struct { *N[P] }; N[P any] struct { *T[P] } ); func (N[P]) f() {}", true, []int{0, 0}, true},
1928  		{"var a T[int]; type ( T[P any] struct { *N[P] }; N[P any] struct { *T[P] } ); func (T[P]) f() {}", true, []int{0}, false},
1929  	}
1930  
1931  	for _, test := range tests {
1932  		pkg := mustTypecheck("package p;"+test.src, nil, nil)
1933  
1934  		obj := pkg.Scope().Lookup("a")
1935  		if obj == nil {
1936  			if obj = pkg.Scope().Lookup("x"); obj == nil {
1937  				t.Errorf("%s: incorrect test case - no object a or x", test.src)
1938  				continue
1939  			}
1940  		}
1941  
1942  		f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1943  		if (f != nil) != test.found {
1944  			if f == nil {
1945  				t.Errorf("%s: got no object; want one", test.src)
1946  			} else {
1947  				t.Errorf("%s: got object = %v; want none", test.src, f)
1948  			}
1949  		}
1950  		if !slices.Equal(index, test.index) {
1951  			t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1952  		}
1953  		if indirect != test.indirect {
1954  			t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1955  		}
1956  	}
1957  }
1958  
1959  // Test for go.dev/issue/52715
1960  func TestLookupFieldOrMethod_RecursiveGeneric(t *testing.T) {
1961  	const src = `
1962  package pkg
1963  
1964  type Tree[T any] struct {
1965  	*Node[T]
1966  }
1967  
1968  func (*Tree[R]) N(r R) R { return r }
1969  
1970  type Node[T any] struct {
1971  	*Tree[T]
1972  }
1973  
1974  type Instance = *Tree[int]
1975  `
1976  
1977  	fset := token.NewFileSet()
1978  	f := mustParse(fset, src)
1979  	pkg := NewPackage("pkg", f.Name.Name)
1980  	if err := NewChecker(nil, fset, pkg, nil).Files([]*ast.File{f}); err != nil {
1981  		panic(err)
1982  	}
1983  
1984  	T := pkg.Scope().Lookup("Instance").Type()
1985  	_, _, _ = LookupFieldOrMethod(T, false, pkg, "M") // verify that LookupFieldOrMethod terminates
1986  }
1987  
1988  // newDefined creates a new defined type named T with the given underlying type.
1989  // Helper function for use with TestIncompleteInterfaces only.
1990  func newDefined(underlying Type) *Named {
1991  	tname := NewTypeName(nopos, nil, "T", nil)
1992  	return NewNamed(tname, underlying, nil)
1993  }
1994  
1995  func TestConvertibleTo(t *testing.T) {
1996  	for _, test := range []struct {
1997  		v, t Type
1998  		want bool
1999  	}{
2000  		{Typ[Int], Typ[Int], true},
2001  		{Typ[Int], Typ[Float32], true},
2002  		{Typ[Int], Typ[String], true},
2003  		{newDefined(Typ[Int]), Typ[Int], true},
2004  		{newDefined(new(Struct)), new(Struct), true},
2005  		{newDefined(Typ[Int]), new(Struct), false},
2006  		{Typ[UntypedInt], Typ[Int], true},
2007  		{NewSlice(Typ[Int]), NewArray(Typ[Int], 10), true},
2008  		{NewSlice(Typ[Int]), NewArray(Typ[Uint], 10), false},
2009  		{NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
2010  		{NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
2011  		// Untyped string values are not permitted by the spec, so the behavior below is undefined.
2012  		{Typ[UntypedString], Typ[String], true},
2013  	} {
2014  		if got := ConvertibleTo(test.v, test.t); got != test.want {
2015  			t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
2016  		}
2017  	}
2018  }
2019  
2020  func TestAssignableTo(t *testing.T) {
2021  	for _, test := range []struct {
2022  		v, t Type
2023  		want bool
2024  	}{
2025  		{Typ[Int], Typ[Int], true},
2026  		{Typ[Int], Typ[Float32], false},
2027  		{newDefined(Typ[Int]), Typ[Int], false},
2028  		{newDefined(new(Struct)), new(Struct), true},
2029  		{Typ[UntypedBool], Typ[Bool], true},
2030  		{Typ[UntypedString], Typ[Bool], false},
2031  		// Neither untyped string nor untyped numeric assignments arise during
2032  		// normal type checking, so the below behavior is technically undefined by
2033  		// the spec.
2034  		{Typ[UntypedString], Typ[String], true},
2035  		{Typ[UntypedInt], Typ[Int], true},
2036  	} {
2037  		if got := AssignableTo(test.v, test.t); got != test.want {
2038  			t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
2039  		}
2040  	}
2041  }
2042  
2043  func TestIdentical(t *testing.T) {
2044  	// For each test, we compare the types of objects X and Y in the source.
2045  	tests := []struct {
2046  		src  string
2047  		want bool
2048  	}{
2049  		// Basic types.
2050  		{"var X int; var Y int", true},
2051  		{"var X int; var Y string", false},
2052  
2053  		// TODO: add more tests for complex types.
2054  
2055  		// Named types.
2056  		{"type X int; type Y int", false},
2057  
2058  		// Aliases.
2059  		{"type X = int; type Y = int", true},
2060  
2061  		// Functions.
2062  		{`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
2063  		{`func X() string { return "" }; func Y(int) string { return "" }`, false},
2064  		{`func X(int) string { return "" }; func Y(int) {}`, false},
2065  
2066  		// Generic functions. Type parameters should be considered identical modulo
2067  		// renaming. See also go.dev/issue/49722.
2068  		{`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
2069  		{`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
2070  		{`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
2071  		{`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
2072  		{`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
2073  		{`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
2074  	}
2075  
2076  	for _, test := range tests {
2077  		pkg := mustTypecheck("package p;"+test.src, nil, nil)
2078  		X := pkg.Scope().Lookup("X")
2079  		Y := pkg.Scope().Lookup("Y")
2080  		if X == nil || Y == nil {
2081  			t.Fatal("test must declare both X and Y")
2082  		}
2083  		if got := Identical(X.Type(), Y.Type()); got != test.want {
2084  			t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
2085  		}
2086  	}
2087  }
2088  
2089  func TestIdentical_issue15173(t *testing.T) {
2090  	// Identical should allow nil arguments and be symmetric.
2091  	for _, test := range []struct {
2092  		x, y Type
2093  		want bool
2094  	}{
2095  		{Typ[Int], Typ[Int], true},
2096  		{Typ[Int], nil, false},
2097  		{nil, Typ[Int], false},
2098  		{nil, nil, true},
2099  	} {
2100  		if got := Identical(test.x, test.y); got != test.want {
2101  			t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2102  		}
2103  	}
2104  }
2105  
2106  func TestIdenticalUnions(t *testing.T) {
2107  	tname := NewTypeName(nopos, nil, "myInt", nil)
2108  	myInt := NewNamed(tname, Typ[Int], nil)
2109  	tmap := map[string]*Term{
2110  		"int":     NewTerm(false, Typ[Int]),
2111  		"~int":    NewTerm(true, Typ[Int]),
2112  		"string":  NewTerm(false, Typ[String]),
2113  		"~string": NewTerm(true, Typ[String]),
2114  		"myInt":   NewTerm(false, myInt),
2115  	}
2116  	makeUnion := func(s string) *Union {
2117  		parts := strings.Split(s, "|")
2118  		var terms []*Term
2119  		for _, p := range parts {
2120  			term := tmap[p]
2121  			if term == nil {
2122  				t.Fatalf("missing term %q", p)
2123  			}
2124  			terms = append(terms, term)
2125  		}
2126  		return NewUnion(terms)
2127  	}
2128  	for _, test := range []struct {
2129  		x, y string
2130  		want bool
2131  	}{
2132  		// These tests are just sanity checks. The tests for type sets and
2133  		// interfaces provide much more test coverage.
2134  		{"int|~int", "~int", true},
2135  		{"myInt|~int", "~int", true},
2136  		{"int|string", "string|int", true},
2137  		{"int|int|string", "string|int", true},
2138  		{"myInt|string", "int|string", false},
2139  	} {
2140  		x := makeUnion(test.x)
2141  		y := makeUnion(test.y)
2142  		if got := Identical(x, y); got != test.want {
2143  			t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2144  		}
2145  	}
2146  }
2147  
2148  func TestIssue61737(t *testing.T) {
2149  	// This test verifies that it is possible to construct invalid interfaces
2150  	// containing duplicate methods using the go/types API.
2151  	//
2152  	// It must be possible for importers to construct such invalid interfaces.
2153  	// Previously, this panicked.
2154  
2155  	sig1 := NewSignatureType(nil, nil, nil, NewTuple(NewParam(nopos, nil, "", Typ[Int])), nil, false)
2156  	sig2 := NewSignatureType(nil, nil, nil, NewTuple(NewParam(nopos, nil, "", Typ[String])), nil, false)
2157  
2158  	methods := []*Func{
2159  		NewFunc(nopos, nil, "M", sig1),
2160  		NewFunc(nopos, nil, "M", sig2),
2161  	}
2162  
2163  	embeddedMethods := []*Func{
2164  		NewFunc(nopos, nil, "M", sig2),
2165  	}
2166  	embedded := NewInterfaceType(embeddedMethods, nil)
2167  	iface := NewInterfaceType(methods, []Type{embedded})
2168  	iface.Complete()
2169  }
2170  
2171  func TestNewAlias_Issue65455(t *testing.T) {
2172  	obj := NewTypeName(nopos, nil, "A", nil)
2173  	alias := NewAlias(obj, Typ[Int])
2174  	alias.Underlying() // must not panic
2175  }
2176  
2177  func TestIssue15305(t *testing.T) {
2178  	const src = "package p; func f() int16; var _ = f(undef)"
2179  	fset := token.NewFileSet()
2180  	f := mustParse(fset, src)
2181  	conf := Config{
2182  		Error: func(err error) {}, // allow errors
2183  	}
2184  	info := &Info{
2185  		Types: make(map[ast.Expr]TypeAndValue),
2186  	}
2187  	conf.Check("p", fset, []*ast.File{f}, info) // ignore result
2188  	for e, tv := range info.Types {
2189  		if _, ok := e.(*ast.CallExpr); ok {
2190  			if tv.Type != Typ[Int16] {
2191  				t.Errorf("CallExpr has type %v, want int16", tv.Type)
2192  			}
2193  			return
2194  		}
2195  	}
2196  	t.Errorf("CallExpr has no type")
2197  }
2198  
2199  // TestCompositeLitTypes verifies that Info.Types registers the correct
2200  // types for composite literal expressions and composite literal type
2201  // expressions.
2202  func TestCompositeLitTypes(t *testing.T) {
2203  	for i, test := range []struct {
2204  		lit, typ string
2205  	}{
2206  		{`[16]byte{}`, `[16]byte`},
2207  		{`[...]byte{}`, `[0]byte`},                // test for go.dev/issue/14092
2208  		{`[...]int{1, 2, 3}`, `[3]int`},           // test for go.dev/issue/14092
2209  		{`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for go.dev/issue/14092
2210  		{`[]int{}`, `[]int`},
2211  		{`map[string]bool{"foo": true}`, `map[string]bool`},
2212  		{`struct{}{}`, `struct{}`},
2213  		{`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
2214  	} {
2215  		fset := token.NewFileSet()
2216  		f := mustParse(fset, fmt.Sprintf("package p%d; var _ = %s", i, test.lit))
2217  		types := make(map[ast.Expr]TypeAndValue)
2218  		if _, err := new(Config).Check("p", fset, []*ast.File{f}, &Info{Types: types}); err != nil {
2219  			t.Fatalf("%s: %v", test.lit, err)
2220  		}
2221  
2222  		cmptype := func(x ast.Expr, want string) {
2223  			tv, ok := types[x]
2224  			if !ok {
2225  				t.Errorf("%s: no Types entry found", test.lit)
2226  				return
2227  			}
2228  			if tv.Type == nil {
2229  				t.Errorf("%s: type is nil", test.lit)
2230  				return
2231  			}
2232  			if got := tv.Type.String(); got != want {
2233  				t.Errorf("%s: got %v, want %s", test.lit, got, want)
2234  			}
2235  		}
2236  
2237  		// test type of composite literal expression
2238  		rhs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0]
2239  		cmptype(rhs, test.typ)
2240  
2241  		// test type of composite literal type expression
2242  		cmptype(rhs.(*ast.CompositeLit).Type, test.typ)
2243  	}
2244  }
2245  
2246  // TestObjectParents verifies that objects have parent scopes or not
2247  // as specified by the Object interface.
2248  func TestObjectParents(t *testing.T) {
2249  	const src = `
2250  package p
2251  
2252  const C = 0
2253  
2254  type T1 struct {
2255  	a, b int
2256  	T2
2257  }
2258  
2259  type T2 interface {
2260  	im1()
2261  	im2()
2262  }
2263  
2264  func (T1) m1() {}
2265  func (*T1) m2() {}
2266  
2267  func f(x int) { y := x; print(y) }
2268  `
2269  
2270  	fset := token.NewFileSet()
2271  	f := mustParse(fset, src)
2272  
2273  	info := &Info{
2274  		Defs: make(map[*ast.Ident]Object),
2275  	}
2276  	if _, err := new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
2277  		t.Fatal(err)
2278  	}
2279  
2280  	for ident, obj := range info.Defs {
2281  		if obj == nil {
2282  			// only package names and implicit vars have a nil object
2283  			// (in this test we only need to handle the package name)
2284  			if ident.Name != "p" {
2285  				t.Errorf("%v has nil object", ident)
2286  			}
2287  			continue
2288  		}
2289  
2290  		// struct fields, type-associated and interface methods
2291  		// have no parent scope
2292  		wantParent := true
2293  		switch obj := obj.(type) {
2294  		case *Var:
2295  			if obj.IsField() {
2296  				wantParent = false
2297  			}
2298  		case *Func:
2299  			if obj.Signature().Recv() != nil { // method
2300  				wantParent = false
2301  			}
2302  		}
2303  
2304  		gotParent := obj.Parent() != nil
2305  		switch {
2306  		case gotParent && !wantParent:
2307  			t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
2308  		case !gotParent && wantParent:
2309  			t.Errorf("%v: no parent found", ident)
2310  		}
2311  	}
2312  }
2313  
2314  // TestFailedImport tests that we don't get follow-on errors
2315  // elsewhere in a package due to failing to import a package.
2316  func TestFailedImport(t *testing.T) {
2317  	testenv.MustHaveGoBuild(t)
2318  
2319  	const src = `
2320  package p
2321  
2322  import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
2323  
2324  const c = foo.C
2325  type T = foo.T
2326  var v T = c
2327  func f(x T) T { return foo.F(x) }
2328  `
2329  	fset := token.NewFileSet()
2330  	f := mustParse(fset, src)
2331  	files := []*ast.File{f}
2332  
2333  	// type-check using all possible importers
2334  	for _, compiler := range []string{"gc", "gccgo", "source"} {
2335  		errcount := 0
2336  		conf := Config{
2337  			Error: func(err error) {
2338  				// we should only see the import error
2339  				if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
2340  					t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
2341  				}
2342  				errcount++
2343  			},
2344  			Importer: importer.For(compiler, nil),
2345  		}
2346  
2347  		info := &Info{
2348  			Uses: make(map[*ast.Ident]Object),
2349  		}
2350  		pkg, _ := conf.Check("p", fset, files, info)
2351  		if pkg == nil {
2352  			t.Errorf("for %s importer, type-checking failed to return a package", compiler)
2353  			continue
2354  		}
2355  
2356  		imports := pkg.Imports()
2357  		if len(imports) != 1 {
2358  			t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
2359  			continue
2360  		}
2361  		imp := imports[0]
2362  		if imp.Name() != "foo" {
2363  			t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
2364  			continue
2365  		}
2366  
2367  		// verify that all uses of foo refer to the imported package foo (imp)
2368  		for ident, obj := range info.Uses {
2369  			if ident.Name == "foo" {
2370  				if obj, ok := obj.(*PkgName); ok {
2371  					if obj.Imported() != imp {
2372  						t.Errorf("%s resolved to %v; want %v", ident, obj.Imported(), imp)
2373  					}
2374  				} else {
2375  					t.Errorf("%s resolved to %v; want package name", ident, obj)
2376  				}
2377  			}
2378  		}
2379  	}
2380  }
2381  
2382  func TestInstantiate(t *testing.T) {
2383  	// eventually we like more tests but this is a start
2384  	const src = "package p; type T[P any] *T[P]"
2385  	pkg := mustTypecheck(src, nil, nil)
2386  
2387  	// type T should have one type parameter
2388  	T := pkg.Scope().Lookup("T").Type().(*Named)
2389  	if n := T.TypeParams().Len(); n != 1 {
2390  		t.Fatalf("expected 1 type parameter; found %d", n)
2391  	}
2392  
2393  	// instantiation should succeed (no endless recursion)
2394  	// even with a nil *Checker
2395  	res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
2396  	if err != nil {
2397  		t.Fatal(err)
2398  	}
2399  
2400  	// instantiated type should point to itself
2401  	if p := res.Underlying().(*Pointer).Elem(); p != res {
2402  		t.Fatalf("unexpected result type: %s points to %s", res, p)
2403  	}
2404  }
2405  
2406  func TestInstantiateConcurrent(t *testing.T) {
2407  	const src = `package p
2408  
2409  type I[P any] interface {
2410  	m(P)
2411  	n() P
2412  }
2413  
2414  type J = I[int]
2415  
2416  type Nested[P any] *interface{b(P)}
2417  
2418  type K = Nested[string]
2419  `
2420  	pkg := mustTypecheck(src, nil, nil)
2421  
2422  	insts := []*Interface{
2423  		pkg.Scope().Lookup("J").Type().Underlying().(*Interface),
2424  		pkg.Scope().Lookup("K").Type().Underlying().(*Pointer).Elem().(*Interface),
2425  	}
2426  
2427  	// Use the interface instances concurrently.
2428  	for _, inst := range insts {
2429  		var (
2430  			counts  [2]int      // method counts
2431  			methods [2][]string // method strings
2432  		)
2433  		var wg sync.WaitGroup
2434  		for i := 0; i < 2; i++ {
2435  			i := i
2436  			wg.Add(1)
2437  			go func() {
2438  				defer wg.Done()
2439  
2440  				counts[i] = inst.NumMethods()
2441  				for mi := 0; mi < counts[i]; mi++ {
2442  					methods[i] = append(methods[i], inst.Method(mi).String())
2443  				}
2444  			}()
2445  		}
2446  		wg.Wait()
2447  
2448  		if counts[0] != counts[1] {
2449  			t.Errorf("mismatching method counts for %s: %d vs %d", inst, counts[0], counts[1])
2450  			continue
2451  		}
2452  		for i := 0; i < counts[0]; i++ {
2453  			if m0, m1 := methods[0][i], methods[1][i]; m0 != m1 {
2454  				t.Errorf("mismatching methods for %s: %s vs %s", inst, m0, m1)
2455  			}
2456  		}
2457  	}
2458  }
2459  
2460  func TestInstantiateErrors(t *testing.T) {
2461  	tests := []struct {
2462  		src    string // by convention, T must be the type being instantiated
2463  		targs  []Type
2464  		wantAt int // -1 indicates no error
2465  	}{
2466  		{"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
2467  		{"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
2468  		{"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
2469  		{"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
2470  	}
2471  
2472  	for _, test := range tests {
2473  		src := "package p; " + test.src
2474  		pkg := mustTypecheck(src, nil, nil)
2475  
2476  		T := pkg.Scope().Lookup("T").Type().(*Named)
2477  
2478  		_, err := Instantiate(nil, T, test.targs, true)
2479  		if err == nil {
2480  			t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
2481  		}
2482  
2483  		var argErr *ArgumentError
2484  		if !errors.As(err, &argErr) {
2485  			t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
2486  		}
2487  
2488  		if argErr.Index != test.wantAt {
2489  			t.Errorf("Instantiate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2490  		}
2491  	}
2492  }
2493  
2494  func TestArgumentErrorUnwrapping(t *testing.T) {
2495  	var err error = &ArgumentError{
2496  		Index: 1,
2497  		Err:   Error{Msg: "test"},
2498  	}
2499  	var e Error
2500  	if !errors.As(err, &e) {
2501  		t.Fatalf("error %v does not wrap types.Error", err)
2502  	}
2503  	if e.Msg != "test" {
2504  		t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2505  	}
2506  }
2507  
2508  func TestInstanceIdentity(t *testing.T) {
2509  	imports := make(testImporter)
2510  	conf := Config{Importer: imports}
2511  	makePkg := func(src string) {
2512  		fset := token.NewFileSet()
2513  		f := mustParse(fset, src)
2514  		name := f.Name.Name
2515  		pkg, err := conf.Check(name, fset, []*ast.File{f}, nil)
2516  		if err != nil {
2517  			t.Fatal(err)
2518  		}
2519  		imports[name] = pkg
2520  	}
2521  	makePkg(`package lib; type T[P any] struct{}`)
2522  	makePkg(`package a; import "lib"; var A lib.T[int]`)
2523  	makePkg(`package b; import "lib"; var B lib.T[int]`)
2524  	a := imports["a"].Scope().Lookup("A")
2525  	b := imports["b"].Scope().Lookup("B")
2526  	if !Identical(a.Type(), b.Type()) {
2527  		t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
2528  	}
2529  }
2530  
2531  // TestInstantiatedObjects verifies properties of instantiated objects.
2532  func TestInstantiatedObjects(t *testing.T) {
2533  	const src = `
2534  package p
2535  
2536  type T[P any] struct {
2537  	field P
2538  }
2539  
2540  func (recv *T[Q]) concreteMethod(mParam Q) (mResult Q) { return }
2541  
2542  type FT[P any] func(ftParam P) (ftResult P)
2543  
2544  func F[P any](fParam P) (fResult P){ return }
2545  
2546  type I[P any] interface {
2547  	interfaceMethod(P)
2548  }
2549  
2550  type R[P any] T[P]
2551  
2552  func (R[P]) m() {} // having a method triggers expansion of R
2553  
2554  var (
2555  	t T[int]
2556  	ft FT[int]
2557  	f = F[int]
2558  	i I[int]
2559  )
2560  
2561  func fn() {
2562  	var r R[int]
2563  	_ = r
2564  }
2565  `
2566  	info := &Info{
2567  		Defs: make(map[*ast.Ident]Object),
2568  	}
2569  	fset := token.NewFileSet()
2570  	f := mustParse(fset, src)
2571  	conf := Config{}
2572  	pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
2573  	if err != nil {
2574  		t.Fatal(err)
2575  	}
2576  
2577  	lookup := func(name string) Type { return pkg.Scope().Lookup(name).Type() }
2578  	fnScope := pkg.Scope().Lookup("fn").(*Func).Scope()
2579  
2580  	tests := []struct {
2581  		name string
2582  		obj  Object
2583  	}{
2584  		// Struct fields
2585  		{"field", lookup("t").Underlying().(*Struct).Field(0)},
2586  		{"field", fnScope.Lookup("r").Type().Underlying().(*Struct).Field(0)},
2587  
2588  		// Methods and method fields
2589  		{"concreteMethod", lookup("t").(*Named).Method(0)},
2590  		{"recv", lookup("t").(*Named).Method(0).Signature().Recv()},
2591  		{"mParam", lookup("t").(*Named).Method(0).Signature().Params().At(0)},
2592  		{"mResult", lookup("t").(*Named).Method(0).Signature().Results().At(0)},
2593  
2594  		// Interface methods
2595  		{"interfaceMethod", lookup("i").Underlying().(*Interface).Method(0)},
2596  
2597  		// Function type fields
2598  		{"ftParam", lookup("ft").Underlying().(*Signature).Params().At(0)},
2599  		{"ftResult", lookup("ft").Underlying().(*Signature).Results().At(0)},
2600  
2601  		// Function fields
2602  		{"fParam", lookup("f").(*Signature).Params().At(0)},
2603  		{"fResult", lookup("f").(*Signature).Results().At(0)},
2604  	}
2605  
2606  	// Collect all identifiers by name.
2607  	idents := make(map[string][]*ast.Ident)
2608  	ast.Inspect(f, func(n ast.Node) bool {
2609  		if id, ok := n.(*ast.Ident); ok {
2610  			idents[id.Name] = append(idents[id.Name], id)
2611  		}
2612  		return true
2613  	})
2614  
2615  	for _, test := range tests {
2616  		test := test
2617  		t.Run(test.name, func(t *testing.T) {
2618  			if got := len(idents[test.name]); got != 1 {
2619  				t.Fatalf("found %d identifiers named %s, want 1", got, test.name)
2620  			}
2621  			ident := idents[test.name][0]
2622  			def := info.Defs[ident]
2623  			if def == test.obj {
2624  				t.Fatalf("info.Defs[%s] contains the test object", test.name)
2625  			}
2626  			if orig := originObject(test.obj); def != orig {
2627  				t.Errorf("info.Defs[%s] does not match obj.Origin()", test.name)
2628  			}
2629  			if def.Pkg() != test.obj.Pkg() {
2630  				t.Errorf("Pkg() = %v, want %v", def.Pkg(), test.obj.Pkg())
2631  			}
2632  			if def.Name() != test.obj.Name() {
2633  				t.Errorf("Name() = %v, want %v", def.Name(), test.obj.Name())
2634  			}
2635  			if def.Pos() != test.obj.Pos() {
2636  				t.Errorf("Pos() = %v, want %v", def.Pos(), test.obj.Pos())
2637  			}
2638  			if def.Parent() != test.obj.Parent() {
2639  				t.Fatalf("Parent() = %v, want %v", def.Parent(), test.obj.Parent())
2640  			}
2641  			if def.Exported() != test.obj.Exported() {
2642  				t.Fatalf("Exported() = %v, want %v", def.Exported(), test.obj.Exported())
2643  			}
2644  			if def.Id() != test.obj.Id() {
2645  				t.Fatalf("Id() = %v, want %v", def.Id(), test.obj.Id())
2646  			}
2647  			// String and Type are expected to differ.
2648  		})
2649  	}
2650  }
2651  
2652  func originObject(obj Object) Object {
2653  	switch obj := obj.(type) {
2654  	case *Var:
2655  		return obj.Origin()
2656  	case *Func:
2657  		return obj.Origin()
2658  	}
2659  	return obj
2660  }
2661  
2662  func TestImplements(t *testing.T) {
2663  	const src = `
2664  package p
2665  
2666  type EmptyIface interface{}
2667  
2668  type I interface {
2669  	m()
2670  }
2671  
2672  type C interface {
2673  	m()
2674  	~int
2675  }
2676  
2677  type Integer interface{
2678  	int8 | int16 | int32 | int64
2679  }
2680  
2681  type EmptyTypeSet interface{
2682  	Integer
2683  	~string
2684  }
2685  
2686  type N1 int
2687  func (N1) m() {}
2688  
2689  type N2 int
2690  func (*N2) m() {}
2691  
2692  type N3 int
2693  func (N3) m(int) {}
2694  
2695  type N4 string
2696  func (N4) m()
2697  
2698  type Bad Bad // invalid type
2699  `
2700  
2701  	fset := token.NewFileSet()
2702  	f := mustParse(fset, src)
2703  	conf := Config{Error: func(error) {}}
2704  	pkg, _ := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
2705  
2706  	lookup := func(tname string) Type { return pkg.Scope().Lookup(tname).Type() }
2707  	var (
2708  		EmptyIface   = lookup("EmptyIface").Underlying().(*Interface)
2709  		I            = lookup("I").(*Named)
2710  		II           = I.Underlying().(*Interface)
2711  		C            = lookup("C").(*Named)
2712  		CI           = C.Underlying().(*Interface)
2713  		Integer      = lookup("Integer").Underlying().(*Interface)
2714  		EmptyTypeSet = lookup("EmptyTypeSet").Underlying().(*Interface)
2715  		N1           = lookup("N1")
2716  		N1p          = NewPointer(N1)
2717  		N2           = lookup("N2")
2718  		N2p          = NewPointer(N2)
2719  		N3           = lookup("N3")
2720  		N4           = lookup("N4")
2721  		Bad          = lookup("Bad")
2722  	)
2723  
2724  	tests := []struct {
2725  		V    Type
2726  		T    *Interface
2727  		want bool
2728  	}{
2729  		{I, II, true},
2730  		{I, CI, false},
2731  		{C, II, true},
2732  		{C, CI, true},
2733  		{Typ[Int8], Integer, true},
2734  		{Typ[Int64], Integer, true},
2735  		{Typ[String], Integer, false},
2736  		{EmptyTypeSet, II, true},
2737  		{EmptyTypeSet, EmptyTypeSet, true},
2738  		{Typ[Int], EmptyTypeSet, false},
2739  		{N1, II, true},
2740  		{N1, CI, true},
2741  		{N1p, II, true},
2742  		{N1p, CI, false},
2743  		{N2, II, false},
2744  		{N2, CI, false},
2745  		{N2p, II, true},
2746  		{N2p, CI, false},
2747  		{N3, II, false},
2748  		{N3, CI, false},
2749  		{N4, II, true},
2750  		{N4, CI, false},
2751  		{Bad, II, false},
2752  		{Bad, CI, false},
2753  		{Bad, EmptyIface, true},
2754  	}
2755  
2756  	for _, test := range tests {
2757  		if got := Implements(test.V, test.T); got != test.want {
2758  			t.Errorf("Implements(%s, %s) = %t, want %t", test.V, test.T, got, test.want)
2759  		}
2760  
2761  		// The type assertion x.(T) is valid if T is an interface or if T implements the type of x.
2762  		// The assertion is never valid if T is a bad type.
2763  		V := test.T
2764  		T := test.V
2765  		want := false
2766  		if _, ok := T.Underlying().(*Interface); (ok || Implements(T, V)) && T != Bad {
2767  			want = true
2768  		}
2769  		if got := AssertableTo(V, T); got != want {
2770  			t.Errorf("AssertableTo(%s, %s) = %t, want %t", V, T, got, want)
2771  		}
2772  	}
2773  }
2774  
2775  func TestMissingMethodAlternative(t *testing.T) {
2776  	const src = `
2777  package p
2778  type T interface {
2779  	m()
2780  }
2781  
2782  type V0 struct{}
2783  func (V0) m() {}
2784  
2785  type V1 struct{}
2786  
2787  type V2 struct{}
2788  func (V2) m() int
2789  
2790  type V3 struct{}
2791  func (*V3) m()
2792  
2793  type V4 struct{}
2794  func (V4) M()
2795  `
2796  
2797  	pkg := mustTypecheck(src, nil, nil)
2798  
2799  	T := pkg.Scope().Lookup("T").Type().Underlying().(*Interface)
2800  	lookup := func(name string) (*Func, bool) {
2801  		return MissingMethod(pkg.Scope().Lookup(name).Type(), T, true)
2802  	}
2803  
2804  	// V0 has method m with correct signature. Should not report wrongType.
2805  	method, wrongType := lookup("V0")
2806  	if method != nil || wrongType {
2807  		t.Fatalf("V0: got method = %v, wrongType = %v", method, wrongType)
2808  	}
2809  
2810  	checkMissingMethod := func(tname string, reportWrongType bool) {
2811  		method, wrongType := lookup(tname)
2812  		if method == nil || method.Name() != "m" || wrongType != reportWrongType {
2813  			t.Fatalf("%s: got method = %v, wrongType = %v", tname, method, wrongType)
2814  		}
2815  	}
2816  
2817  	// V1 has no method m. Should not report wrongType.
2818  	checkMissingMethod("V1", false)
2819  
2820  	// V2 has method m with wrong signature type (ignoring receiver). Should report wrongType.
2821  	checkMissingMethod("V2", true)
2822  
2823  	// V3 has no method m but it exists on *V3. Should report wrongType.
2824  	checkMissingMethod("V3", true)
2825  
2826  	// V4 has no method m but has M. Should not report wrongType.
2827  	checkMissingMethod("V4", false)
2828  }
2829  
2830  func TestErrorURL(t *testing.T) {
2831  	var conf Config
2832  	*stringFieldAddr(&conf, "_ErrorURL") = " [go.dev/e/%s]"
2833  
2834  	// test case for a one-line error
2835  	const src1 = `
2836  package p
2837  var _ T
2838  `
2839  	_, err := typecheck(src1, &conf, nil)
2840  	if err == nil || !strings.HasSuffix(err.Error(), " [go.dev/e/UndeclaredName]") {
2841  		t.Errorf("src1: unexpected error: got %v", err)
2842  	}
2843  
2844  	// test case for a multi-line error
2845  	const src2 = `
2846  package p
2847  func f() int { return 0 }
2848  var _ = f(1, 2)
2849  `
2850  	_, err = typecheck(src2, &conf, nil)
2851  	if err == nil || !strings.Contains(err.Error(), " [go.dev/e/WrongArgCount]\n") {
2852  		t.Errorf("src1: unexpected error: got %v", err)
2853  	}
2854  }
2855  
2856  func TestModuleVersion(t *testing.T) {
2857  	// version go1.dd must be able to typecheck go1.dd.0, go1.dd.1, etc.
2858  	goversion := fmt.Sprintf("go1.%d", goversion.Version)
2859  	for _, v := range []string{
2860  		goversion,
2861  		goversion + ".0",
2862  		goversion + ".1",
2863  		goversion + ".rc",
2864  	} {
2865  		conf := Config{GoVersion: v}
2866  		pkg := mustTypecheck("package p", &conf, nil)
2867  		if pkg.GoVersion() != conf.GoVersion {
2868  			t.Errorf("got %s; want %s", pkg.GoVersion(), conf.GoVersion)
2869  		}
2870  	}
2871  }
2872  
2873  func TestFileVersions(t *testing.T) {
2874  	for _, test := range []struct {
2875  		goVersion   string
2876  		fileVersion string
2877  		wantVersion string
2878  	}{
2879  		{"", "", ""},                    // no versions specified
2880  		{"go1.19", "", "go1.19"},        // module version specified
2881  		{"", "go1.20", "go1.21"},        // file version specified below minimum of 1.21
2882  		{"go1", "", "go1"},              // no file version specified
2883  		{"go1", "goo1.22", "go1"},       // invalid file version specified
2884  		{"go1", "go1.19", "go1.21"},     // file version specified below minimum of 1.21
2885  		{"go1", "go1.20", "go1.21"},     // file version specified below minimum of 1.21
2886  		{"go1", "go1.21", "go1.21"},     // file version specified at 1.21
2887  		{"go1", "go1.22", "go1.22"},     // file version specified above 1.21
2888  		{"go1.19", "", "go1.19"},        // no file version specified
2889  		{"go1.19", "goo1.22", "go1.19"}, // invalid file version specified
2890  		{"go1.19", "go1.20", "go1.21"},  // file version specified below minimum of 1.21
2891  		{"go1.19", "go1.21", "go1.21"},  // file version specified at 1.21
2892  		{"go1.19", "go1.22", "go1.22"},  // file version specified above 1.21
2893  		{"go1.20", "", "go1.20"},        // no file version specified
2894  		{"go1.20", "goo1.22", "go1.20"}, // invalid file version specified
2895  		{"go1.20", "go1.19", "go1.21"},  // file version specified below minimum of 1.21
2896  		{"go1.20", "go1.20", "go1.21"},  // file version specified below minimum of 1.21
2897  		{"go1.20", "go1.21", "go1.21"},  // file version specified at 1.21
2898  		{"go1.20", "go1.22", "go1.22"},  // file version specified above 1.21
2899  		{"go1.21", "", "go1.21"},        // no file version specified
2900  		{"go1.21", "goo1.22", "go1.21"}, // invalid file version specified
2901  		{"go1.21", "go1.19", "go1.21"},  // file version specified below minimum of 1.21
2902  		{"go1.21", "go1.20", "go1.21"},  // file version specified below minimum of 1.21
2903  		{"go1.21", "go1.21", "go1.21"},  // file version specified at 1.21
2904  		{"go1.21", "go1.22", "go1.22"},  // file version specified above 1.21
2905  		{"go1.22", "", "go1.22"},        // no file version specified
2906  		{"go1.22", "goo1.22", "go1.22"}, // invalid file version specified
2907  		{"go1.22", "go1.19", "go1.21"},  // file version specified below minimum of 1.21
2908  		{"go1.22", "go1.20", "go1.21"},  // file version specified below minimum of 1.21
2909  		{"go1.22", "go1.21", "go1.21"},  // file version specified at 1.21
2910  		{"go1.22", "go1.22", "go1.22"},  // file version specified above 1.21
2911  
2912  		// versions containing release numbers
2913  		// (file versions containing release numbers are considered invalid)
2914  		{"go1.19.0", "", "go1.19.0"},         // no file version specified
2915  		{"go1.20.1", "go1.19.1", "go1.20.1"}, // invalid file version
2916  		{"go1.20.1", "go1.21.1", "go1.20.1"}, // invalid file version
2917  		{"go1.21.1", "go1.19.1", "go1.21.1"}, // invalid file version
2918  		{"go1.21.1", "go1.21.1", "go1.21.1"}, // invalid file version
2919  		{"go1.22.1", "go1.19.1", "go1.22.1"}, // invalid file version
2920  		{"go1.22.1", "go1.21.1", "go1.22.1"}, // invalid file version
2921  	} {
2922  		var src string
2923  		if test.fileVersion != "" {
2924  			src = "//go:build " + test.fileVersion + "\n"
2925  		}
2926  		src += "package p"
2927  
2928  		conf := Config{GoVersion: test.goVersion}
2929  		versions := make(map[*ast.File]string)
2930  		var info Info
2931  		info.FileVersions = versions
2932  		mustTypecheck(src, &conf, &info)
2933  
2934  		n := 0
2935  		for _, v := range versions {
2936  			want := test.wantVersion
2937  			if v != want {
2938  				t.Errorf("%q: unexpected file version: got %q, want %q", src, v, want)
2939  			}
2940  			n++
2941  		}
2942  		if n != 1 {
2943  			t.Errorf("%q: incorrect number of map entries: got %d", src, n)
2944  		}
2945  	}
2946  }
2947  
2948  // TestTooNew ensures that "too new" errors are emitted when the file
2949  // or module is tagged with a newer version of Go than this go/types.
2950  func TestTooNew(t *testing.T) {
2951  	for _, test := range []struct {
2952  		goVersion   string // package's Go version (as if derived from go.mod file)
2953  		fileVersion string // file's Go version (becomes a build tag)
2954  		wantErr     string // expected substring of concatenation of all errors
2955  	}{
2956  		{"go1.98", "", "package requires newer Go version go1.98"},
2957  		{"", "go1.99", "p:2:9: file requires newer Go version go1.99"},
2958  		{"go1.98", "go1.99", "package requires newer Go version go1.98"}, // (two
2959  		{"go1.98", "go1.99", "file requires newer Go version go1.99"},    // errors)
2960  	} {
2961  		var src string
2962  		if test.fileVersion != "" {
2963  			src = "//go:build " + test.fileVersion + "\n"
2964  		}
2965  		src += "package p; func f()"
2966  
2967  		var errs []error
2968  		conf := Config{
2969  			GoVersion: test.goVersion,
2970  			Error:     func(err error) { errs = append(errs, err) },
2971  		}
2972  		info := &Info{Defs: make(map[*ast.Ident]Object)}
2973  		typecheck(src, &conf, info)
2974  		got := fmt.Sprint(errs)
2975  		if !strings.Contains(got, test.wantErr) {
2976  			t.Errorf("%q: unexpected error: got %q, want substring %q",
2977  				src, got, test.wantErr)
2978  		}
2979  
2980  		// Assert that declarations were type checked nonetheless.
2981  		var gotObjs []string
2982  		for id, obj := range info.Defs {
2983  			if obj != nil {
2984  				objStr := strings.ReplaceAll(fmt.Sprintf("%s:%T", id.Name, obj), "types2", "types")
2985  				gotObjs = append(gotObjs, objStr)
2986  			}
2987  		}
2988  		wantObjs := "f:*types.Func"
2989  		if !strings.Contains(fmt.Sprint(gotObjs), wantObjs) {
2990  			t.Errorf("%q: got %s, want substring %q",
2991  				src, gotObjs, wantObjs)
2992  		}
2993  	}
2994  }
2995  
2996  // This is a regression test for #66704.
2997  func TestUnaliasTooSoonInCycle(t *testing.T) {
2998  	setGotypesalias(t, true)
2999  	const src = `package a
3000  
3001  var x T[B] // this appears to cause Unalias to be called on B while still Invalid
3002  
3003  type T[_ any] struct{}
3004  type A T[B]
3005  type B = T[A]
3006  `
3007  	pkg := mustTypecheck(src, nil, nil)
3008  	B := pkg.Scope().Lookup("B")
3009  
3010  	got, want := Unalias(B.Type()).String(), "a.T[a.A]"
3011  	if got != want {
3012  		t.Errorf("Unalias(type B = T[A]) = %q, want %q", got, want)
3013  	}
3014  }
3015  
3016  func TestAlias_Rhs(t *testing.T) {
3017  	setGotypesalias(t, true)
3018  	const src = `package p
3019  
3020  type A = B
3021  type B = C
3022  type C = int
3023  `
3024  
3025  	pkg := mustTypecheck(src, nil, nil)
3026  	A := pkg.Scope().Lookup("A")
3027  
3028  	got, want := A.Type().(*Alias).Rhs().String(), "p.B"
3029  	if got != want {
3030  		t.Errorf("A.Rhs = %s, want %s", got, want)
3031  	}
3032  }
3033  
3034  // Test the hijacking described of "any" described in golang/go#66921, for type
3035  // checking.
3036  func TestAnyHijacking_Check(t *testing.T) {
3037  	for _, enableAlias := range []bool{false, true} {
3038  		t.Run(fmt.Sprintf("EnableAlias=%t", enableAlias), func(t *testing.T) {
3039  			setGotypesalias(t, enableAlias)
3040  			var wg sync.WaitGroup
3041  			for i := 0; i < 10; i++ {
3042  				wg.Add(1)
3043  				go func() {
3044  					defer wg.Done()
3045  					pkg := mustTypecheck("package p; var x any", nil, nil)
3046  					x := pkg.Scope().Lookup("x")
3047  					if _, gotAlias := x.Type().(*Alias); gotAlias != enableAlias {
3048  						t.Errorf(`Lookup("x").Type() is %T: got Alias: %t, want %t`, x.Type(), gotAlias, enableAlias)
3049  					}
3050  				}()
3051  			}
3052  			wg.Wait()
3053  		})
3054  	}
3055  }
3056  
3057  // Test the hijacking described of "any" described in golang/go#66921, for
3058  // Scope.Lookup outside of type checking.
3059  func TestAnyHijacking_Lookup(t *testing.T) {
3060  	for _, enableAlias := range []bool{false, true} {
3061  		t.Run(fmt.Sprintf("EnableAlias=%t", enableAlias), func(t *testing.T) {
3062  			setGotypesalias(t, enableAlias)
3063  			a := Universe.Lookup("any")
3064  			if _, gotAlias := a.Type().(*Alias); gotAlias != enableAlias {
3065  				t.Errorf(`Lookup("x").Type() is %T: got Alias: %t, want %t`, a.Type(), gotAlias, enableAlias)
3066  			}
3067  		})
3068  	}
3069  }
3070  
3071  func setGotypesalias(t *testing.T, enable bool) {
3072  	if enable {
3073  		t.Setenv("GODEBUG", "gotypesalias=1")
3074  	} else {
3075  		t.Setenv("GODEBUG", "gotypesalias=0")
3076  	}
3077  }
3078  
3079  // TestVersionIssue69477 is a regression test for issue #69477,
3080  // in which the type checker would panic while attempting
3081  // to compute which file it is "in" based on syntax position.
3082  func TestVersionIssue69477(t *testing.T) {
3083  	fset := token.NewFileSet()
3084  	f, _ := parser.ParseFile(fset, "a.go", "package p; const k = 123", 0)
3085  
3086  	// Set an invalid Pos on the BasicLit.
3087  	ast.Inspect(f, func(n ast.Node) bool {
3088  		if lit, ok := n.(*ast.BasicLit); ok {
3089  			lit.ValuePos = 99999
3090  		}
3091  		return true
3092  	})
3093  
3094  	// Type check. The checker will consult the effective
3095  	// version for the BasicLit 123. This used to panic.
3096  	pkg := NewPackage("p", "p")
3097  	check := NewChecker(&Config{}, fset, pkg, nil)
3098  	if err := check.Files([]*ast.File{f}); err != nil {
3099  		t.Fatal(err)
3100  	}
3101  }
3102  
3103  // TestVersionWithoutPos is a regression test for issue #69477,
3104  // in which the type checker would use position information
3105  // to compute which file it is "in" based on syntax position.
3106  //
3107  // As a rule the type checker should not depend on position
3108  // information for correctness, only for error messages and
3109  // Object.Pos. (Scope.LookupParent was a mistake.)
3110  //
3111  // The Checker now holds the effective version in a state variable.
3112  func TestVersionWithoutPos(t *testing.T) {
3113  	fset := token.NewFileSet()
3114  	f, _ := parser.ParseFile(fset, "a.go", "//go:build go1.22\n\npackage p; var _ int", 0)
3115  
3116  	// Splice in a decl from another file. Its pos will be wrong.
3117  	f2, _ := parser.ParseFile(fset, "a.go", "package q; func _(s func(func() bool)) { for range s {} }", 0)
3118  	f.Decls[0] = f2.Decls[0]
3119  
3120  	// Type check. The checker will consult the effective
3121  	// version (1.22) for the for-range stmt to know whether
3122  	// range-over-func are permitted: they are not.
3123  	// (Previously, no error was reported.)
3124  	pkg := NewPackage("p", "p")
3125  	check := NewChecker(&Config{}, fset, pkg, nil)
3126  	err := check.Files([]*ast.File{f})
3127  	got := fmt.Sprint(err)
3128  	want := "range over s (variable of type func(func() bool)): requires go1.23"
3129  	if !strings.Contains(got, want) {
3130  		t.Errorf("check error was %q, want substring %q", got, want)
3131  	}
3132  }
3133  
3134  func TestVarKind(t *testing.T) {
3135  	fset := token.NewFileSet()
3136  	f, _ := parser.ParseFile(fset, "a.go", `package p
3137  
3138  var global int
3139  
3140  type T struct { field int }
3141  
3142  func (recv T) f(param int) (result int) {
3143  	var local int
3144  	local2 := 0
3145  	switch local3 := any(local).(type) {
3146  	default:
3147  		_ = local3
3148  	}
3149  	return local2
3150  }
3151  `, 0)
3152  
3153  	pkg := NewPackage("p", "p")
3154  	info := &Info{Defs: make(map[*ast.Ident]Object)}
3155  	check := NewChecker(&Config{}, fset, pkg, info)
3156  	if err := check.Files([]*ast.File{f}); err != nil {
3157  		t.Fatal(err)
3158  	}
3159  	var got []string
3160  	for _, obj := range info.Defs {
3161  		if v, ok := obj.(*Var); ok {
3162  			got = append(got, fmt.Sprintf("%s: %v", v.Name(), v.Kind()))
3163  		}
3164  	}
3165  	sort.Strings(got)
3166  	want := []string{
3167  		"field: FieldVar",
3168  		"global: PackageVar",
3169  		"local2: LocalVar",
3170  		"local: LocalVar",
3171  		"param: ParamVar",
3172  		"recv: RecvVar",
3173  		"result: ResultVar",
3174  	}
3175  	if !slices.Equal(got, want) {
3176  		t.Errorf("got:\n%s\nwant:\n%s", got, want)
3177  	}
3178  }
3179  
3180  func TestIssue73871(t *testing.T) {
3181  	const src = `package p
3182  
3183  func f[T ~[]byte](y T) []byte { return append([]byte(nil), y...) }
3184  
3185  // for illustration only:
3186  type B []byte
3187  var _ = f[B]
3188  `
3189  	fset := token.NewFileSet()
3190  	f, _ := parser.ParseFile(fset, "p.go", src, 0)
3191  
3192  	pkg := NewPackage("p", "p")
3193  	info := &Info{Types: make(map[ast.Expr]TypeAndValue)}
3194  	check := NewChecker(&Config{}, fset, pkg, info)
3195  	if err := check.Files([]*ast.File{f}); err != nil {
3196  		t.Fatal(err)
3197  	}
3198  
3199  	// Check type inferred for 'append'.
3200  	//
3201  	// Before the fix, the inferred type of append's y parameter
3202  	// was T. When a client such as x/tools/go/ssa instantiated T=B,
3203  	// it would result in the Signature "func([]byte, B)" with the
3204  	// variadic flag set, an invalid combination that caused
3205  	// NewSignatureType to panic.
3206  	append := f.Decls[0].(*ast.FuncDecl).Body.List[0].(*ast.ReturnStmt).Results[0].(*ast.CallExpr).Fun
3207  	tAppend := info.TypeOf(append).(*Signature)
3208  	want := "func([]byte, ...byte) []byte"
3209  	if got := fmt.Sprint(tAppend); got != want {
3210  		// Before the fix, tAppend was func([]byte, T) []byte,
3211  		// where T prints as "<expected string type>".
3212  		t.Errorf("for append, inferred type %s, want %s", tAppend, want)
3213  	}
3214  }
3215