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