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