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