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