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