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