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