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