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