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