]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/api_test.go
go/types, types2: rename generic 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                 {`package issue59956; func f(func(int), func(string), func(bool)) {}; func g[P any](P) {}; func _() { f(g, g, g) }`,
587                         []testInst{
588                                 {`g`, []string{`int`}, `func(int)`},
589                                 {`g`, []string{`string`}, `func(string)`},
590                                 {`g`, []string{`bool`}, `func(bool)`},
591                         },
592                 },
593         }
594
595         for _, test := range tests {
596                 imports := make(testImporter)
597                 conf := Config{
598                         Importer: imports,
599                         // Unexported field: set below with boolFieldAddr
600                         // _EnableReverseTypeInference: true,
601                 }
602                 *boolFieldAddr(&conf, "_EnableReverseTypeInference") = true
603                 instMap := make(map[*ast.Ident]Instance)
604                 useMap := make(map[*ast.Ident]Object)
605                 makePkg := func(src string) *Package {
606                         pkg, err := typecheck(src, &conf, &Info{Instances: instMap, Uses: useMap})
607                         // allow error for issue51803
608                         if err != nil && (pkg == nil || pkg.Name() != "issue51803") {
609                                 t.Fatal(err)
610                         }
611                         imports[pkg.Name()] = pkg
612                         return pkg
613                 }
614                 makePkg(lib)
615                 pkg := makePkg(test.src)
616
617                 t.Run(pkg.Name(), func(t *testing.T) {
618                         // Sort instances in source order for stability.
619                         instances := sortedInstances(instMap)
620                         if got, want := len(instances), len(test.instances); got != want {
621                                 t.Fatalf("got %d instances, want %d", got, want)
622                         }
623
624                         // Pairwise compare with the expected instances.
625                         for ii, inst := range instances {
626                                 var targs []Type
627                                 for i := 0; i < inst.Inst.TypeArgs.Len(); i++ {
628                                         targs = append(targs, inst.Inst.TypeArgs.At(i))
629                                 }
630                                 typ := inst.Inst.Type
631
632                                 testInst := test.instances[ii]
633                                 if got := inst.Ident.Name; got != testInst.name {
634                                         t.Fatalf("got name %s, want %s", got, testInst.name)
635                                 }
636                                 if len(targs) != len(testInst.targs) {
637                                         t.Fatalf("got %d type arguments; want %d", len(targs), len(testInst.targs))
638                                 }
639                                 for i, targ := range targs {
640                                         if got := targ.String(); got != testInst.targs[i] {
641                                                 t.Errorf("type argument %d: got %s; want %s", i, got, testInst.targs[i])
642                                         }
643                                 }
644                                 if got := typ.Underlying().String(); got != testInst.typ {
645                                         t.Errorf("package %s: got %s; want %s", pkg.Name(), got, testInst.typ)
646                                 }
647
648                                 // Verify the invariant that re-instantiating the corresponding generic
649                                 // type with TypeArgs results in an identical instance.
650                                 ptype := useMap[inst.Ident].Type()
651                                 lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
652                                 if lister == nil || lister.TypeParams().Len() == 0 {
653                                         t.Fatalf("info.Types[%v] = %v, want parameterized type", inst.Ident, ptype)
654                                 }
655                                 inst2, err := Instantiate(nil, ptype, targs, true)
656                                 if err != nil {
657                                         t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
658                                 }
659                                 if !Identical(inst.Inst.Type, inst2) {
660                                         t.Errorf("%v and %v are not identical", inst.Inst.Type, inst2)
661                                 }
662                         }
663                 })
664         }
665 }
666
667 type recordedInstance struct {
668         Ident *ast.Ident
669         Inst  Instance
670 }
671
672 func sortedInstances(m map[*ast.Ident]Instance) (instances []recordedInstance) {
673         for id, inst := range m {
674                 instances = append(instances, recordedInstance{id, inst})
675         }
676         sort.Slice(instances, func(i, j int) bool {
677                 return CmpPos(instances[i].Ident.Pos(), instances[j].Ident.Pos()) < 0
678         })
679         return instances
680 }
681
682 func TestDefsInfo(t *testing.T) {
683         var tests = []struct {
684                 src  string
685                 obj  string
686                 want string
687         }{
688                 {`package p0; const x = 42`, `x`, `const p0.x untyped int`},
689                 {`package p1; const x int = 42`, `x`, `const p1.x int`},
690                 {`package p2; var x int`, `x`, `var p2.x int`},
691                 {`package p3; type x int`, `x`, `type p3.x int`},
692                 {`package p4; func f()`, `f`, `func p4.f()`},
693                 {`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
694
695                 // Tests using generics.
696                 {`package g0; type x[T any] int`, `x`, `type g0.x[T any] int`},
697                 {`package g1; func f[T any]() {}`, `f`, `func g1.f[T any]()`},
698                 {`package g2; type x[T any] int; func (*x[_]) m() {}`, `m`, `func (*g2.x[_]).m()`},
699         }
700
701         for _, test := range tests {
702                 info := Info{
703                         Defs: make(map[*ast.Ident]Object),
704                 }
705                 name := mustTypecheck(test.src, nil, &info).Name()
706
707                 // find object
708                 var def Object
709                 for id, obj := range info.Defs {
710                         if id.Name == test.obj {
711                                 def = obj
712                                 break
713                         }
714                 }
715                 if def == nil {
716                         t.Errorf("package %s: %s not found", name, test.obj)
717                         continue
718                 }
719
720                 if got := def.String(); got != test.want {
721                         t.Errorf("package %s: got %s; want %s", name, got, test.want)
722                 }
723         }
724 }
725
726 func TestUsesInfo(t *testing.T) {
727         var tests = []struct {
728                 src  string
729                 obj  string
730                 want string
731         }{
732                 {`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
733                 {`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
734                 {`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
735                 {`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
736                 {`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
737
738                 // Tests using generics.
739                 {`package g0; func _[T any]() { _ = x }; const x = 42`, `x`, `const g0.x untyped int`},
740                 {`package g1; func _[T any](x T) { }`, `T`, `type parameter T any`},
741                 {`package g2; type N[A any] int; var _ N[int]`, `N`, `type g2.N[A any] int`},
742                 {`package g3; type N[A any] int; func (N[_]) m() {}`, `N`, `type g3.N[A any] int`},
743
744                 // Uses of fields are instantiated.
745                 {`package s1; type N[A any] struct{ a A }; var f = N[int]{}.a`, `a`, `field a int`},
746                 {`package s1; type N[A any] struct{ a A }; func (r N[B]) m(b B) { r.a = b }`, `a`, `field a B`},
747
748                 // Uses of methods are uses of the instantiated method.
749                 {`package m0; type N[A any] int; func (r N[B]) m() { r.n() }; func (N[C]) n() {}`, `n`, `func (m0.N[B]).n()`},
750                 {`package m1; type N[A any] int; func (r N[B]) m() { }; var f = N[int].m`, `m`, `func (m1.N[int]).m()`},
751                 {`package m2; func _[A any](v interface{ m() A }) { v.m() }`, `m`, `func (interface).m() A`},
752                 {`package m3; func f[A any]() interface{ m() A } { return nil }; var _ = f[int]().m()`, `m`, `func (interface).m() int`},
753                 {`package m4; type T[A any] func() interface{ m() A }; var x T[int]; var y = x().m`, `m`, `func (interface).m() int`},
754                 {`package m5; type T[A any] interface{ m() A }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m5.T[B]).m() B`},
755                 {`package m6; type T[A any] interface{ m() }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m6.T[B]).m()`},
756                 {`package m7; type T[A any] interface{ m() A }; func _(t T[int]) { t.m() }`, `m`, `func (m7.T[int]).m() int`},
757                 {`package m8; type T[A any] interface{ m() }; func _(t T[int]) { t.m() }`, `m`, `func (m8.T[int]).m()`},
758                 {`package m9; type T[A any] interface{ m() }; func _(t T[int]) { _ = t.m }`, `m`, `func (m9.T[int]).m()`},
759                 {
760                         `package m10; type E[A any] interface{ m() }; type T[B any] interface{ E[B]; n() }; func _(t T[int]) { t.m() }`,
761                         `m`,
762                         `func (m10.E[int]).m()`,
763                 },
764                 {`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()`},
765                 {`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()`},
766         }
767
768         for _, test := range tests {
769                 info := Info{
770                         Uses: make(map[*ast.Ident]Object),
771                 }
772                 name := mustTypecheck(test.src, nil, &info).Name()
773
774                 // find object
775                 var use Object
776                 for id, obj := range info.Uses {
777                         if id.Name == test.obj {
778                                 if use != nil {
779                                         panic(fmt.Sprintf("multiple uses of %q", id.Name))
780                                 }
781                                 use = obj
782                         }
783                 }
784                 if use == nil {
785                         t.Errorf("package %s: %s not found", name, test.obj)
786                         continue
787                 }
788
789                 if got := use.String(); got != test.want {
790                         t.Errorf("package %s: got %s; want %s", name, got, test.want)
791                 }
792         }
793 }
794
795 func TestGenericMethodInfo(t *testing.T) {
796         src := `package p
797
798 type N[A any] int
799
800 func (r N[B]) m() { r.m(); r.n() }
801
802 func (r *N[C]) n() {  }
803 `
804         fset := token.NewFileSet()
805         f := mustParse(fset, src)
806         info := Info{
807                 Defs:       make(map[*ast.Ident]Object),
808                 Uses:       make(map[*ast.Ident]Object),
809                 Selections: make(map[*ast.SelectorExpr]*Selection),
810         }
811         var conf Config
812         pkg, err := conf.Check("p", fset, []*ast.File{f}, &info)
813         if err != nil {
814                 t.Fatal(err)
815         }
816
817         N := pkg.Scope().Lookup("N").Type().(*Named)
818
819         // Find the generic methods stored on N.
820         gm, gn := N.Method(0), N.Method(1)
821         if gm.Name() == "n" {
822                 gm, gn = gn, gm
823         }
824
825         // Collect objects from info.
826         var dm, dn *Func   // the declared methods
827         var dmm, dmn *Func // the methods used in the body of m
828         for _, decl := range f.Decls {
829                 fdecl, ok := decl.(*ast.FuncDecl)
830                 if !ok {
831                         continue
832                 }
833                 def := info.Defs[fdecl.Name].(*Func)
834                 switch fdecl.Name.Name {
835                 case "m":
836                         dm = def
837                         ast.Inspect(fdecl.Body, func(n ast.Node) bool {
838                                 if call, ok := n.(*ast.CallExpr); ok {
839                                         sel := call.Fun.(*ast.SelectorExpr)
840                                         use := info.Uses[sel.Sel].(*Func)
841                                         selection := info.Selections[sel]
842                                         if selection.Kind() != MethodVal {
843                                                 t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
844                                         }
845                                         if selection.Obj() != use {
846                                                 t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
847                                         }
848                                         switch sel.Sel.Name {
849                                         case "m":
850                                                 dmm = use
851                                         case "n":
852                                                 dmn = use
853                                         }
854                                 }
855                                 return true
856                         })
857                 case "n":
858                         dn = def
859                 }
860         }
861
862         if gm != dm {
863                 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
864         }
865         if gn != dn {
866                 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
867         }
868         if dmm != dm {
869                 t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
870         }
871         if dmn == dn {
872                 t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
873         }
874 }
875
876 func TestImplicitsInfo(t *testing.T) {
877         testenv.MustHaveGoBuild(t)
878
879         var tests = []struct {
880                 src  string
881                 want string
882         }{
883                 {`package p2; import . "fmt"; var _ = Println`, ""},           // no Implicits entry
884                 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
885                 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
886
887                 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
888                 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
889                 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
890                 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
891
892                 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
893                 {`package p8; func f(int) {}`, "field: var  int"},
894                 {`package p9; func f() (complex64) { return 0 }`, "field: var  complex64"},
895                 {`package p10; type T struct{}; func (*T) f() {}`, "field: var  *p10.T"},
896
897                 // Tests using generics.
898                 {`package f0; func f[T any](x int) {}`, ""}, // no Implicits entry
899                 {`package f1; func f[T any](int) {}`, "field: var  int"},
900                 {`package f2; func f[T any](T) {}`, "field: var  T"},
901                 {`package f3; func f[T any]() (complex64) { return 0 }`, "field: var  complex64"},
902                 {`package f4; func f[T any](t T) (T) { return t }`, "field: var  T"},
903                 {`package t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var  *t0.T[_]"},
904                 {`package t1; type T[A any] struct{}; func _(x interface{}) { switch t := x.(type) { case T[int]: _ = t } }`, "caseClause: var t t1.T[int]"},
905                 {`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]"},
906                 {`package t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
907         }
908
909         for _, test := range tests {
910                 info := Info{
911                         Implicits: make(map[ast.Node]Object),
912                 }
913                 name := mustTypecheck(test.src, nil, &info).Name()
914
915                 // the test cases expect at most one Implicits entry
916                 if len(info.Implicits) > 1 {
917                         t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
918                         continue
919                 }
920
921                 // extract Implicits entry, if any
922                 var got string
923                 for n, obj := range info.Implicits {
924                         switch x := n.(type) {
925                         case *ast.ImportSpec:
926                                 got = "importSpec"
927                         case *ast.CaseClause:
928                                 got = "caseClause"
929                         case *ast.Field:
930                                 got = "field"
931                         default:
932                                 t.Fatalf("package %s: unexpected %T", name, x)
933                         }
934                         got += ": " + obj.String()
935                 }
936
937                 // verify entry
938                 if got != test.want {
939                         t.Errorf("package %s: got %q; want %q", name, got, test.want)
940                 }
941         }
942 }
943
944 func predString(tv TypeAndValue) string {
945         var buf strings.Builder
946         pred := func(b bool, s string) {
947                 if b {
948                         if buf.Len() > 0 {
949                                 buf.WriteString(", ")
950                         }
951                         buf.WriteString(s)
952                 }
953         }
954
955         pred(tv.IsVoid(), "void")
956         pred(tv.IsType(), "type")
957         pred(tv.IsBuiltin(), "builtin")
958         pred(tv.IsValue() && tv.Value != nil, "const")
959         pred(tv.IsValue() && tv.Value == nil, "value")
960         pred(tv.IsNil(), "nil")
961         pred(tv.Addressable(), "addressable")
962         pred(tv.Assignable(), "assignable")
963         pred(tv.HasOk(), "hasOk")
964
965         if buf.Len() == 0 {
966                 return "invalid"
967         }
968         return buf.String()
969 }
970
971 func TestPredicatesInfo(t *testing.T) {
972         testenv.MustHaveGoBuild(t)
973
974         var tests = []struct {
975                 src  string
976                 expr string
977                 pred string
978         }{
979                 // void
980                 {`package n0; func f() { f() }`, `f()`, `void`},
981
982                 // types
983                 {`package t0; type _ int`, `int`, `type`},
984                 {`package t1; type _ []int`, `[]int`, `type`},
985                 {`package t2; type _ func()`, `func()`, `type`},
986                 {`package t3; type _ func(int)`, `int`, `type`},
987                 {`package t3; type _ func(...int)`, `...int`, `type`},
988
989                 // built-ins
990                 {`package b0; var _ = len("")`, `len`, `builtin`},
991                 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
992
993                 // constants
994                 {`package c0; var _ = 42`, `42`, `const`},
995                 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
996                 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
997
998                 // values
999                 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
1000                 {`package v1; var _ = &[]int{1}`, `[]int{…}`, `value`},
1001                 {`package v2; var _ = func(){}`, `(func() literal)`, `value`},
1002                 {`package v4; func f() { _ = f }`, `f`, `value`},
1003                 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
1004                 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
1005
1006                 // addressable (and thus assignable) operands
1007                 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
1008                 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
1009                 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
1010                 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
1011                 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
1012                 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
1013                 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
1014                 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
1015                 // composite literals are not addressable
1016
1017                 // assignable but not addressable values
1018                 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1019                 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1020
1021                 // hasOk expressions
1022                 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
1023                 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
1024
1025                 // missing entries
1026                 // - package names are collected in the Uses map
1027                 // - identifiers being declared are collected in the Defs map
1028                 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
1029                 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
1030                 {`package m2; const c = 0`, `c`, `<missing>`},
1031                 {`package m3; type T int`, `T`, `<missing>`},
1032                 {`package m4; var v int`, `v`, `<missing>`},
1033                 {`package m5; func f() {}`, `f`, `<missing>`},
1034                 {`package m6; func _(x int) {}`, `x`, `<missing>`},
1035                 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
1036                 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
1037         }
1038
1039         for _, test := range tests {
1040                 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
1041                 name := mustTypecheck(test.src, nil, &info).Name()
1042
1043                 // look for expression predicates
1044                 got := "<missing>"
1045                 for e, tv := range info.Types {
1046                         //println(name, ExprString(e))
1047                         if ExprString(e) == test.expr {
1048                                 got = predString(tv)
1049                                 break
1050                         }
1051                 }
1052
1053                 if got != test.pred {
1054                         t.Errorf("package %s: got %s; want %s", name, got, test.pred)
1055                 }
1056         }
1057 }
1058
1059 func TestScopesInfo(t *testing.T) {
1060         testenv.MustHaveGoBuild(t)
1061
1062         var tests = []struct {
1063                 src    string
1064                 scopes []string // list of scope descriptors of the form kind:varlist
1065         }{
1066                 {`package p0`, []string{
1067                         "file:",
1068                 }},
1069                 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
1070                         "file:fmt m",
1071                 }},
1072                 {`package p2; func _() {}`, []string{
1073                         "file:", "func:",
1074                 }},
1075                 {`package p3; func _(x, y int) {}`, []string{
1076                         "file:", "func:x y",
1077                 }},
1078                 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
1079                         "file:", "func:x y z", // redeclaration of x
1080                 }},
1081                 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
1082                         "file:", "func:u x y",
1083                 }},
1084                 {`package p6; func _() { { var x int; _ = x } }`, []string{
1085                         "file:", "func:", "block:x",
1086                 }},
1087                 {`package p7; func _() { if true {} }`, []string{
1088                         "file:", "func:", "if:", "block:",
1089                 }},
1090                 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
1091                         "file:", "func:", "if:x", "block:y",
1092                 }},
1093                 {`package p9; func _() { switch x := 0; x {} }`, []string{
1094                         "file:", "func:", "switch:x",
1095                 }},
1096                 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
1097                         "file:", "func:", "switch:x", "case:y", "case:",
1098                 }},
1099                 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
1100                         "file:", "func:t", "type switch:",
1101                 }},
1102                 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
1103                         "file:", "func:t", "type switch:t",
1104                 }},
1105                 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
1106                         "file:", "func:t", "type switch:", "case:x", // x implicitly declared
1107                 }},
1108                 {`package p14; func _() { select{} }`, []string{
1109                         "file:", "func:",
1110                 }},
1111                 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
1112                         "file:", "func:c", "comm:",
1113                 }},
1114                 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
1115                         "file:", "func:c", "comm:i x",
1116                 }},
1117                 {`package p17; func _() { for{} }`, []string{
1118                         "file:", "func:", "for:", "block:",
1119                 }},
1120                 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
1121                         "file:", "func:n", "for:i", "block:",
1122                 }},
1123                 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
1124                         "file:", "func:a", "range:i", "block:",
1125                 }},
1126                 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
1127                         "file:", "func:a", "range:i x", "block:",
1128                 }},
1129         }
1130
1131         for _, test := range tests {
1132                 info := Info{Scopes: make(map[ast.Node]*Scope)}
1133                 name := mustTypecheck(test.src, nil, &info).Name()
1134
1135                 // number of scopes must match
1136                 if len(info.Scopes) != len(test.scopes) {
1137                         t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
1138                 }
1139
1140                 // scope descriptions must match
1141                 for node, scope := range info.Scopes {
1142                         kind := "<unknown node kind>"
1143                         switch node.(type) {
1144                         case *ast.File:
1145                                 kind = "file"
1146                         case *ast.FuncType:
1147                                 kind = "func"
1148                         case *ast.BlockStmt:
1149                                 kind = "block"
1150                         case *ast.IfStmt:
1151                                 kind = "if"
1152                         case *ast.SwitchStmt:
1153                                 kind = "switch"
1154                         case *ast.TypeSwitchStmt:
1155                                 kind = "type switch"
1156                         case *ast.CaseClause:
1157                                 kind = "case"
1158                         case *ast.CommClause:
1159                                 kind = "comm"
1160                         case *ast.ForStmt:
1161                                 kind = "for"
1162                         case *ast.RangeStmt:
1163                                 kind = "range"
1164                         }
1165
1166                         // look for matching scope description
1167                         desc := kind + ":" + strings.Join(scope.Names(), " ")
1168                         found := false
1169                         for _, d := range test.scopes {
1170                                 if desc == d {
1171                                         found = true
1172                                         break
1173                                 }
1174                         }
1175                         if !found {
1176                                 t.Errorf("package %s: no matching scope found for %s", name, desc)
1177                         }
1178                 }
1179         }
1180 }
1181
1182 func TestInitOrderInfo(t *testing.T) {
1183         var tests = []struct {
1184                 src   string
1185                 inits []string
1186         }{
1187                 {`package p0; var (x = 1; y = x)`, []string{
1188                         "x = 1", "y = x",
1189                 }},
1190                 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
1191                         "a = 1", "b = 2", "c = 3",
1192                 }},
1193                 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
1194                         "a = 1", "b = 2", "c = 3",
1195                 }},
1196                 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
1197                         "_ = f()", // blank var
1198                 }},
1199                 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
1200                         "a = 0", "z = 0", "y = z", "x = y",
1201                 }},
1202                 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
1203                         "a, _ = m[0]", // blank var
1204                 }},
1205                 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
1206                         "z = 0", "a, b = f()",
1207                 }},
1208                 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
1209                         "b = 1", "a = (func() int literal)()",
1210                 }},
1211                 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
1212                         "c = 1", "a, b = (func() (_, _ int) literal)()",
1213                 }},
1214                 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1215                         "y = 1", "x = T.m",
1216                 }},
1217                 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1218                         "a = 0", "b = 0", "c = 0", "d = c + b",
1219                 }},
1220                 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
1221                         "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
1222                 }},
1223                 // emit an initializer for n:1 initializations only once (not for each node
1224                 // on the lhs which may appear in different order in the dependency graph)
1225                 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
1226                         "b = 0", "x, y = m[0]", "a = x",
1227                 }},
1228                 // test case from spec section on package initialization
1229                 {`package p12
1230
1231                 var (
1232                         a = c + b
1233                         b = f()
1234                         c = f()
1235                         d = 3
1236                 )
1237
1238                 func f() int {
1239                         d++
1240                         return d
1241                 }`, []string{
1242                         "d = 3", "b = f()", "c = f()", "a = c + b",
1243                 }},
1244                 // test case for go.dev/issue/7131
1245                 {`package main
1246
1247                 var counter int
1248                 func next() int { counter++; return counter }
1249
1250                 var _ = makeOrder()
1251                 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1252
1253                 var a       = next()
1254                 var b, c    = next(), next()
1255                 var d, e, f = next(), next(), next()
1256                 `, []string{
1257                         "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1258                 }},
1259                 // test case for go.dev/issue/10709
1260                 {`package p13
1261
1262                 var (
1263                     v = t.m()
1264                     t = makeT(0)
1265                 )
1266
1267                 type T struct{}
1268
1269                 func (T) m() int { return 0 }
1270
1271                 func makeT(n int) T {
1272                     if n > 0 {
1273                         return makeT(n-1)
1274                     }
1275                     return T{}
1276                 }`, []string{
1277                         "t = makeT(0)", "v = t.m()",
1278                 }},
1279                 // test case for go.dev/issue/10709: same as test before, but variable decls swapped
1280                 {`package p14
1281
1282                 var (
1283                     t = makeT(0)
1284                     v = t.m()
1285                 )
1286
1287                 type T struct{}
1288
1289                 func (T) m() int { return 0 }
1290
1291                 func makeT(n int) T {
1292                     if n > 0 {
1293                         return makeT(n-1)
1294                     }
1295                     return T{}
1296                 }`, []string{
1297                         "t = makeT(0)", "v = t.m()",
1298                 }},
1299                 // another candidate possibly causing problems with go.dev/issue/10709
1300                 {`package p15
1301
1302                 var y1 = f1()
1303
1304                 func f1() int { return g1() }
1305                 func g1() int { f1(); return x1 }
1306
1307                 var x1 = 0
1308
1309                 var y2 = f2()
1310
1311                 func f2() int { return g2() }
1312                 func g2() int { return x2 }
1313
1314                 var x2 = 0`, []string{
1315                         "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1316                 }},
1317         }
1318
1319         for _, test := range tests {
1320                 info := Info{}
1321                 name := mustTypecheck(test.src, nil, &info).Name()
1322
1323                 // number of initializers must match
1324                 if len(info.InitOrder) != len(test.inits) {
1325                         t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1326                         continue
1327                 }
1328
1329                 // initializers must match
1330                 for i, want := range test.inits {
1331                         got := info.InitOrder[i].String()
1332                         if got != want {
1333                                 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1334                                 continue
1335                         }
1336                 }
1337         }
1338 }
1339
1340 func TestMultiFileInitOrder(t *testing.T) {
1341         fset := token.NewFileSet()
1342         fileA := mustParse(fset, `package main; var a = 1`)
1343         fileB := mustParse(fset, `package main; var b = 2`)
1344
1345         // The initialization order must not depend on the parse
1346         // order of the files, only on the presentation order to
1347         // the type-checker.
1348         for _, test := range []struct {
1349                 files []*ast.File
1350                 want  string
1351         }{
1352                 {[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
1353                 {[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
1354         } {
1355                 var info Info
1356                 if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
1357                         t.Fatal(err)
1358                 }
1359                 if got := fmt.Sprint(info.InitOrder); got != test.want {
1360                         t.Fatalf("got %s; want %s", got, test.want)
1361                 }
1362         }
1363 }
1364
1365 func TestFiles(t *testing.T) {
1366         var sources = []string{
1367                 "package p; type T struct{}; func (T) m1() {}",
1368                 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1369                 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1370                 "package p",
1371         }
1372
1373         var conf Config
1374         fset := token.NewFileSet()
1375         pkg := NewPackage("p", "p")
1376         var info Info
1377         check := NewChecker(&conf, fset, pkg, &info)
1378
1379         for _, src := range sources {
1380                 if err := check.Files([]*ast.File{mustParse(fset, src)}); err != nil {
1381                         t.Error(err)
1382                 }
1383         }
1384
1385         // check InitOrder is [x y]
1386         var vars []string
1387         for _, init := range info.InitOrder {
1388                 for _, v := range init.Lhs {
1389                         vars = append(vars, v.Name())
1390                 }
1391         }
1392         if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1393                 t.Errorf("InitOrder == %s, want %s", got, want)
1394         }
1395 }
1396
1397 type testImporter map[string]*Package
1398
1399 func (m testImporter) Import(path string) (*Package, error) {
1400         if pkg := m[path]; pkg != nil {
1401                 return pkg, nil
1402         }
1403         return nil, fmt.Errorf("package %q not found", path)
1404 }
1405
1406 func TestSelection(t *testing.T) {
1407         selections := make(map[*ast.SelectorExpr]*Selection)
1408
1409         // We need a specific fileset in this test below for positions.
1410         // Cannot use typecheck helper.
1411         fset := token.NewFileSet()
1412         imports := make(testImporter)
1413         conf := Config{Importer: imports}
1414         makePkg := func(path, src string) {
1415                 pkg, err := conf.Check(path, fset, []*ast.File{mustParse(fset, src)}, &Info{Selections: selections})
1416                 if err != nil {
1417                         t.Fatal(err)
1418                 }
1419                 imports[path] = pkg
1420         }
1421
1422         const libSrc = `
1423 package lib
1424 type T float64
1425 const C T = 3
1426 var V T
1427 func F() {}
1428 func (T) M() {}
1429 `
1430         const mainSrc = `
1431 package main
1432 import "lib"
1433
1434 type A struct {
1435         *B
1436         C
1437 }
1438
1439 type B struct {
1440         b int
1441 }
1442
1443 func (B) f(int)
1444
1445 type C struct {
1446         c int
1447 }
1448
1449 type G[P any] struct {
1450         p P
1451 }
1452
1453 func (G[P]) m(P) {}
1454
1455 var Inst G[int]
1456
1457 func (C) g()
1458 func (*C) h()
1459
1460 func main() {
1461         // qualified identifiers
1462         var _ lib.T
1463         _ = lib.C
1464         _ = lib.F
1465         _ = lib.V
1466         _ = lib.T.M
1467
1468         // fields
1469         _ = A{}.B
1470         _ = new(A).B
1471
1472         _ = A{}.C
1473         _ = new(A).C
1474
1475         _ = A{}.b
1476         _ = new(A).b
1477
1478         _ = A{}.c
1479         _ = new(A).c
1480
1481         _ = Inst.p
1482         _ = G[string]{}.p
1483
1484         // methods
1485         _ = A{}.f
1486         _ = new(A).f
1487         _ = A{}.g
1488         _ = new(A).g
1489         _ = new(A).h
1490
1491         _ = B{}.f
1492         _ = new(B).f
1493
1494         _ = C{}.g
1495         _ = new(C).g
1496         _ = new(C).h
1497         _ = Inst.m
1498
1499         // method expressions
1500         _ = A.f
1501         _ = (*A).f
1502         _ = B.f
1503         _ = (*B).f
1504         _ = G[string].m
1505 }`
1506
1507         wantOut := map[string][2]string{
1508                 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1509
1510                 "A{}.B":    {"field (main.A) B *main.B", ".[0]"},
1511                 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1512                 "A{}.C":    {"field (main.A) C main.C", ".[1]"},
1513                 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1514                 "A{}.b":    {"field (main.A) b int", "->[0 0]"},
1515                 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1516                 "A{}.c":    {"field (main.A) c int", ".[1 0]"},
1517                 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1518                 "Inst.p":   {"field (main.G[int]) p int", ".[0]"},
1519
1520                 "A{}.f":    {"method (main.A) f(int)", "->[0 0]"},
1521                 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1522                 "A{}.g":    {"method (main.A) g()", ".[1 0]"},
1523                 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1524                 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1525                 "B{}.f":    {"method (main.B) f(int)", ".[0]"},
1526                 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1527                 "C{}.g":    {"method (main.C) g()", ".[0]"},
1528                 "new(C).g": {"method (*main.C) g()", "->[0]"},
1529                 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1530                 "Inst.m":   {"method (main.G[int]) m(int)", ".[0]"},
1531
1532                 "A.f":           {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1533                 "(*A).f":        {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1534                 "B.f":           {"method expr (main.B) f(main.B, int)", ".[0]"},
1535                 "(*B).f":        {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1536                 "G[string].m":   {"method expr (main.G[string]) m(main.G[string], string)", ".[0]"},
1537                 "G[string]{}.p": {"field (main.G[string]) p string", ".[0]"},
1538         }
1539
1540         makePkg("lib", libSrc)
1541         makePkg("main", mainSrc)
1542
1543         for e, sel := range selections {
1544                 _ = sel.String() // assertion: must not panic
1545
1546                 start := fset.Position(e.Pos()).Offset
1547                 end := fset.Position(e.End()).Offset
1548                 syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1549
1550                 direct := "."
1551                 if sel.Indirect() {
1552                         direct = "->"
1553                 }
1554                 got := [2]string{
1555                         sel.String(),
1556                         fmt.Sprintf("%s%v", direct, sel.Index()),
1557                 }
1558                 want := wantOut[syntax]
1559                 if want != got {
1560                         t.Errorf("%s: got %q; want %q", syntax, got, want)
1561                 }
1562                 delete(wantOut, syntax)
1563
1564                 // We must explicitly assert properties of the
1565                 // Signature's receiver since it doesn't participate
1566                 // in Identical() or String().
1567                 sig, _ := sel.Type().(*Signature)
1568                 if sel.Kind() == MethodVal {
1569                         got := sig.Recv().Type()
1570                         want := sel.Recv()
1571                         if !Identical(got, want) {
1572                                 t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
1573                         }
1574                 } else if sig != nil && sig.Recv() != nil {
1575                         t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1576                 }
1577         }
1578         // Assert that all wantOut entries were used exactly once.
1579         for syntax := range wantOut {
1580                 t.Errorf("no ast.Selection found with syntax %q", syntax)
1581         }
1582 }
1583
1584 func TestIssue8518(t *testing.T) {
1585         fset := token.NewFileSet()
1586         imports := make(testImporter)
1587         conf := Config{
1588                 Error:    func(err error) { t.Log(err) }, // don't exit after first error
1589                 Importer: imports,
1590         }
1591         makePkg := func(path, src string) {
1592                 imports[path], _ = conf.Check(path, fset, []*ast.File{mustParse(fset, src)}, nil) // errors logged via conf.Error
1593         }
1594
1595         const libSrc = `
1596 package a
1597 import "missing"
1598 const C1 = foo
1599 const C2 = missing.C
1600 `
1601
1602         const mainSrc = `
1603 package main
1604 import "a"
1605 var _ = a.C1
1606 var _ = a.C2
1607 `
1608
1609         makePkg("a", libSrc)
1610         makePkg("main", mainSrc) // don't crash when type-checking this package
1611 }
1612
1613 func TestIssue59603(t *testing.T) {
1614         fset := token.NewFileSet()
1615         imports := make(testImporter)
1616         conf := Config{
1617                 Error:    func(err error) { t.Log(err) }, // don't exit after first error
1618                 Importer: imports,
1619         }
1620         makePkg := func(path, src string) {
1621                 imports[path], _ = conf.Check(path, fset, []*ast.File{mustParse(fset, src)}, nil) // errors logged via conf.Error
1622         }
1623
1624         const libSrc = `
1625 package a
1626 const C = foo
1627 `
1628
1629         const mainSrc = `
1630 package main
1631 import "a"
1632 const _ = a.C
1633 `
1634
1635         makePkg("a", libSrc)
1636         makePkg("main", mainSrc) // don't crash when type-checking this package
1637 }
1638
1639 func TestLookupFieldOrMethodOnNil(t *testing.T) {
1640         // LookupFieldOrMethod on a nil type is expected to produce a run-time panic.
1641         defer func() {
1642                 const want = "LookupFieldOrMethod on nil type"
1643                 p := recover()
1644                 if s, ok := p.(string); !ok || s != want {
1645                         t.Fatalf("got %v, want %s", p, want)
1646                 }
1647         }()
1648         LookupFieldOrMethod(nil, false, nil, "")
1649 }
1650
1651 func TestLookupFieldOrMethod(t *testing.T) {
1652         // Test cases assume a lookup of the form a.f or x.f, where a stands for an
1653         // addressable value, and x for a non-addressable value (even though a variable
1654         // for ease of test case writing).
1655         //
1656         // Should be kept in sync with TestMethodSet.
1657         var tests = []struct {
1658                 src      string
1659                 found    bool
1660                 index    []int
1661                 indirect bool
1662         }{
1663                 // field lookups
1664                 {"var x T; type T struct{}", false, nil, false},
1665                 {"var x T; type T struct{ f int }", true, []int{0}, false},
1666                 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1667
1668                 // field lookups on a generic type
1669                 {"var x T[int]; type T[P any] struct{}", false, nil, false},
1670                 {"var x T[int]; type T[P any] struct{ f P }", true, []int{0}, false},
1671                 {"var x T[int]; type T[P any] struct{ a, b, f, c P }", true, []int{2}, false},
1672
1673                 // method lookups
1674                 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1675                 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1676                 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1677                 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1678
1679                 // method lookups on a generic type
1680                 {"var a T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, false},
1681                 {"var a *T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, true},
1682                 {"var a T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, false},
1683                 {"var a *T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1684
1685                 // collisions
1686                 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1687                 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1688
1689                 // collisions on a generic type
1690                 {"type ( E1[P any] struct{ f P }; E2[P any] struct{ f P }; x struct{ E1[int]; *E2[int] })", false, []int{1, 0}, false},
1691                 {"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},
1692
1693                 // outside methodset
1694                 // (*T).f method exists, but value of type T is not addressable
1695                 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1696
1697                 // outside method set of a generic type
1698                 {"var x T[int]; type T[P any] struct{}; func (*T[P]) f() {}", false, nil, true},
1699
1700                 // recursive generic types; see go.dev/issue/52715
1701                 {"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},
1702                 {"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},
1703         }
1704
1705         for _, test := range tests {
1706                 pkg := mustTypecheck("package p;"+test.src, nil, nil)
1707
1708                 obj := pkg.Scope().Lookup("a")
1709                 if obj == nil {
1710                         if obj = pkg.Scope().Lookup("x"); obj == nil {
1711                                 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1712                                 continue
1713                         }
1714                 }
1715
1716                 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1717                 if (f != nil) != test.found {
1718                         if f == nil {
1719                                 t.Errorf("%s: got no object; want one", test.src)
1720                         } else {
1721                                 t.Errorf("%s: got object = %v; want none", test.src, f)
1722                         }
1723                 }
1724                 if !sameSlice(index, test.index) {
1725                         t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1726                 }
1727                 if indirect != test.indirect {
1728                         t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1729                 }
1730         }
1731 }
1732
1733 // Test for go.dev/issue/52715
1734 func TestLookupFieldOrMethod_RecursiveGeneric(t *testing.T) {
1735         const src = `
1736 package pkg
1737
1738 type Tree[T any] struct {
1739         *Node[T]
1740 }
1741
1742 func (*Tree[R]) N(r R) R { return r }
1743
1744 type Node[T any] struct {
1745         *Tree[T]
1746 }
1747
1748 type Instance = *Tree[int]
1749 `
1750
1751         fset := token.NewFileSet()
1752         f := mustParse(fset, src)
1753         pkg := NewPackage("pkg", f.Name.Name)
1754         if err := NewChecker(nil, fset, pkg, nil).Files([]*ast.File{f}); err != nil {
1755                 panic(err)
1756         }
1757
1758         T := pkg.Scope().Lookup("Instance").Type()
1759         _, _, _ = LookupFieldOrMethod(T, false, pkg, "M") // verify that LookupFieldOrMethod terminates
1760 }
1761
1762 func sameSlice(a, b []int) bool {
1763         if len(a) != len(b) {
1764                 return false
1765         }
1766         for i, x := range a {
1767                 if x != b[i] {
1768                         return false
1769                 }
1770         }
1771         return true
1772 }
1773
1774 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1775 // the correct result at various positions with the source.
1776 func TestScopeLookupParent(t *testing.T) {
1777         fset := token.NewFileSet()
1778         imports := make(testImporter)
1779         conf := Config{Importer: imports}
1780         var info Info
1781         makePkg := func(path string, files ...*ast.File) {
1782                 var err error
1783                 imports[path], err = conf.Check(path, fset, files, &info)
1784                 if err != nil {
1785                         t.Fatal(err)
1786                 }
1787         }
1788
1789         makePkg("lib", mustParse(fset, "package lib; var X int"))
1790         // Each /*name=kind:line*/ comment makes the test look up the
1791         // name at that point and checks that it resolves to a decl of
1792         // the specified kind and line number.  "undef" means undefined.
1793         mainSrc := `
1794 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1795 package main
1796
1797 import "lib"
1798 import . "lib"
1799
1800 const Pi = 3.1415
1801 type T struct{}
1802 var Y, _ = lib.X, X
1803
1804 func F(){
1805         const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1806         type /*t=undef*/ t /*t=typename:14*/ *t
1807         print(Y) /*Y=var:10*/
1808         x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1809         var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1810
1811         var a []int
1812         for i, x := range a /*i=undef*/ /*x=var:16*/ { _ = i; _ = x }
1813
1814         var i interface{}
1815         switch y := i.(type) { /*y=undef*/
1816         case /*y=undef*/ int /*y=var:23*/ :
1817         case float32, /*y=undef*/ float64 /*y=var:23*/ :
1818         default /*y=var:23*/:
1819                 println(y)
1820         }
1821         /*y=undef*/
1822
1823         switch int := i.(type) {
1824         case /*int=typename:0*/ int /*int=var:31*/ :
1825                 println(int)
1826         default /*int=var:31*/ :
1827         }
1828 }
1829 /*main=undef*/
1830 `
1831
1832         info.Uses = make(map[*ast.Ident]Object)
1833         f := mustParse(fset, mainSrc)
1834         makePkg("main", f)
1835         mainScope := imports["main"].Scope()
1836         rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1837         for _, group := range f.Comments {
1838                 for _, comment := range group.List {
1839                         // Parse the assertion in the comment.
1840                         m := rx.FindStringSubmatch(comment.Text)
1841                         if m == nil {
1842                                 t.Errorf("%s: bad comment: %s",
1843                                         fset.Position(comment.Pos()), comment.Text)
1844                                 continue
1845                         }
1846                         name, want := m[1], m[2]
1847
1848                         // Look up the name in the innermost enclosing scope.
1849                         inner := mainScope.Innermost(comment.Pos())
1850                         if inner == nil {
1851                                 t.Errorf("%s: at %s: can't find innermost scope",
1852                                         fset.Position(comment.Pos()), comment.Text)
1853                                 continue
1854                         }
1855                         got := "undef"
1856                         if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil {
1857                                 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
1858                                 got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line)
1859                         }
1860                         if got != want {
1861                                 t.Errorf("%s: at %s: %s resolved to %s, want %s",
1862                                         fset.Position(comment.Pos()), comment.Text, name, got, want)
1863                         }
1864                 }
1865         }
1866
1867         // Check that for each referring identifier,
1868         // a lookup of its name on the innermost
1869         // enclosing scope returns the correct object.
1870
1871         for id, wantObj := range info.Uses {
1872                 inner := mainScope.Innermost(id.Pos())
1873                 if inner == nil {
1874                         t.Errorf("%s: can't find innermost scope enclosing %q",
1875                                 fset.Position(id.Pos()), id.Name)
1876                         continue
1877                 }
1878
1879                 // Exclude selectors and qualified identifiers---lexical
1880                 // refs only.  (Ideally, we'd see if the AST parent is a
1881                 // SelectorExpr, but that requires PathEnclosingInterval
1882                 // from golang.org/x/tools/go/ast/astutil.)
1883                 if id.Name == "X" {
1884                         continue
1885                 }
1886
1887                 _, gotObj := inner.LookupParent(id.Name, id.Pos())
1888                 if gotObj != wantObj {
1889                         t.Errorf("%s: got %v, want %v",
1890                                 fset.Position(id.Pos()), gotObj, wantObj)
1891                         continue
1892                 }
1893         }
1894 }
1895
1896 // newDefined creates a new defined type named T with the given underlying type.
1897 // Helper function for use with TestIncompleteInterfaces only.
1898 func newDefined(underlying Type) *Named {
1899         tname := NewTypeName(nopos, nil, "T", nil)
1900         return NewNamed(tname, underlying, nil)
1901 }
1902
1903 func TestConvertibleTo(t *testing.T) {
1904         for _, test := range []struct {
1905                 v, t Type
1906                 want bool
1907         }{
1908                 {Typ[Int], Typ[Int], true},
1909                 {Typ[Int], Typ[Float32], true},
1910                 {Typ[Int], Typ[String], true},
1911                 {newDefined(Typ[Int]), Typ[Int], true},
1912                 {newDefined(new(Struct)), new(Struct), true},
1913                 {newDefined(Typ[Int]), new(Struct), false},
1914                 {Typ[UntypedInt], Typ[Int], true},
1915                 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), true},
1916                 {NewSlice(Typ[Int]), NewArray(Typ[Uint], 10), false},
1917                 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
1918                 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
1919                 // Untyped string values are not permitted by the spec, so the behavior below is undefined.
1920                 {Typ[UntypedString], Typ[String], true},
1921         } {
1922                 if got := ConvertibleTo(test.v, test.t); got != test.want {
1923                         t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1924                 }
1925         }
1926 }
1927
1928 func TestAssignableTo(t *testing.T) {
1929         for _, test := range []struct {
1930                 v, t Type
1931                 want bool
1932         }{
1933                 {Typ[Int], Typ[Int], true},
1934                 {Typ[Int], Typ[Float32], false},
1935                 {newDefined(Typ[Int]), Typ[Int], false},
1936                 {newDefined(new(Struct)), new(Struct), true},
1937                 {Typ[UntypedBool], Typ[Bool], true},
1938                 {Typ[UntypedString], Typ[Bool], false},
1939                 // Neither untyped string nor untyped numeric assignments arise during
1940                 // normal type checking, so the below behavior is technically undefined by
1941                 // the spec.
1942                 {Typ[UntypedString], Typ[String], true},
1943                 {Typ[UntypedInt], Typ[Int], true},
1944         } {
1945                 if got := AssignableTo(test.v, test.t); got != test.want {
1946                         t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1947                 }
1948         }
1949 }
1950
1951 func TestIdentical(t *testing.T) {
1952         // For each test, we compare the types of objects X and Y in the source.
1953         tests := []struct {
1954                 src  string
1955                 want bool
1956         }{
1957                 // Basic types.
1958                 {"var X int; var Y int", true},
1959                 {"var X int; var Y string", false},
1960
1961                 // TODO: add more tests for complex types.
1962
1963                 // Named types.
1964                 {"type X int; type Y int", false},
1965
1966                 // Aliases.
1967                 {"type X = int; type Y = int", true},
1968
1969                 // Functions.
1970                 {`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
1971                 {`func X() string { return "" }; func Y(int) string { return "" }`, false},
1972                 {`func X(int) string { return "" }; func Y(int) {}`, false},
1973
1974                 // Generic functions. Type parameters should be considered identical modulo
1975                 // renaming. See also go.dev/issue/49722.
1976                 {`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
1977                 {`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
1978                 {`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
1979                 {`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
1980                 {`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
1981                 {`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
1982         }
1983
1984         for _, test := range tests {
1985                 pkg := mustTypecheck("package p;"+test.src, nil, nil)
1986                 X := pkg.Scope().Lookup("X")
1987                 Y := pkg.Scope().Lookup("Y")
1988                 if X == nil || Y == nil {
1989                         t.Fatal("test must declare both X and Y")
1990                 }
1991                 if got := Identical(X.Type(), Y.Type()); got != test.want {
1992                         t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
1993                 }
1994         }
1995 }
1996
1997 func TestIdentical_issue15173(t *testing.T) {
1998         // Identical should allow nil arguments and be symmetric.
1999         for _, test := range []struct {
2000                 x, y Type
2001                 want bool
2002         }{
2003                 {Typ[Int], Typ[Int], true},
2004                 {Typ[Int], nil, false},
2005                 {nil, Typ[Int], false},
2006                 {nil, nil, true},
2007         } {
2008                 if got := Identical(test.x, test.y); got != test.want {
2009                         t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2010                 }
2011         }
2012 }
2013
2014 func TestIdenticalUnions(t *testing.T) {
2015         tname := NewTypeName(nopos, nil, "myInt", nil)
2016         myInt := NewNamed(tname, Typ[Int], nil)
2017         tmap := map[string]*Term{
2018                 "int":     NewTerm(false, Typ[Int]),
2019                 "~int":    NewTerm(true, Typ[Int]),
2020                 "string":  NewTerm(false, Typ[String]),
2021                 "~string": NewTerm(true, Typ[String]),
2022                 "myInt":   NewTerm(false, myInt),
2023         }
2024         makeUnion := func(s string) *Union {
2025                 parts := strings.Split(s, "|")
2026                 var terms []*Term
2027                 for _, p := range parts {
2028                         term := tmap[p]
2029                         if term == nil {
2030                                 t.Fatalf("missing term %q", p)
2031                         }
2032                         terms = append(terms, term)
2033                 }
2034                 return NewUnion(terms)
2035         }
2036         for _, test := range []struct {
2037                 x, y string
2038                 want bool
2039         }{
2040                 // These tests are just sanity checks. The tests for type sets and
2041                 // interfaces provide much more test coverage.
2042                 {"int|~int", "~int", true},
2043                 {"myInt|~int", "~int", true},
2044                 {"int|string", "string|int", true},
2045                 {"int|int|string", "string|int", true},
2046                 {"myInt|string", "int|string", false},
2047         } {
2048                 x := makeUnion(test.x)
2049                 y := makeUnion(test.y)
2050                 if got := Identical(x, y); got != test.want {
2051                         t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2052                 }
2053         }
2054 }
2055
2056 func TestIssue15305(t *testing.T) {
2057         const src = "package p; func f() int16; var _ = f(undef)"
2058         fset := token.NewFileSet()
2059         f := mustParse(fset, src)
2060         conf := Config{
2061                 Error: func(err error) {}, // allow errors
2062         }
2063         info := &Info{
2064                 Types: make(map[ast.Expr]TypeAndValue),
2065         }
2066         conf.Check("p", fset, []*ast.File{f}, info) // ignore result
2067         for e, tv := range info.Types {
2068                 if _, ok := e.(*ast.CallExpr); ok {
2069                         if tv.Type != Typ[Int16] {
2070                                 t.Errorf("CallExpr has type %v, want int16", tv.Type)
2071                         }
2072                         return
2073                 }
2074         }
2075         t.Errorf("CallExpr has no type")
2076 }
2077
2078 // TestCompositeLitTypes verifies that Info.Types registers the correct
2079 // types for composite literal expressions and composite literal type
2080 // expressions.
2081 func TestCompositeLitTypes(t *testing.T) {
2082         for i, test := range []struct {
2083                 lit, typ string
2084         }{
2085                 {`[16]byte{}`, `[16]byte`},
2086                 {`[...]byte{}`, `[0]byte`},                // test for go.dev/issue/14092
2087                 {`[...]int{1, 2, 3}`, `[3]int`},           // test for go.dev/issue/14092
2088                 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for go.dev/issue/14092
2089                 {`[]int{}`, `[]int`},
2090                 {`map[string]bool{"foo": true}`, `map[string]bool`},
2091                 {`struct{}{}`, `struct{}`},
2092                 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
2093         } {
2094                 fset := token.NewFileSet()
2095                 f := mustParse(fset, fmt.Sprintf("package p%d; var _ = %s", i, test.lit))
2096                 types := make(map[ast.Expr]TypeAndValue)
2097                 if _, err := new(Config).Check("p", fset, []*ast.File{f}, &Info{Types: types}); err != nil {
2098                         t.Fatalf("%s: %v", test.lit, err)
2099                 }
2100
2101                 cmptype := func(x ast.Expr, want string) {
2102                         tv, ok := types[x]
2103                         if !ok {
2104                                 t.Errorf("%s: no Types entry found", test.lit)
2105                                 return
2106                         }
2107                         if tv.Type == nil {
2108                                 t.Errorf("%s: type is nil", test.lit)
2109                                 return
2110                         }
2111                         if got := tv.Type.String(); got != want {
2112                                 t.Errorf("%s: got %v, want %s", test.lit, got, want)
2113                         }
2114                 }
2115
2116                 // test type of composite literal expression
2117                 rhs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0]
2118                 cmptype(rhs, test.typ)
2119
2120                 // test type of composite literal type expression
2121                 cmptype(rhs.(*ast.CompositeLit).Type, test.typ)
2122         }
2123 }
2124
2125 // TestObjectParents verifies that objects have parent scopes or not
2126 // as specified by the Object interface.
2127 func TestObjectParents(t *testing.T) {
2128         const src = `
2129 package p
2130
2131 const C = 0
2132
2133 type T1 struct {
2134         a, b int
2135         T2
2136 }
2137
2138 type T2 interface {
2139         im1()
2140         im2()
2141 }
2142
2143 func (T1) m1() {}
2144 func (*T1) m2() {}
2145
2146 func f(x int) { y := x; print(y) }
2147 `
2148
2149         fset := token.NewFileSet()
2150         f := mustParse(fset, src)
2151
2152         info := &Info{
2153                 Defs: make(map[*ast.Ident]Object),
2154         }
2155         if _, err := new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
2156                 t.Fatal(err)
2157         }
2158
2159         for ident, obj := range info.Defs {
2160                 if obj == nil {
2161                         // only package names and implicit vars have a nil object
2162                         // (in this test we only need to handle the package name)
2163                         if ident.Name != "p" {
2164                                 t.Errorf("%v has nil object", ident)
2165                         }
2166                         continue
2167                 }
2168
2169                 // struct fields, type-associated and interface methods
2170                 // have no parent scope
2171                 wantParent := true
2172                 switch obj := obj.(type) {
2173                 case *Var:
2174                         if obj.IsField() {
2175                                 wantParent = false
2176                         }
2177                 case *Func:
2178                         if obj.Type().(*Signature).Recv() != nil { // method
2179                                 wantParent = false
2180                         }
2181                 }
2182
2183                 gotParent := obj.Parent() != nil
2184                 switch {
2185                 case gotParent && !wantParent:
2186                         t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
2187                 case !gotParent && wantParent:
2188                         t.Errorf("%v: no parent found", ident)
2189                 }
2190         }
2191 }
2192
2193 // TestFailedImport tests that we don't get follow-on errors
2194 // elsewhere in a package due to failing to import a package.
2195 func TestFailedImport(t *testing.T) {
2196         testenv.MustHaveGoBuild(t)
2197
2198         const src = `
2199 package p
2200
2201 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
2202
2203 const c = foo.C
2204 type T = foo.T
2205 var v T = c
2206 func f(x T) T { return foo.F(x) }
2207 `
2208         fset := token.NewFileSet()
2209         f := mustParse(fset, src)
2210         files := []*ast.File{f}
2211
2212         // type-check using all possible importers
2213         for _, compiler := range []string{"gc", "gccgo", "source"} {
2214                 errcount := 0
2215                 conf := Config{
2216                         Error: func(err error) {
2217                                 // we should only see the import error
2218                                 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
2219                                         t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
2220                                 }
2221                                 errcount++
2222                         },
2223                         Importer: importer.For(compiler, nil),
2224                 }
2225
2226                 info := &Info{
2227                         Uses: make(map[*ast.Ident]Object),
2228                 }
2229                 pkg, _ := conf.Check("p", fset, files, info)
2230                 if pkg == nil {
2231                         t.Errorf("for %s importer, type-checking failed to return a package", compiler)
2232                         continue
2233                 }
2234
2235                 imports := pkg.Imports()
2236                 if len(imports) != 1 {
2237                         t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
2238                         continue
2239                 }
2240                 imp := imports[0]
2241                 if imp.Name() != "foo" {
2242                         t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
2243                         continue
2244                 }
2245
2246                 // verify that all uses of foo refer to the imported package foo (imp)
2247                 for ident, obj := range info.Uses {
2248                         if ident.Name == "foo" {
2249                                 if obj, ok := obj.(*PkgName); ok {
2250                                         if obj.Imported() != imp {
2251                                                 t.Errorf("%s resolved to %v; want %v", ident, obj.Imported(), imp)
2252                                         }
2253                                 } else {
2254                                         t.Errorf("%s resolved to %v; want package name", ident, obj)
2255                                 }
2256                         }
2257                 }
2258         }
2259 }
2260
2261 func TestInstantiate(t *testing.T) {
2262         // eventually we like more tests but this is a start
2263         const src = "package p; type T[P any] *T[P]"
2264         pkg := mustTypecheck(src, nil, nil)
2265
2266         // type T should have one type parameter
2267         T := pkg.Scope().Lookup("T").Type().(*Named)
2268         if n := T.TypeParams().Len(); n != 1 {
2269                 t.Fatalf("expected 1 type parameter; found %d", n)
2270         }
2271
2272         // instantiation should succeed (no endless recursion)
2273         // even with a nil *Checker
2274         res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
2275         if err != nil {
2276                 t.Fatal(err)
2277         }
2278
2279         // instantiated type should point to itself
2280         if p := res.Underlying().(*Pointer).Elem(); p != res {
2281                 t.Fatalf("unexpected result type: %s points to %s", res, p)
2282         }
2283 }
2284
2285 func TestInstantiateErrors(t *testing.T) {
2286         tests := []struct {
2287                 src    string // by convention, T must be the type being instantiated
2288                 targs  []Type
2289                 wantAt int // -1 indicates no error
2290         }{
2291                 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
2292                 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
2293                 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
2294                 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
2295         }
2296
2297         for _, test := range tests {
2298                 src := "package p; " + test.src
2299                 pkg := mustTypecheck(src, nil, nil)
2300
2301                 T := pkg.Scope().Lookup("T").Type().(*Named)
2302
2303                 _, err := Instantiate(nil, T, test.targs, true)
2304                 if err == nil {
2305                         t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
2306                 }
2307
2308                 var argErr *ArgumentError
2309                 if !errors.As(err, &argErr) {
2310                         t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
2311                 }
2312
2313                 if argErr.Index != test.wantAt {
2314                         t.Errorf("Instantiate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2315                 }
2316         }
2317 }
2318
2319 func TestArgumentErrorUnwrapping(t *testing.T) {
2320         var err error = &ArgumentError{
2321                 Index: 1,
2322                 Err:   Error{Msg: "test"},
2323         }
2324         var e Error
2325         if !errors.As(err, &e) {
2326                 t.Fatalf("error %v does not wrap types.Error", err)
2327         }
2328         if e.Msg != "test" {
2329                 t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2330         }
2331 }
2332
2333 func TestInstanceIdentity(t *testing.T) {
2334         imports := make(testImporter)
2335         conf := Config{Importer: imports}
2336         makePkg := func(src string) {
2337                 fset := token.NewFileSet()
2338                 f := mustParse(fset, src)
2339                 name := f.Name.Name
2340                 pkg, err := conf.Check(name, fset, []*ast.File{f}, nil)
2341                 if err != nil {
2342                         t.Fatal(err)
2343                 }
2344                 imports[name] = pkg
2345         }
2346         makePkg(`package lib; type T[P any] struct{}`)
2347         makePkg(`package a; import "lib"; var A lib.T[int]`)
2348         makePkg(`package b; import "lib"; var B lib.T[int]`)
2349         a := imports["a"].Scope().Lookup("A")
2350         b := imports["b"].Scope().Lookup("B")
2351         if !Identical(a.Type(), b.Type()) {
2352                 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
2353         }
2354 }
2355
2356 // TestInstantiatedObjects verifies properties of instantiated objects.
2357 func TestInstantiatedObjects(t *testing.T) {
2358         const src = `
2359 package p
2360
2361 type T[P any] struct {
2362         field P
2363 }
2364
2365 func (recv *T[Q]) concreteMethod(mParam Q) (mResult Q) { return }
2366
2367 type FT[P any] func(ftParam P) (ftResult P)
2368
2369 func F[P any](fParam P) (fResult P){ return }
2370
2371 type I[P any] interface {
2372         interfaceMethod(P)
2373 }
2374
2375 type R[P any] T[P]
2376
2377 func (R[P]) m() {} // having a method triggers expansion of R
2378
2379 var (
2380         t T[int]
2381         ft FT[int]
2382         f = F[int]
2383         i I[int]
2384 )
2385
2386 func fn() {
2387         var r R[int]
2388         _ = r
2389 }
2390 `
2391         info := &Info{
2392                 Defs: make(map[*ast.Ident]Object),
2393         }
2394         fset := token.NewFileSet()
2395         f := mustParse(fset, src)
2396         conf := Config{}
2397         pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
2398         if err != nil {
2399                 t.Fatal(err)
2400         }
2401
2402         lookup := func(name string) Type { return pkg.Scope().Lookup(name).Type() }
2403         fnScope := pkg.Scope().Lookup("fn").(*Func).Scope()
2404
2405         tests := []struct {
2406                 name string
2407                 obj  Object
2408         }{
2409                 // Struct fields
2410                 {"field", lookup("t").Underlying().(*Struct).Field(0)},
2411                 {"field", fnScope.Lookup("r").Type().Underlying().(*Struct).Field(0)},
2412
2413                 // Methods and method fields
2414                 {"concreteMethod", lookup("t").(*Named).Method(0)},
2415                 {"recv", lookup("t").(*Named).Method(0).Type().(*Signature).Recv()},
2416                 {"mParam", lookup("t").(*Named).Method(0).Type().(*Signature).Params().At(0)},
2417                 {"mResult", lookup("t").(*Named).Method(0).Type().(*Signature).Results().At(0)},
2418
2419                 // Interface methods
2420                 {"interfaceMethod", lookup("i").Underlying().(*Interface).Method(0)},
2421
2422                 // Function type fields
2423                 {"ftParam", lookup("ft").Underlying().(*Signature).Params().At(0)},
2424                 {"ftResult", lookup("ft").Underlying().(*Signature).Results().At(0)},
2425
2426                 // Function fields
2427                 {"fParam", lookup("f").(*Signature).Params().At(0)},
2428                 {"fResult", lookup("f").(*Signature).Results().At(0)},
2429         }
2430
2431         // Collect all identifiers by name.
2432         idents := make(map[string][]*ast.Ident)
2433         ast.Inspect(f, func(n ast.Node) bool {
2434                 if id, ok := n.(*ast.Ident); ok {
2435                         idents[id.Name] = append(idents[id.Name], id)
2436                 }
2437                 return true
2438         })
2439
2440         for _, test := range tests {
2441                 test := test
2442                 t.Run(test.name, func(t *testing.T) {
2443                         if got := len(idents[test.name]); got != 1 {
2444                                 t.Fatalf("found %d identifiers named %s, want 1", got, test.name)
2445                         }
2446                         ident := idents[test.name][0]
2447                         def := info.Defs[ident]
2448                         if def == test.obj {
2449                                 t.Fatalf("info.Defs[%s] contains the test object", test.name)
2450                         }
2451                         if orig := originObject(test.obj); def != orig {
2452                                 t.Errorf("info.Defs[%s] does not match obj.Origin()", test.name)
2453                         }
2454                         if def.Pkg() != test.obj.Pkg() {
2455                                 t.Errorf("Pkg() = %v, want %v", def.Pkg(), test.obj.Pkg())
2456                         }
2457                         if def.Name() != test.obj.Name() {
2458                                 t.Errorf("Name() = %v, want %v", def.Name(), test.obj.Name())
2459                         }
2460                         if def.Pos() != test.obj.Pos() {
2461                                 t.Errorf("Pos() = %v, want %v", def.Pos(), test.obj.Pos())
2462                         }
2463                         if def.Parent() != test.obj.Parent() {
2464                                 t.Fatalf("Parent() = %v, want %v", def.Parent(), test.obj.Parent())
2465                         }
2466                         if def.Exported() != test.obj.Exported() {
2467                                 t.Fatalf("Exported() = %v, want %v", def.Exported(), test.obj.Exported())
2468                         }
2469                         if def.Id() != test.obj.Id() {
2470                                 t.Fatalf("Id() = %v, want %v", def.Id(), test.obj.Id())
2471                         }
2472                         // String and Type are expected to differ.
2473                 })
2474         }
2475 }
2476
2477 func originObject(obj Object) Object {
2478         switch obj := obj.(type) {
2479         case *Var:
2480                 return obj.Origin()
2481         case *Func:
2482                 return obj.Origin()
2483         }
2484         return obj
2485 }
2486
2487 func TestImplements(t *testing.T) {
2488         const src = `
2489 package p
2490
2491 type EmptyIface interface{}
2492
2493 type I interface {
2494         m()
2495 }
2496
2497 type C interface {
2498         m()
2499         ~int
2500 }
2501
2502 type Integer interface{
2503         int8 | int16 | int32 | int64
2504 }
2505
2506 type EmptyTypeSet interface{
2507         Integer
2508         ~string
2509 }
2510
2511 type N1 int
2512 func (N1) m() {}
2513
2514 type N2 int
2515 func (*N2) m() {}
2516
2517 type N3 int
2518 func (N3) m(int) {}
2519
2520 type N4 string
2521 func (N4) m()
2522
2523 type Bad Bad // invalid type
2524 `
2525
2526         fset := token.NewFileSet()
2527         f := mustParse(fset, src)
2528         conf := Config{Error: func(error) {}}
2529         pkg, _ := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
2530
2531         lookup := func(tname string) Type { return pkg.Scope().Lookup(tname).Type() }
2532         var (
2533                 EmptyIface   = lookup("EmptyIface").Underlying().(*Interface)
2534                 I            = lookup("I").(*Named)
2535                 II           = I.Underlying().(*Interface)
2536                 C            = lookup("C").(*Named)
2537                 CI           = C.Underlying().(*Interface)
2538                 Integer      = lookup("Integer").Underlying().(*Interface)
2539                 EmptyTypeSet = lookup("EmptyTypeSet").Underlying().(*Interface)
2540                 N1           = lookup("N1")
2541                 N1p          = NewPointer(N1)
2542                 N2           = lookup("N2")
2543                 N2p          = NewPointer(N2)
2544                 N3           = lookup("N3")
2545                 N4           = lookup("N4")
2546                 Bad          = lookup("Bad")
2547         )
2548
2549         tests := []struct {
2550                 V    Type
2551                 T    *Interface
2552                 want bool
2553         }{
2554                 {I, II, true},
2555                 {I, CI, false},
2556                 {C, II, true},
2557                 {C, CI, true},
2558                 {Typ[Int8], Integer, true},
2559                 {Typ[Int64], Integer, true},
2560                 {Typ[String], Integer, false},
2561                 {EmptyTypeSet, II, true},
2562                 {EmptyTypeSet, EmptyTypeSet, true},
2563                 {Typ[Int], EmptyTypeSet, false},
2564                 {N1, II, true},
2565                 {N1, CI, true},
2566                 {N1p, II, true},
2567                 {N1p, CI, false},
2568                 {N2, II, false},
2569                 {N2, CI, false},
2570                 {N2p, II, true},
2571                 {N2p, CI, false},
2572                 {N3, II, false},
2573                 {N3, CI, false},
2574                 {N4, II, true},
2575                 {N4, CI, false},
2576                 {Bad, II, false},
2577                 {Bad, CI, false},
2578                 {Bad, EmptyIface, true},
2579         }
2580
2581         for _, test := range tests {
2582                 if got := Implements(test.V, test.T); got != test.want {
2583                         t.Errorf("Implements(%s, %s) = %t, want %t", test.V, test.T, got, test.want)
2584                 }
2585
2586                 // The type assertion x.(T) is valid if T is an interface or if T implements the type of x.
2587                 // The assertion is never valid if T is a bad type.
2588                 V := test.T
2589                 T := test.V
2590                 want := false
2591                 if _, ok := T.Underlying().(*Interface); (ok || Implements(T, V)) && T != Bad {
2592                         want = true
2593                 }
2594                 if got := AssertableTo(V, T); got != want {
2595                         t.Errorf("AssertableTo(%s, %s) = %t, want %t", V, T, got, want)
2596                 }
2597         }
2598 }
2599
2600 func TestMissingMethodAlternative(t *testing.T) {
2601         const src = `
2602 package p
2603 type T interface {
2604         m()
2605 }
2606
2607 type V0 struct{}
2608 func (V0) m() {}
2609
2610 type V1 struct{}
2611
2612 type V2 struct{}
2613 func (V2) m() int
2614
2615 type V3 struct{}
2616 func (*V3) m()
2617
2618 type V4 struct{}
2619 func (V4) M()
2620 `
2621
2622         pkg := mustTypecheck(src, nil, nil)
2623
2624         T := pkg.Scope().Lookup("T").Type().Underlying().(*Interface)
2625         lookup := func(name string) (*Func, bool) {
2626                 return MissingMethod(pkg.Scope().Lookup(name).Type(), T, true)
2627         }
2628
2629         // V0 has method m with correct signature. Should not report wrongType.
2630         method, wrongType := lookup("V0")
2631         if method != nil || wrongType {
2632                 t.Fatalf("V0: got method = %v, wrongType = %v", method, wrongType)
2633         }
2634
2635         checkMissingMethod := func(tname string, reportWrongType bool) {
2636                 method, wrongType := lookup(tname)
2637                 if method == nil || method.Name() != "m" || wrongType != reportWrongType {
2638                         t.Fatalf("%s: got method = %v, wrongType = %v", tname, method, wrongType)
2639                 }
2640         }
2641
2642         // V1 has no method m. Should not report wrongType.
2643         checkMissingMethod("V1", false)
2644
2645         // V2 has method m with wrong signature type (ignoring receiver). Should report wrongType.
2646         checkMissingMethod("V2", true)
2647
2648         // V3 has no method m but it exists on *V3. Should report wrongType.
2649         checkMissingMethod("V3", true)
2650
2651         // V4 has no method m but has M. Should not report wrongType.
2652         checkMissingMethod("V4", false)
2653 }