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.
13 "go/internal/typeparams"
25 // pkgFor parses and type checks the package specified by path and source,
26 // populating info if provided.
28 // If source begins with "package generic_" and type parameters are enabled,
29 // generic code is permitted.
30 func pkgFor(path, source string, info *Info) (*Package, error) {
31 mode := modeForSource(source)
32 return pkgForMode(path, source, info, mode)
35 func pkgForMode(path, source string, info *Info, mode parser.Mode) (*Package, error) {
36 fset := token.NewFileSet()
37 f, err := parser.ParseFile(fset, path, source, mode)
41 conf := Config{Importer: importer.Default()}
42 return conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
45 func mustTypecheck(t *testing.T, path, source string, info *Info) string {
46 pkg, err := pkgFor(path, source, info)
50 name = "package " + pkg.Name()
52 t.Fatalf("%s: didn't type-check (%s)", name, err)
57 // genericPkg is a prefix for packages that should be type checked with
59 const genericPkg = "package generic_"
61 func modeForSource(src string) parser.Mode {
62 if !strings.HasPrefix(src, genericPkg) {
63 return typeparams.DisallowParsing
68 func mayTypecheck(t *testing.T, path, source string, info *Info) (string, error) {
69 fset := token.NewFileSet()
70 mode := modeForSource(source)
71 f, err := parser.ParseFile(fset, path, source, mode)
72 if f == nil { // ignore errors unless f is nil
73 t.Fatalf("%s: unable to parse: %s", path, err)
76 Error: func(err error) {},
77 Importer: importer.Default(),
79 pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
80 return pkg.Name(), err
83 func TestValuesInfo(t *testing.T) {
84 var tests = []struct {
86 expr string // constant expression
87 typ string // constant type
88 val string // constant value
90 {`package a0; const _ = false`, `false`, `untyped bool`, `false`},
91 {`package a1; const _ = 0`, `0`, `untyped int`, `0`},
92 {`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
93 {`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
94 {`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
95 {`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
97 {`package b0; var _ = false`, `false`, `bool`, `false`},
98 {`package b1; var _ = 0`, `0`, `int`, `0`},
99 {`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
100 {`package b3; var _ = 0.`, `0.`, `float64`, `0`},
101 {`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
102 {`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
104 {`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
105 {`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
106 {`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
108 {`package c1a; var _ = int(0)`, `0`, `int`, `0`},
109 {`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
110 {`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
112 {`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
113 {`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
114 {`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
116 {`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
117 {`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
118 {`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
120 {`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
121 {`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
122 {`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
124 {`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
125 {`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
126 {`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
127 {`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
128 {`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
129 {`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
131 {`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
132 {`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
133 {`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
134 {`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
136 {`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
137 {`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
138 {`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
139 {`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
140 {`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
141 {`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
142 {`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
143 {`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
145 {`package f0 ; var _ float32 = 1e-200`, `1e-200`, `float32`, `0`},
146 {`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
147 {`package f2a; var _ float64 = 1e-2000`, `1e-2000`, `float64`, `0`},
148 {`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
149 {`package f2b; var _ = 1e-2000`, `1e-2000`, `float64`, `0`},
150 {`package f3b; var _ = -1e-2000`, `-1e-2000`, `float64`, `0`},
151 {`package f4 ; var _ complex64 = 1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
152 {`package f5 ; var _ complex64 = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
153 {`package f6a; var _ complex128 = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
154 {`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
155 {`package f6b; var _ = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
156 {`package f7b; var _ = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
158 {`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // issue #22341
159 {`package g1; var(j int32; s int; n = 1.0<<s == j)`, `1.0`, `int32`, `1`}, // issue #48422
162 for _, test := range tests {
164 Types: make(map[ast.Expr]TypeAndValue),
166 name := mustTypecheck(t, "ValuesInfo", test.src, &info)
168 // look for expression
170 for e := range info.Types {
171 if ExprString(e) == test.expr {
177 t.Errorf("package %s: no expression found for %s", name, test.expr)
180 tv := info.Types[expr]
182 // check that type is correct
183 if got := tv.Type.String(); got != test.typ {
184 t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
188 // if we have a constant, check that value is correct
190 if got := tv.Value.ExactString(); got != test.val {
191 t.Errorf("package %s: got value %s; want %s", name, got, test.val)
195 t.Errorf("package %s: no constant found; want %s", name, test.val)
201 func TestTypesInfo(t *testing.T) {
202 // Test sources that are not expected to typecheck must start with the broken prefix.
203 const broken = "package broken_"
205 var tests = []struct {
207 expr string // expression
208 typ string // value type
210 // single-valued expressions of untyped constants
211 {`package b0; var x interface{} = false`, `false`, `bool`},
212 {`package b1; var x interface{} = 0`, `0`, `int`},
213 {`package b2; var x interface{} = 0.`, `0.`, `float64`},
214 {`package b3; var x interface{} = 0i`, `0i`, `complex128`},
215 {`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
218 {`package n0; var _ *int = nil`, `nil`, `untyped nil`},
219 {`package n1; var _ func() = nil`, `nil`, `untyped nil`},
220 {`package n2; var _ []byte = nil`, `nil`, `untyped nil`},
221 {`package n3; var _ map[int]int = nil`, `nil`, `untyped nil`},
222 {`package n4; var _ chan int = nil`, `nil`, `untyped nil`},
223 {`package n5; var _ interface{} = nil`, `nil`, `untyped nil`},
224 {`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `untyped nil`},
226 {`package n10; var (x *int; _ = x == nil)`, `nil`, `untyped nil`},
227 {`package n11; var (x func(); _ = x == nil)`, `nil`, `untyped nil`},
228 {`package n12; var (x []byte; _ = x == nil)`, `nil`, `untyped nil`},
229 {`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `untyped nil`},
230 {`package n14; var (x chan int; _ = x == nil)`, `nil`, `untyped nil`},
231 {`package n15; var (x interface{}; _ = x == nil)`, `nil`, `untyped nil`},
232 {`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `untyped nil`},
234 {`package n20; var _ = (*int)(nil)`, `nil`, `untyped nil`},
235 {`package n21; var _ = (func())(nil)`, `nil`, `untyped nil`},
236 {`package n22; var _ = ([]byte)(nil)`, `nil`, `untyped nil`},
237 {`package n23; var _ = (map[int]int)(nil)`, `nil`, `untyped nil`},
238 {`package n24; var _ = (chan int)(nil)`, `nil`, `untyped nil`},
239 {`package n25; var _ = (interface{})(nil)`, `nil`, `untyped nil`},
240 {`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `untyped nil`},
242 {`package n30; func f(*int) { f(nil) }`, `nil`, `untyped nil`},
243 {`package n31; func f(func()) { f(nil) }`, `nil`, `untyped nil`},
244 {`package n32; func f([]byte) { f(nil) }`, `nil`, `untyped nil`},
245 {`package n33; func f(map[int]int) { f(nil) }`, `nil`, `untyped nil`},
246 {`package n34; func f(chan int) { f(nil) }`, `nil`, `untyped nil`},
247 {`package n35; func f(interface{}) { f(nil) }`, `nil`, `untyped nil`},
248 {`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `untyped nil`},
250 // comma-ok expressions
251 {`package p0; var x interface{}; var _, _ = x.(int)`,
255 {`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
259 {`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
261 `(complex128, p2a.mybool)`,
263 {`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
265 `(complex128, bool)`,
267 {`package p3; var c chan string; var _, _ = <-c`,
273 {`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
277 {`package issue6796_b; var c chan string; var _, _ = (<-c)`,
281 {`package issue6796_c; var c chan string; var _, _ = (<-c)`,
285 {`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
289 {`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
295 {`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
299 {`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
303 {`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
307 {`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
311 {`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
315 {`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
321 {`package issue28277_a; func f(...int)`,
325 {`package issue28277_b; func f(a, b int, c ...[]struct{})`,
331 {`package issue47243_a; var x int32; var _ = x << 3`, `3`, `untyped int`},
332 {`package issue47243_b; var x int32; var _ = x << 3.`, `3.`, `uint`}, // issue 47410: should be untyped float
333 {`package issue47243_c; var x int32; var _ = 1 << x`, `1 << x`, `int`},
334 {`package issue47243_d; var x int32; var _ = 1 << x`, `1`, `int`},
335 {`package issue47243_e; var x int32; var _ = 1 << 2`, `1`, `untyped int`},
336 {`package issue47243_f; var x int32; var _ = 1 << 2`, `2`, `untyped int`},
337 {`package issue47243_g; var x int32; var _ = int(1) << 2`, `2`, `untyped int`},
338 {`package issue47243_h; var x int32; var _ = 1 << (2 << x)`, `1`, `int`},
339 {`package issue47243_i; var x int32; var _ = 1 << (2 << x)`, `(2 << x)`, `untyped int`},
340 {`package issue47243_j; var x int32; var _ = 1 << (2 << x)`, `2`, `untyped int`},
342 // tests for broken code that doesn't parse or type-check
343 {broken + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
344 {broken + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
345 {broken + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a; f: b;}}`, `b`, `string`},
346 {broken + `x3; var x = panic("");`, `panic`, `func(interface{})`},
347 {`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
348 {broken + `x5; func _() { var x map[string][...]int; x = map[string][...]int{"": {1,2,3}} }`, `x`, `map[string]invalid type`},
350 // parameterized functions
351 {genericPkg + `p0; func f[T any](T) {}; var _ = f[int]`, `f`, `func[T any](T)`},
352 {genericPkg + `p1; func f[T any](T) {}; var _ = f[int]`, `f[int]`, `func(int)`},
353 {genericPkg + `p2; func f[T any](T) {}; func _() { f(42) }`, `f`, `func(int)`},
354 {genericPkg + `p3; func f[T any](T) {}; func _() { f[int](42) }`, `f[int]`, `func(int)`},
355 {genericPkg + `p4; func f[T any](T) {}; func _() { f[int](42) }`, `f`, `func[T any](T)`},
356 {genericPkg + `p5; func f[T any](T) {}; func _() { f(42) }`, `f(42)`, `()`},
359 {genericPkg + `t0; type t[] int; var _ t`, `t`, `generic_t0.t`}, // t[] is a syntax error that is ignored in this test in favor of t
360 {genericPkg + `t1; type t[P any] int; var _ t[int]`, `t`, `generic_t1.t[P any]`},
361 {genericPkg + `t2; type t[P interface{}] int; var _ t[int]`, `t`, `generic_t2.t[P interface{}]`},
362 {genericPkg + `t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `generic_t3.t[P, Q interface{}]`},
364 // TODO (rFindley): compare with types2, which resolves the type broken_t4.t[P₁, Q₂ interface{m()}] here
365 {broken + `t4; type t[P, Q interface{ m() }] int; var _ t[int, int]`, `t`, `broken_t4.t`},
367 // instantiated types must be sanitized
368 {genericPkg + `g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `generic_g0.t[int]`},
371 {genericPkg + `issue45096; func _[T interface{ ~int8 | ~int16 | ~int32 }](x T) { _ = x < 0 }`, `0`, `T`},
374 {`package p; import "unsafe"; type S struct { f int }; var s S; var _ = unsafe.Offsetof(s.f)`, `s.f`, `int`},
377 {genericPkg + `u0a; func _[_ interface{int}]() {}`, `int`, `int`},
378 {genericPkg + `u1a; func _[_ interface{~int}]() {}`, `~int`, `~int`},
379 {genericPkg + `u2a; func _[_ interface{int|string}]() {}`, `int | string`, `int|string`},
380 {genericPkg + `u3a; func _[_ interface{int|string|~bool}]() {}`, `int | string | ~bool`, `int|string|~bool`},
381 {genericPkg + `u3a; func _[_ interface{int|string|~bool}]() {}`, `int | string`, `int|string`},
382 {genericPkg + `u3a; func _[_ interface{int|string|~bool}]() {}`, `~bool`, `~bool`},
383 {genericPkg + `u3a; func _[_ interface{int|string|~float64|~bool}]() {}`, `int | string | ~float64`, `int|string|~float64`},
385 {genericPkg + `u0b; func _[_ int]() {}`, `int`, `int`},
386 {genericPkg + `u1b; func _[_ ~int]() {}`, `~int`, `~int`},
387 {genericPkg + `u2b; func _[_ int|string]() {}`, `int | string`, `int|string`},
388 {genericPkg + `u3b; func _[_ int|string|~bool]() {}`, `int | string | ~bool`, `int|string|~bool`},
389 {genericPkg + `u3b; func _[_ int|string|~bool]() {}`, `int | string`, `int|string`},
390 {genericPkg + `u3b; func _[_ int|string|~bool]() {}`, `~bool`, `~bool`},
391 {genericPkg + `u3b; func _[_ int|string|~float64|~bool]() {}`, `int | string | ~float64`, `int|string|~float64`},
393 {genericPkg + `u0c; type _ interface{int}`, `int`, `int`},
394 {genericPkg + `u1c; type _ interface{~int}`, `~int`, `~int`},
395 {genericPkg + `u2c; type _ interface{int|string}`, `int | string`, `int|string`},
396 {genericPkg + `u3c; type _ interface{int|string|~bool}`, `int | string | ~bool`, `int|string|~bool`},
397 {genericPkg + `u3c; type _ interface{int|string|~bool}`, `int | string`, `int|string`},
398 {genericPkg + `u3c; type _ interface{int|string|~bool}`, `~bool`, `~bool`},
399 {genericPkg + `u3c; type _ interface{int|string|~float64|~bool}`, `int | string | ~float64`, `int|string|~float64`},
402 for _, test := range tests {
403 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
405 if strings.HasPrefix(test.src, broken) {
407 name, err = mayTypecheck(t, "TypesInfo", test.src, &info)
409 t.Errorf("package %s: expected to fail but passed", name)
413 name = mustTypecheck(t, "TypesInfo", test.src, &info)
416 // look for expression type
418 for e, tv := range info.Types {
419 if ExprString(e) == test.expr {
425 t.Errorf("package %s: no type found for %s", name, test.expr)
429 // check that type is correct
430 if got := typ.String(); got != test.typ {
431 t.Errorf("package %s: got %s; want %s", name, got, test.typ)
436 func TestInstanceInfo(t *testing.T) {
437 var tests = []struct {
443 {`package p0; func f[T any](T) {}; func _() { f(42) }`,
448 {`package p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
453 {`package p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
455 []string{`complex128`},
456 `func(...complex128) complex128`,
458 {`package p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
460 []string{`float64`, `string`, `byte`},
461 `func(float64, *string, []byte)`,
463 {`package p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
465 []string{`float64`, `byte`},
466 `func(float64, *byte, ...[]byte)`,
469 {`package s1; func f[T any, P interface{~*T}](x T) {}; func _(x string) { f(x) }`,
471 []string{`string`, `*string`},
474 {`package s2; func f[T any, P interface{~*T}](x []T) {}; func _(x []int) { f(x) }`,
476 []string{`int`, `*int`},
479 {`package s3; type C[T any] interface{~chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
481 []string{`int`, `chan<- int`},
484 {`package s4; type C[T any] interface{~chan<- T}; func f[T any, P C[T], Q C[[]*P]](x []T) {}; func _(x []int) { f(x) }`,
486 []string{`int`, `chan<- int`, `chan<- []*chan<- int`},
490 {`package t1; func f[T any, P interface{~*T}]() T { panic(0) }; func _() { _ = f[string] }`,
492 []string{`string`, `*string`},
495 {`package t2; func f[T any, P interface{~*T}]() T { panic(0) }; func _() { _ = (f[string]) }`,
497 []string{`string`, `*string`},
500 {`package t3; type C[T any] interface{~chan<- T}; func f[T any, P C[T]]() []T { return nil }; func _() { _ = f[int] }`,
502 []string{`int`, `chan<- int`},
505 {`package t4; type C[T any] interface{~chan<- T}; func f[T any, P C[T], Q C[[]*P]]() []T { return nil }; func _() { _ = f[int] }`,
507 []string{`int`, `chan<- int`, `chan<- []*chan<- int`},
510 {`package i0; import "lib"; func _() { lib.F(42) }`,
515 {`package type0; type T[P interface{~int}] struct{ x P }; var _ T[int]`,
520 {`package type1; type T[P interface{~int}] struct{ x P }; var _ (T[int])`,
525 {`package type2; type T[P interface{~int}] struct{ x P }; var _ T[(int)]`,
530 {`package type3; type T[P1 interface{~[]P2}, P2 any] struct{ x P1; y P2 }; var _ T[[]int, int]`,
532 []string{`[]int`, `int`},
533 `struct{x []int; y int}`,
535 {`package type4; import "lib"; var _ lib.T[int]`,
542 for _, test := range tests {
543 const lib = `package lib
550 imports := make(testImporter)
551 conf := Config{Importer: imports}
552 instances := make(map[*ast.Ident]Instance)
553 uses := make(map[*ast.Ident]Object)
554 makePkg := func(src string) *Package {
555 f, err := parser.ParseFile(fset, "p.go", src, 0)
559 pkg, err := conf.Check("", fset, []*ast.File{f}, &Info{Instances: instances, Uses: uses})
563 imports[pkg.Name()] = pkg
567 pkg := makePkg(test.src)
569 // look for instance information
572 for ident, inst := range instances {
573 if ExprString(ident) == test.name {
574 for i := 0; i < inst.TypeArgs.Len(); i++ {
575 targs = append(targs, inst.TypeArgs.At(i))
579 // Check that we can find the corresponding parameterized type.
580 ptype := uses[ident].Type()
581 lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
582 if lister == nil || lister.TypeParams().Len() == 0 {
583 t.Errorf("package %s: info.Types[%v] = %v, want parameterized type", pkg.Name(), ident, ptype)
587 // Verify the invariant that re-instantiating the generic type with
588 // TypeArgs results in an equivalent type.
589 inst2, err := Instantiate(nil, ptype, targs, true)
591 t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
593 if !Identical(inst.Type, inst2) {
594 t.Errorf("%v and %v are not identical", inst.Type, inst2)
600 t.Errorf("package %s: no instance information found for %s", pkg.Name(), test.name)
604 // check that type arguments are correct
605 if len(targs) != len(test.targs) {
606 t.Errorf("package %s: got %d type arguments; want %d", pkg.Name(), len(targs), len(test.targs))
609 for i, targ := range targs {
610 if got := targ.String(); got != test.targs[i] {
611 t.Errorf("package %s, %d. type argument: got %s; want %s", pkg.Name(), i, got, test.targs[i])
616 // check that the types match
617 if got := typ.Underlying().String(); got != test.typ {
618 t.Errorf("package %s: got %s; want %s", pkg.Name(), got, test.typ)
623 func TestDefsInfo(t *testing.T) {
624 var tests = []struct {
629 {`package p0; const x = 42`, `x`, `const p0.x untyped int`},
630 {`package p1; const x int = 42`, `x`, `const p1.x int`},
631 {`package p2; var x int`, `x`, `var p2.x int`},
632 {`package p3; type x int`, `x`, `type p3.x int`},
633 {`package p4; func f()`, `f`, `func p4.f()`},
634 {`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
636 // Tests using generics.
637 {`package generic_g0; type x[T any] int`, `x`, `type generic_g0.x[T any] int`},
638 {`package generic_g1; func f[T any]() {}`, `f`, `func generic_g1.f[T any]()`},
639 {`package generic_g2; type x[T any] int; func (*x[_]) m() {}`, `m`, `func (*generic_g2.x[_]).m()`},
642 for _, test := range tests {
644 Defs: make(map[*ast.Ident]Object),
646 name := mustTypecheck(t, "DefsInfo", test.src, &info)
650 for id, obj := range info.Defs {
651 if id.Name == test.obj {
657 t.Errorf("package %s: %s not found", name, test.obj)
661 if got := def.String(); got != test.want {
662 t.Errorf("package %s: got %s; want %s", name, got, test.want)
667 func TestUsesInfo(t *testing.T) {
668 var tests = []struct {
673 {`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
674 {`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
675 {`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
676 {`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
677 {`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
679 // Tests using generics.
680 {`package generic_g0; func _[T any]() { _ = x }; const x = 42`, `x`, `const generic_g0.x untyped int`},
681 {`package generic_g1; func _[T any](x T) { }`, `T`, `type parameter T any`},
682 {`package generic_g2; type N[A any] int; var _ N[int]`, `N`, `type generic_g2.N[A any] int`},
683 {`package generic_g3; type N[A any] int; func (N[_]) m() {}`, `N`, `type generic_g3.N[A any] int`},
685 // Uses of fields are instantiated.
686 {`package generic_s1; type N[A any] struct{ a A }; var f = N[int]{}.a`, `a`, `field a int`},
687 {`package generic_s1; type N[A any] struct{ a A }; func (r N[B]) m(b B) { r.a = b }`, `a`, `field a B`},
689 // Uses of methods are uses of the instantiated method.
690 {`package generic_m0; type N[A any] int; func (r N[B]) m() { r.n() }; func (N[C]) n() {}`, `n`, `func (generic_m0.N[B]).n()`},
691 {`package generic_m1; type N[A any] int; func (r N[B]) m() { }; var f = N[int].m`, `m`, `func (generic_m1.N[int]).m()`},
694 for _, test := range tests {
696 Uses: make(map[*ast.Ident]Object),
698 name := mustTypecheck(t, "UsesInfo", test.src, &info)
702 for id, obj := range info.Uses {
703 if id.Name == test.obj {
709 t.Errorf("package %s: %s not found", name, test.obj)
713 if got := use.String(); got != test.want {
714 t.Errorf("package %s: got %s; want %s", name, got, test.want)
719 func TestGenericMethodInfo(t *testing.T) {
724 func (r N[B]) m() { r.m(); r.n() }
726 func (r *N[C]) n() { }
728 fset := token.NewFileSet()
729 f, err := parser.ParseFile(fset, "p.go", src, 0)
734 Defs: make(map[*ast.Ident]Object),
735 Uses: make(map[*ast.Ident]Object),
736 Selections: make(map[*ast.SelectorExpr]*Selection),
739 pkg, err := conf.Check("p", fset, []*ast.File{f}, &info)
744 N := pkg.Scope().Lookup("N").Type().(*Named)
746 // Find the generic methods stored on N.
747 gm, gn := N.Method(0), N.Method(1)
748 if gm.Name() == "n" {
752 // Collect objects from info.
753 var dm, dn *Func // the declared methods
754 var dmm, dmn *Func // the methods used in the body of m
755 for _, decl := range f.Decls {
756 fdecl, ok := decl.(*ast.FuncDecl)
760 def := info.Defs[fdecl.Name].(*Func)
761 switch fdecl.Name.Name {
764 ast.Inspect(fdecl.Body, func(n ast.Node) bool {
765 if call, ok := n.(*ast.CallExpr); ok {
766 sel := call.Fun.(*ast.SelectorExpr)
767 use := info.Uses[sel.Sel].(*Func)
768 selection := info.Selections[sel]
769 if selection.Kind() != MethodVal {
770 t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
772 if selection.Obj() != use {
773 t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
775 switch sel.Sel.Name {
790 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
793 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
796 t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
799 t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
803 func TestImplicitsInfo(t *testing.T) {
804 testenv.MustHaveGoBuild(t)
806 var tests = []struct {
810 {`package p2; import . "fmt"; var _ = Println`, ""}, // no Implicits entry
811 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
812 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
814 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
815 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
816 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
817 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
819 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
820 {`package p8; func f(int) {}`, "field: var int"},
821 {`package p9; func f() (complex64) { return 0 }`, "field: var complex64"},
822 {`package p10; type T struct{}; func (*T) f() {}`, "field: var *p10.T"},
824 // Tests using generics.
825 {`package generic_f0; func f[T any](x int) {}`, ""}, // no Implicits entry
826 {`package generic_f1; func f[T any](int) {}`, "field: var int"},
827 {`package generic_f2; func f[T any](T) {}`, "field: var T"},
828 {`package generic_f3; func f[T any]() (complex64) { return 0 }`, "field: var complex64"},
829 {`package generic_f4; func f[T any](t T) (T) { return t }`, "field: var T"},
830 {`package generic_t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var *generic_t0.T[_]"},
831 {`package generic_t1; type T[A any] struct{}; func _(x interface{}) { switch t := x.(type) { case T[int]: _ = t } }`, "caseClause: var t generic_t1.T[int]"},
832 {`package generic_t2; type T[A any] struct{}; func _[P any](x interface{}) { switch t := x.(type) { case T[P]: _ = t } }`, "caseClause: var t generic_t2.T[P]"},
833 {`package generic_t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
836 for _, test := range tests {
838 Implicits: make(map[ast.Node]Object),
840 name := mustTypecheck(t, "ImplicitsInfo", test.src, &info)
842 // the test cases expect at most one Implicits entry
843 if len(info.Implicits) > 1 {
844 t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
848 // extract Implicits entry, if any
850 for n, obj := range info.Implicits {
851 switch x := n.(type) {
852 case *ast.ImportSpec:
854 case *ast.CaseClause:
859 t.Fatalf("package %s: unexpected %T", name, x)
861 got += ": " + obj.String()
865 if got != test.want {
866 t.Errorf("package %s: got %q; want %q", name, got, test.want)
871 func predString(tv TypeAndValue) string {
873 pred := func(b bool, s string) {
876 buf.WriteString(", ")
882 pred(tv.IsVoid(), "void")
883 pred(tv.IsType(), "type")
884 pred(tv.IsBuiltin(), "builtin")
885 pred(tv.IsValue() && tv.Value != nil, "const")
886 pred(tv.IsValue() && tv.Value == nil, "value")
887 pred(tv.IsNil(), "nil")
888 pred(tv.Addressable(), "addressable")
889 pred(tv.Assignable(), "assignable")
890 pred(tv.HasOk(), "hasOk")
898 func TestPredicatesInfo(t *testing.T) {
899 testenv.MustHaveGoBuild(t)
901 var tests = []struct {
907 {`package n0; func f() { f() }`, `f()`, `void`},
910 {`package t0; type _ int`, `int`, `type`},
911 {`package t1; type _ []int`, `[]int`, `type`},
912 {`package t2; type _ func()`, `func()`, `type`},
913 {`package t3; type _ func(int)`, `int`, `type`},
914 {`package t3; type _ func(...int)`, `...int`, `type`},
917 {`package b0; var _ = len("")`, `len`, `builtin`},
918 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
921 {`package c0; var _ = 42`, `42`, `const`},
922 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
923 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
926 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
927 {`package v1; var _ = &[]int{1}`, `([]int literal)`, `value`},
928 {`package v2; var _ = func(){}`, `(func() literal)`, `value`},
929 {`package v4; func f() { _ = f }`, `f`, `value`},
930 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
931 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
933 // addressable (and thus assignable) operands
934 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
935 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
936 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
937 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
938 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
939 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
940 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
941 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
942 // composite literals are not addressable
944 // assignable but not addressable values
945 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
946 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
949 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
950 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
953 // - package names are collected in the Uses map
954 // - identifiers being declared are collected in the Defs map
955 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
956 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
957 {`package m2; const c = 0`, `c`, `<missing>`},
958 {`package m3; type T int`, `T`, `<missing>`},
959 {`package m4; var v int`, `v`, `<missing>`},
960 {`package m5; func f() {}`, `f`, `<missing>`},
961 {`package m6; func _(x int) {}`, `x`, `<missing>`},
962 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
963 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
966 for _, test := range tests {
967 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
968 name := mustTypecheck(t, "PredicatesInfo", test.src, &info)
970 // look for expression predicates
972 for e, tv := range info.Types {
973 //println(name, ExprString(e))
974 if ExprString(e) == test.expr {
980 if got != test.pred {
981 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
986 func TestScopesInfo(t *testing.T) {
987 testenv.MustHaveGoBuild(t)
989 var tests = []struct {
991 scopes []string // list of scope descriptors of the form kind:varlist
993 {`package p0`, []string{
996 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
999 {`package p2; func _() {}`, []string{
1002 {`package p3; func _(x, y int) {}`, []string{
1003 "file:", "func:x y",
1005 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
1006 "file:", "func:x y z", // redeclaration of x
1008 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
1009 "file:", "func:u x y",
1011 {`package p6; func _() { { var x int; _ = x } }`, []string{
1012 "file:", "func:", "block:x",
1014 {`package p7; func _() { if true {} }`, []string{
1015 "file:", "func:", "if:", "block:",
1017 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
1018 "file:", "func:", "if:x", "block:y",
1020 {`package p9; func _() { switch x := 0; x {} }`, []string{
1021 "file:", "func:", "switch:x",
1023 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
1024 "file:", "func:", "switch:x", "case:y", "case:",
1026 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
1027 "file:", "func:t", "type switch:",
1029 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
1030 "file:", "func:t", "type switch:t",
1032 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
1033 "file:", "func:t", "type switch:", "case:x", // x implicitly declared
1035 {`package p14; func _() { select{} }`, []string{
1038 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
1039 "file:", "func:c", "comm:",
1041 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
1042 "file:", "func:c", "comm:i x",
1044 {`package p17; func _() { for{} }`, []string{
1045 "file:", "func:", "for:", "block:",
1047 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
1048 "file:", "func:n", "for:i", "block:",
1050 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
1051 "file:", "func:a", "range:i", "block:",
1053 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
1054 "file:", "func:a", "range:i x", "block:",
1058 for _, test := range tests {
1059 info := Info{Scopes: make(map[ast.Node]*Scope)}
1060 name := mustTypecheck(t, "ScopesInfo", test.src, &info)
1062 // number of scopes must match
1063 if len(info.Scopes) != len(test.scopes) {
1064 t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
1067 // scope descriptions must match
1068 for node, scope := range info.Scopes {
1069 kind := "<unknown node kind>"
1070 switch node.(type) {
1075 case *ast.BlockStmt:
1079 case *ast.SwitchStmt:
1081 case *ast.TypeSwitchStmt:
1082 kind = "type switch"
1083 case *ast.CaseClause:
1085 case *ast.CommClause:
1089 case *ast.RangeStmt:
1093 // look for matching scope description
1094 desc := kind + ":" + strings.Join(scope.Names(), " ")
1096 for _, d := range test.scopes {
1103 t.Errorf("package %s: no matching scope found for %s", name, desc)
1109 func TestInitOrderInfo(t *testing.T) {
1110 var tests = []struct {
1114 {`package p0; var (x = 1; y = x)`, []string{
1117 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
1118 "a = 1", "b = 2", "c = 3",
1120 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
1121 "a = 1", "b = 2", "c = 3",
1123 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
1124 "_ = f()", // blank var
1126 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
1127 "a = 0", "z = 0", "y = z", "x = y",
1129 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
1130 "a, _ = m[0]", // blank var
1132 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
1133 "z = 0", "a, b = f()",
1135 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
1136 "b = 1", "a = (func() int literal)()",
1138 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
1139 "c = 1", "a, b = (func() (_, _ int) literal)()",
1141 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1144 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1145 "a = 0", "b = 0", "c = 0", "d = c + b",
1147 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
1148 "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
1150 // emit an initializer for n:1 initializations only once (not for each node
1151 // on the lhs which may appear in different order in the dependency graph)
1152 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
1153 "b = 0", "x, y = m[0]", "a = x",
1155 // test case from spec section on package initialization
1169 "d = 3", "b = f()", "c = f()", "a = c + b",
1171 // test case for issue 7131
1175 func next() int { counter++; return counter }
1178 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1181 var b, c = next(), next()
1182 var d, e, f = next(), next(), next()
1184 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1186 // test case for issue 10709
1196 func (T) m() int { return 0 }
1198 func makeT(n int) T {
1204 "t = makeT(0)", "v = t.m()",
1206 // test case for issue 10709: same as test before, but variable decls swapped
1216 func (T) m() int { return 0 }
1218 func makeT(n int) T {
1224 "t = makeT(0)", "v = t.m()",
1226 // another candidate possibly causing problems with issue 10709
1231 func f1() int { return g1() }
1232 func g1() int { f1(); return x1 }
1238 func f2() int { return g2() }
1239 func g2() int { return x2 }
1241 var x2 = 0`, []string{
1242 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1246 for _, test := range tests {
1248 name := mustTypecheck(t, "InitOrderInfo", test.src, &info)
1250 // number of initializers must match
1251 if len(info.InitOrder) != len(test.inits) {
1252 t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1256 // initializers must match
1257 for i, want := range test.inits {
1258 got := info.InitOrder[i].String()
1260 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1267 func TestMultiFileInitOrder(t *testing.T) {
1268 fset := token.NewFileSet()
1269 mustParse := func(src string) *ast.File {
1270 f, err := parser.ParseFile(fset, "main", src, 0)
1277 fileA := mustParse(`package main; var a = 1`)
1278 fileB := mustParse(`package main; var b = 2`)
1280 // The initialization order must not depend on the parse
1281 // order of the files, only on the presentation order to
1282 // the type-checker.
1283 for _, test := range []struct {
1287 {[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
1288 {[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
1291 if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
1294 if got := fmt.Sprint(info.InitOrder); got != test.want {
1295 t.Fatalf("got %s; want %s", got, test.want)
1300 func TestFiles(t *testing.T) {
1301 var sources = []string{
1302 "package p; type T struct{}; func (T) m1() {}",
1303 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1304 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1309 fset := token.NewFileSet()
1310 pkg := NewPackage("p", "p")
1312 check := NewChecker(&conf, fset, pkg, &info)
1314 for i, src := range sources {
1315 filename := fmt.Sprintf("sources%d", i)
1316 f, err := parser.ParseFile(fset, filename, src, 0)
1320 if err := check.Files([]*ast.File{f}); err != nil {
1325 // check InitOrder is [x y]
1327 for _, init := range info.InitOrder {
1328 for _, v := range init.Lhs {
1329 vars = append(vars, v.Name())
1332 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1333 t.Errorf("InitOrder == %s, want %s", got, want)
1337 type testImporter map[string]*Package
1339 func (m testImporter) Import(path string) (*Package, error) {
1340 if pkg := m[path]; pkg != nil {
1343 return nil, fmt.Errorf("package %q not found", path)
1346 func TestSelection(t *testing.T) {
1347 selections := make(map[*ast.SelectorExpr]*Selection)
1349 fset := token.NewFileSet()
1350 imports := make(testImporter)
1351 conf := Config{Importer: imports}
1352 makePkg := func(path, src string) {
1353 f, err := parser.ParseFile(fset, path+".go", src, 0)
1357 pkg, err := conf.Check(path, fset, []*ast.File{f}, &Info{Selections: selections})
1395 // qualified identifiers
1429 // method expressions
1436 wantOut := map[string][2]string{
1437 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1439 "A{}.B": {"field (main.A) B *main.B", ".[0]"},
1440 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1441 "A{}.C": {"field (main.A) C main.C", ".[1]"},
1442 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1443 "A{}.b": {"field (main.A) b int", "->[0 0]"},
1444 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1445 "A{}.c": {"field (main.A) c int", ".[1 0]"},
1446 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1448 "A{}.f": {"method (main.A) f(int)", "->[0 0]"},
1449 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1450 "A{}.g": {"method (main.A) g()", ".[1 0]"},
1451 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1452 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1453 "B{}.f": {"method (main.B) f(int)", ".[0]"},
1454 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1455 "C{}.g": {"method (main.C) g()", ".[0]"},
1456 "new(C).g": {"method (*main.C) g()", "->[0]"},
1457 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1459 "A.f": {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1460 "(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1461 "B.f": {"method expr (main.B) f(main.B, int)", ".[0]"},
1462 "(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1465 makePkg("lib", libSrc)
1466 makePkg("main", mainSrc)
1468 for e, sel := range selections {
1469 _ = sel.String() // assertion: must not panic
1471 start := fset.Position(e.Pos()).Offset
1472 end := fset.Position(e.End()).Offset
1473 syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1481 fmt.Sprintf("%s%v", direct, sel.Index()),
1483 want := wantOut[syntax]
1485 t.Errorf("%s: got %q; want %q", syntax, got, want)
1487 delete(wantOut, syntax)
1489 // We must explicitly assert properties of the
1490 // Signature's receiver since it doesn't participate
1491 // in Identical() or String().
1492 sig, _ := sel.Type().(*Signature)
1493 if sel.Kind() == MethodVal {
1494 got := sig.Recv().Type()
1496 if !Identical(got, want) {
1497 t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
1499 } else if sig != nil && sig.Recv() != nil {
1500 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1503 // Assert that all wantOut entries were used exactly once.
1504 for syntax := range wantOut {
1505 t.Errorf("no ast.Selection found with syntax %q", syntax)
1509 func TestIssue8518(t *testing.T) {
1510 fset := token.NewFileSet()
1511 imports := make(testImporter)
1513 Error: func(err error) { t.Log(err) }, // don't exit after first error
1516 makePkg := func(path, src string) {
1517 f, err := parser.ParseFile(fset, path, src, 0)
1521 pkg, _ := conf.Check(path, fset, []*ast.File{f}, nil) // errors logged via conf.Error
1529 const C2 = missing.C
1539 makePkg("a", libSrc)
1540 makePkg("main", mainSrc) // don't crash when type-checking this package
1543 func TestLookupFieldOrMethodOnNil(t *testing.T) {
1544 // LookupFieldOrMethod on a nil type is expected to produce a run-time panic.
1546 const want = "LookupFieldOrMethod on nil type"
1548 if s, ok := p.(string); !ok || s != want {
1549 t.Fatalf("got %v, want %s", p, want)
1552 LookupFieldOrMethod(nil, false, nil, "")
1555 func TestLookupFieldOrMethod(t *testing.T) {
1556 // Test cases assume a lookup of the form a.f or x.f, where a stands for an
1557 // addressable value, and x for a non-addressable value (even though a variable
1558 // for ease of test case writing).
1560 // Should be kept in sync with TestMethodSet.
1561 var tests = []struct {
1568 {"var x T; type T struct{}", false, nil, false},
1569 {"var x T; type T struct{ f int }", true, []int{0}, false},
1570 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1573 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1574 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1575 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1576 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1579 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1580 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1582 // outside methodset
1583 // (*T).f method exists, but value of type T is not addressable
1584 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1587 for _, test := range tests {
1588 pkg, err := pkgFor("test", "package p;"+test.src, nil)
1590 t.Errorf("%s: incorrect test case: %s", test.src, err)
1594 obj := pkg.Scope().Lookup("a")
1596 if obj = pkg.Scope().Lookup("x"); obj == nil {
1597 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1602 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1603 if (f != nil) != test.found {
1605 t.Errorf("%s: got no object; want one", test.src)
1607 t.Errorf("%s: got object = %v; want none", test.src, f)
1610 if !sameSlice(index, test.index) {
1611 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1613 if indirect != test.indirect {
1614 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1619 func sameSlice(a, b []int) bool {
1620 if len(a) != len(b) {
1623 for i, x := range a {
1631 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1632 // the correct result at various positions with the source.
1633 func TestScopeLookupParent(t *testing.T) {
1634 fset := token.NewFileSet()
1635 imports := make(testImporter)
1636 conf := Config{Importer: imports}
1637 mustParse := func(src string) *ast.File {
1638 f, err := parser.ParseFile(fset, "dummy.go", src, parser.ParseComments)
1645 makePkg := func(path string, files ...*ast.File) {
1647 imports[path], err = conf.Check(path, fset, files, &info)
1653 makePkg("lib", mustParse("package lib; var X int"))
1654 // Each /*name=kind:line*/ comment makes the test look up the
1655 // name at that point and checks that it resolves to a decl of
1656 // the specified kind and line number. "undef" means undefined.
1658 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1669 const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1670 type /*t=undef*/ t /*t=typename:14*/ *t
1671 print(Y) /*Y=var:10*/
1672 x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1673 var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1676 for i, x := range /*i=undef*/ /*x=var:16*/ a /*i=var:20*/ /*x=var:20*/ { _ = i; _ = x }
1679 switch y := i.(type) { /*y=undef*/
1680 case /*y=undef*/ int /*y=var:23*/ :
1681 case float32, /*y=undef*/ float64 /*y=var:23*/ :
1682 default /*y=var:23*/:
1687 switch int := i.(type) {
1688 case /*int=typename:0*/ int /*int=var:31*/ :
1690 default /*int=var:31*/ :
1696 info.Uses = make(map[*ast.Ident]Object)
1697 f := mustParse(mainSrc)
1699 mainScope := imports["main"].Scope()
1700 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1701 for _, group := range f.Comments {
1702 for _, comment := range group.List {
1703 // Parse the assertion in the comment.
1704 m := rx.FindStringSubmatch(comment.Text)
1706 t.Errorf("%s: bad comment: %s",
1707 fset.Position(comment.Pos()), comment.Text)
1710 name, want := m[1], m[2]
1712 // Look up the name in the innermost enclosing scope.
1713 inner := mainScope.Innermost(comment.Pos())
1715 t.Errorf("%s: at %s: can't find innermost scope",
1716 fset.Position(comment.Pos()), comment.Text)
1720 if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil {
1721 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
1722 got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line)
1725 t.Errorf("%s: at %s: %s resolved to %s, want %s",
1726 fset.Position(comment.Pos()), comment.Text, name, got, want)
1731 // Check that for each referring identifier,
1732 // a lookup of its name on the innermost
1733 // enclosing scope returns the correct object.
1735 for id, wantObj := range info.Uses {
1736 inner := mainScope.Innermost(id.Pos())
1738 t.Errorf("%s: can't find innermost scope enclosing %q",
1739 fset.Position(id.Pos()), id.Name)
1743 // Exclude selectors and qualified identifiers---lexical
1744 // refs only. (Ideally, we'd see if the AST parent is a
1745 // SelectorExpr, but that requires PathEnclosingInterval
1746 // from golang.org/x/tools/go/ast/astutil.)
1751 _, gotObj := inner.LookupParent(id.Name, id.Pos())
1752 if gotObj != wantObj {
1753 t.Errorf("%s: got %v, want %v",
1754 fset.Position(id.Pos()), gotObj, wantObj)
1760 // newDefined creates a new defined type named T with the given underlying type.
1761 // Helper function for use with TestIncompleteInterfaces only.
1762 func newDefined(underlying Type) *Named {
1763 tname := NewTypeName(token.NoPos, nil, "T", nil)
1764 return NewNamed(tname, underlying, nil)
1767 func TestConvertibleTo(t *testing.T) {
1768 for _, test := range []struct {
1772 {Typ[Int], Typ[Int], true},
1773 {Typ[Int], Typ[Float32], true},
1774 {Typ[Int], Typ[String], true},
1775 {newDefined(Typ[Int]), Typ[Int], true},
1776 {newDefined(new(Struct)), new(Struct), true},
1777 {newDefined(Typ[Int]), new(Struct), false},
1778 {Typ[UntypedInt], Typ[Int], true},
1779 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
1780 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), false},
1781 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
1782 // Untyped string values are not permitted by the spec, so the behavior below is undefined.
1783 {Typ[UntypedString], Typ[String], true},
1785 if got := ConvertibleTo(test.v, test.t); got != test.want {
1786 t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1791 func TestAssignableTo(t *testing.T) {
1792 for _, test := range []struct {
1796 {Typ[Int], Typ[Int], true},
1797 {Typ[Int], Typ[Float32], false},
1798 {newDefined(Typ[Int]), Typ[Int], false},
1799 {newDefined(new(Struct)), new(Struct), true},
1800 {Typ[UntypedBool], Typ[Bool], true},
1801 {Typ[UntypedString], Typ[Bool], false},
1802 // Neither untyped string nor untyped numeric assignments arise during
1803 // normal type checking, so the below behavior is technically undefined by
1805 {Typ[UntypedString], Typ[String], true},
1806 {Typ[UntypedInt], Typ[Int], true},
1808 if got := AssignableTo(test.v, test.t); got != test.want {
1809 t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1814 func TestIdentical(t *testing.T) {
1815 // For each test, we compare the types of objects X and Y in the source.
1821 {"var X int; var Y int", true},
1822 {"var X int; var Y string", false},
1824 // TODO: add more tests for complex types.
1827 {"type X int; type Y int", false},
1830 {"type X = int; type Y = int", true},
1833 {`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
1834 {`func X() string { return "" }; func Y(int) string { return "" }`, false},
1835 {`func X(int) string { return "" }; func Y(int) {}`, false},
1837 // Generic functions. Type parameters should be considered identical modulo
1838 // renaming. See also issue #49722.
1839 {`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
1840 {`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
1841 {`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
1842 {`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
1843 {`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
1844 {`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
1847 for _, test := range tests {
1848 pkg, err := pkgForMode("test", "package p;"+test.src, nil, 0)
1850 t.Errorf("%s: incorrect test case: %s", test.src, err)
1853 X := pkg.Scope().Lookup("X")
1854 Y := pkg.Scope().Lookup("Y")
1855 if X == nil || Y == nil {
1856 t.Fatal("test must declare both X and Y")
1858 if got := Identical(X.Type(), Y.Type()); got != test.want {
1859 t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
1864 func TestIdentical_issue15173(t *testing.T) {
1865 // Identical should allow nil arguments and be symmetric.
1866 for _, test := range []struct {
1870 {Typ[Int], Typ[Int], true},
1871 {Typ[Int], nil, false},
1872 {nil, Typ[Int], false},
1875 if got := Identical(test.x, test.y); got != test.want {
1876 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
1881 func TestIdenticalUnions(t *testing.T) {
1882 tname := NewTypeName(token.NoPos, nil, "myInt", nil)
1883 myInt := NewNamed(tname, Typ[Int], nil)
1884 tmap := map[string]*Term{
1885 "int": NewTerm(false, Typ[Int]),
1886 "~int": NewTerm(true, Typ[Int]),
1887 "string": NewTerm(false, Typ[String]),
1888 "~string": NewTerm(true, Typ[String]),
1889 "myInt": NewTerm(false, myInt),
1891 makeUnion := func(s string) *Union {
1892 parts := strings.Split(s, "|")
1894 for _, p := range parts {
1897 t.Fatalf("missing term %q", p)
1899 terms = append(terms, term)
1901 return NewUnion(terms)
1903 for _, test := range []struct {
1907 // These tests are just sanity checks. The tests for type sets and
1908 // interfaces provide much more test coverage.
1909 {"int|~int", "~int", true},
1910 {"myInt|~int", "~int", true},
1911 {"int|string", "string|int", true},
1912 {"int|int|string", "string|int", true},
1913 {"myInt|string", "int|string", false},
1915 x := makeUnion(test.x)
1916 y := makeUnion(test.y)
1917 if got := Identical(x, y); got != test.want {
1918 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
1923 func TestIssue15305(t *testing.T) {
1924 const src = "package p; func f() int16; var _ = f(undef)"
1925 fset := token.NewFileSet()
1926 f, err := parser.ParseFile(fset, "issue15305.go", src, 0)
1931 Error: func(err error) {}, // allow errors
1934 Types: make(map[ast.Expr]TypeAndValue),
1936 conf.Check("p", fset, []*ast.File{f}, info) // ignore result
1937 for e, tv := range info.Types {
1938 if _, ok := e.(*ast.CallExpr); ok {
1939 if tv.Type != Typ[Int16] {
1940 t.Errorf("CallExpr has type %v, want int16", tv.Type)
1945 t.Errorf("CallExpr has no type")
1948 // TestCompositeLitTypes verifies that Info.Types registers the correct
1949 // types for composite literal expressions and composite literal type
1951 func TestCompositeLitTypes(t *testing.T) {
1952 for _, test := range []struct {
1955 {`[16]byte{}`, `[16]byte`},
1956 {`[...]byte{}`, `[0]byte`}, // test for issue #14092
1957 {`[...]int{1, 2, 3}`, `[3]int`}, // test for issue #14092
1958 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for issue #14092
1959 {`[]int{}`, `[]int`},
1960 {`map[string]bool{"foo": true}`, `map[string]bool`},
1961 {`struct{}{}`, `struct{}`},
1962 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
1964 fset := token.NewFileSet()
1965 f, err := parser.ParseFile(fset, test.lit, "package p; var _ = "+test.lit, 0)
1967 t.Fatalf("%s: %v", test.lit, err)
1971 Types: make(map[ast.Expr]TypeAndValue),
1973 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
1974 t.Fatalf("%s: %v", test.lit, err)
1977 cmptype := func(x ast.Expr, want string) {
1978 tv, ok := info.Types[x]
1980 t.Errorf("%s: no Types entry found", test.lit)
1984 t.Errorf("%s: type is nil", test.lit)
1987 if got := tv.Type.String(); got != want {
1988 t.Errorf("%s: got %v, want %s", test.lit, got, want)
1992 // test type of composite literal expression
1993 rhs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0]
1994 cmptype(rhs, test.typ)
1996 // test type of composite literal type expression
1997 cmptype(rhs.(*ast.CompositeLit).Type, test.typ)
2001 // TestObjectParents verifies that objects have parent scopes or not
2002 // as specified by the Object interface.
2003 func TestObjectParents(t *testing.T) {
2022 func f(x int) { y := x; print(y) }
2025 fset := token.NewFileSet()
2026 f, err := parser.ParseFile(fset, "src", src, 0)
2032 Defs: make(map[*ast.Ident]Object),
2034 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
2038 for ident, obj := range info.Defs {
2040 // only package names and implicit vars have a nil object
2041 // (in this test we only need to handle the package name)
2042 if ident.Name != "p" {
2043 t.Errorf("%v has nil object", ident)
2048 // struct fields, type-associated and interface methods
2049 // have no parent scope
2051 switch obj := obj.(type) {
2057 if obj.Type().(*Signature).Recv() != nil { // method
2062 gotParent := obj.Parent() != nil
2064 case gotParent && !wantParent:
2065 t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
2066 case !gotParent && wantParent:
2067 t.Errorf("%v: no parent found", ident)
2072 // TestFailedImport tests that we don't get follow-on errors
2073 // elsewhere in a package due to failing to import a package.
2074 func TestFailedImport(t *testing.T) {
2075 testenv.MustHaveGoBuild(t)
2080 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
2085 func f(x T) T { return foo.F(x) }
2087 fset := token.NewFileSet()
2088 f, err := parser.ParseFile(fset, "src", src, 0)
2092 files := []*ast.File{f}
2094 // type-check using all possible importers
2095 for _, compiler := range []string{"gc", "gccgo", "source"} {
2098 Error: func(err error) {
2099 // we should only see the import error
2100 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
2101 t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
2105 Importer: importer.For(compiler, nil),
2109 Uses: make(map[*ast.Ident]Object),
2111 pkg, _ := conf.Check("p", fset, files, info)
2113 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
2117 imports := pkg.Imports()
2118 if len(imports) != 1 {
2119 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
2123 if imp.Name() != "foo" {
2124 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
2128 // verify that all uses of foo refer to the imported package foo (imp)
2129 for ident, obj := range info.Uses {
2130 if ident.Name == "foo" {
2131 if obj, ok := obj.(*PkgName); ok {
2132 if obj.Imported() != imp {
2133 t.Errorf("%s resolved to %v; want %v", ident, obj.Imported(), imp)
2136 t.Errorf("%s resolved to %v; want package name", ident, obj)
2143 func TestInstantiate(t *testing.T) {
2144 // eventually we like more tests but this is a start
2145 const src = "package p; type T[P any] *T[P]"
2146 pkg, err := pkgForMode(".", src, nil, 0)
2151 // type T should have one type parameter
2152 T := pkg.Scope().Lookup("T").Type().(*Named)
2153 if n := T.TypeParams().Len(); n != 1 {
2154 t.Fatalf("expected 1 type parameter; found %d", n)
2157 // instantiation should succeed (no endless recursion)
2158 // even with a nil *Checker
2159 res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
2164 // instantiated type should point to itself
2165 if p := res.Underlying().(*Pointer).Elem(); p != res {
2166 t.Fatalf("unexpected result type: %s points to %s", res, p)
2170 func TestInstantiateErrors(t *testing.T) {
2172 src string // by convention, T must be the type being instantiated
2174 wantAt int // -1 indicates no error
2176 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
2177 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
2178 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
2179 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
2182 for _, test := range tests {
2183 src := "package p; " + test.src
2184 pkg, err := pkgForMode(".", src, nil, 0)
2189 T := pkg.Scope().Lookup("T").Type().(*Named)
2191 _, err = Instantiate(nil, T, test.targs, true)
2193 t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
2196 var argErr *ArgumentError
2197 if !errors.As(err, &argErr) {
2198 t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
2201 if argErr.Index != test.wantAt {
2202 t.Errorf("Instantate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2207 func TestArgumentErrorUnwrapping(t *testing.T) {
2208 var err error = &ArgumentError{
2210 Err: Error{Msg: "test"},
2213 if !errors.As(err, &e) {
2214 t.Fatalf("error %v does not wrap types.Error", err)
2216 if e.Msg != "test" {
2217 t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2221 func TestInstanceIdentity(t *testing.T) {
2222 imports := make(testImporter)
2223 conf := Config{Importer: imports}
2224 makePkg := func(src string) {
2225 fset := token.NewFileSet()
2226 f, err := parser.ParseFile(fset, "", src, 0)
2231 pkg, err := conf.Check(name, fset, []*ast.File{f}, nil)
2237 makePkg(genericPkg + `lib; type T[P any] struct{}`)
2238 makePkg(genericPkg + `a; import "generic_lib"; var A generic_lib.T[int]`)
2239 makePkg(genericPkg + `b; import "generic_lib"; var B generic_lib.T[int]`)
2240 a := imports["generic_a"].Scope().Lookup("A")
2241 b := imports["generic_b"].Scope().Lookup("B")
2242 if !Identical(a.Type(), b.Type()) {
2243 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
2247 func TestImplements(t *testing.T) {
2251 type EmptyIface interface{}
2262 type Integer interface{
2263 int8 | int16 | int32 | int64
2266 type EmptyTypeSet interface{
2283 type Bad Bad // invalid type
2286 fset := token.NewFileSet()
2287 f, err := parser.ParseFile(fset, "p.go", src, 0)
2291 conf := Config{Error: func(error) {}}
2292 pkg, _ := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
2294 scope := pkg.Scope()
2296 EmptyIface = scope.Lookup("EmptyIface").Type().Underlying().(*Interface)
2297 I = scope.Lookup("I").Type().(*Named)
2298 II = I.Underlying().(*Interface)
2299 C = scope.Lookup("C").Type().(*Named)
2300 CI = C.Underlying().(*Interface)
2301 Integer = scope.Lookup("Integer").Type().Underlying().(*Interface)
2302 EmptyTypeSet = scope.Lookup("EmptyTypeSet").Type().Underlying().(*Interface)
2303 N1 = scope.Lookup("N1").Type()
2304 N1p = NewPointer(N1)
2305 N2 = scope.Lookup("N2").Type()
2306 N2p = NewPointer(N2)
2307 N3 = scope.Lookup("N3").Type()
2308 N4 = scope.Lookup("N4").Type()
2309 Bad = scope.Lookup("Bad").Type()
2321 {Typ[Int8], Integer, true},
2322 {Typ[Int64], Integer, true},
2323 {Typ[String], Integer, false},
2324 {EmptyTypeSet, II, true},
2325 {EmptyTypeSet, EmptyTypeSet, true},
2326 {Typ[Int], EmptyTypeSet, false},
2341 {Bad, EmptyIface, true},
2344 for _, test := range tests {
2345 if got := Implements(test.t, test.i); got != test.want {
2346 t.Errorf("Implements(%s, %s) = %t, want %t", test.t, test.i, got, test.want)