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