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.`, `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()`,
734 {`package generic_m11; type T[A any] interface{ m(); n() }; func _(t1 T[int], t2 T[string]) { t1.m(); t2.n() }`, `m`, `func (generic_m11.T[int]).m()`},
735 {`package generic_m12; type T[A any] interface{ m(); n() }; func _(t1 T[int], t2 T[string]) { t1.m(); t2.n() }`, `n`, `func (generic_m12.T[string]).n()`},
738 for _, test := range tests {
740 Uses: make(map[*ast.Ident]Object),
742 name := mustTypecheck(t, "UsesInfo", test.src, &info)
746 for id, obj := range info.Uses {
747 if id.Name == test.obj {
749 panic(fmt.Sprintf("multiple uses of %q", id.Name))
755 t.Errorf("package %s: %s not found", name, test.obj)
759 if got := use.String(); got != test.want {
760 t.Errorf("package %s: got %s; want %s", name, got, test.want)
765 func TestGenericMethodInfo(t *testing.T) {
770 func (r N[B]) m() { r.m(); r.n() }
772 func (r *N[C]) n() { }
774 fset := token.NewFileSet()
775 f, err := parser.ParseFile(fset, "p.go", src, 0)
780 Defs: make(map[*ast.Ident]Object),
781 Uses: make(map[*ast.Ident]Object),
782 Selections: make(map[*ast.SelectorExpr]*Selection),
785 pkg, err := conf.Check("p", fset, []*ast.File{f}, &info)
790 N := pkg.Scope().Lookup("N").Type().(*Named)
792 // Find the generic methods stored on N.
793 gm, gn := N.Method(0), N.Method(1)
794 if gm.Name() == "n" {
798 // Collect objects from info.
799 var dm, dn *Func // the declared methods
800 var dmm, dmn *Func // the methods used in the body of m
801 for _, decl := range f.Decls {
802 fdecl, ok := decl.(*ast.FuncDecl)
806 def := info.Defs[fdecl.Name].(*Func)
807 switch fdecl.Name.Name {
810 ast.Inspect(fdecl.Body, func(n ast.Node) bool {
811 if call, ok := n.(*ast.CallExpr); ok {
812 sel := call.Fun.(*ast.SelectorExpr)
813 use := info.Uses[sel.Sel].(*Func)
814 selection := info.Selections[sel]
815 if selection.Kind() != MethodVal {
816 t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
818 if selection.Obj() != use {
819 t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
821 switch sel.Sel.Name {
836 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
839 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
842 t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
845 t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
849 func TestImplicitsInfo(t *testing.T) {
850 testenv.MustHaveGoBuild(t)
852 var tests = []struct {
856 {`package p2; import . "fmt"; var _ = Println`, ""}, // no Implicits entry
857 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
858 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
860 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
861 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
862 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
863 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
865 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
866 {`package p8; func f(int) {}`, "field: var int"},
867 {`package p9; func f() (complex64) { return 0 }`, "field: var complex64"},
868 {`package p10; type T struct{}; func (*T) f() {}`, "field: var *p10.T"},
870 // Tests using generics.
871 {`package generic_f0; func f[T any](x int) {}`, ""}, // no Implicits entry
872 {`package generic_f1; func f[T any](int) {}`, "field: var int"},
873 {`package generic_f2; func f[T any](T) {}`, "field: var T"},
874 {`package generic_f3; func f[T any]() (complex64) { return 0 }`, "field: var complex64"},
875 {`package generic_f4; func f[T any](t T) (T) { return t }`, "field: var T"},
876 {`package generic_t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var *generic_t0.T[_]"},
877 {`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]"},
878 {`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]"},
879 {`package generic_t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
882 for _, test := range tests {
884 Implicits: make(map[ast.Node]Object),
886 name := mustTypecheck(t, "ImplicitsInfo", test.src, &info)
888 // the test cases expect at most one Implicits entry
889 if len(info.Implicits) > 1 {
890 t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
894 // extract Implicits entry, if any
896 for n, obj := range info.Implicits {
897 switch x := n.(type) {
898 case *ast.ImportSpec:
900 case *ast.CaseClause:
905 t.Fatalf("package %s: unexpected %T", name, x)
907 got += ": " + obj.String()
911 if got != test.want {
912 t.Errorf("package %s: got %q; want %q", name, got, test.want)
917 func predString(tv TypeAndValue) string {
919 pred := func(b bool, s string) {
922 buf.WriteString(", ")
928 pred(tv.IsVoid(), "void")
929 pred(tv.IsType(), "type")
930 pred(tv.IsBuiltin(), "builtin")
931 pred(tv.IsValue() && tv.Value != nil, "const")
932 pred(tv.IsValue() && tv.Value == nil, "value")
933 pred(tv.IsNil(), "nil")
934 pred(tv.Addressable(), "addressable")
935 pred(tv.Assignable(), "assignable")
936 pred(tv.HasOk(), "hasOk")
944 func TestPredicatesInfo(t *testing.T) {
945 testenv.MustHaveGoBuild(t)
947 var tests = []struct {
953 {`package n0; func f() { f() }`, `f()`, `void`},
956 {`package t0; type _ int`, `int`, `type`},
957 {`package t1; type _ []int`, `[]int`, `type`},
958 {`package t2; type _ func()`, `func()`, `type`},
959 {`package t3; type _ func(int)`, `int`, `type`},
960 {`package t3; type _ func(...int)`, `...int`, `type`},
963 {`package b0; var _ = len("")`, `len`, `builtin`},
964 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
967 {`package c0; var _ = 42`, `42`, `const`},
968 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
969 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
972 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
973 {`package v1; var _ = &[]int{1}`, `([]int literal)`, `value`},
974 {`package v2; var _ = func(){}`, `(func() literal)`, `value`},
975 {`package v4; func f() { _ = f }`, `f`, `value`},
976 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
977 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
979 // addressable (and thus assignable) operands
980 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
981 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
982 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
983 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
984 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
985 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
986 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
987 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
988 // composite literals are not addressable
990 // assignable but not addressable values
991 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
992 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
995 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
996 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
999 // - package names are collected in the Uses map
1000 // - identifiers being declared are collected in the Defs map
1001 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
1002 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
1003 {`package m2; const c = 0`, `c`, `<missing>`},
1004 {`package m3; type T int`, `T`, `<missing>`},
1005 {`package m4; var v int`, `v`, `<missing>`},
1006 {`package m5; func f() {}`, `f`, `<missing>`},
1007 {`package m6; func _(x int) {}`, `x`, `<missing>`},
1008 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
1009 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
1012 for _, test := range tests {
1013 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
1014 name := mustTypecheck(t, "PredicatesInfo", test.src, &info)
1016 // look for expression predicates
1018 for e, tv := range info.Types {
1019 //println(name, ExprString(e))
1020 if ExprString(e) == test.expr {
1021 got = predString(tv)
1026 if got != test.pred {
1027 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
1032 func TestScopesInfo(t *testing.T) {
1033 testenv.MustHaveGoBuild(t)
1035 var tests = []struct {
1037 scopes []string // list of scope descriptors of the form kind:varlist
1039 {`package p0`, []string{
1042 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
1045 {`package p2; func _() {}`, []string{
1048 {`package p3; func _(x, y int) {}`, []string{
1049 "file:", "func:x y",
1051 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
1052 "file:", "func:x y z", // redeclaration of x
1054 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
1055 "file:", "func:u x y",
1057 {`package p6; func _() { { var x int; _ = x } }`, []string{
1058 "file:", "func:", "block:x",
1060 {`package p7; func _() { if true {} }`, []string{
1061 "file:", "func:", "if:", "block:",
1063 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
1064 "file:", "func:", "if:x", "block:y",
1066 {`package p9; func _() { switch x := 0; x {} }`, []string{
1067 "file:", "func:", "switch:x",
1069 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
1070 "file:", "func:", "switch:x", "case:y", "case:",
1072 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
1073 "file:", "func:t", "type switch:",
1075 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
1076 "file:", "func:t", "type switch:t",
1078 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
1079 "file:", "func:t", "type switch:", "case:x", // x implicitly declared
1081 {`package p14; func _() { select{} }`, []string{
1084 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
1085 "file:", "func:c", "comm:",
1087 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
1088 "file:", "func:c", "comm:i x",
1090 {`package p17; func _() { for{} }`, []string{
1091 "file:", "func:", "for:", "block:",
1093 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
1094 "file:", "func:n", "for:i", "block:",
1096 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
1097 "file:", "func:a", "range:i", "block:",
1099 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
1100 "file:", "func:a", "range:i x", "block:",
1104 for _, test := range tests {
1105 info := Info{Scopes: make(map[ast.Node]*Scope)}
1106 name := mustTypecheck(t, "ScopesInfo", test.src, &info)
1108 // number of scopes must match
1109 if len(info.Scopes) != len(test.scopes) {
1110 t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
1113 // scope descriptions must match
1114 for node, scope := range info.Scopes {
1115 kind := "<unknown node kind>"
1116 switch node.(type) {
1121 case *ast.BlockStmt:
1125 case *ast.SwitchStmt:
1127 case *ast.TypeSwitchStmt:
1128 kind = "type switch"
1129 case *ast.CaseClause:
1131 case *ast.CommClause:
1135 case *ast.RangeStmt:
1139 // look for matching scope description
1140 desc := kind + ":" + strings.Join(scope.Names(), " ")
1142 for _, d := range test.scopes {
1149 t.Errorf("package %s: no matching scope found for %s", name, desc)
1155 func TestInitOrderInfo(t *testing.T) {
1156 var tests = []struct {
1160 {`package p0; var (x = 1; y = x)`, []string{
1163 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
1164 "a = 1", "b = 2", "c = 3",
1166 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
1167 "a = 1", "b = 2", "c = 3",
1169 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
1170 "_ = f()", // blank var
1172 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
1173 "a = 0", "z = 0", "y = z", "x = y",
1175 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
1176 "a, _ = m[0]", // blank var
1178 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
1179 "z = 0", "a, b = f()",
1181 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
1182 "b = 1", "a = (func() int literal)()",
1184 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
1185 "c = 1", "a, b = (func() (_, _ int) literal)()",
1187 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1190 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1191 "a = 0", "b = 0", "c = 0", "d = c + b",
1193 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
1194 "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
1196 // emit an initializer for n:1 initializations only once (not for each node
1197 // on the lhs which may appear in different order in the dependency graph)
1198 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
1199 "b = 0", "x, y = m[0]", "a = x",
1201 // test case from spec section on package initialization
1215 "d = 3", "b = f()", "c = f()", "a = c + b",
1217 // test case for issue 7131
1221 func next() int { counter++; return counter }
1224 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1227 var b, c = next(), next()
1228 var d, e, f = next(), next(), next()
1230 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1232 // test case for issue 10709
1242 func (T) m() int { return 0 }
1244 func makeT(n int) T {
1250 "t = makeT(0)", "v = t.m()",
1252 // test case for issue 10709: same as test before, but variable decls swapped
1262 func (T) m() int { return 0 }
1264 func makeT(n int) T {
1270 "t = makeT(0)", "v = t.m()",
1272 // another candidate possibly causing problems with issue 10709
1277 func f1() int { return g1() }
1278 func g1() int { f1(); return x1 }
1284 func f2() int { return g2() }
1285 func g2() int { return x2 }
1287 var x2 = 0`, []string{
1288 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1292 for _, test := range tests {
1294 name := mustTypecheck(t, "InitOrderInfo", test.src, &info)
1296 // number of initializers must match
1297 if len(info.InitOrder) != len(test.inits) {
1298 t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1302 // initializers must match
1303 for i, want := range test.inits {
1304 got := info.InitOrder[i].String()
1306 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1313 func TestMultiFileInitOrder(t *testing.T) {
1314 fset := token.NewFileSet()
1315 mustParse := func(src string) *ast.File {
1316 f, err := parser.ParseFile(fset, "main", src, 0)
1323 fileA := mustParse(`package main; var a = 1`)
1324 fileB := mustParse(`package main; var b = 2`)
1326 // The initialization order must not depend on the parse
1327 // order of the files, only on the presentation order to
1328 // the type-checker.
1329 for _, test := range []struct {
1333 {[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
1334 {[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
1337 if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
1340 if got := fmt.Sprint(info.InitOrder); got != test.want {
1341 t.Fatalf("got %s; want %s", got, test.want)
1346 func TestFiles(t *testing.T) {
1347 var sources = []string{
1348 "package p; type T struct{}; func (T) m1() {}",
1349 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1350 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1355 fset := token.NewFileSet()
1356 pkg := NewPackage("p", "p")
1358 check := NewChecker(&conf, fset, pkg, &info)
1360 for i, src := range sources {
1361 filename := fmt.Sprintf("sources%d", i)
1362 f, err := parser.ParseFile(fset, filename, src, 0)
1366 if err := check.Files([]*ast.File{f}); err != nil {
1371 // check InitOrder is [x y]
1373 for _, init := range info.InitOrder {
1374 for _, v := range init.Lhs {
1375 vars = append(vars, v.Name())
1378 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1379 t.Errorf("InitOrder == %s, want %s", got, want)
1383 type testImporter map[string]*Package
1385 func (m testImporter) Import(path string) (*Package, error) {
1386 if pkg := m[path]; pkg != nil {
1389 return nil, fmt.Errorf("package %q not found", path)
1392 func TestSelection(t *testing.T) {
1393 selections := make(map[*ast.SelectorExpr]*Selection)
1395 fset := token.NewFileSet()
1396 imports := make(testImporter)
1397 conf := Config{Importer: imports}
1398 makePkg := func(path, src string) {
1399 f, err := parser.ParseFile(fset, path+".go", src, 0)
1403 pkg, err := conf.Check(path, fset, []*ast.File{f}, &Info{Selections: selections})
1437 type G[P any] struct {
1449 // qualified identifiers
1487 // method expressions
1495 wantOut := map[string][2]string{
1496 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1498 "A{}.B": {"field (main.A) B *main.B", ".[0]"},
1499 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1500 "A{}.C": {"field (main.A) C main.C", ".[1]"},
1501 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1502 "A{}.b": {"field (main.A) b int", "->[0 0]"},
1503 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1504 "A{}.c": {"field (main.A) c int", ".[1 0]"},
1505 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1506 "Inst.p": {"field (main.G[int]) p int", ".[0]"},
1508 "A{}.f": {"method (main.A) f(int)", "->[0 0]"},
1509 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1510 "A{}.g": {"method (main.A) g()", ".[1 0]"},
1511 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1512 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1513 "B{}.f": {"method (main.B) f(int)", ".[0]"},
1514 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1515 "C{}.g": {"method (main.C) g()", ".[0]"},
1516 "new(C).g": {"method (*main.C) g()", "->[0]"},
1517 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1518 "Inst.m": {"method (main.G[int]) m(int)", ".[0]"},
1520 "A.f": {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1521 "(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1522 "B.f": {"method expr (main.B) f(main.B, int)", ".[0]"},
1523 "(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1524 "G[string].m": {"method expr (main.G[string]) m(main.G[string], string)", ".[0]"},
1525 "G[string]{}.p": {"field (main.G[string]) p string", ".[0]"},
1528 makePkg("lib", libSrc)
1529 makePkg("main", mainSrc)
1531 for e, sel := range selections {
1532 _ = sel.String() // assertion: must not panic
1534 start := fset.Position(e.Pos()).Offset
1535 end := fset.Position(e.End()).Offset
1536 syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1544 fmt.Sprintf("%s%v", direct, sel.Index()),
1546 want := wantOut[syntax]
1548 t.Errorf("%s: got %q; want %q", syntax, got, want)
1550 delete(wantOut, syntax)
1552 // We must explicitly assert properties of the
1553 // Signature's receiver since it doesn't participate
1554 // in Identical() or String().
1555 sig, _ := sel.Type().(*Signature)
1556 if sel.Kind() == MethodVal {
1557 got := sig.Recv().Type()
1559 if !Identical(got, want) {
1560 t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
1562 } else if sig != nil && sig.Recv() != nil {
1563 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1566 // Assert that all wantOut entries were used exactly once.
1567 for syntax := range wantOut {
1568 t.Errorf("no ast.Selection found with syntax %q", syntax)
1572 func TestIssue8518(t *testing.T) {
1573 fset := token.NewFileSet()
1574 imports := make(testImporter)
1576 Error: func(err error) { t.Log(err) }, // don't exit after first error
1579 makePkg := func(path, src string) {
1580 f, err := parser.ParseFile(fset, path, src, 0)
1584 pkg, _ := conf.Check(path, fset, []*ast.File{f}, nil) // errors logged via conf.Error
1592 const C2 = missing.C
1602 makePkg("a", libSrc)
1603 makePkg("main", mainSrc) // don't crash when type-checking this package
1606 func TestLookupFieldOrMethodOnNil(t *testing.T) {
1607 // LookupFieldOrMethod on a nil type is expected to produce a run-time panic.
1609 const want = "LookupFieldOrMethod on nil type"
1611 if s, ok := p.(string); !ok || s != want {
1612 t.Fatalf("got %v, want %s", p, want)
1615 LookupFieldOrMethod(nil, false, nil, "")
1618 func TestLookupFieldOrMethod(t *testing.T) {
1619 // Test cases assume a lookup of the form a.f or x.f, where a stands for an
1620 // addressable value, and x for a non-addressable value (even though a variable
1621 // for ease of test case writing).
1623 // Should be kept in sync with TestMethodSet.
1624 var tests = []struct {
1631 {"var x T; type T struct{}", false, nil, false},
1632 {"var x T; type T struct{ f int }", true, []int{0}, false},
1633 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1635 // field lookups on a generic type
1636 {"var x T[int]; type T[P any] struct{}", false, nil, false},
1637 {"var x T[int]; type T[P any] struct{ f P }", true, []int{0}, false},
1638 {"var x T[int]; type T[P any] struct{ a, b, f, c P }", true, []int{2}, false},
1641 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1642 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1643 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1644 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1646 // method lookups on a generic type
1647 {"var a T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, false},
1648 {"var a *T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, true},
1649 {"var a T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, false},
1650 {"var a *T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1653 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1654 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1656 // collisions on a generic type
1657 {"type ( E1[P any] struct{ f P }; E2[P any] struct{ f P }; x struct{ E1[int]; *E2[int] })", false, []int{1, 0}, false},
1658 {"type ( E1[P any] struct{ f P }; E2[P any] struct{}; x struct{ E1[int]; *E2[int] }); func (E2[P]) f() {}", false, []int{1, 0}, false},
1660 // outside methodset
1661 // (*T).f method exists, but value of type T is not addressable
1662 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1664 // outside method set of a generic type
1665 {"var x T[int]; type T[P any] struct{}; func (*T[P]) f() {}", false, nil, true},
1667 // recursive generic types; see golang/go#52715
1668 {"var a T[int]; type ( T[P any] struct { *N[P] }; N[P any] struct { *T[P] } ); func (N[P]) f() {}", true, []int{0, 0}, true},
1669 {"var a T[int]; type ( T[P any] struct { *N[P] }; N[P any] struct { *T[P] } ); func (T[P]) f() {}", true, []int{0}, false},
1672 for _, test := range tests {
1673 pkg, err := pkgForMode("test", "package p;"+test.src, nil, 0)
1675 t.Errorf("%s: incorrect test case: %s", test.src, err)
1679 obj := pkg.Scope().Lookup("a")
1681 if obj = pkg.Scope().Lookup("x"); obj == nil {
1682 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1687 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1688 if (f != nil) != test.found {
1690 t.Errorf("%s: got no object; want one", test.src)
1692 t.Errorf("%s: got object = %v; want none", test.src, f)
1695 if !sameSlice(index, test.index) {
1696 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1698 if indirect != test.indirect {
1699 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1704 // Test for golang/go#52715
1705 func TestLookupFieldOrMethod_RecursiveGeneric(t *testing.T) {
1709 type Tree[T any] struct {
1713 func (*Tree[R]) N(r R) R { return r }
1715 type Node[T any] struct {
1719 type Instance = *Tree[int]
1722 fset := token.NewFileSet()
1723 f, err := parser.ParseFile(fset, "foo.go", src, 0)
1727 pkg := NewPackage("pkg", f.Name.Name)
1728 if err := NewChecker(nil, fset, pkg, nil).Files([]*ast.File{f}); err != nil {
1732 T := pkg.Scope().Lookup("Instance").Type()
1733 _, _, _ = LookupFieldOrMethod(T, false, pkg, "M") // verify that LookupFieldOrMethod terminates
1736 func sameSlice(a, b []int) bool {
1737 if len(a) != len(b) {
1740 for i, x := range a {
1748 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1749 // the correct result at various positions with the source.
1750 func TestScopeLookupParent(t *testing.T) {
1751 fset := token.NewFileSet()
1752 imports := make(testImporter)
1753 conf := Config{Importer: imports}
1754 mustParse := func(src string) *ast.File {
1755 f, err := parser.ParseFile(fset, "dummy.go", src, parser.ParseComments)
1762 makePkg := func(path string, files ...*ast.File) {
1764 imports[path], err = conf.Check(path, fset, files, &info)
1770 makePkg("lib", mustParse("package lib; var X int"))
1771 // Each /*name=kind:line*/ comment makes the test look up the
1772 // name at that point and checks that it resolves to a decl of
1773 // the specified kind and line number. "undef" means undefined.
1775 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1786 const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1787 type /*t=undef*/ t /*t=typename:14*/ *t
1788 print(Y) /*Y=var:10*/
1789 x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1790 var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1793 for i, x := range a /*i=undef*/ /*x=var:16*/ { _ = i; _ = x }
1796 switch y := i.(type) { /*y=undef*/
1797 case /*y=undef*/ int /*y=var:23*/ :
1798 case float32, /*y=undef*/ float64 /*y=var:23*/ :
1799 default /*y=var:23*/:
1804 switch int := i.(type) {
1805 case /*int=typename:0*/ int /*int=var:31*/ :
1807 default /*int=var:31*/ :
1813 info.Uses = make(map[*ast.Ident]Object)
1814 f := mustParse(mainSrc)
1816 mainScope := imports["main"].Scope()
1817 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1818 for _, group := range f.Comments {
1819 for _, comment := range group.List {
1820 // Parse the assertion in the comment.
1821 m := rx.FindStringSubmatch(comment.Text)
1823 t.Errorf("%s: bad comment: %s",
1824 fset.Position(comment.Pos()), comment.Text)
1827 name, want := m[1], m[2]
1829 // Look up the name in the innermost enclosing scope.
1830 inner := mainScope.Innermost(comment.Pos())
1832 t.Errorf("%s: at %s: can't find innermost scope",
1833 fset.Position(comment.Pos()), comment.Text)
1837 if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil {
1838 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
1839 got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line)
1842 t.Errorf("%s: at %s: %s resolved to %s, want %s",
1843 fset.Position(comment.Pos()), comment.Text, name, got, want)
1848 // Check that for each referring identifier,
1849 // a lookup of its name on the innermost
1850 // enclosing scope returns the correct object.
1852 for id, wantObj := range info.Uses {
1853 inner := mainScope.Innermost(id.Pos())
1855 t.Errorf("%s: can't find innermost scope enclosing %q",
1856 fset.Position(id.Pos()), id.Name)
1860 // Exclude selectors and qualified identifiers---lexical
1861 // refs only. (Ideally, we'd see if the AST parent is a
1862 // SelectorExpr, but that requires PathEnclosingInterval
1863 // from golang.org/x/tools/go/ast/astutil.)
1868 _, gotObj := inner.LookupParent(id.Name, id.Pos())
1869 if gotObj != wantObj {
1870 t.Errorf("%s: got %v, want %v",
1871 fset.Position(id.Pos()), gotObj, wantObj)
1877 // newDefined creates a new defined type named T with the given underlying type.
1878 // Helper function for use with TestIncompleteInterfaces only.
1879 func newDefined(underlying Type) *Named {
1880 tname := NewTypeName(token.NoPos, nil, "T", nil)
1881 return NewNamed(tname, underlying, nil)
1884 func TestConvertibleTo(t *testing.T) {
1885 for _, test := range []struct {
1889 {Typ[Int], Typ[Int], true},
1890 {Typ[Int], Typ[Float32], true},
1891 {Typ[Int], Typ[String], true},
1892 {newDefined(Typ[Int]), Typ[Int], true},
1893 {newDefined(new(Struct)), new(Struct), true},
1894 {newDefined(Typ[Int]), new(Struct), false},
1895 {Typ[UntypedInt], Typ[Int], true},
1896 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
1897 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), false},
1898 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
1899 // Untyped string values are not permitted by the spec, so the behavior below is undefined.
1900 {Typ[UntypedString], Typ[String], true},
1902 if got := ConvertibleTo(test.v, test.t); got != test.want {
1903 t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1908 func TestAssignableTo(t *testing.T) {
1909 for _, test := range []struct {
1913 {Typ[Int], Typ[Int], true},
1914 {Typ[Int], Typ[Float32], false},
1915 {newDefined(Typ[Int]), Typ[Int], false},
1916 {newDefined(new(Struct)), new(Struct), true},
1917 {Typ[UntypedBool], Typ[Bool], true},
1918 {Typ[UntypedString], Typ[Bool], false},
1919 // Neither untyped string nor untyped numeric assignments arise during
1920 // normal type checking, so the below behavior is technically undefined by
1922 {Typ[UntypedString], Typ[String], true},
1923 {Typ[UntypedInt], Typ[Int], true},
1925 if got := AssignableTo(test.v, test.t); got != test.want {
1926 t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1931 func TestIdentical(t *testing.T) {
1932 // For each test, we compare the types of objects X and Y in the source.
1938 {"var X int; var Y int", true},
1939 {"var X int; var Y string", false},
1941 // TODO: add more tests for complex types.
1944 {"type X int; type Y int", false},
1947 {"type X = int; type Y = int", true},
1950 {`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
1951 {`func X() string { return "" }; func Y(int) string { return "" }`, false},
1952 {`func X(int) string { return "" }; func Y(int) {}`, false},
1954 // Generic functions. Type parameters should be considered identical modulo
1955 // renaming. See also issue #49722.
1956 {`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
1957 {`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
1958 {`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
1959 {`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
1960 {`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
1961 {`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
1964 for _, test := range tests {
1965 pkg, err := pkgForMode("test", "package p;"+test.src, nil, 0)
1967 t.Errorf("%s: incorrect test case: %s", test.src, err)
1970 X := pkg.Scope().Lookup("X")
1971 Y := pkg.Scope().Lookup("Y")
1972 if X == nil || Y == nil {
1973 t.Fatal("test must declare both X and Y")
1975 if got := Identical(X.Type(), Y.Type()); got != test.want {
1976 t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
1981 func TestIdentical_issue15173(t *testing.T) {
1982 // Identical should allow nil arguments and be symmetric.
1983 for _, test := range []struct {
1987 {Typ[Int], Typ[Int], true},
1988 {Typ[Int], nil, false},
1989 {nil, Typ[Int], false},
1992 if got := Identical(test.x, test.y); got != test.want {
1993 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
1998 func TestIdenticalUnions(t *testing.T) {
1999 tname := NewTypeName(token.NoPos, nil, "myInt", nil)
2000 myInt := NewNamed(tname, Typ[Int], nil)
2001 tmap := map[string]*Term{
2002 "int": NewTerm(false, Typ[Int]),
2003 "~int": NewTerm(true, Typ[Int]),
2004 "string": NewTerm(false, Typ[String]),
2005 "~string": NewTerm(true, Typ[String]),
2006 "myInt": NewTerm(false, myInt),
2008 makeUnion := func(s string) *Union {
2009 parts := strings.Split(s, "|")
2011 for _, p := range parts {
2014 t.Fatalf("missing term %q", p)
2016 terms = append(terms, term)
2018 return NewUnion(terms)
2020 for _, test := range []struct {
2024 // These tests are just sanity checks. The tests for type sets and
2025 // interfaces provide much more test coverage.
2026 {"int|~int", "~int", true},
2027 {"myInt|~int", "~int", true},
2028 {"int|string", "string|int", true},
2029 {"int|int|string", "string|int", true},
2030 {"myInt|string", "int|string", false},
2032 x := makeUnion(test.x)
2033 y := makeUnion(test.y)
2034 if got := Identical(x, y); got != test.want {
2035 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2040 func TestIssue15305(t *testing.T) {
2041 const src = "package p; func f() int16; var _ = f(undef)"
2042 fset := token.NewFileSet()
2043 f, err := parser.ParseFile(fset, "issue15305.go", src, 0)
2048 Error: func(err error) {}, // allow errors
2051 Types: make(map[ast.Expr]TypeAndValue),
2053 conf.Check("p", fset, []*ast.File{f}, info) // ignore result
2054 for e, tv := range info.Types {
2055 if _, ok := e.(*ast.CallExpr); ok {
2056 if tv.Type != Typ[Int16] {
2057 t.Errorf("CallExpr has type %v, want int16", tv.Type)
2062 t.Errorf("CallExpr has no type")
2065 // TestCompositeLitTypes verifies that Info.Types registers the correct
2066 // types for composite literal expressions and composite literal type
2068 func TestCompositeLitTypes(t *testing.T) {
2069 for _, test := range []struct {
2072 {`[16]byte{}`, `[16]byte`},
2073 {`[...]byte{}`, `[0]byte`}, // test for issue #14092
2074 {`[...]int{1, 2, 3}`, `[3]int`}, // test for issue #14092
2075 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for issue #14092
2076 {`[]int{}`, `[]int`},
2077 {`map[string]bool{"foo": true}`, `map[string]bool`},
2078 {`struct{}{}`, `struct{}`},
2079 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
2081 fset := token.NewFileSet()
2082 f, err := parser.ParseFile(fset, test.lit, "package p; var _ = "+test.lit, 0)
2084 t.Fatalf("%s: %v", test.lit, err)
2088 Types: make(map[ast.Expr]TypeAndValue),
2090 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
2091 t.Fatalf("%s: %v", test.lit, err)
2094 cmptype := func(x ast.Expr, want string) {
2095 tv, ok := info.Types[x]
2097 t.Errorf("%s: no Types entry found", test.lit)
2101 t.Errorf("%s: type is nil", test.lit)
2104 if got := tv.Type.String(); got != want {
2105 t.Errorf("%s: got %v, want %s", test.lit, got, want)
2109 // test type of composite literal expression
2110 rhs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0]
2111 cmptype(rhs, test.typ)
2113 // test type of composite literal type expression
2114 cmptype(rhs.(*ast.CompositeLit).Type, test.typ)
2118 // TestObjectParents verifies that objects have parent scopes or not
2119 // as specified by the Object interface.
2120 func TestObjectParents(t *testing.T) {
2139 func f(x int) { y := x; print(y) }
2142 fset := token.NewFileSet()
2143 f, err := parser.ParseFile(fset, "src", src, 0)
2149 Defs: make(map[*ast.Ident]Object),
2151 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
2155 for ident, obj := range info.Defs {
2157 // only package names and implicit vars have a nil object
2158 // (in this test we only need to handle the package name)
2159 if ident.Name != "p" {
2160 t.Errorf("%v has nil object", ident)
2165 // struct fields, type-associated and interface methods
2166 // have no parent scope
2168 switch obj := obj.(type) {
2174 if obj.Type().(*Signature).Recv() != nil { // method
2179 gotParent := obj.Parent() != nil
2181 case gotParent && !wantParent:
2182 t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
2183 case !gotParent && wantParent:
2184 t.Errorf("%v: no parent found", ident)
2189 // TestFailedImport tests that we don't get follow-on errors
2190 // elsewhere in a package due to failing to import a package.
2191 func TestFailedImport(t *testing.T) {
2192 testenv.MustHaveGoBuild(t)
2197 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
2202 func f(x T) T { return foo.F(x) }
2204 fset := token.NewFileSet()
2205 f, err := parser.ParseFile(fset, "src", src, 0)
2209 files := []*ast.File{f}
2211 // type-check using all possible importers
2212 for _, compiler := range []string{"gc", "gccgo", "source"} {
2215 Error: func(err error) {
2216 // we should only see the import error
2217 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
2218 t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
2222 Importer: importer.For(compiler, nil),
2226 Uses: make(map[*ast.Ident]Object),
2228 pkg, _ := conf.Check("p", fset, files, info)
2230 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
2234 imports := pkg.Imports()
2235 if len(imports) != 1 {
2236 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
2240 if imp.Name() != "foo" {
2241 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
2245 // verify that all uses of foo refer to the imported package foo (imp)
2246 for ident, obj := range info.Uses {
2247 if ident.Name == "foo" {
2248 if obj, ok := obj.(*PkgName); ok {
2249 if obj.Imported() != imp {
2250 t.Errorf("%s resolved to %v; want %v", ident, obj.Imported(), imp)
2253 t.Errorf("%s resolved to %v; want package name", ident, obj)
2260 func TestInstantiate(t *testing.T) {
2261 // eventually we like more tests but this is a start
2262 const src = "package p; type T[P any] *T[P]"
2263 pkg, err := pkgForMode(".", src, nil, 0)
2268 // type T should have one type parameter
2269 T := pkg.Scope().Lookup("T").Type().(*Named)
2270 if n := T.TypeParams().Len(); n != 1 {
2271 t.Fatalf("expected 1 type parameter; found %d", n)
2274 // instantiation should succeed (no endless recursion)
2275 // even with a nil *Checker
2276 res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
2281 // instantiated type should point to itself
2282 if p := res.Underlying().(*Pointer).Elem(); p != res {
2283 t.Fatalf("unexpected result type: %s points to %s", res, p)
2287 func TestInstantiateErrors(t *testing.T) {
2289 src string // by convention, T must be the type being instantiated
2291 wantAt int // -1 indicates no error
2293 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
2294 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
2295 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
2296 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
2299 for _, test := range tests {
2300 src := "package p; " + test.src
2301 pkg, err := pkgForMode(".", src, nil, 0)
2306 T := pkg.Scope().Lookup("T").Type().(*Named)
2308 _, err = Instantiate(nil, T, test.targs, true)
2310 t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
2313 var argErr *ArgumentError
2314 if !errors.As(err, &argErr) {
2315 t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
2318 if argErr.Index != test.wantAt {
2319 t.Errorf("Instantate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2324 func TestArgumentErrorUnwrapping(t *testing.T) {
2325 var err error = &ArgumentError{
2327 Err: Error{Msg: "test"},
2330 if !errors.As(err, &e) {
2331 t.Fatalf("error %v does not wrap types.Error", err)
2333 if e.Msg != "test" {
2334 t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2338 func TestInstanceIdentity(t *testing.T) {
2339 imports := make(testImporter)
2340 conf := Config{Importer: imports}
2341 makePkg := func(src string) {
2342 fset := token.NewFileSet()
2343 f, err := parser.ParseFile(fset, "", src, 0)
2348 pkg, err := conf.Check(name, fset, []*ast.File{f}, nil)
2354 makePkg(genericPkg + `lib; type T[P any] struct{}`)
2355 makePkg(genericPkg + `a; import "generic_lib"; var A generic_lib.T[int]`)
2356 makePkg(genericPkg + `b; import "generic_lib"; var B generic_lib.T[int]`)
2357 a := imports["generic_a"].Scope().Lookup("A")
2358 b := imports["generic_b"].Scope().Lookup("B")
2359 if !Identical(a.Type(), b.Type()) {
2360 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
2364 // TestInstantiatedObjects verifies properties of instantiated objects.
2365 func TestInstantiatedObjects(t *testing.T) {
2369 type T[P any] struct {
2373 func (recv *T[Q]) concreteMethod(mParam Q) (mResult Q) { return }
2375 type FT[P any] func(ftParam P) (ftResult P)
2377 func F[P any](fParam P) (fResult P){ return }
2379 type I[P any] interface {
2385 func (R[P]) m() {} // having a method triggers expansion of R
2400 Defs: make(map[*ast.Ident]Object),
2402 fset := token.NewFileSet()
2403 f, err := parser.ParseFile(fset, "p.go", src, 0)
2408 pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
2413 lookup := func(name string) Type { return pkg.Scope().Lookup(name).Type() }
2414 fnScope := pkg.Scope().Lookup("fn").(*Func).Scope()
2421 {"field", lookup("t").Underlying().(*Struct).Field(0)},
2422 {"field", fnScope.Lookup("r").Type().Underlying().(*Struct).Field(0)},
2424 // Methods and method fields
2425 {"concreteMethod", lookup("t").(*Named).Method(0)},
2426 {"recv", lookup("t").(*Named).Method(0).Type().(*Signature).Recv()},
2427 {"mParam", lookup("t").(*Named).Method(0).Type().(*Signature).Params().At(0)},
2428 {"mResult", lookup("t").(*Named).Method(0).Type().(*Signature).Results().At(0)},
2430 // Interface methods
2431 {"interfaceMethod", lookup("i").Underlying().(*Interface).Method(0)},
2433 // Function type fields
2434 {"ftParam", lookup("ft").Underlying().(*Signature).Params().At(0)},
2435 {"ftResult", lookup("ft").Underlying().(*Signature).Results().At(0)},
2438 {"fParam", lookup("f").(*Signature).Params().At(0)},
2439 {"fResult", lookup("f").(*Signature).Results().At(0)},
2442 // Collect all identifiers by name.
2443 idents := make(map[string][]*ast.Ident)
2444 ast.Inspect(f, func(n ast.Node) bool {
2445 if id, ok := n.(*ast.Ident); ok {
2446 idents[id.Name] = append(idents[id.Name], id)
2451 for _, test := range tests {
2453 t.Run(test.name, func(t *testing.T) {
2454 if got := len(idents[test.name]); got != 1 {
2455 t.Fatalf("found %d identifiers named %s, want 1", got, test.name)
2457 ident := idents[test.name][0]
2458 def := info.Defs[ident]
2459 if def == test.obj {
2460 t.Fatalf("info.Defs[%s] contains the test object", test.name)
2462 if orig := originObject(test.obj); def != orig {
2463 t.Errorf("info.Defs[%s] does not match obj.Origin()", test.name)
2465 if def.Pkg() != test.obj.Pkg() {
2466 t.Errorf("Pkg() = %v, want %v", def.Pkg(), test.obj.Pkg())
2468 if def.Name() != test.obj.Name() {
2469 t.Errorf("Name() = %v, want %v", def.Name(), test.obj.Name())
2471 if def.Pos() != test.obj.Pos() {
2472 t.Errorf("Pos() = %v, want %v", def.Pos(), test.obj.Pos())
2474 if def.Parent() != test.obj.Parent() {
2475 t.Fatalf("Parent() = %v, want %v", def.Parent(), test.obj.Parent())
2477 if def.Exported() != test.obj.Exported() {
2478 t.Fatalf("Exported() = %v, want %v", def.Exported(), test.obj.Exported())
2480 if def.Id() != test.obj.Id() {
2481 t.Fatalf("Id() = %v, want %v", def.Id(), test.obj.Id())
2483 // String and Type are expected to differ.
2488 func originObject(obj Object) Object {
2489 switch obj := obj.(type) {
2498 func TestImplements(t *testing.T) {
2502 type EmptyIface interface{}
2513 type Integer interface{
2514 int8 | int16 | int32 | int64
2517 type EmptyTypeSet interface{
2534 type Bad Bad // invalid type
2537 fset := token.NewFileSet()
2538 f, err := parser.ParseFile(fset, "p.go", src, 0)
2542 conf := Config{Error: func(error) {}}
2543 pkg, _ := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
2545 lookup := func(tname string) Type { return pkg.Scope().Lookup(tname).Type() }
2547 EmptyIface = lookup("EmptyIface").Underlying().(*Interface)
2548 I = lookup("I").(*Named)
2549 II = I.Underlying().(*Interface)
2550 C = lookup("C").(*Named)
2551 CI = C.Underlying().(*Interface)
2552 Integer = lookup("Integer").Underlying().(*Interface)
2553 EmptyTypeSet = lookup("EmptyTypeSet").Underlying().(*Interface)
2555 N1p = NewPointer(N1)
2557 N2p = NewPointer(N2)
2572 {Typ[Int8], Integer, true},
2573 {Typ[Int64], Integer, true},
2574 {Typ[String], Integer, false},
2575 {EmptyTypeSet, II, true},
2576 {EmptyTypeSet, EmptyTypeSet, true},
2577 {Typ[Int], EmptyTypeSet, false},
2592 {Bad, EmptyIface, true},
2595 for _, test := range tests {
2596 if got := Implements(test.V, test.T); got != test.want {
2597 t.Errorf("Implements(%s, %s) = %t, want %t", test.V, test.T, got, test.want)
2600 // The type assertion x.(T) is valid if T is an interface or if T implements the type of x.
2601 // The assertion is never valid if T is a bad type.
2605 if _, ok := T.Underlying().(*Interface); (ok || Implements(T, V)) && T != Bad {
2608 if got := AssertableTo(V, T); got != want {
2609 t.Errorf("AssertableTo(%s, %s) = %t, want %t", V, T, got, want)
2614 func TestMissingMethodAlternative(t *testing.T) {
2636 pkg, err := pkgFor("p.go", src, nil)
2641 T := pkg.Scope().Lookup("T").Type().Underlying().(*Interface)
2642 lookup := func(name string) (*Func, bool) {
2643 return MissingMethod(pkg.Scope().Lookup(name).Type(), T, true)
2646 // V0 has method m with correct signature. Should not report wrongType.
2647 method, wrongType := lookup("V0")
2648 if method != nil || wrongType {
2649 t.Fatalf("V0: got method = %v, wrongType = %v", method, wrongType)
2652 checkMissingMethod := func(tname string, reportWrongType bool) {
2653 method, wrongType := lookup(tname)
2654 if method == nil || method.Name() != "m" || wrongType != reportWrongType {
2655 t.Fatalf("%s: got method = %v, wrongType = %v", tname, method, wrongType)
2659 // V1 has no method m. Should not report wrongType.
2660 checkMissingMethod("V1", false)
2662 // V2 has method m with wrong signature type (ignoring receiver). Should report wrongType.
2663 checkMissingMethod("V2", true)
2665 // V3 has no method m but it exists on *V3. Should report wrongType.
2666 checkMissingMethod("V3", true)
2668 // V4 has no method m but has M. Should not report wrongType.
2669 checkMissingMethod("V4", false)