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