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.
23 func pkgFor(path, source string, info *Info) (*Package, error) {
24 fset := token.NewFileSet()
25 f, err := parser.ParseFile(fset, path, source, 0)
29 conf := Config{Importer: importer.Default()}
30 return conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
33 func mustTypecheck(t *testing.T, path, source string, info *Info) string {
34 pkg, err := pkgFor(path, source, info)
38 name = "package " + pkg.Name()
40 t.Fatalf("%s: didn't type-check (%s)", name, err)
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)
52 Error: func(err error) {},
53 Importer: importer.Default(),
55 pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
56 return pkg.Name(), err
59 func TestValuesInfo(t *testing.T) {
60 var tests = []struct {
62 expr string // constant expression
63 typ string // constant type
64 val string // constant value
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"`},
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"`},
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`},
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`},
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`},
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`},
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)`},
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`, ``},
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"`},
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)`},
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)`},
135 {`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // issue #22341
138 for _, test := range tests {
140 Types: make(map[ast.Expr]TypeAndValue),
142 name := mustTypecheck(t, "ValuesInfo", test.src, &info)
144 // look for expression
146 for e := range info.Types {
147 if ExprString(e) == test.expr {
153 t.Errorf("package %s: no expression found for %s", name, test.expr)
156 tv := info.Types[expr]
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)
164 // if we have a constant, check that value is correct
166 if got := tv.Value.ExactString(); got != test.val {
167 t.Errorf("package %s: got value %s; want %s", name, got, test.val)
171 t.Errorf("package %s: no constant found; want %s", name, test.val)
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_"
181 var tests = []struct {
183 expr string // expression
184 typ string // value type
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`},
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`},
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`},
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`},
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`},
226 // comma-ok expressions
227 {`package p0; var x interface{}; var _, _ = x.(int)`,
231 {`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
235 {`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
237 `(complex128, p2a.mybool)`,
239 {`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
241 `(complex128, bool)`,
243 {`package p3; var c chan string; var _, _ = <-c`,
249 {`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
253 {`package issue6796_b; var c chan string; var _, _ = (<-c)`,
257 {`package issue6796_c; var c chan string; var _, _ = (<-c)`,
261 {`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
265 {`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
271 {`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
275 {`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
279 {`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
283 {`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
287 {`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
291 {`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
297 {`package issue28277_a; func f(...int)`,
301 {`package issue28277_b; func f(a, b int, c ...[]struct{})`,
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`},
315 for _, test := range tests {
316 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
318 if strings.HasPrefix(test.src, broken) {
320 name, err = mayTypecheck(t, "TypesInfo", test.src, &info)
322 t.Errorf("package %s: expected to fail but passed", name)
326 name = mustTypecheck(t, "TypesInfo", test.src, &info)
329 // look for expression type
331 for e, tv := range info.Types {
332 if ExprString(e) == test.expr {
338 t.Errorf("package %s: no type found for %s", name, test.expr)
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)
349 func TestImplicitsInfo(t *testing.T) {
350 testenv.MustHaveGoBuild(t)
352 var tests = []struct {
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"},
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{}"},
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"},
371 for _, test := range tests {
373 Implicits: make(map[ast.Node]Object),
375 name := mustTypecheck(t, "ImplicitsInfo", test.src, &info)
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))
383 // extract Implicits entry, if any
385 for n, obj := range info.Implicits {
386 switch x := n.(type) {
387 case *ast.ImportSpec:
389 case *ast.CaseClause:
394 t.Fatalf("package %s: unexpected %T", name, x)
396 got += ": " + obj.String()
400 if got != test.want {
401 t.Errorf("package %s: got %q; want %q", name, got, test.want)
406 func predString(tv TypeAndValue) string {
408 pred := func(b bool, s string) {
411 buf.WriteString(", ")
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")
433 func TestPredicatesInfo(t *testing.T) {
434 testenv.MustHaveGoBuild(t)
436 var tests = []struct {
442 {`package n0; func f() { f() }`, `f()`, `void`},
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`},
452 {`package b0; var _ = len("")`, `len`, `builtin`},
453 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
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`},
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`},
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
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`},
484 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
485 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
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>`},
501 for _, test := range tests {
502 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
503 name := mustTypecheck(t, "PredicatesInfo", test.src, &info)
505 // look for expression predicates
507 for e, tv := range info.Types {
508 //println(name, ExprString(e))
509 if ExprString(e) == test.expr {
515 if got != test.pred {
516 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
521 func TestScopesInfo(t *testing.T) {
522 testenv.MustHaveGoBuild(t)
524 var tests = []struct {
526 scopes []string // list of scope descriptors of the form kind:varlist
528 {`package p0`, []string{
531 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
534 {`package p2; func _() {}`, []string{
537 {`package p3; func _(x, y int) {}`, []string{
540 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
541 "file:", "func:x y z", // redeclaration of x
543 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
544 "file:", "func:u x y",
546 {`package p6; func _() { { var x int; _ = x } }`, []string{
547 "file:", "func:", "block:x",
549 {`package p7; func _() { if true {} }`, []string{
550 "file:", "func:", "if:", "block:",
552 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
553 "file:", "func:", "if:x", "block:y",
555 {`package p9; func _() { switch x := 0; x {} }`, []string{
556 "file:", "func:", "switch:x",
558 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
559 "file:", "func:", "switch:x", "case:y", "case:",
561 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
562 "file:", "func:t", "type switch:",
564 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
565 "file:", "func:t", "type switch:t",
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
570 {`package p14; func _() { select{} }`, []string{
573 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
574 "file:", "func:c", "comm:",
576 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
577 "file:", "func:c", "comm:i x",
579 {`package p17; func _() { for{} }`, []string{
580 "file:", "func:", "for:", "block:",
582 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
583 "file:", "func:n", "for:i", "block:",
585 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
586 "file:", "func:a", "range:i", "block:",
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:",
593 for _, test := range tests {
594 info := Info{Scopes: make(map[ast.Node]*Scope)}
595 name := mustTypecheck(t, "ScopesInfo", test.src, &info)
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))
602 // scope descriptions must match
603 for node, scope := range info.Scopes {
604 kind := "<unknown node kind>"
614 case *ast.SwitchStmt:
616 case *ast.TypeSwitchStmt:
618 case *ast.CaseClause:
620 case *ast.CommClause:
628 // look for matching scope description
629 desc := kind + ":" + strings.Join(scope.Names(), " ")
631 for _, d := range test.scopes {
638 t.Errorf("package %s: no matching scope found for %s", name, desc)
644 func TestInitOrderInfo(t *testing.T) {
645 var tests = []struct {
649 {`package p0; var (x = 1; y = x)`, []string{
652 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
653 "a = 1", "b = 2", "c = 3",
655 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
656 "a = 1", "b = 2", "c = 3",
658 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
659 "_ = f()", // blank var
661 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
662 "a = 0", "z = 0", "y = z", "x = y",
664 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
665 "a, _ = m[0]", // blank var
667 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
668 "z = 0", "a, b = f()",
670 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
671 "b = 1", "a = (func() int literal)()",
673 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
674 "c = 1", "a, b = (func() (_, _ int) literal)()",
676 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
679 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
680 "a = 0", "b = 0", "c = 0", "d = c + b",
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",
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",
690 // test case from spec section on package initialization
704 "d = 3", "b = f()", "c = f()", "a = c + b",
706 // test case for issue 7131
710 func next() int { counter++; return counter }
713 func makeOrder() []int { return []int{f, b, d, e, c, a} }
716 var b, c = next(), next()
717 var d, e, f = next(), next(), next()
719 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
721 // test case for issue 10709
731 func (T) m() int { return 0 }
733 func makeT(n int) T {
739 "t = makeT(0)", "v = t.m()",
741 // test case for issue 10709: same as test before, but variable decls swapped
751 func (T) m() int { return 0 }
753 func makeT(n int) T {
759 "t = makeT(0)", "v = t.m()",
761 // another candidate possibly causing problems with issue 10709
766 func f1() int { return g1() }
767 func g1() int { f1(); return x1 }
773 func f2() int { return g2() }
774 func g2() int { return x2 }
776 var x2 = 0`, []string{
777 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
781 for _, test := range tests {
783 name := mustTypecheck(t, "InitOrderInfo", test.src, &info)
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))
791 // initializers must match
792 for i, want := range test.inits {
793 got := info.InitOrder[i].String()
795 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
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)
812 fileA := mustParse(`package main; var a = 1`)
813 fileB := mustParse(`package main; var b = 2`)
815 // The initialization order must not depend on the parse
816 // order of the files, only on the presentation order to
818 for _, test := range []struct {
822 {[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
823 {[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
826 if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
829 if got := fmt.Sprint(info.InitOrder); got != test.want {
830 t.Fatalf("got %s; want %s", got, test.want)
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{}",
844 fset := token.NewFileSet()
845 pkg := NewPackage("p", "p")
847 check := NewChecker(&conf, fset, pkg, &info)
849 for i, src := range sources {
850 filename := fmt.Sprintf("sources%d", i)
851 f, err := parser.ParseFile(fset, filename, src, 0)
855 if err := check.Files([]*ast.File{f}); err != nil {
860 // check InitOrder is [x y]
862 for _, init := range info.InitOrder {
863 for _, v := range init.Lhs {
864 vars = append(vars, v.Name())
867 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
868 t.Errorf("InitOrder == %s, want %s", got, want)
872 type testImporter map[string]*Package
874 func (m testImporter) Import(path string) (*Package, error) {
875 if pkg := m[path]; pkg != nil {
878 return nil, fmt.Errorf("package %q not found", path)
881 func TestSelection(t *testing.T) {
882 selections := make(map[*ast.SelectorExpr]*Selection)
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)
892 pkg, err := conf.Check(path, fset, []*ast.File{f}, &Info{Selections: selections})
930 // qualified identifiers
964 // method expressions
971 wantOut := map[string][2]string{
972 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
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]"},
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] ?
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]"},
1000 makePkg("lib", libSrc)
1001 makePkg("main", mainSrc)
1003 for e, sel := range selections {
1004 _ = sel.String() // assertion: must not panic
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)
1016 fmt.Sprintf("%s%v", direct, sel.Index()),
1018 want := wantOut[syntax]
1020 t.Errorf("%s: got %q; want %q", syntax, got, want)
1022 delete(wantOut, syntax)
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()
1031 if !Identical(got, want) {
1032 t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
1034 } else if sig != nil && sig.Recv() != nil {
1035 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
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)
1044 func TestIssue8518(t *testing.T) {
1045 fset := token.NewFileSet()
1046 imports := make(testImporter)
1048 Error: func(err error) { t.Log(err) }, // don't exit after first error
1051 makePkg := func(path, src string) {
1052 f, err := parser.ParseFile(fset, path, src, 0)
1056 pkg, _ := conf.Check(path, fset, []*ast.File{f}, nil) // errors logged via conf.Error
1064 const C2 = missing.C
1074 makePkg("a", libSrc)
1075 makePkg("main", mainSrc) // don't crash when type-checking this package
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 {
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},
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?
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},
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},
1108 for _, test := range tests {
1109 pkg, err := pkgFor("test", "package p;"+test.src, nil)
1111 t.Errorf("%s: incorrect test case: %s", test.src, err)
1115 obj := pkg.Scope().Lookup("a")
1117 if obj = pkg.Scope().Lookup("x"); obj == nil {
1118 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1123 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1124 if (f != nil) != test.found {
1126 t.Errorf("%s: got no object; want one", test.src)
1128 t.Errorf("%s: got object = %v; want none", test.src, f)
1131 if !sameSlice(index, test.index) {
1132 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1134 if indirect != test.indirect {
1135 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1140 func sameSlice(a, b []int) bool {
1141 if len(a) != len(b) {
1144 for i, x := range a {
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)
1166 makePkg := func(path string, files ...*ast.File) {
1168 imports[path], err = conf.Check(path, fset, files, &info)
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.
1179 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
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
1197 for i, x := range /*i=undef*/ /*x=var:16*/ a /*i=var:20*/ /*x=var:20*/ { _ = i; _ = x }
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*/:
1208 switch int := i.(type) {
1209 case /*int=typename:0*/ int /*int=var:31*/ :
1211 default /*int=var:31*/ :
1217 info.Uses = make(map[*ast.Ident]Object)
1218 f := mustParse(mainSrc)
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)
1227 t.Errorf("%s: bad comment: %s",
1228 fset.Position(comment.Pos()), comment.Text)
1231 name, want := m[1], m[2]
1233 // Look up the name in the innermost enclosing scope.
1234 inner := mainScope.Innermost(comment.Pos())
1236 t.Errorf("%s: at %s: can't find innermost scope",
1237 fset.Position(comment.Pos()), comment.Text)
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)
1246 t.Errorf("%s: at %s: %s resolved to %s, want %s",
1247 fset.Position(comment.Pos()), comment.Text, name, got, want)
1252 // Check that for each referring identifier,
1253 // a lookup of its name on the innermost
1254 // enclosing scope returns the correct object.
1256 for id, wantObj := range info.Uses {
1257 inner := mainScope.Innermost(id.Pos())
1259 t.Errorf("%s: can't find innermost scope enclosing %q",
1260 fset.Position(id.Pos()), id.Name)
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.)
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)
1281 func TestConvertibleTo(t *testing.T) {
1282 for _, test := range []struct {
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},
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)
1302 func TestAssignableTo(t *testing.T) {
1303 for _, test := range []struct {
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
1316 {Typ[UntypedString], Typ[String], true},
1317 {Typ[UntypedInt], Typ[Int], true},
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)
1325 func TestIdentical_issue15173(t *testing.T) {
1326 // Identical should allow nil arguments and be symmetric.
1327 for _, test := range []struct {
1331 {Typ[Int], Typ[Int], true},
1332 {Typ[Int], nil, false},
1333 {nil, Typ[Int], false},
1336 if got := Identical(test.x, test.y); got != test.want {
1337 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
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)
1350 Error: func(err error) {}, // allow errors
1353 Types: make(map[ast.Expr]TypeAndValue),
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)
1364 t.Errorf("CallExpr has no type")
1367 // TestCompositeLitTypes verifies that Info.Types registers the correct
1368 // types for composite literal expressions and composite literal type
1370 func TestCompositeLitTypes(t *testing.T) {
1371 for _, test := range []struct {
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}`},
1383 fset := token.NewFileSet()
1384 f, err := parser.ParseFile(fset, test.lit, "package p; var _ = "+test.lit, 0)
1386 t.Fatalf("%s: %v", test.lit, err)
1390 Types: make(map[ast.Expr]TypeAndValue),
1392 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
1393 t.Fatalf("%s: %v", test.lit, err)
1396 cmptype := func(x ast.Expr, want string) {
1397 tv, ok := info.Types[x]
1399 t.Errorf("%s: no Types entry found", test.lit)
1403 t.Errorf("%s: type is nil", test.lit)
1406 if got := tv.Type.String(); got != want {
1407 t.Errorf("%s: got %v, want %s", test.lit, got, want)
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)
1415 // test type of composite literal type expression
1416 cmptype(rhs.(*ast.CompositeLit).Type, test.typ)
1420 // TestObjectParents verifies that objects have parent scopes or not
1421 // as specified by the Object interface.
1422 func TestObjectParents(t *testing.T) {
1441 func f(x int) { y := x; print(y) }
1444 fset := token.NewFileSet()
1445 f, err := parser.ParseFile(fset, "src", src, 0)
1451 Defs: make(map[*ast.Ident]Object),
1453 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
1457 for ident, obj := range info.Defs {
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)
1467 // struct fields, type-associated and interface methods
1468 // have no parent scope
1470 switch obj := obj.(type) {
1476 if obj.Type().(*Signature).Recv() != nil { // method
1481 gotParent := obj.Parent() != nil
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)
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)
1499 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
1504 func f(x T) T { return foo.F(x) }
1506 fset := token.NewFileSet()
1507 f, err := parser.ParseFile(fset, "src", src, 0)
1511 files := []*ast.File{f}
1513 // type-check using all possible importers
1514 for _, compiler := range []string{"gc", "gccgo", "source"} {
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)
1524 Importer: importer.For(compiler, nil),
1528 Uses: make(map[*ast.Ident]Object),
1530 pkg, _ := conf.Check("p", fset, files, info)
1532 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
1536 imports := pkg.Imports()
1537 if len(imports) != 1 {
1538 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
1542 if imp.Name() != "foo" {
1543 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
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)
1555 t.Errorf("%s resolved to %v; want package name", ident, obj)