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"
26 // pkgFor parses and type checks the package specified by path and source,
27 // populating info if provided.
29 // If source begins with "package generic_" and type parameters are enabled,
30 // generic code is permitted.
31 func pkgFor(path, source string, info *Info) (*Package, error) {
32 mode := modeForSource(source)
33 return pkgForMode(path, source, info, mode)
36 func pkgForMode(path, source string, info *Info, mode parser.Mode) (*Package, error) {
37 fset := token.NewFileSet()
38 f, err := parser.ParseFile(fset, path, source, mode)
42 conf := Config{Importer: importer.Default()}
43 return conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
46 func mustTypecheck(t *testing.T, path, source string, info *Info) string {
47 pkg, err := pkgFor(path, source, info)
51 name = "package " + pkg.Name()
53 t.Fatalf("%s: didn't type-check (%s)", name, err)
58 // genericPkg is a prefix for packages that should be type checked with
60 const genericPkg = "package generic_"
62 func modeForSource(src string) parser.Mode {
63 if !strings.HasPrefix(src, genericPkg) {
64 return typeparams.DisallowParsing
69 func mayTypecheck(t *testing.T, path, source string, info *Info) (string, error) {
70 fset := token.NewFileSet()
71 mode := modeForSource(source)
72 f, err := parser.ParseFile(fset, path, source, mode)
73 if f == nil { // ignore errors unless f is nil
74 t.Fatalf("%s: unable to parse: %s", path, err)
77 Error: func(err error) {},
78 Importer: importer.Default(),
80 pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
81 return pkg.Name(), err
84 func TestValuesInfo(t *testing.T) {
85 var tests = []struct {
87 expr string // constant expression
88 typ string // constant type
89 val string // constant value
91 {`package a0; const _ = false`, `false`, `untyped bool`, `false`},
92 {`package a1; const _ = 0`, `0`, `untyped int`, `0`},
93 {`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
94 {`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
95 {`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
96 {`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
98 {`package b0; var _ = false`, `false`, `bool`, `false`},
99 {`package b1; var _ = 0`, `0`, `int`, `0`},
100 {`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
101 {`package b3; var _ = 0.`, `0.`, `float64`, `0`},
102 {`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
103 {`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
105 {`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
106 {`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
107 {`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
109 {`package c1a; var _ = int(0)`, `0`, `int`, `0`},
110 {`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
111 {`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
113 {`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
114 {`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
115 {`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
117 {`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
118 {`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
119 {`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
121 {`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
122 {`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
123 {`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
125 {`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
126 {`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
127 {`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
128 {`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
129 {`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
130 {`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
132 {`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
133 {`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
134 {`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
135 {`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
137 {`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
138 {`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
139 {`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
140 {`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
141 {`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
142 {`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
143 {`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
144 {`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
146 {`package f0 ; var _ float32 = 1e-200`, `1e-200`, `float32`, `0`},
147 {`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
148 {`package f2a; var _ float64 = 1e-2000`, `1e-2000`, `float64`, `0`},
149 {`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
150 {`package f2b; var _ = 1e-2000`, `1e-2000`, `float64`, `0`},
151 {`package f3b; var _ = -1e-2000`, `-1e-2000`, `float64`, `0`},
152 {`package f4 ; var _ complex64 = 1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
153 {`package f5 ; var _ complex64 = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
154 {`package f6a; var _ complex128 = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
155 {`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
156 {`package f6b; var _ = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
157 {`package f7b; var _ = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
159 {`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // issue #22341
160 {`package g1; var(j int32; s int; n = 1.0<<s == j)`, `1.0`, `int32`, `1`}, // issue #48422
163 for _, test := range tests {
165 Types: make(map[ast.Expr]TypeAndValue),
167 name := mustTypecheck(t, "ValuesInfo", test.src, &info)
169 // look for expression
171 for e := range info.Types {
172 if ExprString(e) == test.expr {
178 t.Errorf("package %s: no expression found for %s", name, test.expr)
181 tv := info.Types[expr]
183 // check that type is correct
184 if got := tv.Type.String(); got != test.typ {
185 t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
189 // if we have a constant, check that value is correct
191 if got := tv.Value.ExactString(); got != test.val {
192 t.Errorf("package %s: got value %s; want %s", name, got, test.val)
196 t.Errorf("package %s: no constant found; want %s", name, test.val)
202 func TestTypesInfo(t *testing.T) {
203 // Test sources that are not expected to typecheck must start with the broken prefix.
204 const broken = "package broken_"
206 var tests = []struct {
208 expr string // expression
209 typ string // value type
211 // single-valued expressions of untyped constants
212 {`package b0; var x interface{} = false`, `false`, `bool`},
213 {`package b1; var x interface{} = 0`, `0`, `int`},
214 {`package b2; var x interface{} = 0.`, `0.`, `float64`},
215 {`package b3; var x interface{} = 0i`, `0i`, `complex128`},
216 {`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
219 {`package n0; var _ *int = nil`, `nil`, `untyped nil`},
220 {`package n1; var _ func() = nil`, `nil`, `untyped nil`},
221 {`package n2; var _ []byte = nil`, `nil`, `untyped nil`},
222 {`package n3; var _ map[int]int = nil`, `nil`, `untyped nil`},
223 {`package n4; var _ chan int = nil`, `nil`, `untyped nil`},
224 {`package n5; var _ interface{} = nil`, `nil`, `untyped nil`},
225 {`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `untyped nil`},
227 {`package n10; var (x *int; _ = x == nil)`, `nil`, `untyped nil`},
228 {`package n11; var (x func(); _ = x == nil)`, `nil`, `untyped nil`},
229 {`package n12; var (x []byte; _ = x == nil)`, `nil`, `untyped nil`},
230 {`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `untyped nil`},
231 {`package n14; var (x chan int; _ = x == nil)`, `nil`, `untyped nil`},
232 {`package n15; var (x interface{}; _ = x == nil)`, `nil`, `untyped nil`},
233 {`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `untyped nil`},
235 {`package n20; var _ = (*int)(nil)`, `nil`, `untyped nil`},
236 {`package n21; var _ = (func())(nil)`, `nil`, `untyped nil`},
237 {`package n22; var _ = ([]byte)(nil)`, `nil`, `untyped nil`},
238 {`package n23; var _ = (map[int]int)(nil)`, `nil`, `untyped nil`},
239 {`package n24; var _ = (chan int)(nil)`, `nil`, `untyped nil`},
240 {`package n25; var _ = (interface{})(nil)`, `nil`, `untyped nil`},
241 {`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `untyped nil`},
243 {`package n30; func f(*int) { f(nil) }`, `nil`, `untyped nil`},
244 {`package n31; func f(func()) { f(nil) }`, `nil`, `untyped nil`},
245 {`package n32; func f([]byte) { f(nil) }`, `nil`, `untyped nil`},
246 {`package n33; func f(map[int]int) { f(nil) }`, `nil`, `untyped nil`},
247 {`package n34; func f(chan int) { f(nil) }`, `nil`, `untyped nil`},
248 {`package n35; func f(interface{}) { f(nil) }`, `nil`, `untyped nil`},
249 {`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `untyped nil`},
251 // comma-ok expressions
252 {`package p0; var x interface{}; var _, _ = x.(int)`,
256 {`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
260 {`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
262 `(complex128, p2a.mybool)`,
264 {`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
266 `(complex128, bool)`,
268 {`package p3; var c chan string; var _, _ = <-c`,
274 {`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
278 {`package issue6796_b; var c chan string; var _, _ = (<-c)`,
282 {`package issue6796_c; var c chan string; var _, _ = (<-c)`,
286 {`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
290 {`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
296 {`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
300 {`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
304 {`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
308 {`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
312 {`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
316 {`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
322 {`package issue28277_a; func f(...int)`,
326 {`package issue28277_b; func f(a, b int, c ...[]struct{})`,
332 {`package issue47243_a; var x int32; var _ = x << 3`, `3`, `untyped int`},
333 {`package issue47243_b; var x int32; var _ = x << 3.`, `3.`, `uint`}, // issue 47410: should be untyped float
334 {`package issue47243_c; var x int32; var _ = 1 << x`, `1 << x`, `int`},
335 {`package issue47243_d; var x int32; var _ = 1 << x`, `1`, `int`},
336 {`package issue47243_e; var x int32; var _ = 1 << 2`, `1`, `untyped int`},
337 {`package issue47243_f; var x int32; var _ = 1 << 2`, `2`, `untyped int`},
338 {`package issue47243_g; var x int32; var _ = int(1) << 2`, `2`, `untyped int`},
339 {`package issue47243_h; var x int32; var _ = 1 << (2 << x)`, `1`, `int`},
340 {`package issue47243_i; var x int32; var _ = 1 << (2 << x)`, `(2 << x)`, `untyped int`},
341 {`package issue47243_j; var x int32; var _ = 1 << (2 << x)`, `2`, `untyped int`},
343 // tests for broken code that doesn't parse or type-check
344 {broken + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
345 {broken + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
346 {broken + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a; f: b;}}`, `b`, `string`},
347 {broken + `x3; var x = panic("");`, `panic`, `func(interface{})`},
348 {`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
349 {broken + `x5; func _() { var x map[string][...]int; x = map[string][...]int{"": {1,2,3}} }`, `x`, `map[string]invalid type`},
351 // parameterized functions
352 {genericPkg + `p0; func f[T any](T) {}; var _ = f[int]`, `f`, `func[T any](T)`},
353 {genericPkg + `p1; func f[T any](T) {}; var _ = f[int]`, `f[int]`, `func(int)`},
354 {genericPkg + `p2; func f[T any](T) {}; func _() { f(42) }`, `f`, `func(int)`},
355 {genericPkg + `p3; func f[T any](T) {}; func _() { f[int](42) }`, `f[int]`, `func(int)`},
356 {genericPkg + `p4; func f[T any](T) {}; func _() { f[int](42) }`, `f`, `func[T any](T)`},
357 {genericPkg + `p5; func f[T any](T) {}; func _() { f(42) }`, `f(42)`, `()`},
360 {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
361 {genericPkg + `t1; type t[P any] int; var _ t[int]`, `t`, `generic_t1.t[P any]`},
362 {genericPkg + `t2; type t[P interface{}] int; var _ t[int]`, `t`, `generic_t2.t[P interface{}]`},
363 {genericPkg + `t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `generic_t3.t[P, Q interface{}]`},
365 // TODO (rFindley): compare with types2, which resolves the type broken_t4.t[P₁, Q₂ interface{m()}] here
366 {broken + `t4; type t[P, Q interface{ m() }] int; var _ t[int, int]`, `t`, `broken_t4.t`},
368 // instantiated types must be sanitized
369 {genericPkg + `g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `generic_g0.t[int]`},
372 {genericPkg + `issue45096; func _[T interface{ ~int8 | ~int16 | ~int32 }](x T) { _ = x < 0 }`, `0`, `T`},
375 {`package p; import "unsafe"; type S struct { f int }; var s S; var _ = unsafe.Offsetof(s.f)`, `s.f`, `int`},
378 {genericPkg + `u0a; func _[_ interface{int}]() {}`, `int`, `int`},
379 {genericPkg + `u1a; func _[_ interface{~int}]() {}`, `~int`, `~int`},
380 {genericPkg + `u2a; func _[_ interface{int|string}]() {}`, `int | string`, `int|string`},
381 {genericPkg + `u3a; func _[_ interface{int|string|~bool}]() {}`, `int | string | ~bool`, `int|string|~bool`},
382 {genericPkg + `u3a; func _[_ interface{int|string|~bool}]() {}`, `int | string`, `int|string`},
383 {genericPkg + `u3a; func _[_ interface{int|string|~bool}]() {}`, `~bool`, `~bool`},
384 {genericPkg + `u3a; func _[_ interface{int|string|~float64|~bool}]() {}`, `int | string | ~float64`, `int|string|~float64`},
386 {genericPkg + `u0b; func _[_ int]() {}`, `int`, `int`},
387 {genericPkg + `u1b; func _[_ ~int]() {}`, `~int`, `~int`},
388 {genericPkg + `u2b; func _[_ int|string]() {}`, `int | string`, `int|string`},
389 {genericPkg + `u3b; func _[_ int|string|~bool]() {}`, `int | string | ~bool`, `int|string|~bool`},
390 {genericPkg + `u3b; func _[_ int|string|~bool]() {}`, `int | string`, `int|string`},
391 {genericPkg + `u3b; func _[_ int|string|~bool]() {}`, `~bool`, `~bool`},
392 {genericPkg + `u3b; func _[_ int|string|~float64|~bool]() {}`, `int | string | ~float64`, `int|string|~float64`},
394 {genericPkg + `u0c; type _ interface{int}`, `int`, `int`},
395 {genericPkg + `u1c; type _ interface{~int}`, `~int`, `~int`},
396 {genericPkg + `u2c; type _ interface{int|string}`, `int | string`, `int|string`},
397 {genericPkg + `u3c; type _ interface{int|string|~bool}`, `int | string | ~bool`, `int|string|~bool`},
398 {genericPkg + `u3c; type _ interface{int|string|~bool}`, `int | string`, `int|string`},
399 {genericPkg + `u3c; type _ interface{int|string|~bool}`, `~bool`, `~bool`},
400 {genericPkg + `u3c; type _ interface{int|string|~float64|~bool}`, `int | string | ~float64`, `int|string|~float64`},
403 for _, test := range tests {
404 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
406 if strings.HasPrefix(test.src, broken) {
408 name, err = mayTypecheck(t, "TypesInfo", test.src, &info)
410 t.Errorf("package %s: expected to fail but passed", name)
414 name = mustTypecheck(t, "TypesInfo", test.src, &info)
417 // look for expression type
419 for e, tv := range info.Types {
420 if ExprString(e) == test.expr {
426 t.Errorf("package %s: no type found for %s", name, test.expr)
430 // check that type is correct
431 if got := typ.String(); got != test.typ {
432 t.Errorf("package %s: got %s; want %s", name, got, test.typ)
437 func TestInstanceInfo(t *testing.T) {
438 const lib = `package lib
445 type testInst struct {
451 var tests = []struct {
453 instances []testInst // recorded instances in source order
455 {`package p0; func f[T any](T) {}; func _() { f(42) }`,
456 []testInst{{`f`, []string{`int`}, `func(int)`}},
458 {`package p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
459 []testInst{{`f`, []string{`rune`}, `func(rune) rune`}},
461 {`package p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
462 []testInst{{`f`, []string{`complex128`}, `func(...complex128) complex128`}},
464 {`package p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
465 []testInst{{`f`, []string{`float64`, `string`, `byte`}, `func(float64, *string, []byte)`}},
467 {`package p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
468 []testInst{{`f`, []string{`float64`, `byte`}, `func(float64, *byte, ...[]byte)`}},
471 {`package s1; func f[T any, P interface{*T}](x T) {}; func _(x string) { f(x) }`,
472 []testInst{{`f`, []string{`string`, `*string`}, `func(x string)`}},
474 {`package s2; func f[T any, P interface{*T}](x []T) {}; func _(x []int) { f(x) }`,
475 []testInst{{`f`, []string{`int`, `*int`}, `func(x []int)`}},
477 {`package s3; type C[T any] interface{chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
479 {`C`, []string{`T`}, `interface{chan<- T}`},
480 {`f`, []string{`int`, `chan<- int`}, `func(x []int)`},
483 {`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) }`,
485 {`C`, []string{`T`}, `interface{chan<- T}`},
486 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
487 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func(x []int)`},
491 {`package t1; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = f[string] }`,
492 []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
494 {`package t2; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = (f[string]) }`,
495 []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
497 {`package t3; type C[T any] interface{chan<- T}; func f[T any, P C[T], Q C[[]*P]]() []T { return nil }; func _() { _ = f[int] }`,
499 {`C`, []string{`T`}, `interface{chan<- T}`},
500 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
501 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
504 {`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]) }`,
506 {`C`, []string{`T`}, `interface{chan<- T}`},
507 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
508 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
511 {`package i0; import "lib"; func _() { lib.F(42) }`,
512 []testInst{{`F`, []string{`int`}, `func(int)`}},
515 {`package duplfunc0; func f[T any](T) {}; func _() { f(42); f("foo"); f[int](3) }`,
517 {`f`, []string{`int`}, `func(int)`},
518 {`f`, []string{`string`}, `func(string)`},
519 {`f`, []string{`int`}, `func(int)`},
522 {`package duplfunc1; import "lib"; func _() { lib.F(42); lib.F("foo"); lib.F(3) }`,
524 {`F`, []string{`int`}, `func(int)`},
525 {`F`, []string{`string`}, `func(string)`},
526 {`F`, []string{`int`}, `func(int)`},
530 {`package type0; type T[P interface{~int}] struct{ x P }; var _ T[int]`,
531 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
533 {`package type1; type T[P interface{~int}] struct{ x P }; var _ (T[int])`,
534 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
536 {`package type2; type T[P interface{~int}] struct{ x P }; var _ T[(int)]`,
537 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
539 {`package type3; type T[P1 interface{~[]P2}, P2 any] struct{ x P1; y P2 }; var _ T[[]int, int]`,
540 []testInst{{`T`, []string{`[]int`, `int`}, `struct{x []int; y int}`}},
542 {`package type4; import "lib"; var _ lib.T[int]`,
543 []testInst{{`T`, []string{`int`}, `[]int`}},
546 {`package dupltype0; type T[P interface{~int}] struct{ x P }; var x T[int]; var y T[int]`,
548 {`T`, []string{`int`}, `struct{x int}`},
549 {`T`, []string{`int`}, `struct{x int}`},
552 {`package dupltype1; type T[P ~int] struct{ x P }; func (r *T[Q]) add(z T[Q]) { r.x += z.x }`,
554 {`T`, []string{`Q`}, `struct{x Q}`},
555 {`T`, []string{`Q`}, `struct{x Q}`},
558 {`package dupltype1; import "lib"; var x lib.T[int]; var y lib.T[int]; var z lib.T[string]`,
560 {`T`, []string{`int`}, `[]int`},
561 {`T`, []string{`int`}, `[]int`},
562 {`T`, []string{`string`}, `[]string`},
567 for _, test := range tests {
568 imports := make(testImporter)
569 conf := Config{Importer: imports}
570 instMap := make(map[*ast.Ident]Instance)
571 useMap := make(map[*ast.Ident]Object)
572 makePkg := func(src string) *Package {
573 f, err := parser.ParseFile(fset, "p.go", src, 0)
577 pkg, err := conf.Check("", fset, []*ast.File{f}, &Info{Instances: instMap, Uses: useMap})
581 imports[pkg.Name()] = pkg
585 pkg := makePkg(test.src)
587 t.Run(pkg.Name(), func(t *testing.T) {
588 // Sort instances in source order for stability.
589 instances := sortedInstances(instMap)
590 if got, want := len(instances), len(test.instances); got != want {
591 t.Fatalf("got %d instances, want %d", got, want)
594 // Pairwise compare with the expected instances.
595 for ii, inst := range instances {
597 for i := 0; i < inst.Inst.TypeArgs.Len(); i++ {
598 targs = append(targs, inst.Inst.TypeArgs.At(i))
600 typ := inst.Inst.Type
602 testInst := test.instances[ii]
603 if got := inst.Ident.Name; got != testInst.name {
604 t.Fatalf("got name %s, want %s", got, testInst.name)
606 if len(targs) != len(testInst.targs) {
607 t.Fatalf("got %d type arguments; want %d", len(targs), len(testInst.targs))
609 for i, targ := range targs {
610 if got := targ.String(); got != testInst.targs[i] {
611 t.Errorf("type argument %d: got %s; want %s", i, got, testInst.targs[i])
614 if got := typ.Underlying().String(); got != testInst.typ {
615 t.Errorf("package %s: got %s; want %s", pkg.Name(), got, testInst.typ)
618 // Verify the invariant that re-instantiating the corresponding generic
619 // type with TypeArgs results in an identical instance.
620 ptype := useMap[inst.Ident].Type()
621 lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
622 if lister == nil || lister.TypeParams().Len() == 0 {
623 t.Fatalf("info.Types[%v] = %v, want parameterized type", inst.Ident, ptype)
625 inst2, err := Instantiate(nil, ptype, targs, true)
627 t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
629 if !Identical(inst.Inst.Type, inst2) {
630 t.Errorf("%v and %v are not identical", inst.Inst.Type, inst2)
637 type recordedInstance struct {
642 func sortedInstances(m map[*ast.Ident]Instance) (instances []recordedInstance) {
643 for id, inst := range m {
644 instances = append(instances, recordedInstance{id, inst})
646 sort.Slice(instances, func(i, j int) bool {
647 return instances[i].Ident.Pos() < instances[j].Ident.Pos()
652 func TestDefsInfo(t *testing.T) {
653 var tests = []struct {
658 {`package p0; const x = 42`, `x`, `const p0.x untyped int`},
659 {`package p1; const x int = 42`, `x`, `const p1.x int`},
660 {`package p2; var x int`, `x`, `var p2.x int`},
661 {`package p3; type x int`, `x`, `type p3.x int`},
662 {`package p4; func f()`, `f`, `func p4.f()`},
663 {`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
665 // Tests using generics.
666 {`package generic_g0; type x[T any] int`, `x`, `type generic_g0.x[T any] int`},
667 {`package generic_g1; func f[T any]() {}`, `f`, `func generic_g1.f[T any]()`},
668 {`package generic_g2; type x[T any] int; func (*x[_]) m() {}`, `m`, `func (*generic_g2.x[_]).m()`},
671 for _, test := range tests {
673 Defs: make(map[*ast.Ident]Object),
675 name := mustTypecheck(t, "DefsInfo", test.src, &info)
679 for id, obj := range info.Defs {
680 if id.Name == test.obj {
686 t.Errorf("package %s: %s not found", name, test.obj)
690 if got := def.String(); got != test.want {
691 t.Errorf("package %s: got %s; want %s", name, got, test.want)
696 func TestUsesInfo(t *testing.T) {
697 var tests = []struct {
702 {`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
703 {`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
704 {`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
705 {`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
706 {`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
708 // Tests using generics.
709 {`package generic_g0; func _[T any]() { _ = x }; const x = 42`, `x`, `const generic_g0.x untyped int`},
710 {`package generic_g1; func _[T any](x T) { }`, `T`, `type parameter T any`},
711 {`package generic_g2; type N[A any] int; var _ N[int]`, `N`, `type generic_g2.N[A any] int`},
712 {`package generic_g3; type N[A any] int; func (N[_]) m() {}`, `N`, `type generic_g3.N[A any] int`},
714 // Uses of fields are instantiated.
715 {`package generic_s1; type N[A any] struct{ a A }; var f = N[int]{}.a`, `a`, `field a int`},
716 {`package generic_s1; type N[A any] struct{ a A }; func (r N[B]) m(b B) { r.a = b }`, `a`, `field a B`},
718 // Uses of methods are uses of the instantiated method.
719 {`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()`},
720 {`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()`},
721 {`package generic_m2; func _[A any](v interface{ m() A }) { v.m() }`, `m`, `func (interface).m() A`},
722 {`package generic_m3; func f[A any]() interface{ m() A } { return nil }; var _ = f[int]().m()`, `m`, `func (interface).m() int`},
723 {`package generic_m4; type T[A any] func() interface{ m() A }; var x T[int]; var y = x().m`, `m`, `func (interface).m() int`},
724 {`package generic_m5; type T[A any] interface{ m() A }; func _[B any](t T[B]) { t.m() }`, `m`, `func (generic_m5.T[B]).m() B`},
725 {`package generic_m6; type T[A any] interface{ m() }; func _[B any](t T[B]) { t.m() }`, `m`, `func (generic_m6.T[B]).m()`},
726 {`package generic_m7; type T[A any] interface{ m() A }; func _(t T[int]) { t.m() }`, `m`, `func (generic_m7.T[int]).m() int`},
727 {`package generic_m8; type T[A any] interface{ m() }; func _(t T[int]) { t.m() }`, `m`, `func (generic_m8.T[int]).m()`},
728 {`package generic_m9; type T[A any] interface{ m() }; func _(t T[int]) { _ = t.m }`, `m`, `func (generic_m9.T[int]).m()`},
730 `package generic_m10; type E[A any] interface{ m() }; type T[B any] interface{ E[B]; n() }; func _(t T[int]) { t.m() }`,
732 `func (generic_m10.E[int]).m()`,
736 for _, test := range tests {
738 Uses: make(map[*ast.Ident]Object),
740 name := mustTypecheck(t, "UsesInfo", test.src, &info)
744 for id, obj := range info.Uses {
745 if id.Name == test.obj {
747 panic(fmt.Sprintf("multiple uses of %q", id.Name))
753 t.Errorf("package %s: %s not found", name, test.obj)
757 if got := use.String(); got != test.want {
758 t.Errorf("package %s: got %s; want %s", name, got, test.want)
763 func TestGenericMethodInfo(t *testing.T) {
768 func (r N[B]) m() { r.m(); r.n() }
770 func (r *N[C]) n() { }
772 fset := token.NewFileSet()
773 f, err := parser.ParseFile(fset, "p.go", src, 0)
778 Defs: make(map[*ast.Ident]Object),
779 Uses: make(map[*ast.Ident]Object),
780 Selections: make(map[*ast.SelectorExpr]*Selection),
783 pkg, err := conf.Check("p", fset, []*ast.File{f}, &info)
788 N := pkg.Scope().Lookup("N").Type().(*Named)
790 // Find the generic methods stored on N.
791 gm, gn := N.Method(0), N.Method(1)
792 if gm.Name() == "n" {
796 // Collect objects from info.
797 var dm, dn *Func // the declared methods
798 var dmm, dmn *Func // the methods used in the body of m
799 for _, decl := range f.Decls {
800 fdecl, ok := decl.(*ast.FuncDecl)
804 def := info.Defs[fdecl.Name].(*Func)
805 switch fdecl.Name.Name {
808 ast.Inspect(fdecl.Body, func(n ast.Node) bool {
809 if call, ok := n.(*ast.CallExpr); ok {
810 sel := call.Fun.(*ast.SelectorExpr)
811 use := info.Uses[sel.Sel].(*Func)
812 selection := info.Selections[sel]
813 if selection.Kind() != MethodVal {
814 t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
816 if selection.Obj() != use {
817 t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
819 switch sel.Sel.Name {
834 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
837 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
840 t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
843 t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
847 func TestImplicitsInfo(t *testing.T) {
848 testenv.MustHaveGoBuild(t)
850 var tests = []struct {
854 {`package p2; import . "fmt"; var _ = Println`, ""}, // no Implicits entry
855 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
856 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
858 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
859 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
860 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
861 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
863 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
864 {`package p8; func f(int) {}`, "field: var int"},
865 {`package p9; func f() (complex64) { return 0 }`, "field: var complex64"},
866 {`package p10; type T struct{}; func (*T) f() {}`, "field: var *p10.T"},
868 // Tests using generics.
869 {`package generic_f0; func f[T any](x int) {}`, ""}, // no Implicits entry
870 {`package generic_f1; func f[T any](int) {}`, "field: var int"},
871 {`package generic_f2; func f[T any](T) {}`, "field: var T"},
872 {`package generic_f3; func f[T any]() (complex64) { return 0 }`, "field: var complex64"},
873 {`package generic_f4; func f[T any](t T) (T) { return t }`, "field: var T"},
874 {`package generic_t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var *generic_t0.T[_]"},
875 {`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]"},
876 {`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]"},
877 {`package generic_t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
880 for _, test := range tests {
882 Implicits: make(map[ast.Node]Object),
884 name := mustTypecheck(t, "ImplicitsInfo", test.src, &info)
886 // the test cases expect at most one Implicits entry
887 if len(info.Implicits) > 1 {
888 t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
892 // extract Implicits entry, if any
894 for n, obj := range info.Implicits {
895 switch x := n.(type) {
896 case *ast.ImportSpec:
898 case *ast.CaseClause:
903 t.Fatalf("package %s: unexpected %T", name, x)
905 got += ": " + obj.String()
909 if got != test.want {
910 t.Errorf("package %s: got %q; want %q", name, got, test.want)
915 func predString(tv TypeAndValue) string {
917 pred := func(b bool, s string) {
920 buf.WriteString(", ")
926 pred(tv.IsVoid(), "void")
927 pred(tv.IsType(), "type")
928 pred(tv.IsBuiltin(), "builtin")
929 pred(tv.IsValue() && tv.Value != nil, "const")
930 pred(tv.IsValue() && tv.Value == nil, "value")
931 pred(tv.IsNil(), "nil")
932 pred(tv.Addressable(), "addressable")
933 pred(tv.Assignable(), "assignable")
934 pred(tv.HasOk(), "hasOk")
942 func TestPredicatesInfo(t *testing.T) {
943 testenv.MustHaveGoBuild(t)
945 var tests = []struct {
951 {`package n0; func f() { f() }`, `f()`, `void`},
954 {`package t0; type _ int`, `int`, `type`},
955 {`package t1; type _ []int`, `[]int`, `type`},
956 {`package t2; type _ func()`, `func()`, `type`},
957 {`package t3; type _ func(int)`, `int`, `type`},
958 {`package t3; type _ func(...int)`, `...int`, `type`},
961 {`package b0; var _ = len("")`, `len`, `builtin`},
962 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
965 {`package c0; var _ = 42`, `42`, `const`},
966 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
967 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
970 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
971 {`package v1; var _ = &[]int{1}`, `([]int literal)`, `value`},
972 {`package v2; var _ = func(){}`, `(func() literal)`, `value`},
973 {`package v4; func f() { _ = f }`, `f`, `value`},
974 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
975 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
977 // addressable (and thus assignable) operands
978 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
979 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
980 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
981 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
982 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
983 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
984 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
985 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
986 // composite literals are not addressable
988 // assignable but not addressable values
989 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
990 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
993 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
994 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
997 // - package names are collected in the Uses map
998 // - identifiers being declared are collected in the Defs map
999 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
1000 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
1001 {`package m2; const c = 0`, `c`, `<missing>`},
1002 {`package m3; type T int`, `T`, `<missing>`},
1003 {`package m4; var v int`, `v`, `<missing>`},
1004 {`package m5; func f() {}`, `f`, `<missing>`},
1005 {`package m6; func _(x int) {}`, `x`, `<missing>`},
1006 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
1007 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
1010 for _, test := range tests {
1011 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
1012 name := mustTypecheck(t, "PredicatesInfo", test.src, &info)
1014 // look for expression predicates
1016 for e, tv := range info.Types {
1017 //println(name, ExprString(e))
1018 if ExprString(e) == test.expr {
1019 got = predString(tv)
1024 if got != test.pred {
1025 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
1030 func TestScopesInfo(t *testing.T) {
1031 testenv.MustHaveGoBuild(t)
1033 var tests = []struct {
1035 scopes []string // list of scope descriptors of the form kind:varlist
1037 {`package p0`, []string{
1040 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
1043 {`package p2; func _() {}`, []string{
1046 {`package p3; func _(x, y int) {}`, []string{
1047 "file:", "func:x y",
1049 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
1050 "file:", "func:x y z", // redeclaration of x
1052 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
1053 "file:", "func:u x y",
1055 {`package p6; func _() { { var x int; _ = x } }`, []string{
1056 "file:", "func:", "block:x",
1058 {`package p7; func _() { if true {} }`, []string{
1059 "file:", "func:", "if:", "block:",
1061 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
1062 "file:", "func:", "if:x", "block:y",
1064 {`package p9; func _() { switch x := 0; x {} }`, []string{
1065 "file:", "func:", "switch:x",
1067 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
1068 "file:", "func:", "switch:x", "case:y", "case:",
1070 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
1071 "file:", "func:t", "type switch:",
1073 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
1074 "file:", "func:t", "type switch:t",
1076 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
1077 "file:", "func:t", "type switch:", "case:x", // x implicitly declared
1079 {`package p14; func _() { select{} }`, []string{
1082 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
1083 "file:", "func:c", "comm:",
1085 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
1086 "file:", "func:c", "comm:i x",
1088 {`package p17; func _() { for{} }`, []string{
1089 "file:", "func:", "for:", "block:",
1091 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
1092 "file:", "func:n", "for:i", "block:",
1094 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
1095 "file:", "func:a", "range:i", "block:",
1097 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
1098 "file:", "func:a", "range:i x", "block:",
1102 for _, test := range tests {
1103 info := Info{Scopes: make(map[ast.Node]*Scope)}
1104 name := mustTypecheck(t, "ScopesInfo", test.src, &info)
1106 // number of scopes must match
1107 if len(info.Scopes) != len(test.scopes) {
1108 t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
1111 // scope descriptions must match
1112 for node, scope := range info.Scopes {
1113 kind := "<unknown node kind>"
1114 switch node.(type) {
1119 case *ast.BlockStmt:
1123 case *ast.SwitchStmt:
1125 case *ast.TypeSwitchStmt:
1126 kind = "type switch"
1127 case *ast.CaseClause:
1129 case *ast.CommClause:
1133 case *ast.RangeStmt:
1137 // look for matching scope description
1138 desc := kind + ":" + strings.Join(scope.Names(), " ")
1140 for _, d := range test.scopes {
1147 t.Errorf("package %s: no matching scope found for %s", name, desc)
1153 func TestInitOrderInfo(t *testing.T) {
1154 var tests = []struct {
1158 {`package p0; var (x = 1; y = x)`, []string{
1161 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
1162 "a = 1", "b = 2", "c = 3",
1164 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
1165 "a = 1", "b = 2", "c = 3",
1167 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
1168 "_ = f()", // blank var
1170 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
1171 "a = 0", "z = 0", "y = z", "x = y",
1173 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
1174 "a, _ = m[0]", // blank var
1176 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
1177 "z = 0", "a, b = f()",
1179 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
1180 "b = 1", "a = (func() int literal)()",
1182 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
1183 "c = 1", "a, b = (func() (_, _ int) literal)()",
1185 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1188 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1189 "a = 0", "b = 0", "c = 0", "d = c + b",
1191 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
1192 "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
1194 // emit an initializer for n:1 initializations only once (not for each node
1195 // on the lhs which may appear in different order in the dependency graph)
1196 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
1197 "b = 0", "x, y = m[0]", "a = x",
1199 // test case from spec section on package initialization
1213 "d = 3", "b = f()", "c = f()", "a = c + b",
1215 // test case for issue 7131
1219 func next() int { counter++; return counter }
1222 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1225 var b, c = next(), next()
1226 var d, e, f = next(), next(), next()
1228 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1230 // test case for issue 10709
1240 func (T) m() int { return 0 }
1242 func makeT(n int) T {
1248 "t = makeT(0)", "v = t.m()",
1250 // test case for issue 10709: same as test before, but variable decls swapped
1260 func (T) m() int { return 0 }
1262 func makeT(n int) T {
1268 "t = makeT(0)", "v = t.m()",
1270 // another candidate possibly causing problems with issue 10709
1275 func f1() int { return g1() }
1276 func g1() int { f1(); return x1 }
1282 func f2() int { return g2() }
1283 func g2() int { return x2 }
1285 var x2 = 0`, []string{
1286 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1290 for _, test := range tests {
1292 name := mustTypecheck(t, "InitOrderInfo", test.src, &info)
1294 // number of initializers must match
1295 if len(info.InitOrder) != len(test.inits) {
1296 t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1300 // initializers must match
1301 for i, want := range test.inits {
1302 got := info.InitOrder[i].String()
1304 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1311 func TestMultiFileInitOrder(t *testing.T) {
1312 fset := token.NewFileSet()
1313 mustParse := func(src string) *ast.File {
1314 f, err := parser.ParseFile(fset, "main", src, 0)
1321 fileA := mustParse(`package main; var a = 1`)
1322 fileB := mustParse(`package main; var b = 2`)
1324 // The initialization order must not depend on the parse
1325 // order of the files, only on the presentation order to
1326 // the type-checker.
1327 for _, test := range []struct {
1331 {[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
1332 {[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
1335 if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
1338 if got := fmt.Sprint(info.InitOrder); got != test.want {
1339 t.Fatalf("got %s; want %s", got, test.want)
1344 func TestFiles(t *testing.T) {
1345 var sources = []string{
1346 "package p; type T struct{}; func (T) m1() {}",
1347 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1348 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1353 fset := token.NewFileSet()
1354 pkg := NewPackage("p", "p")
1356 check := NewChecker(&conf, fset, pkg, &info)
1358 for i, src := range sources {
1359 filename := fmt.Sprintf("sources%d", i)
1360 f, err := parser.ParseFile(fset, filename, src, 0)
1364 if err := check.Files([]*ast.File{f}); err != nil {
1369 // check InitOrder is [x y]
1371 for _, init := range info.InitOrder {
1372 for _, v := range init.Lhs {
1373 vars = append(vars, v.Name())
1376 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1377 t.Errorf("InitOrder == %s, want %s", got, want)
1381 type testImporter map[string]*Package
1383 func (m testImporter) Import(path string) (*Package, error) {
1384 if pkg := m[path]; pkg != nil {
1387 return nil, fmt.Errorf("package %q not found", path)
1390 func TestSelection(t *testing.T) {
1391 selections := make(map[*ast.SelectorExpr]*Selection)
1393 fset := token.NewFileSet()
1394 imports := make(testImporter)
1395 conf := Config{Importer: imports}
1396 makePkg := func(path, src string) {
1397 f, err := parser.ParseFile(fset, path+".go", src, 0)
1401 pkg, err := conf.Check(path, fset, []*ast.File{f}, &Info{Selections: selections})
1435 type G[P any] struct {
1447 // qualified identifiers
1485 // method expressions
1493 wantOut := map[string][2]string{
1494 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1496 "A{}.B": {"field (main.A) B *main.B", ".[0]"},
1497 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1498 "A{}.C": {"field (main.A) C main.C", ".[1]"},
1499 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1500 "A{}.b": {"field (main.A) b int", "->[0 0]"},
1501 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1502 "A{}.c": {"field (main.A) c int", ".[1 0]"},
1503 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1504 "Inst.p": {"field (main.G[int]) p int", ".[0]"},
1506 "A{}.f": {"method (main.A) f(int)", "->[0 0]"},
1507 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1508 "A{}.g": {"method (main.A) g()", ".[1 0]"},
1509 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1510 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1511 "B{}.f": {"method (main.B) f(int)", ".[0]"},
1512 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1513 "C{}.g": {"method (main.C) g()", ".[0]"},
1514 "new(C).g": {"method (*main.C) g()", "->[0]"},
1515 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1516 "Inst.m": {"method (main.G[int]) m(int)", ".[0]"},
1518 "A.f": {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1519 "(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1520 "B.f": {"method expr (main.B) f(main.B, int)", ".[0]"},
1521 "(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1522 "G[string].m": {"method expr (main.G[string]) m(main.G[string], string)", ".[0]"},
1523 "G[string]{}.p": {"field (main.G[string]) p string", ".[0]"},
1526 makePkg("lib", libSrc)
1527 makePkg("main", mainSrc)
1529 for e, sel := range selections {
1530 _ = sel.String() // assertion: must not panic
1532 start := fset.Position(e.Pos()).Offset
1533 end := fset.Position(e.End()).Offset
1534 syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1542 fmt.Sprintf("%s%v", direct, sel.Index()),
1544 want := wantOut[syntax]
1546 t.Errorf("%s: got %q; want %q", syntax, got, want)
1548 delete(wantOut, syntax)
1550 // We must explicitly assert properties of the
1551 // Signature's receiver since it doesn't participate
1552 // in Identical() or String().
1553 sig, _ := sel.Type().(*Signature)
1554 if sel.Kind() == MethodVal {
1555 got := sig.Recv().Type()
1557 if !Identical(got, want) {
1558 t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
1560 } else if sig != nil && sig.Recv() != nil {
1561 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1564 // Assert that all wantOut entries were used exactly once.
1565 for syntax := range wantOut {
1566 t.Errorf("no ast.Selection found with syntax %q", syntax)
1570 func TestIssue8518(t *testing.T) {
1571 fset := token.NewFileSet()
1572 imports := make(testImporter)
1574 Error: func(err error) { t.Log(err) }, // don't exit after first error
1577 makePkg := func(path, src string) {
1578 f, err := parser.ParseFile(fset, path, src, 0)
1582 pkg, _ := conf.Check(path, fset, []*ast.File{f}, nil) // errors logged via conf.Error
1590 const C2 = missing.C
1600 makePkg("a", libSrc)
1601 makePkg("main", mainSrc) // don't crash when type-checking this package
1604 func TestLookupFieldOrMethodOnNil(t *testing.T) {
1605 // LookupFieldOrMethod on a nil type is expected to produce a run-time panic.
1607 const want = "LookupFieldOrMethod on nil type"
1609 if s, ok := p.(string); !ok || s != want {
1610 t.Fatalf("got %v, want %s", p, want)
1613 LookupFieldOrMethod(nil, false, nil, "")
1616 func TestLookupFieldOrMethod(t *testing.T) {
1617 // Test cases assume a lookup of the form a.f or x.f, where a stands for an
1618 // addressable value, and x for a non-addressable value (even though a variable
1619 // for ease of test case writing).
1621 // Should be kept in sync with TestMethodSet.
1622 var tests = []struct {
1629 {"var x T; type T struct{}", false, nil, false},
1630 {"var x T; type T struct{ f int }", true, []int{0}, false},
1631 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1634 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1635 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1636 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1637 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1640 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1641 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1643 // outside methodset
1644 // (*T).f method exists, but value of type T is not addressable
1645 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1648 for _, test := range tests {
1649 pkg, err := pkgFor("test", "package p;"+test.src, nil)
1651 t.Errorf("%s: incorrect test case: %s", test.src, err)
1655 obj := pkg.Scope().Lookup("a")
1657 if obj = pkg.Scope().Lookup("x"); obj == nil {
1658 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1663 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1664 if (f != nil) != test.found {
1666 t.Errorf("%s: got no object; want one", test.src)
1668 t.Errorf("%s: got object = %v; want none", test.src, f)
1671 if !sameSlice(index, test.index) {
1672 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1674 if indirect != test.indirect {
1675 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1680 func sameSlice(a, b []int) bool {
1681 if len(a) != len(b) {
1684 for i, x := range a {
1692 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1693 // the correct result at various positions with the source.
1694 func TestScopeLookupParent(t *testing.T) {
1695 fset := token.NewFileSet()
1696 imports := make(testImporter)
1697 conf := Config{Importer: imports}
1698 mustParse := func(src string) *ast.File {
1699 f, err := parser.ParseFile(fset, "dummy.go", src, parser.ParseComments)
1706 makePkg := func(path string, files ...*ast.File) {
1708 imports[path], err = conf.Check(path, fset, files, &info)
1714 makePkg("lib", mustParse("package lib; var X int"))
1715 // Each /*name=kind:line*/ comment makes the test look up the
1716 // name at that point and checks that it resolves to a decl of
1717 // the specified kind and line number. "undef" means undefined.
1719 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1730 const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1731 type /*t=undef*/ t /*t=typename:14*/ *t
1732 print(Y) /*Y=var:10*/
1733 x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1734 var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1737 for i, x := range a /*i=undef*/ /*x=var:16*/ { _ = i; _ = x }
1740 switch y := i.(type) { /*y=undef*/
1741 case /*y=undef*/ int /*y=var:23*/ :
1742 case float32, /*y=undef*/ float64 /*y=var:23*/ :
1743 default /*y=var:23*/:
1748 switch int := i.(type) {
1749 case /*int=typename:0*/ int /*int=var:31*/ :
1751 default /*int=var:31*/ :
1757 info.Uses = make(map[*ast.Ident]Object)
1758 f := mustParse(mainSrc)
1760 mainScope := imports["main"].Scope()
1761 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1762 for _, group := range f.Comments {
1763 for _, comment := range group.List {
1764 // Parse the assertion in the comment.
1765 m := rx.FindStringSubmatch(comment.Text)
1767 t.Errorf("%s: bad comment: %s",
1768 fset.Position(comment.Pos()), comment.Text)
1771 name, want := m[1], m[2]
1773 // Look up the name in the innermost enclosing scope.
1774 inner := mainScope.Innermost(comment.Pos())
1776 t.Errorf("%s: at %s: can't find innermost scope",
1777 fset.Position(comment.Pos()), comment.Text)
1781 if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil {
1782 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
1783 got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line)
1786 t.Errorf("%s: at %s: %s resolved to %s, want %s",
1787 fset.Position(comment.Pos()), comment.Text, name, got, want)
1792 // Check that for each referring identifier,
1793 // a lookup of its name on the innermost
1794 // enclosing scope returns the correct object.
1796 for id, wantObj := range info.Uses {
1797 inner := mainScope.Innermost(id.Pos())
1799 t.Errorf("%s: can't find innermost scope enclosing %q",
1800 fset.Position(id.Pos()), id.Name)
1804 // Exclude selectors and qualified identifiers---lexical
1805 // refs only. (Ideally, we'd see if the AST parent is a
1806 // SelectorExpr, but that requires PathEnclosingInterval
1807 // from golang.org/x/tools/go/ast/astutil.)
1812 _, gotObj := inner.LookupParent(id.Name, id.Pos())
1813 if gotObj != wantObj {
1814 t.Errorf("%s: got %v, want %v",
1815 fset.Position(id.Pos()), gotObj, wantObj)
1821 // newDefined creates a new defined type named T with the given underlying type.
1822 // Helper function for use with TestIncompleteInterfaces only.
1823 func newDefined(underlying Type) *Named {
1824 tname := NewTypeName(token.NoPos, nil, "T", nil)
1825 return NewNamed(tname, underlying, nil)
1828 func TestConvertibleTo(t *testing.T) {
1829 for _, test := range []struct {
1833 {Typ[Int], Typ[Int], true},
1834 {Typ[Int], Typ[Float32], true},
1835 {Typ[Int], Typ[String], true},
1836 {newDefined(Typ[Int]), Typ[Int], true},
1837 {newDefined(new(Struct)), new(Struct), true},
1838 {newDefined(Typ[Int]), new(Struct), false},
1839 {Typ[UntypedInt], Typ[Int], true},
1840 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
1841 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), false},
1842 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
1843 // Untyped string values are not permitted by the spec, so the behavior below is undefined.
1844 {Typ[UntypedString], Typ[String], true},
1846 if got := ConvertibleTo(test.v, test.t); got != test.want {
1847 t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1852 func TestAssignableTo(t *testing.T) {
1853 for _, test := range []struct {
1857 {Typ[Int], Typ[Int], true},
1858 {Typ[Int], Typ[Float32], false},
1859 {newDefined(Typ[Int]), Typ[Int], false},
1860 {newDefined(new(Struct)), new(Struct), true},
1861 {Typ[UntypedBool], Typ[Bool], true},
1862 {Typ[UntypedString], Typ[Bool], false},
1863 // Neither untyped string nor untyped numeric assignments arise during
1864 // normal type checking, so the below behavior is technically undefined by
1866 {Typ[UntypedString], Typ[String], true},
1867 {Typ[UntypedInt], Typ[Int], true},
1869 if got := AssignableTo(test.v, test.t); got != test.want {
1870 t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1875 func TestIdentical(t *testing.T) {
1876 // For each test, we compare the types of objects X and Y in the source.
1882 {"var X int; var Y int", true},
1883 {"var X int; var Y string", false},
1885 // TODO: add more tests for complex types.
1888 {"type X int; type Y int", false},
1891 {"type X = int; type Y = int", true},
1894 {`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
1895 {`func X() string { return "" }; func Y(int) string { return "" }`, false},
1896 {`func X(int) string { return "" }; func Y(int) {}`, false},
1898 // Generic functions. Type parameters should be considered identical modulo
1899 // renaming. See also issue #49722.
1900 {`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
1901 {`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
1902 {`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
1903 {`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
1904 {`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
1905 {`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
1908 for _, test := range tests {
1909 pkg, err := pkgForMode("test", "package p;"+test.src, nil, 0)
1911 t.Errorf("%s: incorrect test case: %s", test.src, err)
1914 X := pkg.Scope().Lookup("X")
1915 Y := pkg.Scope().Lookup("Y")
1916 if X == nil || Y == nil {
1917 t.Fatal("test must declare both X and Y")
1919 if got := Identical(X.Type(), Y.Type()); got != test.want {
1920 t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
1925 func TestIdentical_issue15173(t *testing.T) {
1926 // Identical should allow nil arguments and be symmetric.
1927 for _, test := range []struct {
1931 {Typ[Int], Typ[Int], true},
1932 {Typ[Int], nil, false},
1933 {nil, Typ[Int], false},
1936 if got := Identical(test.x, test.y); got != test.want {
1937 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
1942 func TestIdenticalUnions(t *testing.T) {
1943 tname := NewTypeName(token.NoPos, nil, "myInt", nil)
1944 myInt := NewNamed(tname, Typ[Int], nil)
1945 tmap := map[string]*Term{
1946 "int": NewTerm(false, Typ[Int]),
1947 "~int": NewTerm(true, Typ[Int]),
1948 "string": NewTerm(false, Typ[String]),
1949 "~string": NewTerm(true, Typ[String]),
1950 "myInt": NewTerm(false, myInt),
1952 makeUnion := func(s string) *Union {
1953 parts := strings.Split(s, "|")
1955 for _, p := range parts {
1958 t.Fatalf("missing term %q", p)
1960 terms = append(terms, term)
1962 return NewUnion(terms)
1964 for _, test := range []struct {
1968 // These tests are just sanity checks. The tests for type sets and
1969 // interfaces provide much more test coverage.
1970 {"int|~int", "~int", true},
1971 {"myInt|~int", "~int", true},
1972 {"int|string", "string|int", true},
1973 {"int|int|string", "string|int", true},
1974 {"myInt|string", "int|string", false},
1976 x := makeUnion(test.x)
1977 y := makeUnion(test.y)
1978 if got := Identical(x, y); got != test.want {
1979 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
1984 func TestIssue15305(t *testing.T) {
1985 const src = "package p; func f() int16; var _ = f(undef)"
1986 fset := token.NewFileSet()
1987 f, err := parser.ParseFile(fset, "issue15305.go", src, 0)
1992 Error: func(err error) {}, // allow errors
1995 Types: make(map[ast.Expr]TypeAndValue),
1997 conf.Check("p", fset, []*ast.File{f}, info) // ignore result
1998 for e, tv := range info.Types {
1999 if _, ok := e.(*ast.CallExpr); ok {
2000 if tv.Type != Typ[Int16] {
2001 t.Errorf("CallExpr has type %v, want int16", tv.Type)
2006 t.Errorf("CallExpr has no type")
2009 // TestCompositeLitTypes verifies that Info.Types registers the correct
2010 // types for composite literal expressions and composite literal type
2012 func TestCompositeLitTypes(t *testing.T) {
2013 for _, test := range []struct {
2016 {`[16]byte{}`, `[16]byte`},
2017 {`[...]byte{}`, `[0]byte`}, // test for issue #14092
2018 {`[...]int{1, 2, 3}`, `[3]int`}, // test for issue #14092
2019 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for issue #14092
2020 {`[]int{}`, `[]int`},
2021 {`map[string]bool{"foo": true}`, `map[string]bool`},
2022 {`struct{}{}`, `struct{}`},
2023 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
2025 fset := token.NewFileSet()
2026 f, err := parser.ParseFile(fset, test.lit, "package p; var _ = "+test.lit, 0)
2028 t.Fatalf("%s: %v", test.lit, err)
2032 Types: make(map[ast.Expr]TypeAndValue),
2034 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
2035 t.Fatalf("%s: %v", test.lit, err)
2038 cmptype := func(x ast.Expr, want string) {
2039 tv, ok := info.Types[x]
2041 t.Errorf("%s: no Types entry found", test.lit)
2045 t.Errorf("%s: type is nil", test.lit)
2048 if got := tv.Type.String(); got != want {
2049 t.Errorf("%s: got %v, want %s", test.lit, got, want)
2053 // test type of composite literal expression
2054 rhs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0]
2055 cmptype(rhs, test.typ)
2057 // test type of composite literal type expression
2058 cmptype(rhs.(*ast.CompositeLit).Type, test.typ)
2062 // TestObjectParents verifies that objects have parent scopes or not
2063 // as specified by the Object interface.
2064 func TestObjectParents(t *testing.T) {
2083 func f(x int) { y := x; print(y) }
2086 fset := token.NewFileSet()
2087 f, err := parser.ParseFile(fset, "src", src, 0)
2093 Defs: make(map[*ast.Ident]Object),
2095 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
2099 for ident, obj := range info.Defs {
2101 // only package names and implicit vars have a nil object
2102 // (in this test we only need to handle the package name)
2103 if ident.Name != "p" {
2104 t.Errorf("%v has nil object", ident)
2109 // struct fields, type-associated and interface methods
2110 // have no parent scope
2112 switch obj := obj.(type) {
2118 if obj.Type().(*Signature).Recv() != nil { // method
2123 gotParent := obj.Parent() != nil
2125 case gotParent && !wantParent:
2126 t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
2127 case !gotParent && wantParent:
2128 t.Errorf("%v: no parent found", ident)
2133 // TestFailedImport tests that we don't get follow-on errors
2134 // elsewhere in a package due to failing to import a package.
2135 func TestFailedImport(t *testing.T) {
2136 testenv.MustHaveGoBuild(t)
2141 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
2146 func f(x T) T { return foo.F(x) }
2148 fset := token.NewFileSet()
2149 f, err := parser.ParseFile(fset, "src", src, 0)
2153 files := []*ast.File{f}
2155 // type-check using all possible importers
2156 for _, compiler := range []string{"gc", "gccgo", "source"} {
2159 Error: func(err error) {
2160 // we should only see the import error
2161 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
2162 t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
2166 Importer: importer.For(compiler, nil),
2170 Uses: make(map[*ast.Ident]Object),
2172 pkg, _ := conf.Check("p", fset, files, info)
2174 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
2178 imports := pkg.Imports()
2179 if len(imports) != 1 {
2180 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
2184 if imp.Name() != "foo" {
2185 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
2189 // verify that all uses of foo refer to the imported package foo (imp)
2190 for ident, obj := range info.Uses {
2191 if ident.Name == "foo" {
2192 if obj, ok := obj.(*PkgName); ok {
2193 if obj.Imported() != imp {
2194 t.Errorf("%s resolved to %v; want %v", ident, obj.Imported(), imp)
2197 t.Errorf("%s resolved to %v; want package name", ident, obj)
2204 func TestInstantiate(t *testing.T) {
2205 // eventually we like more tests but this is a start
2206 const src = "package p; type T[P any] *T[P]"
2207 pkg, err := pkgForMode(".", src, nil, 0)
2212 // type T should have one type parameter
2213 T := pkg.Scope().Lookup("T").Type().(*Named)
2214 if n := T.TypeParams().Len(); n != 1 {
2215 t.Fatalf("expected 1 type parameter; found %d", n)
2218 // instantiation should succeed (no endless recursion)
2219 // even with a nil *Checker
2220 res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
2225 // instantiated type should point to itself
2226 if p := res.Underlying().(*Pointer).Elem(); p != res {
2227 t.Fatalf("unexpected result type: %s points to %s", res, p)
2231 func TestInstantiateErrors(t *testing.T) {
2233 src string // by convention, T must be the type being instantiated
2235 wantAt int // -1 indicates no error
2237 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
2238 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
2239 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
2240 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
2243 for _, test := range tests {
2244 src := "package p; " + test.src
2245 pkg, err := pkgForMode(".", src, nil, 0)
2250 T := pkg.Scope().Lookup("T").Type().(*Named)
2252 _, err = Instantiate(nil, T, test.targs, true)
2254 t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
2257 var argErr *ArgumentError
2258 if !errors.As(err, &argErr) {
2259 t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
2262 if argErr.Index != test.wantAt {
2263 t.Errorf("Instantate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2268 func TestArgumentErrorUnwrapping(t *testing.T) {
2269 var err error = &ArgumentError{
2271 Err: Error{Msg: "test"},
2274 if !errors.As(err, &e) {
2275 t.Fatalf("error %v does not wrap types.Error", err)
2277 if e.Msg != "test" {
2278 t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2282 func TestInstanceIdentity(t *testing.T) {
2283 imports := make(testImporter)
2284 conf := Config{Importer: imports}
2285 makePkg := func(src string) {
2286 fset := token.NewFileSet()
2287 f, err := parser.ParseFile(fset, "", src, 0)
2292 pkg, err := conf.Check(name, fset, []*ast.File{f}, nil)
2298 makePkg(genericPkg + `lib; type T[P any] struct{}`)
2299 makePkg(genericPkg + `a; import "generic_lib"; var A generic_lib.T[int]`)
2300 makePkg(genericPkg + `b; import "generic_lib"; var B generic_lib.T[int]`)
2301 a := imports["generic_a"].Scope().Lookup("A")
2302 b := imports["generic_b"].Scope().Lookup("B")
2303 if !Identical(a.Type(), b.Type()) {
2304 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
2308 func TestImplements(t *testing.T) {
2312 type EmptyIface interface{}
2323 type Integer interface{
2324 int8 | int16 | int32 | int64
2327 type EmptyTypeSet interface{
2344 type Bad Bad // invalid type
2347 fset := token.NewFileSet()
2348 f, err := parser.ParseFile(fset, "p.go", src, 0)
2352 conf := Config{Error: func(error) {}}
2353 pkg, _ := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
2355 lookup := func(tname string) Type { return pkg.Scope().Lookup(tname).Type() }
2357 EmptyIface = lookup("EmptyIface").Underlying().(*Interface)
2358 I = lookup("I").(*Named)
2359 II = I.Underlying().(*Interface)
2360 C = lookup("C").(*Named)
2361 CI = C.Underlying().(*Interface)
2362 Integer = lookup("Integer").Underlying().(*Interface)
2363 EmptyTypeSet = lookup("EmptyTypeSet").Underlying().(*Interface)
2365 N1p = NewPointer(N1)
2367 N2p = NewPointer(N2)
2382 {Typ[Int8], Integer, true},
2383 {Typ[Int64], Integer, true},
2384 {Typ[String], Integer, false},
2385 {EmptyTypeSet, II, true},
2386 {EmptyTypeSet, EmptyTypeSet, true},
2387 {Typ[Int], EmptyTypeSet, false},
2402 {Bad, EmptyIface, true},
2405 for _, test := range tests {
2406 if got := Implements(test.V, test.T); got != test.want {
2407 t.Errorf("Implements(%s, %s) = %t, want %t", test.V, test.T, got, test.want)
2410 // The type assertion x.(T) is valid if T is an interface or if T implements the type of x.
2411 // The assertion is never valid if T is a bad type.
2415 if _, ok := T.Underlying().(*Interface); (ok || Implements(T, V)) && T != Bad {
2418 if got := AssertableTo(V, T); got != want {
2419 t.Errorf("AssertableTo(%s, %s) = %t, want %t", V, T, got, want)
2424 func TestMissingMethodAlternative(t *testing.T) {
2446 pkg, err := pkgFor("p.go", src, nil)
2451 T := pkg.Scope().Lookup("T").Type().Underlying().(*Interface)
2452 lookup := func(name string) (*Func, bool) {
2453 return MissingMethod(pkg.Scope().Lookup(name).Type(), T, true)
2456 // V0 has method m with correct signature. Should not report wrongType.
2457 method, wrongType := lookup("V0")
2458 if method != nil || wrongType {
2459 t.Fatalf("V0: got method = %v, wrongType = %v", method, wrongType)
2462 checkMissingMethod := func(tname string, reportWrongType bool) {
2463 method, wrongType := lookup(tname)
2464 if method == nil || method.Name() != "m" || wrongType != reportWrongType {
2465 t.Fatalf("%s: got method = %v, wrongType = %v", tname, method, wrongType)
2469 // V1 has no method m. Should not report wrongType.
2470 checkMissingMethod("V1", false)
2472 // V2 has method m with wrong signature type (ignoring receiver). Should report wrongType.
2473 checkMissingMethod("V2", true)
2475 // V3 has no method m but it exists on *V3. Should report wrongType.
2476 checkMissingMethod("V3", true)
2478 // V4 has no method m but has M. Should not report wrongType.
2479 checkMissingMethod("V4", false)