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