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