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