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