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