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