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