]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/api_test.go
go/types, types2: remove Config.EnableReverseTypeInference flag
[gostls13.git] / src / cmd / compile / internal / types2 / api_test.go
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 types2_test
6
7 import (
8         "cmd/compile/internal/syntax"
9         "errors"
10         "fmt"
11         "internal/testenv"
12         "reflect"
13         "regexp"
14         "sort"
15         "strings"
16         "testing"
17
18         . "cmd/compile/internal/types2"
19 )
20
21 // nopos indicates an unknown position
22 var nopos syntax.Pos
23
24 func mustParse(src string) *syntax.File {
25         f, err := syntax.Parse(syntax.NewFileBase(pkgName(src)), strings.NewReader(src), nil, nil, 0)
26         if err != nil {
27                 panic(err) // so we don't need to pass *testing.T
28         }
29         return f
30 }
31
32 func typecheck(src string, conf *Config, info *Info) (*Package, error) {
33         f := mustParse(src)
34         if conf == nil {
35                 conf = &Config{
36                         Error:    func(err error) {}, // collect all errors
37                         Importer: defaultImporter(),
38                 }
39         }
40         return conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
41 }
42
43 func mustTypecheck(src string, conf *Config, info *Info) *Package {
44         pkg, err := typecheck(src, conf, info)
45         if err != nil {
46                 panic(err) // so we don't need to pass *testing.T
47         }
48         return pkg
49 }
50
51 // pkgName extracts the package name from src, which must contain a package header.
52 func pkgName(src string) string {
53         const kw = "package "
54         if i := strings.Index(src, kw); i >= 0 {
55                 after := src[i+len(kw):]
56                 n := len(after)
57                 if i := strings.IndexAny(after, "\n\t ;/"); i >= 0 {
58                         n = i
59                 }
60                 return after[:n]
61         }
62         panic("missing package header: " + src)
63 }
64
65 func TestValuesInfo(t *testing.T) {
66         var tests = []struct {
67                 src  string
68                 expr string // constant expression
69                 typ  string // constant type
70                 val  string // constant value
71         }{
72                 {`package a0; const _ = false`, `false`, `untyped bool`, `false`},
73                 {`package a1; const _ = 0`, `0`, `untyped int`, `0`},
74                 {`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
75                 {`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
76                 {`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
77                 {`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
78
79                 {`package b0; var _ = false`, `false`, `bool`, `false`},
80                 {`package b1; var _ = 0`, `0`, `int`, `0`},
81                 {`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
82                 {`package b3; var _ = 0.`, `0.`, `float64`, `0`},
83                 {`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
84                 {`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
85
86                 {`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
87                 {`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
88                 {`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
89
90                 {`package c1a; var _ = int(0)`, `0`, `int`, `0`},
91                 {`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
92                 {`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
93
94                 {`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
95                 {`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
96                 {`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
97
98                 {`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
99                 {`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
100                 {`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
101
102                 {`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
103                 {`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
104                 {`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
105
106                 {`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
107                 {`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
108                 {`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
109                 {`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
110                 {`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
111                 {`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
112
113                 {`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
114                 {`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
115                 {`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
116                 {`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
117
118                 {`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
119                 {`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
120                 {`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
121                 {`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
122                 {`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
123                 {`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
124                 {`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
125                 {`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
126
127                 {`package f0 ; var _ float32 =  1e-200`, `1e-200`, `float32`, `0`},
128                 {`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
129                 {`package f2a; var _ float64 =  1e-2000`, `1e-2000`, `float64`, `0`},
130                 {`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
131                 {`package f2b; var _         =  1e-2000`, `1e-2000`, `float64`, `0`},
132                 {`package f3b; var _         = -1e-2000`, `-1e-2000`, `float64`, `0`},
133                 {`package f4 ; var _ complex64  =  1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
134                 {`package f5 ; var _ complex64  = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
135                 {`package f6a; var _ complex128 =  1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
136                 {`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
137                 {`package f6b; var _            =  1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
138                 {`package f7b; var _            = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
139
140                 {`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // go.dev/issue/22341
141                 {`package g1; var(j int32; s int; n = 1.0<<s == j)`, `1.0`, `int32`, `1`},        // go.dev/issue/48422
142         }
143
144         for _, test := range tests {
145                 info := Info{
146                         Types: make(map[syntax.Expr]TypeAndValue),
147                 }
148                 name := mustTypecheck(test.src, nil, &info).Name()
149
150                 // look for expression
151                 var expr syntax.Expr
152                 for e := range info.Types {
153                         if syntax.String(e) == test.expr {
154                                 expr = e
155                                 break
156                         }
157                 }
158                 if expr == nil {
159                         t.Errorf("package %s: no expression found for %s", name, test.expr)
160                         continue
161                 }
162                 tv := info.Types[expr]
163
164                 // check that type is correct
165                 if got := tv.Type.String(); got != test.typ {
166                         t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
167                         continue
168                 }
169
170                 // if we have a constant, check that value is correct
171                 if tv.Value != nil {
172                         if got := tv.Value.ExactString(); got != test.val {
173                                 t.Errorf("package %s: got value %s; want %s", name, got, test.val)
174                         }
175                 } else {
176                         if test.val != "" {
177                                 t.Errorf("package %s: no constant found; want %s", name, test.val)
178                         }
179                 }
180         }
181 }
182
183 func TestTypesInfo(t *testing.T) {
184         // Test sources that are not expected to typecheck must start with the broken prefix.
185         const brokenPkg = "package broken_"
186
187         var tests = []struct {
188                 src  string
189                 expr string // expression
190                 typ  string // value type
191         }{
192                 // single-valued expressions of untyped constants
193                 {`package b0; var x interface{} = false`, `false`, `bool`},
194                 {`package b1; var x interface{} = 0`, `0`, `int`},
195                 {`package b2; var x interface{} = 0.`, `0.`, `float64`},
196                 {`package b3; var x interface{} = 0i`, `0i`, `complex128`},
197                 {`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
198
199                 // uses of nil
200                 {`package n0; var _ *int = nil`, `nil`, `*int`},
201                 {`package n1; var _ func() = nil`, `nil`, `func()`},
202                 {`package n2; var _ []byte = nil`, `nil`, `[]byte`},
203                 {`package n3; var _ map[int]int = nil`, `nil`, `map[int]int`},
204                 {`package n4; var _ chan int = nil`, `nil`, `chan int`},
205                 {`package n5a; var _ interface{} = (*int)(nil)`, `nil`, `*int`},
206                 {`package n5b; var _ interface{m()} = nil`, `nil`, `interface{m()}`},
207                 {`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `unsafe.Pointer`},
208
209                 {`package n10; var (x *int; _ = x == nil)`, `nil`, `*int`},
210                 {`package n11; var (x func(); _ = x == nil)`, `nil`, `func()`},
211                 {`package n12; var (x []byte; _ = x == nil)`, `nil`, `[]byte`},
212                 {`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `map[int]int`},
213                 {`package n14; var (x chan int; _ = x == nil)`, `nil`, `chan int`},
214                 {`package n15a; var (x interface{}; _ = x == (*int)(nil))`, `nil`, `*int`},
215                 {`package n15b; var (x interface{m()}; _ = x == nil)`, `nil`, `interface{m()}`},
216                 {`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `unsafe.Pointer`},
217
218                 {`package n20; var _ = (*int)(nil)`, `nil`, `*int`},
219                 {`package n21; var _ = (func())(nil)`, `nil`, `func()`},
220                 {`package n22; var _ = ([]byte)(nil)`, `nil`, `[]byte`},
221                 {`package n23; var _ = (map[int]int)(nil)`, `nil`, `map[int]int`},
222                 {`package n24; var _ = (chan int)(nil)`, `nil`, `chan int`},
223                 {`package n25a; var _ = (interface{})((*int)(nil))`, `nil`, `*int`},
224                 {`package n25b; var _ = (interface{m()})(nil)`, `nil`, `interface{m()}`},
225                 {`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `unsafe.Pointer`},
226
227                 {`package n30; func f(*int) { f(nil) }`, `nil`, `*int`},
228                 {`package n31; func f(func()) { f(nil) }`, `nil`, `func()`},
229                 {`package n32; func f([]byte) { f(nil) }`, `nil`, `[]byte`},
230                 {`package n33; func f(map[int]int) { f(nil) }`, `nil`, `map[int]int`},
231                 {`package n34; func f(chan int) { f(nil) }`, `nil`, `chan int`},
232                 {`package n35a; func f(interface{}) { f((*int)(nil)) }`, `nil`, `*int`},
233                 {`package n35b; func f(interface{m()}) { f(nil) }`, `nil`, `interface{m()}`},
234                 {`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `unsafe.Pointer`},
235
236                 // comma-ok expressions
237                 {`package p0; var x interface{}; var _, _ = x.(int)`,
238                         `x.(int)`,
239                         `(int, bool)`,
240                 },
241                 {`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
242                         `x.(int)`,
243                         `(int, bool)`,
244                 },
245                 {`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
246                         `m["foo"]`,
247                         `(complex128, p2a.mybool)`,
248                 },
249                 {`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
250                         `m["foo"]`,
251                         `(complex128, bool)`,
252                 },
253                 {`package p3; var c chan string; var _, _ = <-c`,
254                         `<-c`,
255                         `(string, bool)`,
256                 },
257
258                 // go.dev/issue/6796
259                 {`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
260                         `x.(int)`,
261                         `(int, bool)`,
262                 },
263                 {`package issue6796_b; var c chan string; var _, _ = (<-c)`,
264                         `(<-c)`,
265                         `(string, bool)`,
266                 },
267                 {`package issue6796_c; var c chan string; var _, _ = (<-c)`,
268                         `<-c`,
269                         `(string, bool)`,
270                 },
271                 {`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
272                         `(<-c)`,
273                         `(string, bool)`,
274                 },
275                 {`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
276                         `(<-c)`,
277                         `(string, bool)`,
278                 },
279
280                 // go.dev/issue/7060
281                 {`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
282                         `m[0]`,
283                         `(string, bool)`,
284                 },
285                 {`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
286                         `m[0]`,
287                         `(string, bool)`,
288                 },
289                 {`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
290                         `m[0]`,
291                         `(string, bool)`,
292                 },
293                 {`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
294                         `<-ch`,
295                         `(string, bool)`,
296                 },
297                 {`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
298                         `<-ch`,
299                         `(string, bool)`,
300                 },
301                 {`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
302                         `<-ch`,
303                         `(string, bool)`,
304                 },
305
306                 // go.dev/issue/28277
307                 {`package issue28277_a; func f(...int)`,
308                         `...int`,
309                         `[]int`,
310                 },
311                 {`package issue28277_b; func f(a, b int, c ...[]struct{})`,
312                         `...[]struct{}`,
313                         `[][]struct{}`,
314                 },
315
316                 // go.dev/issue/47243
317                 {`package issue47243_a; var x int32; var _ = x << 3`, `3`, `untyped int`},
318                 {`package issue47243_b; var x int32; var _ = x << 3.`, `3.`, `untyped float`},
319                 {`package issue47243_c; var x int32; var _ = 1 << x`, `1 << x`, `int`},
320                 {`package issue47243_d; var x int32; var _ = 1 << x`, `1`, `int`},
321                 {`package issue47243_e; var x int32; var _ = 1 << 2`, `1`, `untyped int`},
322                 {`package issue47243_f; var x int32; var _ = 1 << 2`, `2`, `untyped int`},
323                 {`package issue47243_g; var x int32; var _ = int(1) << 2`, `2`, `untyped int`},
324                 {`package issue47243_h; var x int32; var _ = 1 << (2 << x)`, `1`, `int`},
325                 {`package issue47243_i; var x int32; var _ = 1 << (2 << x)`, `(2 << x)`, `untyped int`},
326                 {`package issue47243_j; var x int32; var _ = 1 << (2 << x)`, `2`, `untyped int`},
327
328                 // tests for broken code that doesn't type-check
329                 {brokenPkg + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
330                 {brokenPkg + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
331                 {brokenPkg + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a, f: b,}}`, `b`, `string`},
332                 {brokenPkg + `x3; var x = panic("");`, `panic`, `func(interface{})`},
333                 {`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
334                 {brokenPkg + `x5; func _() { var x map[string][...]int; x = map[string][...]int{"": {1,2,3}} }`, `x`, `map[string]invalid type`},
335
336                 // parameterized functions
337                 {`package p0; func f[T any](T) {}; var _ = f[int]`, `f`, `func[T any](T)`},
338                 {`package p1; func f[T any](T) {}; var _ = f[int]`, `f[int]`, `func(int)`},
339                 {`package p2; func f[T any](T) {}; func _() { f(42) }`, `f`, `func(int)`},
340                 {`package p3; func f[T any](T) {}; func _() { f[int](42) }`, `f[int]`, `func(int)`},
341                 {`package p4; func f[T any](T) {}; func _() { f[int](42) }`, `f`, `func[T any](T)`},
342                 {`package p5; func f[T any](T) {}; func _() { f(42) }`, `f(42)`, `()`},
343
344                 // type parameters
345                 {`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
346                 {`package t1; type t[P any] int; var _ t[int]`, `t`, `t1.t[P any]`},
347                 {`package t2; type t[P interface{}] int; var _ t[int]`, `t`, `t2.t[P interface{}]`},
348                 {`package t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `t3.t[P, Q interface{}]`},
349                 {brokenPkg + `t4; type t[P, Q interface{ m() }] int; var _ t[int, int]`, `t`, `broken_t4.t[P, Q interface{m()}]`},
350
351                 // instantiated types must be sanitized
352                 {`package g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `g0.t[int]`},
353
354                 // go.dev/issue/45096
355                 {`package issue45096; func _[T interface{ ~int8 | ~int16 | ~int32 }](x T) { _ = x < 0 }`, `0`, `T`},
356
357                 // go.dev/issue/47895
358                 {`package p; import "unsafe"; type S struct { f int }; var s S; var _ = unsafe.Offsetof(s.f)`, `s.f`, `int`},
359
360                 // go.dev/issue/50093
361                 {`package u0a; func _[_ interface{int}]() {}`, `int`, `int`},
362                 {`package u1a; func _[_ interface{~int}]() {}`, `~int`, `~int`},
363                 {`package u2a; func _[_ interface{int | string}]() {}`, `int | string`, `int | string`},
364                 {`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `int | string | ~bool`, `int | string | ~bool`},
365                 {`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `int | string`, `int | string`},
366                 {`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `~bool`, `~bool`},
367                 {`package u3a; func _[_ interface{int | string | ~float64|~bool}]() {}`, `int | string | ~float64`, `int | string | ~float64`},
368
369                 {`package u0b; func _[_ int]() {}`, `int`, `int`},
370                 {`package u1b; func _[_ ~int]() {}`, `~int`, `~int`},
371                 {`package u2b; func _[_ int | string]() {}`, `int | string`, `int | string`},
372                 {`package u3b; func _[_ int | string | ~bool]() {}`, `int | string | ~bool`, `int | string | ~bool`},
373                 {`package u3b; func _[_ int | string | ~bool]() {}`, `int | string`, `int | string`},
374                 {`package u3b; func _[_ int | string | ~bool]() {}`, `~bool`, `~bool`},
375                 {`package u3b; func _[_ int | string | ~float64|~bool]() {}`, `int | string | ~float64`, `int | string | ~float64`},
376
377                 {`package u0c; type _ interface{int}`, `int`, `int`},
378                 {`package u1c; type _ interface{~int}`, `~int`, `~int`},
379                 {`package u2c; type _ interface{int | string}`, `int | string`, `int | string`},
380                 {`package u3c; type _ interface{int | string | ~bool}`, `int | string | ~bool`, `int | string | ~bool`},
381                 {`package u3c; type _ interface{int | string | ~bool}`, `int | string`, `int | string`},
382                 {`package u3c; type _ interface{int | string | ~bool}`, `~bool`, `~bool`},
383                 {`package u3c; type _ interface{int | string | ~float64|~bool}`, `int | string | ~float64`, `int | string | ~float64`},
384         }
385
386         for _, test := range tests {
387                 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
388                 var name string
389                 if strings.HasPrefix(test.src, brokenPkg) {
390                         pkg, err := typecheck(test.src, nil, &info)
391                         if err == nil {
392                                 t.Errorf("package %s: expected to fail but passed", pkg.Name())
393                                 continue
394                         }
395                         if pkg != nil {
396                                 name = pkg.Name()
397                         }
398                 } else {
399                         name = mustTypecheck(test.src, nil, &info).Name()
400                 }
401
402                 // look for expression type
403                 var typ Type
404                 for e, tv := range info.Types {
405                         if syntax.String(e) == test.expr {
406                                 typ = tv.Type
407                                 break
408                         }
409                 }
410                 if typ == nil {
411                         t.Errorf("package %s: no type found for %s", name, test.expr)
412                         continue
413                 }
414
415                 // check that type is correct
416                 if got := typ.String(); got != test.typ {
417                         t.Errorf("package %s: got %s; want %s", name, got, test.typ)
418                 }
419         }
420 }
421
422 func TestInstanceInfo(t *testing.T) {
423         const lib = `package lib
424
425 func F[P any](P) {}
426
427 type T[P any] []P
428 `
429
430         type testInst struct {
431                 name  string
432                 targs []string
433                 typ   string
434         }
435
436         var tests = []struct {
437                 src       string
438                 instances []testInst // recorded instances in source order
439         }{
440                 {`package p0; func f[T any](T) {}; func _() { f(42) }`,
441                         []testInst{{`f`, []string{`int`}, `func(int)`}},
442                 },
443                 {`package p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
444                         []testInst{{`f`, []string{`rune`}, `func(rune) rune`}},
445                 },
446                 {`package p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
447                         []testInst{{`f`, []string{`complex128`}, `func(...complex128) complex128`}},
448                 },
449                 {`package p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
450                         []testInst{{`f`, []string{`float64`, `string`, `byte`}, `func(float64, *string, []byte)`}},
451                 },
452                 {`package p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
453                         []testInst{{`f`, []string{`float64`, `byte`}, `func(float64, *byte, ...[]byte)`}},
454                 },
455
456                 {`package s1; func f[T any, P interface{*T}](x T) {}; func _(x string) { f(x) }`,
457                         []testInst{{`f`, []string{`string`, `*string`}, `func(x string)`}},
458                 },
459                 {`package s2; func f[T any, P interface{*T}](x []T) {}; func _(x []int) { f(x) }`,
460                         []testInst{{`f`, []string{`int`, `*int`}, `func(x []int)`}},
461                 },
462                 {`package s3; type C[T any] interface{chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
463                         []testInst{
464                                 {`C`, []string{`T`}, `interface{chan<- T}`},
465                                 {`f`, []string{`int`, `chan<- int`}, `func(x []int)`},
466                         },
467                 },
468                 {`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) }`,
469                         []testInst{
470                                 {`C`, []string{`T`}, `interface{chan<- T}`},
471                                 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
472                                 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func(x []int)`},
473                         },
474                 },
475
476                 {`package t1; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = f[string] }`,
477                         []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
478                 },
479                 {`package t2; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = (f[string]) }`,
480                         []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
481                 },
482                 {`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] }`,
483                         []testInst{
484                                 {`C`, []string{`T`}, `interface{chan<- T}`},
485                                 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
486                                 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
487                         },
488                 },
489                 {`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]) }`,
490                         []testInst{
491                                 {`C`, []string{`T`}, `interface{chan<- T}`},
492                                 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
493                                 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
494                         },
495                 },
496                 {`package i0; import "lib"; func _() { lib.F(42) }`,
497                         []testInst{{`F`, []string{`int`}, `func(int)`}},
498                 },
499
500                 {`package duplfunc0; func f[T any](T) {}; func _() { f(42); f("foo"); f[int](3) }`,
501                         []testInst{
502                                 {`f`, []string{`int`}, `func(int)`},
503                                 {`f`, []string{`string`}, `func(string)`},
504                                 {`f`, []string{`int`}, `func(int)`},
505                         },
506                 },
507                 {`package duplfunc1; import "lib"; func _() { lib.F(42); lib.F("foo"); lib.F(3) }`,
508                         []testInst{
509                                 {`F`, []string{`int`}, `func(int)`},
510                                 {`F`, []string{`string`}, `func(string)`},
511                                 {`F`, []string{`int`}, `func(int)`},
512                         },
513                 },
514
515                 {`package type0; type T[P interface{~int}] struct{ x P }; var _ T[int]`,
516                         []testInst{{`T`, []string{`int`}, `struct{x int}`}},
517                 },
518                 {`package type1; type T[P interface{~int}] struct{ x P }; var _ (T[int])`,
519                         []testInst{{`T`, []string{`int`}, `struct{x int}`}},
520                 },
521                 {`package type2; type T[P interface{~int}] struct{ x P }; var _ T[(int)]`,
522                         []testInst{{`T`, []string{`int`}, `struct{x int}`}},
523                 },
524                 {`package type3; type T[P1 interface{~[]P2}, P2 any] struct{ x P1; y P2 }; var _ T[[]int, int]`,
525                         []testInst{{`T`, []string{`[]int`, `int`}, `struct{x []int; y int}`}},
526                 },
527                 {`package type4; import "lib"; var _ lib.T[int]`,
528                         []testInst{{`T`, []string{`int`}, `[]int`}},
529                 },
530
531                 {`package dupltype0; type T[P interface{~int}] struct{ x P }; var x T[int]; var y T[int]`,
532                         []testInst{
533                                 {`T`, []string{`int`}, `struct{x int}`},
534                                 {`T`, []string{`int`}, `struct{x int}`},
535                         },
536                 },
537                 {`package dupltype1; type T[P ~int] struct{ x P }; func (r *T[Q]) add(z T[Q]) { r.x += z.x }`,
538                         []testInst{
539                                 {`T`, []string{`Q`}, `struct{x Q}`},
540                                 {`T`, []string{`Q`}, `struct{x Q}`},
541                         },
542                 },
543                 {`package dupltype1; import "lib"; var x lib.T[int]; var y lib.T[int]; var z lib.T[string]`,
544                         []testInst{
545                                 {`T`, []string{`int`}, `[]int`},
546                                 {`T`, []string{`int`}, `[]int`},
547                                 {`T`, []string{`string`}, `[]string`},
548                         },
549                 },
550                 {`package issue51803; func foo[T any](T) {}; func _() { foo[int]( /* leave arg away on purpose */ ) }`,
551                         []testInst{{`foo`, []string{`int`}, `func(int)`}},
552                 },
553
554                 // reverse type parameter inference
555                 {`package reverse1a; var f func(int) = g; func g[P any](P) {}`,
556                         []testInst{{`g`, []string{`int`}, `func(int)`}},
557                 },
558                 {`package reverse1b; func f(func(int)) {}; func g[P any](P) {}; func _() { f(g) }`,
559                         []testInst{{`g`, []string{`int`}, `func(int)`}},
560                 },
561                 {`package reverse2a; var f func(int) string = g; func g[P, Q any](P) Q { var q Q; return q }`,
562                         []testInst{{`g`, []string{`int`, `string`}, `func(int) string`}},
563                 },
564                 {`package reverse2b; func f(func(int) string) {}; func g[P, Q any](P) Q { var q Q; return q }; func _() { f(g) }`,
565                         []testInst{{`g`, []string{`int`, `string`}, `func(int) string`}},
566                 },
567                 // reverse3a not possible (cannot assign to generic function outside of argument passing)
568                 {`package reverse3b; func f[R any](func(int) R) {}; func g[P any](P) string { return "" }; func _() { f(g) }`,
569                         []testInst{
570                                 {`f`, []string{`string`}, `func(func(int) string)`},
571                                 {`g`, []string{`int`}, `func(int) string`},
572                         },
573                 },
574                 {`package reverse4a; var _, _ func([]int, *float32) = g, h; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}`,
575                         []testInst{
576                                 {`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
577                                 {`h`, []string{`int`}, `func([]int, *float32)`},
578                         },
579                 },
580                 {`package reverse4b; func f(_, _ func([]int, *float32)) {}; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}; func _() { f(g, h) }`,
581                         []testInst{
582                                 {`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
583                                 {`h`, []string{`int`}, `func([]int, *float32)`},
584                         },
585                 },
586                 {`package issue59956; func f(func(int), func(string), func(bool)) {}; func g[P any](P) {}; func _() { f(g, g, g) }`,
587                         []testInst{
588                                 {`g`, []string{`int`}, `func(int)`},
589                                 {`g`, []string{`string`}, `func(string)`},
590                                 {`g`, []string{`bool`}, `func(bool)`},
591                         },
592                 },
593         }
594
595         for _, test := range tests {
596                 imports := make(testImporter)
597                 conf := Config{Importer: imports}
598                 instMap := make(map[*syntax.Name]Instance)
599                 useMap := make(map[*syntax.Name]Object)
600                 makePkg := func(src string) *Package {
601                         pkg, err := typecheck(src, &conf, &Info{Instances: instMap, Uses: useMap})
602                         // allow error for issue51803
603                         if err != nil && (pkg == nil || pkg.Name() != "issue51803") {
604                                 t.Fatal(err)
605                         }
606                         imports[pkg.Name()] = pkg
607                         return pkg
608                 }
609                 makePkg(lib)
610                 pkg := makePkg(test.src)
611
612                 t.Run(pkg.Name(), func(t *testing.T) {
613                         // Sort instances in source order for stability.
614                         instances := sortedInstances(instMap)
615                         if got, want := len(instances), len(test.instances); got != want {
616                                 t.Fatalf("got %d instances, want %d", got, want)
617                         }
618
619                         // Pairwise compare with the expected instances.
620                         for ii, inst := range instances {
621                                 var targs []Type
622                                 for i := 0; i < inst.Inst.TypeArgs.Len(); i++ {
623                                         targs = append(targs, inst.Inst.TypeArgs.At(i))
624                                 }
625                                 typ := inst.Inst.Type
626
627                                 testInst := test.instances[ii]
628                                 if got := inst.Name.Value; got != testInst.name {
629                                         t.Fatalf("got name %s, want %s", got, testInst.name)
630                                 }
631
632                                 if len(targs) != len(testInst.targs) {
633                                         t.Fatalf("got %d type arguments; want %d", len(targs), len(testInst.targs))
634                                 }
635                                 for i, targ := range targs {
636                                         if got := targ.String(); got != testInst.targs[i] {
637                                                 t.Errorf("type argument %d: got %s; want %s", i, got, testInst.targs[i])
638                                         }
639                                 }
640                                 if got := typ.Underlying().String(); got != testInst.typ {
641                                         t.Errorf("package %s: got %s; want %s", pkg.Name(), got, testInst.typ)
642                                 }
643
644                                 // Verify the invariant that re-instantiating the corresponding generic
645                                 // type with TypeArgs results in an identical instance.
646                                 ptype := useMap[inst.Name].Type()
647                                 lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
648                                 if lister == nil || lister.TypeParams().Len() == 0 {
649                                         t.Fatalf("info.Types[%v] = %v, want parameterized type", inst.Name, ptype)
650                                 }
651                                 inst2, err := Instantiate(nil, ptype, targs, true)
652                                 if err != nil {
653                                         t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
654                                 }
655                                 if !Identical(inst.Inst.Type, inst2) {
656                                         t.Errorf("%v and %v are not identical", inst.Inst.Type, inst2)
657                                 }
658                         }
659                 })
660         }
661 }
662
663 type recordedInstance struct {
664         Name *syntax.Name
665         Inst Instance
666 }
667
668 func sortedInstances(m map[*syntax.Name]Instance) (instances []recordedInstance) {
669         for id, inst := range m {
670                 instances = append(instances, recordedInstance{id, inst})
671         }
672         sort.Slice(instances, func(i, j int) bool {
673                 return CmpPos(instances[i].Name.Pos(), instances[j].Name.Pos()) < 0
674         })
675         return instances
676 }
677
678 func TestDefsInfo(t *testing.T) {
679         var tests = []struct {
680                 src  string
681                 obj  string
682                 want string
683         }{
684                 {`package p0; const x = 42`, `x`, `const p0.x untyped int`},
685                 {`package p1; const x int = 42`, `x`, `const p1.x int`},
686                 {`package p2; var x int`, `x`, `var p2.x int`},
687                 {`package p3; type x int`, `x`, `type p3.x int`},
688                 {`package p4; func f()`, `f`, `func p4.f()`},
689                 {`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
690
691                 // Tests using generics.
692                 {`package g0; type x[T any] int`, `x`, `type g0.x[T any] int`},
693                 {`package g1; func f[T any]() {}`, `f`, `func g1.f[T any]()`},
694                 {`package g2; type x[T any] int; func (*x[_]) m() {}`, `m`, `func (*g2.x[_]).m()`},
695         }
696
697         for _, test := range tests {
698                 info := Info{
699                         Defs: make(map[*syntax.Name]Object),
700                 }
701                 name := mustTypecheck(test.src, nil, &info).Name()
702
703                 // find object
704                 var def Object
705                 for id, obj := range info.Defs {
706                         if id.Value == test.obj {
707                                 def = obj
708                                 break
709                         }
710                 }
711                 if def == nil {
712                         t.Errorf("package %s: %s not found", name, test.obj)
713                         continue
714                 }
715
716                 if got := def.String(); got != test.want {
717                         t.Errorf("package %s: got %s; want %s", name, got, test.want)
718                 }
719         }
720 }
721
722 func TestUsesInfo(t *testing.T) {
723         var tests = []struct {
724                 src  string
725                 obj  string
726                 want string
727         }{
728                 {`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
729                 {`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
730                 {`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
731                 {`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
732                 {`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
733
734                 // Tests using generics.
735                 {`package g0; func _[T any]() { _ = x }; const x = 42`, `x`, `const g0.x untyped int`},
736                 {`package g1; func _[T any](x T) { }`, `T`, `type parameter T any`},
737                 {`package g2; type N[A any] int; var _ N[int]`, `N`, `type g2.N[A any] int`},
738                 {`package g3; type N[A any] int; func (N[_]) m() {}`, `N`, `type g3.N[A any] int`},
739
740                 // Uses of fields are instantiated.
741                 {`package s1; type N[A any] struct{ a A }; var f = N[int]{}.a`, `a`, `field a int`},
742                 {`package s1; type N[A any] struct{ a A }; func (r N[B]) m(b B) { r.a = b }`, `a`, `field a B`},
743
744                 // Uses of methods are uses of the instantiated method.
745                 {`package m0; type N[A any] int; func (r N[B]) m() { r.n() }; func (N[C]) n() {}`, `n`, `func (m0.N[B]).n()`},
746                 {`package m1; type N[A any] int; func (r N[B]) m() { }; var f = N[int].m`, `m`, `func (m1.N[int]).m()`},
747                 {`package m2; func _[A any](v interface{ m() A }) { v.m() }`, `m`, `func (interface).m() A`},
748                 {`package m3; func f[A any]() interface{ m() A } { return nil }; var _ = f[int]().m()`, `m`, `func (interface).m() int`},
749                 {`package m4; type T[A any] func() interface{ m() A }; var x T[int]; var y = x().m`, `m`, `func (interface).m() int`},
750                 {`package m5; type T[A any] interface{ m() A }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m5.T[B]).m() B`},
751                 {`package m6; type T[A any] interface{ m() }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m6.T[B]).m()`},
752                 {`package m7; type T[A any] interface{ m() A }; func _(t T[int]) { t.m() }`, `m`, `func (m7.T[int]).m() int`},
753                 {`package m8; type T[A any] interface{ m() }; func _(t T[int]) { t.m() }`, `m`, `func (m8.T[int]).m()`},
754                 {`package m9; type T[A any] interface{ m() }; func _(t T[int]) { _ = t.m }`, `m`, `func (m9.T[int]).m()`},
755                 {
756                         `package m10; type E[A any] interface{ m() }; type T[B any] interface{ E[B]; n() }; func _(t T[int]) { t.m() }`,
757                         `m`,
758                         `func (m10.E[int]).m()`,
759                 },
760         }
761
762         for _, test := range tests {
763                 info := Info{
764                         Uses: make(map[*syntax.Name]Object),
765                 }
766                 name := mustTypecheck(test.src, nil, &info).Name()
767
768                 // find object
769                 var use Object
770                 for id, obj := range info.Uses {
771                         if id.Value == test.obj {
772                                 if use != nil {
773                                         panic(fmt.Sprintf("multiple uses of %q", id.Value))
774                                 }
775                                 use = obj
776                         }
777                 }
778                 if use == nil {
779                         t.Errorf("package %s: %s not found", name, test.obj)
780                         continue
781                 }
782
783                 if got := use.String(); got != test.want {
784                         t.Errorf("package %s: got %s; want %s", name, got, test.want)
785                 }
786         }
787 }
788
789 func TestGenericMethodInfo(t *testing.T) {
790         src := `package p
791
792 type N[A any] int
793
794 func (r N[B]) m() { r.m(); r.n() }
795
796 func (r *N[C]) n() {  }
797 `
798         f := mustParse(src)
799         info := Info{
800                 Defs:       make(map[*syntax.Name]Object),
801                 Uses:       make(map[*syntax.Name]Object),
802                 Selections: make(map[*syntax.SelectorExpr]*Selection),
803         }
804         var conf Config
805         pkg, err := conf.Check("p", []*syntax.File{f}, &info)
806         if err != nil {
807                 t.Fatal(err)
808         }
809
810         N := pkg.Scope().Lookup("N").Type().(*Named)
811
812         // Find the generic methods stored on N.
813         gm, gn := N.Method(0), N.Method(1)
814         if gm.Name() == "n" {
815                 gm, gn = gn, gm
816         }
817
818         // Collect objects from info.
819         var dm, dn *Func   // the declared methods
820         var dmm, dmn *Func // the methods used in the body of m
821         for _, decl := range f.DeclList {
822                 fdecl, ok := decl.(*syntax.FuncDecl)
823                 if !ok {
824                         continue
825                 }
826                 def := info.Defs[fdecl.Name].(*Func)
827                 switch fdecl.Name.Value {
828                 case "m":
829                         dm = def
830                         syntax.Inspect(fdecl.Body, func(n syntax.Node) bool {
831                                 if call, ok := n.(*syntax.CallExpr); ok {
832                                         sel := call.Fun.(*syntax.SelectorExpr)
833                                         use := info.Uses[sel.Sel].(*Func)
834                                         selection := info.Selections[sel]
835                                         if selection.Kind() != MethodVal {
836                                                 t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
837                                         }
838                                         if selection.Obj() != use {
839                                                 t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
840                                         }
841                                         switch sel.Sel.Value {
842                                         case "m":
843                                                 dmm = use
844                                         case "n":
845                                                 dmn = use
846                                         }
847                                 }
848                                 return true
849                         })
850                 case "n":
851                         dn = def
852                 }
853         }
854
855         if gm != dm {
856                 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
857         }
858         if gn != dn {
859                 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
860         }
861         if dmm != dm {
862                 t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
863         }
864         if dmn == dn {
865                 t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
866         }
867 }
868
869 func TestImplicitsInfo(t *testing.T) {
870         testenv.MustHaveGoBuild(t)
871
872         var tests = []struct {
873                 src  string
874                 want string
875         }{
876                 {`package p2; import . "fmt"; var _ = Println`, ""},           // no Implicits entry
877                 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
878                 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
879
880                 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
881                 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
882                 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
883                 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
884
885                 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
886                 {`package p8; func f(int) {}`, "field: var  int"},
887                 {`package p9; func f() (complex64) { return 0 }`, "field: var  complex64"},
888                 {`package p10; type T struct{}; func (*T) f() {}`, "field: var  *p10.T"},
889
890                 // Tests using generics.
891                 {`package f0; func f[T any](x int) {}`, ""}, // no Implicits entry
892                 {`package f1; func f[T any](int) {}`, "field: var  int"},
893                 {`package f2; func f[T any](T) {}`, "field: var  T"},
894                 {`package f3; func f[T any]() (complex64) { return 0 }`, "field: var  complex64"},
895                 {`package f4; func f[T any](t T) (T) { return t }`, "field: var  T"},
896                 {`package t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var  *t0.T[_]"},
897                 {`package t1; type T[A any] struct{}; func _(x interface{}) { switch t := x.(type) { case T[int]: _ = t } }`, "caseClause: var t t1.T[int]"},
898                 {`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]"},
899                 {`package t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
900         }
901
902         for _, test := range tests {
903                 info := Info{
904                         Implicits: make(map[syntax.Node]Object),
905                 }
906                 name := mustTypecheck(test.src, nil, &info).Name()
907
908                 // the test cases expect at most one Implicits entry
909                 if len(info.Implicits) > 1 {
910                         t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
911                         continue
912                 }
913
914                 // extract Implicits entry, if any
915                 var got string
916                 for n, obj := range info.Implicits {
917                         switch x := n.(type) {
918                         case *syntax.ImportDecl:
919                                 got = "importSpec"
920                         case *syntax.CaseClause:
921                                 got = "caseClause"
922                         case *syntax.Field:
923                                 got = "field"
924                         default:
925                                 t.Fatalf("package %s: unexpected %T", name, x)
926                         }
927                         got += ": " + obj.String()
928                 }
929
930                 // verify entry
931                 if got != test.want {
932                         t.Errorf("package %s: got %q; want %q", name, got, test.want)
933                 }
934         }
935 }
936
937 func predString(tv TypeAndValue) string {
938         var buf strings.Builder
939         pred := func(b bool, s string) {
940                 if b {
941                         if buf.Len() > 0 {
942                                 buf.WriteString(", ")
943                         }
944                         buf.WriteString(s)
945                 }
946         }
947
948         pred(tv.IsVoid(), "void")
949         pred(tv.IsType(), "type")
950         pred(tv.IsBuiltin(), "builtin")
951         pred(tv.IsValue() && tv.Value != nil, "const")
952         pred(tv.IsValue() && tv.Value == nil, "value")
953         pred(tv.IsNil(), "nil")
954         pred(tv.Addressable(), "addressable")
955         pred(tv.Assignable(), "assignable")
956         pred(tv.HasOk(), "hasOk")
957
958         if buf.Len() == 0 {
959                 return "invalid"
960         }
961         return buf.String()
962 }
963
964 func TestPredicatesInfo(t *testing.T) {
965         testenv.MustHaveGoBuild(t)
966
967         var tests = []struct {
968                 src  string
969                 expr string
970                 pred string
971         }{
972                 // void
973                 {`package n0; func f() { f() }`, `f()`, `void`},
974
975                 // types
976                 {`package t0; type _ int`, `int`, `type`},
977                 {`package t1; type _ []int`, `[]int`, `type`},
978                 {`package t2; type _ func()`, `func()`, `type`},
979                 {`package t3; type _ func(int)`, `int`, `type`},
980                 {`package t3; type _ func(...int)`, `...int`, `type`},
981
982                 // built-ins
983                 {`package b0; var _ = len("")`, `len`, `builtin`},
984                 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
985
986                 // constants
987                 {`package c0; var _ = 42`, `42`, `const`},
988                 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
989                 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
990
991                 // values
992                 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
993                 {`package v1; var _ = &[]int{1}`, `[]int{…}`, `value`},
994                 {`package v2; var _ = func(){}`, `func() {}`, `value`},
995                 {`package v4; func f() { _ = f }`, `f`, `value`},
996                 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
997                 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
998
999                 // addressable (and thus assignable) operands
1000                 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
1001                 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
1002                 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
1003                 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
1004                 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
1005                 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
1006                 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
1007                 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
1008                 // composite literals are not addressable
1009
1010                 // assignable but not addressable values
1011                 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1012                 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1013
1014                 // hasOk expressions
1015                 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
1016                 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
1017
1018                 // missing entries
1019                 // - package names are collected in the Uses map
1020                 // - identifiers being declared are collected in the Defs map
1021                 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
1022                 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
1023                 {`package m2; const c = 0`, `c`, `<missing>`},
1024                 {`package m3; type T int`, `T`, `<missing>`},
1025                 {`package m4; var v int`, `v`, `<missing>`},
1026                 {`package m5; func f() {}`, `f`, `<missing>`},
1027                 {`package m6; func _(x int) {}`, `x`, `<missing>`},
1028                 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
1029                 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
1030         }
1031
1032         for _, test := range tests {
1033                 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
1034                 name := mustTypecheck(test.src, nil, &info).Name()
1035
1036                 // look for expression predicates
1037                 got := "<missing>"
1038                 for e, tv := range info.Types {
1039                         //println(name, syntax.String(e))
1040                         if syntax.String(e) == test.expr {
1041                                 got = predString(tv)
1042                                 break
1043                         }
1044                 }
1045
1046                 if got != test.pred {
1047                         t.Errorf("package %s: got %s; want %s", name, got, test.pred)
1048                 }
1049         }
1050 }
1051
1052 func TestScopesInfo(t *testing.T) {
1053         testenv.MustHaveGoBuild(t)
1054
1055         var tests = []struct {
1056                 src    string
1057                 scopes []string // list of scope descriptors of the form kind:varlist
1058         }{
1059                 {`package p0`, []string{
1060                         "file:",
1061                 }},
1062                 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
1063                         "file:fmt m",
1064                 }},
1065                 {`package p2; func _() {}`, []string{
1066                         "file:", "func:",
1067                 }},
1068                 {`package p3; func _(x, y int) {}`, []string{
1069                         "file:", "func:x y",
1070                 }},
1071                 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
1072                         "file:", "func:x y z", // redeclaration of x
1073                 }},
1074                 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
1075                         "file:", "func:u x y",
1076                 }},
1077                 {`package p6; func _() { { var x int; _ = x } }`, []string{
1078                         "file:", "func:", "block:x",
1079                 }},
1080                 {`package p7; func _() { if true {} }`, []string{
1081                         "file:", "func:", "if:", "block:",
1082                 }},
1083                 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
1084                         "file:", "func:", "if:x", "block:y",
1085                 }},
1086                 {`package p9; func _() { switch x := 0; x {} }`, []string{
1087                         "file:", "func:", "switch:x",
1088                 }},
1089                 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
1090                         "file:", "func:", "switch:x", "case:y", "case:",
1091                 }},
1092                 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
1093                         "file:", "func:t", "switch:",
1094                 }},
1095                 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
1096                         "file:", "func:t", "switch:t",
1097                 }},
1098                 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
1099                         "file:", "func:t", "switch:", "case:x", // x implicitly declared
1100                 }},
1101                 {`package p14; func _() { select{} }`, []string{
1102                         "file:", "func:",
1103                 }},
1104                 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
1105                         "file:", "func:c", "comm:",
1106                 }},
1107                 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
1108                         "file:", "func:c", "comm:i x",
1109                 }},
1110                 {`package p17; func _() { for{} }`, []string{
1111                         "file:", "func:", "for:", "block:",
1112                 }},
1113                 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
1114                         "file:", "func:n", "for:i", "block:",
1115                 }},
1116                 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
1117                         "file:", "func:a", "for:i", "block:",
1118                 }},
1119                 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
1120                         "file:", "func:a", "for:i x", "block:",
1121                 }},
1122         }
1123
1124         for _, test := range tests {
1125                 info := Info{Scopes: make(map[syntax.Node]*Scope)}
1126                 name := mustTypecheck(test.src, nil, &info).Name()
1127
1128                 // number of scopes must match
1129                 if len(info.Scopes) != len(test.scopes) {
1130                         t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
1131                 }
1132
1133                 // scope descriptions must match
1134                 for node, scope := range info.Scopes {
1135                         var kind string
1136                         switch node.(type) {
1137                         case *syntax.File:
1138                                 kind = "file"
1139                         case *syntax.FuncType:
1140                                 kind = "func"
1141                         case *syntax.BlockStmt:
1142                                 kind = "block"
1143                         case *syntax.IfStmt:
1144                                 kind = "if"
1145                         case *syntax.SwitchStmt:
1146                                 kind = "switch"
1147                         case *syntax.SelectStmt:
1148                                 kind = "select"
1149                         case *syntax.CaseClause:
1150                                 kind = "case"
1151                         case *syntax.CommClause:
1152                                 kind = "comm"
1153                         case *syntax.ForStmt:
1154                                 kind = "for"
1155                         default:
1156                                 kind = fmt.Sprintf("%T", node)
1157                         }
1158
1159                         // look for matching scope description
1160                         desc := kind + ":" + strings.Join(scope.Names(), " ")
1161                         found := false
1162                         for _, d := range test.scopes {
1163                                 if desc == d {
1164                                         found = true
1165                                         break
1166                                 }
1167                         }
1168                         if !found {
1169                                 t.Errorf("package %s: no matching scope found for %s", name, desc)
1170                         }
1171                 }
1172         }
1173 }
1174
1175 func TestInitOrderInfo(t *testing.T) {
1176         var tests = []struct {
1177                 src   string
1178                 inits []string
1179         }{
1180                 {`package p0; var (x = 1; y = x)`, []string{
1181                         "x = 1", "y = x",
1182                 }},
1183                 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
1184                         "a = 1", "b = 2", "c = 3",
1185                 }},
1186                 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
1187                         "a = 1", "b = 2", "c = 3",
1188                 }},
1189                 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
1190                         "_ = f()", // blank var
1191                 }},
1192                 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
1193                         "a = 0", "z = 0", "y = z", "x = y",
1194                 }},
1195                 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
1196                         "a, _ = m[0]", // blank var
1197                 }},
1198                 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
1199                         "z = 0", "a, b = f()",
1200                 }},
1201                 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
1202                         "b = 1", "a = func() int {…}()",
1203                 }},
1204                 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
1205                         "c = 1", "a, b = func() (_, _ int) {…}()",
1206                 }},
1207                 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1208                         "y = 1", "x = T.m",
1209                 }},
1210                 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1211                         "a = 0", "b = 0", "c = 0", "d = c + b",
1212                 }},
1213                 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
1214                         "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
1215                 }},
1216                 // emit an initializer for n:1 initializations only once (not for each node
1217                 // on the lhs which may appear in different order in the dependency graph)
1218                 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
1219                         "b = 0", "x, y = m[0]", "a = x",
1220                 }},
1221                 // test case from spec section on package initialization
1222                 {`package p12
1223
1224                 var (
1225                         a = c + b
1226                         b = f()
1227                         c = f()
1228                         d = 3
1229                 )
1230
1231                 func f() int {
1232                         d++
1233                         return d
1234                 }`, []string{
1235                         "d = 3", "b = f()", "c = f()", "a = c + b",
1236                 }},
1237                 // test case for go.dev/issue/7131
1238                 {`package main
1239
1240                 var counter int
1241                 func next() int { counter++; return counter }
1242
1243                 var _ = makeOrder()
1244                 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1245
1246                 var a       = next()
1247                 var b, c    = next(), next()
1248                 var d, e, f = next(), next(), next()
1249                 `, []string{
1250                         "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1251                 }},
1252                 // test case for go.dev/issue/10709
1253                 {`package p13
1254
1255                 var (
1256                     v = t.m()
1257                     t = makeT(0)
1258                 )
1259
1260                 type T struct{}
1261
1262                 func (T) m() int { return 0 }
1263
1264                 func makeT(n int) T {
1265                     if n > 0 {
1266                         return makeT(n-1)
1267                     }
1268                     return T{}
1269                 }`, []string{
1270                         "t = makeT(0)", "v = t.m()",
1271                 }},
1272                 // test case for go.dev/issue/10709: same as test before, but variable decls swapped
1273                 {`package p14
1274
1275                 var (
1276                     t = makeT(0)
1277                     v = t.m()
1278                 )
1279
1280                 type T struct{}
1281
1282                 func (T) m() int { return 0 }
1283
1284                 func makeT(n int) T {
1285                     if n > 0 {
1286                         return makeT(n-1)
1287                     }
1288                     return T{}
1289                 }`, []string{
1290                         "t = makeT(0)", "v = t.m()",
1291                 }},
1292                 // another candidate possibly causing problems with go.dev/issue/10709
1293                 {`package p15
1294
1295                 var y1 = f1()
1296
1297                 func f1() int { return g1() }
1298                 func g1() int { f1(); return x1 }
1299
1300                 var x1 = 0
1301
1302                 var y2 = f2()
1303
1304                 func f2() int { return g2() }
1305                 func g2() int { return x2 }
1306
1307                 var x2 = 0`, []string{
1308                         "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1309                 }},
1310         }
1311
1312         for _, test := range tests {
1313                 info := Info{}
1314                 name := mustTypecheck(test.src, nil, &info).Name()
1315
1316                 // number of initializers must match
1317                 if len(info.InitOrder) != len(test.inits) {
1318                         t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1319                         continue
1320                 }
1321
1322                 // initializers must match
1323                 for i, want := range test.inits {
1324                         got := info.InitOrder[i].String()
1325                         if got != want {
1326                                 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1327                                 continue
1328                         }
1329                 }
1330         }
1331 }
1332
1333 func TestMultiFileInitOrder(t *testing.T) {
1334         fileA := mustParse(`package main; var a = 1`)
1335         fileB := mustParse(`package main; var b = 2`)
1336
1337         // The initialization order must not depend on the parse
1338         // order of the files, only on the presentation order to
1339         // the type-checker.
1340         for _, test := range []struct {
1341                 files []*syntax.File
1342                 want  string
1343         }{
1344                 {[]*syntax.File{fileA, fileB}, "[a = 1 b = 2]"},
1345                 {[]*syntax.File{fileB, fileA}, "[b = 2 a = 1]"},
1346         } {
1347                 var info Info
1348                 if _, err := new(Config).Check("main", test.files, &info); err != nil {
1349                         t.Fatal(err)
1350                 }
1351                 if got := fmt.Sprint(info.InitOrder); got != test.want {
1352                         t.Fatalf("got %s; want %s", got, test.want)
1353                 }
1354         }
1355 }
1356
1357 func TestFiles(t *testing.T) {
1358         var sources = []string{
1359                 "package p; type T struct{}; func (T) m1() {}",
1360                 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1361                 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1362                 "package p",
1363         }
1364
1365         var conf Config
1366         pkg := NewPackage("p", "p")
1367         var info Info
1368         check := NewChecker(&conf, pkg, &info)
1369
1370         for _, src := range sources {
1371                 if err := check.Files([]*syntax.File{mustParse(src)}); err != nil {
1372                         t.Error(err)
1373                 }
1374         }
1375
1376         // check InitOrder is [x y]
1377         var vars []string
1378         for _, init := range info.InitOrder {
1379                 for _, v := range init.Lhs {
1380                         vars = append(vars, v.Name())
1381                 }
1382         }
1383         if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1384                 t.Errorf("InitOrder == %s, want %s", got, want)
1385         }
1386 }
1387
1388 type testImporter map[string]*Package
1389
1390 func (m testImporter) Import(path string) (*Package, error) {
1391         if pkg := m[path]; pkg != nil {
1392                 return pkg, nil
1393         }
1394         return nil, fmt.Errorf("package %q not found", path)
1395 }
1396
1397 func TestSelection(t *testing.T) {
1398         selections := make(map[*syntax.SelectorExpr]*Selection)
1399
1400         imports := make(testImporter)
1401         conf := Config{Importer: imports}
1402         makePkg := func(path, src string) {
1403                 pkg := mustTypecheck(src, &conf, &Info{Selections: selections})
1404                 imports[path] = pkg
1405         }
1406
1407         const libSrc = `
1408 package lib
1409 type T float64
1410 const C T = 3
1411 var V T
1412 func F() {}
1413 func (T) M() {}
1414 `
1415         const mainSrc = `
1416 package main
1417 import "lib"
1418
1419 type A struct {
1420         *B
1421         C
1422 }
1423
1424 type B struct {
1425         b int
1426 }
1427
1428 func (B) f(int)
1429
1430 type C struct {
1431         c int
1432 }
1433
1434 type G[P any] struct {
1435         p P
1436 }
1437
1438 func (G[P]) m(P) {}
1439
1440 var Inst G[int]
1441
1442 func (C) g()
1443 func (*C) h()
1444
1445 func main() {
1446         // qualified identifiers
1447         var _ lib.T
1448         _ = lib.C
1449         _ = lib.F
1450         _ = lib.V
1451         _ = lib.T.M
1452
1453         // fields
1454         _ = A{}.B
1455         _ = new(A).B
1456
1457         _ = A{}.C
1458         _ = new(A).C
1459
1460         _ = A{}.b
1461         _ = new(A).b
1462
1463         _ = A{}.c
1464         _ = new(A).c
1465
1466         _ = Inst.p
1467         _ = G[string]{}.p
1468
1469         // methods
1470         _ = A{}.f
1471         _ = new(A).f
1472         _ = A{}.g
1473         _ = new(A).g
1474         _ = new(A).h
1475
1476         _ = B{}.f
1477         _ = new(B).f
1478
1479         _ = C{}.g
1480         _ = new(C).g
1481         _ = new(C).h
1482         _ = Inst.m
1483
1484         // method expressions
1485         _ = A.f
1486         _ = (*A).f
1487         _ = B.f
1488         _ = (*B).f
1489         _ = G[string].m
1490 }`
1491
1492         wantOut := map[string][2]string{
1493                 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1494
1495                 "A{}.B":    {"field (main.A) B *main.B", ".[0]"},
1496                 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1497                 "A{}.C":    {"field (main.A) C main.C", ".[1]"},
1498                 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1499                 "A{}.b":    {"field (main.A) b int", "->[0 0]"},
1500                 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1501                 "A{}.c":    {"field (main.A) c int", ".[1 0]"},
1502                 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1503                 "Inst.p":   {"field (main.G[int]) p int", ".[0]"},
1504
1505                 "A{}.f":    {"method (main.A) f(int)", "->[0 0]"},
1506                 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1507                 "A{}.g":    {"method (main.A) g()", ".[1 0]"},
1508                 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1509                 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1510                 "B{}.f":    {"method (main.B) f(int)", ".[0]"},
1511                 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1512                 "C{}.g":    {"method (main.C) g()", ".[0]"},
1513                 "new(C).g": {"method (*main.C) g()", "->[0]"},
1514                 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1515                 "Inst.m":   {"method (main.G[int]) m(int)", ".[0]"},
1516
1517                 "A.f":           {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1518                 "(*A).f":        {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1519                 "B.f":           {"method expr (main.B) f(main.B, int)", ".[0]"},
1520                 "(*B).f":        {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1521                 "G[string].m":   {"method expr (main.G[string]) m(main.G[string], string)", ".[0]"},
1522                 "G[string]{}.p": {"field (main.G[string]) p string", ".[0]"},
1523         }
1524
1525         makePkg("lib", libSrc)
1526         makePkg("main", mainSrc)
1527
1528         for e, sel := range selections {
1529                 _ = sel.String() // assertion: must not panic
1530
1531                 start := indexFor(mainSrc, syntax.StartPos(e))
1532                 end := indexFor(mainSrc, syntax.EndPos(e))
1533                 segment := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1534
1535                 direct := "."
1536                 if sel.Indirect() {
1537                         direct = "->"
1538                 }
1539                 got := [2]string{
1540                         sel.String(),
1541                         fmt.Sprintf("%s%v", direct, sel.Index()),
1542                 }
1543                 want := wantOut[segment]
1544                 if want != got {
1545                         t.Errorf("%s: got %q; want %q", segment, got, want)
1546                 }
1547                 delete(wantOut, segment)
1548
1549                 // We must explicitly assert properties of the
1550                 // Signature's receiver since it doesn't participate
1551                 // in Identical() or String().
1552                 sig, _ := sel.Type().(*Signature)
1553                 if sel.Kind() == MethodVal {
1554                         got := sig.Recv().Type()
1555                         want := sel.Recv()
1556                         if !Identical(got, want) {
1557                                 t.Errorf("%s: Recv() = %s, want %s", segment, got, want)
1558                         }
1559                 } else if sig != nil && sig.Recv() != nil {
1560                         t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1561                 }
1562         }
1563         // Assert that all wantOut entries were used exactly once.
1564         for segment := range wantOut {
1565                 t.Errorf("no syntax.Selection found with syntax %q", segment)
1566         }
1567 }
1568
1569 // indexFor returns the index into s corresponding to the position pos.
1570 func indexFor(s string, pos syntax.Pos) int {
1571         i, line := 0, 1 // string index and corresponding line
1572         target := int(pos.Line())
1573         for line < target && i < len(s) {
1574                 if s[i] == '\n' {
1575                         line++
1576                 }
1577                 i++
1578         }
1579         return i + int(pos.Col()-1) // columns are 1-based
1580 }
1581
1582 func TestIssue8518(t *testing.T) {
1583         imports := make(testImporter)
1584         conf := Config{
1585                 Error:    func(err error) { t.Log(err) }, // don't exit after first error
1586                 Importer: imports,
1587         }
1588         makePkg := func(path, src string) {
1589                 imports[path], _ = conf.Check(path, []*syntax.File{mustParse(src)}, nil) // errors logged via conf.Error
1590         }
1591
1592         const libSrc = `
1593 package a
1594 import "missing"
1595 const C1 = foo
1596 const C2 = missing.C
1597 `
1598
1599         const mainSrc = `
1600 package main
1601 import "a"
1602 var _ = a.C1
1603 var _ = a.C2
1604 `
1605
1606         makePkg("a", libSrc)
1607         makePkg("main", mainSrc) // don't crash when type-checking this package
1608 }
1609
1610 func TestIssue59603(t *testing.T) {
1611         imports := make(testImporter)
1612         conf := Config{
1613                 Error:    func(err error) { t.Log(err) }, // don't exit after first error
1614                 Importer: imports,
1615         }
1616         makePkg := func(path, src string) {
1617                 imports[path], _ = conf.Check(path, []*syntax.File{mustParse(src)}, nil) // errors logged via conf.Error
1618         }
1619
1620         const libSrc = `
1621 package a
1622 const C = foo
1623 `
1624
1625         const mainSrc = `
1626 package main
1627 import "a"
1628 const _ = a.C
1629 `
1630
1631         makePkg("a", libSrc)
1632         makePkg("main", mainSrc) // don't crash when type-checking this package
1633 }
1634
1635 func TestLookupFieldOrMethodOnNil(t *testing.T) {
1636         // LookupFieldOrMethod on a nil type is expected to produce a run-time panic.
1637         defer func() {
1638                 const want = "LookupFieldOrMethod on nil type"
1639                 p := recover()
1640                 if s, ok := p.(string); !ok || s != want {
1641                         t.Fatalf("got %v, want %s", p, want)
1642                 }
1643         }()
1644         LookupFieldOrMethod(nil, false, nil, "")
1645 }
1646
1647 func TestLookupFieldOrMethod(t *testing.T) {
1648         // Test cases assume a lookup of the form a.f or x.f, where a stands for an
1649         // addressable value, and x for a non-addressable value (even though a variable
1650         // for ease of test case writing).
1651         var tests = []struct {
1652                 src      string
1653                 found    bool
1654                 index    []int
1655                 indirect bool
1656         }{
1657                 // field lookups
1658                 {"var x T; type T struct{}", false, nil, false},
1659                 {"var x T; type T struct{ f int }", true, []int{0}, false},
1660                 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1661
1662                 // field lookups on a generic type
1663                 {"var x T[int]; type T[P any] struct{}", false, nil, false},
1664                 {"var x T[int]; type T[P any] struct{ f P }", true, []int{0}, false},
1665                 {"var x T[int]; type T[P any] struct{ a, b, f, c P }", true, []int{2}, false},
1666
1667                 // method lookups
1668                 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1669                 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1670                 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1671                 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1672
1673                 // method lookups on a generic type
1674                 {"var a T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, false},
1675                 {"var a *T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, true},
1676                 {"var a T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, false},
1677                 {"var a *T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1678
1679                 // collisions
1680                 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1681                 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1682
1683                 // collisions on a generic type
1684                 {"type ( E1[P any] struct{ f P }; E2[P any] struct{ f P }; x struct{ E1[int]; *E2[int] })", false, []int{1, 0}, false},
1685                 {"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},
1686
1687                 // outside methodset
1688                 // (*T).f method exists, but value of type T is not addressable
1689                 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1690
1691                 // outside method set of a generic type
1692                 {"var x T[int]; type T[P any] struct{}; func (*T[P]) f() {}", false, nil, true},
1693
1694                 // recursive generic types; see go.dev/issue/52715
1695                 {"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},
1696                 {"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},
1697         }
1698
1699         for _, test := range tests {
1700                 pkg := mustTypecheck("package p;"+test.src, nil, nil)
1701
1702                 obj := pkg.Scope().Lookup("a")
1703                 if obj == nil {
1704                         if obj = pkg.Scope().Lookup("x"); obj == nil {
1705                                 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1706                                 continue
1707                         }
1708                 }
1709
1710                 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1711                 if (f != nil) != test.found {
1712                         if f == nil {
1713                                 t.Errorf("%s: got no object; want one", test.src)
1714                         } else {
1715                                 t.Errorf("%s: got object = %v; want none", test.src, f)
1716                         }
1717                 }
1718                 if !sameSlice(index, test.index) {
1719                         t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1720                 }
1721                 if indirect != test.indirect {
1722                         t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1723                 }
1724         }
1725 }
1726
1727 // Test for go.dev/issue/52715
1728 func TestLookupFieldOrMethod_RecursiveGeneric(t *testing.T) {
1729         const src = `
1730 package pkg
1731
1732 type Tree[T any] struct {
1733         *Node[T]
1734 }
1735
1736 func (*Tree[R]) N(r R) R { return r }
1737
1738 type Node[T any] struct {
1739         *Tree[T]
1740 }
1741
1742 type Instance = *Tree[int]
1743 `
1744
1745         f := mustParse(src)
1746         pkg := NewPackage("pkg", f.PkgName.Value)
1747         if err := NewChecker(nil, pkg, nil).Files([]*syntax.File{f}); err != nil {
1748                 panic(err)
1749         }
1750
1751         T := pkg.Scope().Lookup("Instance").Type()
1752         _, _, _ = LookupFieldOrMethod(T, false, pkg, "M") // verify that LookupFieldOrMethod terminates
1753 }
1754
1755 func sameSlice(a, b []int) bool {
1756         if len(a) != len(b) {
1757                 return false
1758         }
1759         for i, x := range a {
1760                 if x != b[i] {
1761                         return false
1762                 }
1763         }
1764         return true
1765 }
1766
1767 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1768 // the correct result at various positions within the source.
1769 func TestScopeLookupParent(t *testing.T) {
1770         imports := make(testImporter)
1771         conf := Config{Importer: imports}
1772         var info Info
1773         makePkg := func(path, src string) {
1774                 var err error
1775                 imports[path], err = conf.Check(path, []*syntax.File{mustParse(src)}, &info)
1776                 if err != nil {
1777                         t.Fatal(err)
1778                 }
1779         }
1780
1781         makePkg("lib", "package lib; var X int")
1782         // Each /*name=kind:line*/ comment makes the test look up the
1783         // name at that point and checks that it resolves to a decl of
1784         // the specified kind and line number.  "undef" means undefined.
1785         mainSrc := `
1786 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1787 package main
1788
1789 import "lib"
1790 import . "lib"
1791
1792 const Pi = 3.1415
1793 type T struct{}
1794 var Y, _ = lib.X, X
1795
1796 func F(){
1797         const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1798         type /*t=undef*/ t /*t=typename:14*/ *t
1799         print(Y) /*Y=var:10*/
1800         x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1801         var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1802
1803         var a []int
1804         for i, x := range a /*i=undef*/ /*x=var:16*/ { _ = i; _ = x }
1805
1806         var i interface{}
1807         switch y := i.(type) { /*y=undef*/
1808         case /*y=undef*/ int /*y=var:23*/ :
1809         case float32, /*y=undef*/ float64 /*y=var:23*/ :
1810         default /*y=var:23*/:
1811                 println(y)
1812         }
1813         /*y=undef*/
1814
1815         switch int := i.(type) {
1816         case /*int=typename:0*/ int /*int=var:31*/ :
1817                 println(int)
1818         default /*int=var:31*/ :
1819         }
1820 }
1821 /*main=undef*/
1822 `
1823
1824         info.Uses = make(map[*syntax.Name]Object)
1825         makePkg("main", mainSrc)
1826         mainScope := imports["main"].Scope()
1827
1828         rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1829
1830         base := syntax.NewFileBase("main")
1831         syntax.CommentsDo(strings.NewReader(mainSrc), func(line, col uint, text string) {
1832                 pos := syntax.MakePos(base, line, col)
1833
1834                 // Syntax errors are not comments.
1835                 if text[0] != '/' {
1836                         t.Errorf("%s: %s", pos, text)
1837                         return
1838                 }
1839
1840                 // Parse the assertion in the comment.
1841                 m := rx.FindStringSubmatch(text)
1842                 if m == nil {
1843                         t.Errorf("%s: bad comment: %s", pos, text)
1844                         return
1845                 }
1846                 name, want := m[1], m[2]
1847
1848                 // Look up the name in the innermost enclosing scope.
1849                 inner := mainScope.Innermost(pos)
1850                 if inner == nil {
1851                         t.Errorf("%s: at %s: can't find innermost scope", pos, text)
1852                         return
1853                 }
1854                 got := "undef"
1855                 if _, obj := inner.LookupParent(name, pos); obj != nil {
1856                         kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types2."))
1857                         got = fmt.Sprintf("%s:%d", kind, obj.Pos().Line())
1858                 }
1859                 if got != want {
1860                         t.Errorf("%s: at %s: %s resolved to %s, want %s", pos, text, name, got, want)
1861                 }
1862         })
1863
1864         // Check that for each referring identifier,
1865         // a lookup of its name on the innermost
1866         // enclosing scope returns the correct object.
1867
1868         for id, wantObj := range info.Uses {
1869                 inner := mainScope.Innermost(id.Pos())
1870                 if inner == nil {
1871                         t.Errorf("%s: can't find innermost scope enclosing %q", id.Pos(), id.Value)
1872                         continue
1873                 }
1874
1875                 // Exclude selectors and qualified identifiers---lexical
1876                 // refs only.  (Ideally, we'd see if the AST parent is a
1877                 // SelectorExpr, but that requires PathEnclosingInterval
1878                 // from golang.org/x/tools/go/ast/astutil.)
1879                 if id.Value == "X" {
1880                         continue
1881                 }
1882
1883                 _, gotObj := inner.LookupParent(id.Value, id.Pos())
1884                 if gotObj != wantObj {
1885                         t.Errorf("%s: got %v, want %v", id.Pos(), gotObj, wantObj)
1886                         continue
1887                 }
1888         }
1889 }
1890
1891 // newDefined creates a new defined type named T with the given underlying type.
1892 func newDefined(underlying Type) *Named {
1893         tname := NewTypeName(nopos, nil, "T", nil)
1894         return NewNamed(tname, underlying, nil)
1895 }
1896
1897 func TestConvertibleTo(t *testing.T) {
1898         for _, test := range []struct {
1899                 v, t Type
1900                 want bool
1901         }{
1902                 {Typ[Int], Typ[Int], true},
1903                 {Typ[Int], Typ[Float32], true},
1904                 {Typ[Int], Typ[String], true},
1905                 {newDefined(Typ[Int]), Typ[Int], true},
1906                 {newDefined(new(Struct)), new(Struct), true},
1907                 {newDefined(Typ[Int]), new(Struct), false},
1908                 {Typ[UntypedInt], Typ[Int], true},
1909                 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), true},
1910                 {NewSlice(Typ[Int]), NewArray(Typ[Uint], 10), false},
1911                 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
1912                 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
1913                 // Untyped string values are not permitted by the spec, so the behavior below is undefined.
1914                 {Typ[UntypedString], Typ[String], true},
1915         } {
1916                 if got := ConvertibleTo(test.v, test.t); got != test.want {
1917                         t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1918                 }
1919         }
1920 }
1921
1922 func TestAssignableTo(t *testing.T) {
1923         for _, test := range []struct {
1924                 v, t Type
1925                 want bool
1926         }{
1927                 {Typ[Int], Typ[Int], true},
1928                 {Typ[Int], Typ[Float32], false},
1929                 {newDefined(Typ[Int]), Typ[Int], false},
1930                 {newDefined(new(Struct)), new(Struct), true},
1931                 {Typ[UntypedBool], Typ[Bool], true},
1932                 {Typ[UntypedString], Typ[Bool], false},
1933                 // Neither untyped string nor untyped numeric assignments arise during
1934                 // normal type checking, so the below behavior is technically undefined by
1935                 // the spec.
1936                 {Typ[UntypedString], Typ[String], true},
1937                 {Typ[UntypedInt], Typ[Int], true},
1938         } {
1939                 if got := AssignableTo(test.v, test.t); got != test.want {
1940                         t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1941                 }
1942         }
1943 }
1944
1945 func TestIdentical(t *testing.T) {
1946         // For each test, we compare the types of objects X and Y in the source.
1947         tests := []struct {
1948                 src  string
1949                 want bool
1950         }{
1951                 // Basic types.
1952                 {"var X int; var Y int", true},
1953                 {"var X int; var Y string", false},
1954
1955                 // TODO: add more tests for complex types.
1956
1957                 // Named types.
1958                 {"type X int; type Y int", false},
1959
1960                 // Aliases.
1961                 {"type X = int; type Y = int", true},
1962
1963                 // Functions.
1964                 {`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
1965                 {`func X() string { return "" }; func Y(int) string { return "" }`, false},
1966                 {`func X(int) string { return "" }; func Y(int) {}`, false},
1967
1968                 // Generic functions. Type parameters should be considered identical modulo
1969                 // renaming. See also go.dev/issue/49722.
1970                 {`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
1971                 {`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
1972                 {`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
1973                 {`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
1974                 {`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
1975                 {`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
1976         }
1977
1978         for _, test := range tests {
1979                 pkg := mustTypecheck("package p;"+test.src, nil, nil)
1980                 X := pkg.Scope().Lookup("X")
1981                 Y := pkg.Scope().Lookup("Y")
1982                 if X == nil || Y == nil {
1983                         t.Fatal("test must declare both X and Y")
1984                 }
1985                 if got := Identical(X.Type(), Y.Type()); got != test.want {
1986                         t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
1987                 }
1988         }
1989 }
1990
1991 func TestIdentical_issue15173(t *testing.T) {
1992         // Identical should allow nil arguments and be symmetric.
1993         for _, test := range []struct {
1994                 x, y Type
1995                 want bool
1996         }{
1997                 {Typ[Int], Typ[Int], true},
1998                 {Typ[Int], nil, false},
1999                 {nil, Typ[Int], false},
2000                 {nil, nil, true},
2001         } {
2002                 if got := Identical(test.x, test.y); got != test.want {
2003                         t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2004                 }
2005         }
2006 }
2007
2008 func TestIdenticalUnions(t *testing.T) {
2009         tname := NewTypeName(nopos, nil, "myInt", nil)
2010         myInt := NewNamed(tname, Typ[Int], nil)
2011         tmap := map[string]*Term{
2012                 "int":     NewTerm(false, Typ[Int]),
2013                 "~int":    NewTerm(true, Typ[Int]),
2014                 "string":  NewTerm(false, Typ[String]),
2015                 "~string": NewTerm(true, Typ[String]),
2016                 "myInt":   NewTerm(false, myInt),
2017         }
2018         makeUnion := func(s string) *Union {
2019                 parts := strings.Split(s, "|")
2020                 var terms []*Term
2021                 for _, p := range parts {
2022                         term := tmap[p]
2023                         if term == nil {
2024                                 t.Fatalf("missing term %q", p)
2025                         }
2026                         terms = append(terms, term)
2027                 }
2028                 return NewUnion(terms)
2029         }
2030         for _, test := range []struct {
2031                 x, y string
2032                 want bool
2033         }{
2034                 // These tests are just sanity checks. The tests for type sets and
2035                 // interfaces provide much more test coverage.
2036                 {"int|~int", "~int", true},
2037                 {"myInt|~int", "~int", true},
2038                 {"int|string", "string|int", true},
2039                 {"int|int|string", "string|int", true},
2040                 {"myInt|string", "int|string", false},
2041         } {
2042                 x := makeUnion(test.x)
2043                 y := makeUnion(test.y)
2044                 if got := Identical(x, y); got != test.want {
2045                         t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2046                 }
2047         }
2048 }
2049
2050 func TestIssue15305(t *testing.T) {
2051         const src = "package p; func f() int16; var _ = f(undef)"
2052         f := mustParse(src)
2053         conf := Config{
2054                 Error: func(err error) {}, // allow errors
2055         }
2056         info := &Info{
2057                 Types: make(map[syntax.Expr]TypeAndValue),
2058         }
2059         conf.Check("p", []*syntax.File{f}, info) // ignore result
2060         for e, tv := range info.Types {
2061                 if _, ok := e.(*syntax.CallExpr); ok {
2062                         if tv.Type != Typ[Int16] {
2063                                 t.Errorf("CallExpr has type %v, want int16", tv.Type)
2064                         }
2065                         return
2066                 }
2067         }
2068         t.Errorf("CallExpr has no type")
2069 }
2070
2071 // TestCompositeLitTypes verifies that Info.Types registers the correct
2072 // types for composite literal expressions and composite literal type
2073 // expressions.
2074 func TestCompositeLitTypes(t *testing.T) {
2075         for i, test := range []struct {
2076                 lit, typ string
2077         }{
2078                 {`[16]byte{}`, `[16]byte`},
2079                 {`[...]byte{}`, `[0]byte`},                // test for go.dev/issue/14092
2080                 {`[...]int{1, 2, 3}`, `[3]int`},           // test for go.dev/issue/14092
2081                 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for go.dev/issue/14092
2082                 {`[]int{}`, `[]int`},
2083                 {`map[string]bool{"foo": true}`, `map[string]bool`},
2084                 {`struct{}{}`, `struct{}`},
2085                 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
2086         } {
2087                 f := mustParse(fmt.Sprintf("package p%d; var _ = %s", i, test.lit))
2088                 types := make(map[syntax.Expr]TypeAndValue)
2089                 if _, err := new(Config).Check("p", []*syntax.File{f}, &Info{Types: types}); err != nil {
2090                         t.Fatalf("%s: %v", test.lit, err)
2091                 }
2092
2093                 cmptype := func(x syntax.Expr, want string) {
2094                         tv, ok := types[x]
2095                         if !ok {
2096                                 t.Errorf("%s: no Types entry found", test.lit)
2097                                 return
2098                         }
2099                         if tv.Type == nil {
2100                                 t.Errorf("%s: type is nil", test.lit)
2101                                 return
2102                         }
2103                         if got := tv.Type.String(); got != want {
2104                                 t.Errorf("%s: got %v, want %s", test.lit, got, want)
2105                         }
2106                 }
2107
2108                 // test type of composite literal expression
2109                 rhs := f.DeclList[0].(*syntax.VarDecl).Values
2110                 cmptype(rhs, test.typ)
2111
2112                 // test type of composite literal type expression
2113                 cmptype(rhs.(*syntax.CompositeLit).Type, test.typ)
2114         }
2115 }
2116
2117 // TestObjectParents verifies that objects have parent scopes or not
2118 // as specified by the Object interface.
2119 func TestObjectParents(t *testing.T) {
2120         const src = `
2121 package p
2122
2123 const C = 0
2124
2125 type T1 struct {
2126         a, b int
2127         T2
2128 }
2129
2130 type T2 interface {
2131         im1()
2132         im2()
2133 }
2134
2135 func (T1) m1() {}
2136 func (*T1) m2() {}
2137
2138 func f(x int) { y := x; print(y) }
2139 `
2140
2141         f := mustParse(src)
2142
2143         info := &Info{
2144                 Defs: make(map[*syntax.Name]Object),
2145         }
2146         if _, err := new(Config).Check("p", []*syntax.File{f}, info); err != nil {
2147                 t.Fatal(err)
2148         }
2149
2150         for ident, obj := range info.Defs {
2151                 if obj == nil {
2152                         // only package names and implicit vars have a nil object
2153                         // (in this test we only need to handle the package name)
2154                         if ident.Value != "p" {
2155                                 t.Errorf("%v has nil object", ident)
2156                         }
2157                         continue
2158                 }
2159
2160                 // struct fields, type-associated and interface methods
2161                 // have no parent scope
2162                 wantParent := true
2163                 switch obj := obj.(type) {
2164                 case *Var:
2165                         if obj.IsField() {
2166                                 wantParent = false
2167                         }
2168                 case *Func:
2169                         if obj.Type().(*Signature).Recv() != nil { // method
2170                                 wantParent = false
2171                         }
2172                 }
2173
2174                 gotParent := obj.Parent() != nil
2175                 switch {
2176                 case gotParent && !wantParent:
2177                         t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
2178                 case !gotParent && wantParent:
2179                         t.Errorf("%v: no parent found", ident)
2180                 }
2181         }
2182 }
2183
2184 // TestFailedImport tests that we don't get follow-on errors
2185 // elsewhere in a package due to failing to import a package.
2186 func TestFailedImport(t *testing.T) {
2187         testenv.MustHaveGoBuild(t)
2188
2189         const src = `
2190 package p
2191
2192 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
2193
2194 const c = foo.C
2195 type T = foo.T
2196 var v T = c
2197 func f(x T) T { return foo.F(x) }
2198 `
2199         f := mustParse(src)
2200         files := []*syntax.File{f}
2201
2202         // type-check using all possible importers
2203         for _, compiler := range []string{"gc", "gccgo", "source"} {
2204                 errcount := 0
2205                 conf := Config{
2206                         Error: func(err error) {
2207                                 // we should only see the import error
2208                                 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
2209                                         t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
2210                                 }
2211                                 errcount++
2212                         },
2213                         //Importer: importer.For(compiler, nil),
2214                 }
2215
2216                 info := &Info{
2217                         Uses: make(map[*syntax.Name]Object),
2218                 }
2219                 pkg, _ := conf.Check("p", files, info)
2220                 if pkg == nil {
2221                         t.Errorf("for %s importer, type-checking failed to return a package", compiler)
2222                         continue
2223                 }
2224
2225                 imports := pkg.Imports()
2226                 if len(imports) != 1 {
2227                         t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
2228                         continue
2229                 }
2230                 imp := imports[0]
2231                 if imp.Name() != "foo" {
2232                         t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
2233                         continue
2234                 }
2235
2236                 // verify that all uses of foo refer to the imported package foo (imp)
2237                 for ident, obj := range info.Uses {
2238                         if ident.Value == "foo" {
2239                                 if obj, ok := obj.(*PkgName); ok {
2240                                         if obj.Imported() != imp {
2241                                                 t.Errorf("%s resolved to %v; want %v", ident.Value, obj.Imported(), imp)
2242                                         }
2243                                 } else {
2244                                         t.Errorf("%s resolved to %v; want package name", ident.Value, obj)
2245                                 }
2246                         }
2247                 }
2248         }
2249 }
2250
2251 func TestInstantiate(t *testing.T) {
2252         // eventually we like more tests but this is a start
2253         const src = "package p; type T[P any] *T[P]"
2254         pkg := mustTypecheck(src, nil, nil)
2255
2256         // type T should have one type parameter
2257         T := pkg.Scope().Lookup("T").Type().(*Named)
2258         if n := T.TypeParams().Len(); n != 1 {
2259                 t.Fatalf("expected 1 type parameter; found %d", n)
2260         }
2261
2262         // instantiation should succeed (no endless recursion)
2263         // even with a nil *Checker
2264         res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
2265         if err != nil {
2266                 t.Fatal(err)
2267         }
2268
2269         // instantiated type should point to itself
2270         if p := res.Underlying().(*Pointer).Elem(); p != res {
2271                 t.Fatalf("unexpected result type: %s points to %s", res, p)
2272         }
2273 }
2274
2275 func TestInstantiateErrors(t *testing.T) {
2276         tests := []struct {
2277                 src    string // by convention, T must be the type being instantiated
2278                 targs  []Type
2279                 wantAt int // -1 indicates no error
2280         }{
2281                 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
2282                 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
2283                 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
2284                 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
2285         }
2286
2287         for _, test := range tests {
2288                 src := "package p; " + test.src
2289                 pkg := mustTypecheck(src, nil, nil)
2290
2291                 T := pkg.Scope().Lookup("T").Type().(*Named)
2292
2293                 _, err := Instantiate(nil, T, test.targs, true)
2294                 if err == nil {
2295                         t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
2296                 }
2297
2298                 var argErr *ArgumentError
2299                 if !errors.As(err, &argErr) {
2300                         t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
2301                 }
2302
2303                 if argErr.Index != test.wantAt {
2304                         t.Errorf("Instantiate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2305                 }
2306         }
2307 }
2308
2309 func TestArgumentErrorUnwrapping(t *testing.T) {
2310         var err error = &ArgumentError{
2311                 Index: 1,
2312                 Err:   Error{Msg: "test"},
2313         }
2314         var e Error
2315         if !errors.As(err, &e) {
2316                 t.Fatalf("error %v does not wrap types.Error", err)
2317         }
2318         if e.Msg != "test" {
2319                 t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2320         }
2321 }
2322
2323 func TestInstanceIdentity(t *testing.T) {
2324         imports := make(testImporter)
2325         conf := Config{Importer: imports}
2326         makePkg := func(src string) {
2327                 f := mustParse(src)
2328                 name := f.PkgName.Value
2329                 pkg, err := conf.Check(name, []*syntax.File{f}, nil)
2330                 if err != nil {
2331                         t.Fatal(err)
2332                 }
2333                 imports[name] = pkg
2334         }
2335         makePkg(`package lib; type T[P any] struct{}`)
2336         makePkg(`package a; import "lib"; var A lib.T[int]`)
2337         makePkg(`package b; import "lib"; var B lib.T[int]`)
2338         a := imports["a"].Scope().Lookup("A")
2339         b := imports["b"].Scope().Lookup("B")
2340         if !Identical(a.Type(), b.Type()) {
2341                 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
2342         }
2343 }
2344
2345 // TestInstantiatedObjects verifies properties of instantiated objects.
2346 func TestInstantiatedObjects(t *testing.T) {
2347         const src = `
2348 package p
2349
2350 type T[P any] struct {
2351         field P
2352 }
2353
2354 func (recv *T[Q]) concreteMethod(mParam Q) (mResult Q) { return }
2355
2356 type FT[P any] func(ftParam P) (ftResult P)
2357
2358 func F[P any](fParam P) (fResult P){ return }
2359
2360 type I[P any] interface {
2361         interfaceMethod(P)
2362 }
2363
2364 type R[P any] T[P]
2365
2366 func (R[P]) m() {} // having a method triggers expansion of R
2367
2368 var (
2369         t T[int]
2370         ft FT[int]
2371         f = F[int]
2372         i I[int]
2373 )
2374
2375 func fn() {
2376         var r R[int]
2377         _ = r
2378 }
2379 `
2380         info := &Info{
2381                 Defs: make(map[*syntax.Name]Object),
2382         }
2383         f := mustParse(src)
2384         conf := Config{}
2385         pkg, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
2386         if err != nil {
2387                 t.Fatal(err)
2388         }
2389
2390         lookup := func(name string) Type { return pkg.Scope().Lookup(name).Type() }
2391         fnScope := pkg.Scope().Lookup("fn").(*Func).Scope()
2392
2393         tests := []struct {
2394                 name string
2395                 obj  Object
2396         }{
2397                 // Struct fields
2398                 {"field", lookup("t").Underlying().(*Struct).Field(0)},
2399                 {"field", fnScope.Lookup("r").Type().Underlying().(*Struct).Field(0)},
2400
2401                 // Methods and method fields
2402                 {"concreteMethod", lookup("t").(*Named).Method(0)},
2403                 {"recv", lookup("t").(*Named).Method(0).Type().(*Signature).Recv()},
2404                 {"mParam", lookup("t").(*Named).Method(0).Type().(*Signature).Params().At(0)},
2405                 {"mResult", lookup("t").(*Named).Method(0).Type().(*Signature).Results().At(0)},
2406
2407                 // Interface methods
2408                 {"interfaceMethod", lookup("i").Underlying().(*Interface).Method(0)},
2409
2410                 // Function type fields
2411                 {"ftParam", lookup("ft").Underlying().(*Signature).Params().At(0)},
2412                 {"ftResult", lookup("ft").Underlying().(*Signature).Results().At(0)},
2413
2414                 // Function fields
2415                 {"fParam", lookup("f").(*Signature).Params().At(0)},
2416                 {"fResult", lookup("f").(*Signature).Results().At(0)},
2417         }
2418
2419         // Collect all identifiers by name.
2420         idents := make(map[string][]*syntax.Name)
2421         syntax.Inspect(f, func(n syntax.Node) bool {
2422                 if id, ok := n.(*syntax.Name); ok {
2423                         idents[id.Value] = append(idents[id.Value], id)
2424                 }
2425                 return true
2426         })
2427
2428         for _, test := range tests {
2429                 test := test
2430                 t.Run(test.name, func(t *testing.T) {
2431                         if got := len(idents[test.name]); got != 1 {
2432                                 t.Fatalf("found %d identifiers named %s, want 1", got, test.name)
2433                         }
2434                         ident := idents[test.name][0]
2435                         def := info.Defs[ident]
2436                         if def == test.obj {
2437                                 t.Fatalf("info.Defs[%s] contains the test object", test.name)
2438                         }
2439                         if orig := originObject(test.obj); def != orig {
2440                                 t.Errorf("info.Defs[%s] does not match obj.Origin()", test.name)
2441                         }
2442                         if def.Pkg() != test.obj.Pkg() {
2443                                 t.Errorf("Pkg() = %v, want %v", def.Pkg(), test.obj.Pkg())
2444                         }
2445                         if def.Name() != test.obj.Name() {
2446                                 t.Errorf("Name() = %v, want %v", def.Name(), test.obj.Name())
2447                         }
2448                         if def.Pos() != test.obj.Pos() {
2449                                 t.Errorf("Pos() = %v, want %v", def.Pos(), test.obj.Pos())
2450                         }
2451                         if def.Parent() != test.obj.Parent() {
2452                                 t.Fatalf("Parent() = %v, want %v", def.Parent(), test.obj.Parent())
2453                         }
2454                         if def.Exported() != test.obj.Exported() {
2455                                 t.Fatalf("Exported() = %v, want %v", def.Exported(), test.obj.Exported())
2456                         }
2457                         if def.Id() != test.obj.Id() {
2458                                 t.Fatalf("Id() = %v, want %v", def.Id(), test.obj.Id())
2459                         }
2460                         // String and Type are expected to differ.
2461                 })
2462         }
2463 }
2464
2465 func originObject(obj Object) Object {
2466         switch obj := obj.(type) {
2467         case *Var:
2468                 return obj.Origin()
2469         case *Func:
2470                 return obj.Origin()
2471         }
2472         return obj
2473 }
2474
2475 func TestImplements(t *testing.T) {
2476         const src = `
2477 package p
2478
2479 type EmptyIface interface{}
2480
2481 type I interface {
2482         m()
2483 }
2484
2485 type C interface {
2486         m()
2487         ~int
2488 }
2489
2490 type Integer interface{
2491         int8 | int16 | int32 | int64
2492 }
2493
2494 type EmptyTypeSet interface{
2495         Integer
2496         ~string
2497 }
2498
2499 type N1 int
2500 func (N1) m() {}
2501
2502 type N2 int
2503 func (*N2) m() {}
2504
2505 type N3 int
2506 func (N3) m(int) {}
2507
2508 type N4 string
2509 func (N4) m()
2510
2511 type Bad Bad // invalid type
2512 `
2513
2514         f := mustParse(src)
2515         conf := Config{Error: func(error) {}}
2516         pkg, _ := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
2517
2518         lookup := func(tname string) Type { return pkg.Scope().Lookup(tname).Type() }
2519         var (
2520                 EmptyIface   = lookup("EmptyIface").Underlying().(*Interface)
2521                 I            = lookup("I").(*Named)
2522                 II           = I.Underlying().(*Interface)
2523                 C            = lookup("C").(*Named)
2524                 CI           = C.Underlying().(*Interface)
2525                 Integer      = lookup("Integer").Underlying().(*Interface)
2526                 EmptyTypeSet = lookup("EmptyTypeSet").Underlying().(*Interface)
2527                 N1           = lookup("N1")
2528                 N1p          = NewPointer(N1)
2529                 N2           = lookup("N2")
2530                 N2p          = NewPointer(N2)
2531                 N3           = lookup("N3")
2532                 N4           = lookup("N4")
2533                 Bad          = lookup("Bad")
2534         )
2535
2536         tests := []struct {
2537                 V    Type
2538                 T    *Interface
2539                 want bool
2540         }{
2541                 {I, II, true},
2542                 {I, CI, false},
2543                 {C, II, true},
2544                 {C, CI, true},
2545                 {Typ[Int8], Integer, true},
2546                 {Typ[Int64], Integer, true},
2547                 {Typ[String], Integer, false},
2548                 {EmptyTypeSet, II, true},
2549                 {EmptyTypeSet, EmptyTypeSet, true},
2550                 {Typ[Int], EmptyTypeSet, false},
2551                 {N1, II, true},
2552                 {N1, CI, true},
2553                 {N1p, II, true},
2554                 {N1p, CI, false},
2555                 {N2, II, false},
2556                 {N2, CI, false},
2557                 {N2p, II, true},
2558                 {N2p, CI, false},
2559                 {N3, II, false},
2560                 {N3, CI, false},
2561                 {N4, II, true},
2562                 {N4, CI, false},
2563                 {Bad, II, false},
2564                 {Bad, CI, false},
2565                 {Bad, EmptyIface, true},
2566         }
2567
2568         for _, test := range tests {
2569                 if got := Implements(test.V, test.T); got != test.want {
2570                         t.Errorf("Implements(%s, %s) = %t, want %t", test.V, test.T, got, test.want)
2571                 }
2572
2573                 // The type assertion x.(T) is valid if T is an interface or if T implements the type of x.
2574                 // The assertion is never valid if T is a bad type.
2575                 V := test.T
2576                 T := test.V
2577                 want := false
2578                 if _, ok := T.Underlying().(*Interface); (ok || Implements(T, V)) && T != Bad {
2579                         want = true
2580                 }
2581                 if got := AssertableTo(V, T); got != want {
2582                         t.Errorf("AssertableTo(%s, %s) = %t, want %t", V, T, got, want)
2583                 }
2584         }
2585 }
2586
2587 func TestMissingMethodAlternative(t *testing.T) {
2588         const src = `
2589 package p
2590 type T interface {
2591         m()
2592 }
2593
2594 type V0 struct{}
2595 func (V0) m() {}
2596
2597 type V1 struct{}
2598
2599 type V2 struct{}
2600 func (V2) m() int
2601
2602 type V3 struct{}
2603 func (*V3) m()
2604
2605 type V4 struct{}
2606 func (V4) M()
2607 `
2608
2609         pkg := mustTypecheck(src, nil, nil)
2610
2611         T := pkg.Scope().Lookup("T").Type().Underlying().(*Interface)
2612         lookup := func(name string) (*Func, bool) {
2613                 return MissingMethod(pkg.Scope().Lookup(name).Type(), T, true)
2614         }
2615
2616         // V0 has method m with correct signature. Should not report wrongType.
2617         method, wrongType := lookup("V0")
2618         if method != nil || wrongType {
2619                 t.Fatalf("V0: got method = %v, wrongType = %v", method, wrongType)
2620         }
2621
2622         checkMissingMethod := func(tname string, reportWrongType bool) {
2623                 method, wrongType := lookup(tname)
2624                 if method == nil || method.Name() != "m" || wrongType != reportWrongType {
2625                         t.Fatalf("%s: got method = %v, wrongType = %v", tname, method, wrongType)
2626                 }
2627         }
2628
2629         // V1 has no method m. Should not report wrongType.
2630         checkMissingMethod("V1", false)
2631
2632         // V2 has method m with wrong signature type (ignoring receiver). Should report wrongType.
2633         checkMissingMethod("V2", true)
2634
2635         // V3 has no method m but it exists on *V3. Should report wrongType.
2636         checkMissingMethod("V3", true)
2637
2638         // V4 has no method m but has M. Should not report wrongType.
2639         checkMissingMethod("V4", false)
2640 }