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