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.
8 "cmd/compile/internal/syntax"
18 . "cmd/compile/internal/types2"
21 // nopos indicates an unknown position
24 func mustParse(src string) *syntax.File {
25 f, err := syntax.Parse(syntax.NewFileBase(pkgName(src)), strings.NewReader(src), nil, nil, 0)
27 panic(err) // so we don't need to pass *testing.T
32 func typecheck(src string, conf *Config, info *Info) (*Package, error) {
36 Error: func(err error) {}, // collect all errors
37 Importer: defaultImporter(),
40 return conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
43 func mustTypecheck(src string, conf *Config, info *Info) *Package {
44 pkg, err := typecheck(src, conf, info)
46 panic(err) // so we don't need to pass *testing.T
51 // pkgName extracts the package name from src, which must contain a package header.
52 func pkgName(src string) string {
54 if i := strings.Index(src, kw); i >= 0 {
55 after := src[i+len(kw):]
57 if i := strings.IndexAny(after, "\n\t ;/"); i >= 0 {
62 panic("missing package header: " + src)
65 func TestValuesInfo(t *testing.T) {
66 var tests = []struct {
68 expr string // constant expression
69 typ string // constant type
70 val string // constant value
72 {`package a0; const _ = false`, `false`, `untyped bool`, `false`},
73 {`package a1; const _ = 0`, `0`, `untyped int`, `0`},
74 {`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
75 {`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
76 {`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
77 {`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
79 {`package b0; var _ = false`, `false`, `bool`, `false`},
80 {`package b1; var _ = 0`, `0`, `int`, `0`},
81 {`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
82 {`package b3; var _ = 0.`, `0.`, `float64`, `0`},
83 {`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
84 {`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
86 {`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
87 {`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
88 {`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
90 {`package c1a; var _ = int(0)`, `0`, `int`, `0`},
91 {`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
92 {`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
94 {`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
95 {`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
96 {`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
98 {`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
99 {`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
100 {`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
102 {`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
103 {`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
104 {`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
106 {`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
107 {`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
108 {`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
109 {`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
110 {`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
111 {`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
113 {`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
114 {`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
115 {`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
116 {`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
118 {`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
119 {`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
120 {`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
121 {`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
122 {`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
123 {`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
124 {`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
125 {`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
127 {`package f0 ; var _ float32 = 1e-200`, `1e-200`, `float32`, `0`},
128 {`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
129 {`package f2a; var _ float64 = 1e-2000`, `1e-2000`, `float64`, `0`},
130 {`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
131 {`package f2b; var _ = 1e-2000`, `1e-2000`, `float64`, `0`},
132 {`package f3b; var _ = -1e-2000`, `-1e-2000`, `float64`, `0`},
133 {`package f4 ; var _ complex64 = 1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
134 {`package f5 ; var _ complex64 = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
135 {`package f6a; var _ complex128 = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
136 {`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
137 {`package f6b; var _ = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
138 {`package f7b; var _ = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
140 {`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // go.dev/issue/22341
141 {`package g1; var(j int32; s int; n = 1.0<<s == j)`, `1.0`, `int32`, `1`}, // go.dev/issue/48422
144 for _, test := range tests {
146 Types: make(map[syntax.Expr]TypeAndValue),
148 name := mustTypecheck(test.src, nil, &info).Name()
150 // look for expression
152 for e := range info.Types {
153 if syntax.String(e) == test.expr {
159 t.Errorf("package %s: no expression found for %s", name, test.expr)
162 tv := info.Types[expr]
164 // check that type is correct
165 if got := tv.Type.String(); got != test.typ {
166 t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
170 // if we have a constant, check that value is correct
172 if got := tv.Value.ExactString(); got != test.val {
173 t.Errorf("package %s: got value %s; want %s", name, got, test.val)
177 t.Errorf("package %s: no constant found; want %s", name, test.val)
183 func TestTypesInfo(t *testing.T) {
184 // Test sources that are not expected to typecheck must start with the broken prefix.
185 const brokenPkg = "package broken_"
187 var tests = []struct {
189 expr string // expression
190 typ string // value type
192 // single-valued expressions of untyped constants
193 {`package b0; var x interface{} = false`, `false`, `bool`},
194 {`package b1; var x interface{} = 0`, `0`, `int`},
195 {`package b2; var x interface{} = 0.`, `0.`, `float64`},
196 {`package b3; var x interface{} = 0i`, `0i`, `complex128`},
197 {`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
200 {`package n0; var _ *int = nil`, `nil`, `*int`},
201 {`package n1; var _ func() = nil`, `nil`, `func()`},
202 {`package n2; var _ []byte = nil`, `nil`, `[]byte`},
203 {`package n3; var _ map[int]int = nil`, `nil`, `map[int]int`},
204 {`package n4; var _ chan int = nil`, `nil`, `chan int`},
205 {`package n5a; var _ interface{} = (*int)(nil)`, `nil`, `*int`},
206 {`package n5b; var _ interface{m()} = nil`, `nil`, `interface{m()}`},
207 {`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `unsafe.Pointer`},
209 {`package n10; var (x *int; _ = x == nil)`, `nil`, `*int`},
210 {`package n11; var (x func(); _ = x == nil)`, `nil`, `func()`},
211 {`package n12; var (x []byte; _ = x == nil)`, `nil`, `[]byte`},
212 {`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `map[int]int`},
213 {`package n14; var (x chan int; _ = x == nil)`, `nil`, `chan int`},
214 {`package n15a; var (x interface{}; _ = x == (*int)(nil))`, `nil`, `*int`},
215 {`package n15b; var (x interface{m()}; _ = x == nil)`, `nil`, `interface{m()}`},
216 {`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `unsafe.Pointer`},
218 {`package n20; var _ = (*int)(nil)`, `nil`, `*int`},
219 {`package n21; var _ = (func())(nil)`, `nil`, `func()`},
220 {`package n22; var _ = ([]byte)(nil)`, `nil`, `[]byte`},
221 {`package n23; var _ = (map[int]int)(nil)`, `nil`, `map[int]int`},
222 {`package n24; var _ = (chan int)(nil)`, `nil`, `chan int`},
223 {`package n25a; var _ = (interface{})((*int)(nil))`, `nil`, `*int`},
224 {`package n25b; var _ = (interface{m()})(nil)`, `nil`, `interface{m()}`},
225 {`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `unsafe.Pointer`},
227 {`package n30; func f(*int) { f(nil) }`, `nil`, `*int`},
228 {`package n31; func f(func()) { f(nil) }`, `nil`, `func()`},
229 {`package n32; func f([]byte) { f(nil) }`, `nil`, `[]byte`},
230 {`package n33; func f(map[int]int) { f(nil) }`, `nil`, `map[int]int`},
231 {`package n34; func f(chan int) { f(nil) }`, `nil`, `chan int`},
232 {`package n35a; func f(interface{}) { f((*int)(nil)) }`, `nil`, `*int`},
233 {`package n35b; func f(interface{m()}) { f(nil) }`, `nil`, `interface{m()}`},
234 {`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `unsafe.Pointer`},
236 // comma-ok expressions
237 {`package p0; var x interface{}; var _, _ = x.(int)`,
241 {`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
245 {`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
247 `(complex128, p2a.mybool)`,
249 {`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
251 `(complex128, bool)`,
253 {`package p3; var c chan string; var _, _ = <-c`,
259 {`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
263 {`package issue6796_b; var c chan string; var _, _ = (<-c)`,
267 {`package issue6796_c; var c chan string; var _, _ = (<-c)`,
271 {`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
275 {`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
281 {`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
285 {`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
289 {`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
293 {`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
297 {`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
301 {`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
306 // go.dev/issue/28277
307 {`package issue28277_a; func f(...int)`,
311 {`package issue28277_b; func f(a, b int, c ...[]struct{})`,
316 // go.dev/issue/47243
317 {`package issue47243_a; var x int32; var _ = x << 3`, `3`, `untyped int`},
318 {`package issue47243_b; var x int32; var _ = x << 3.`, `3.`, `untyped float`},
319 {`package issue47243_c; var x int32; var _ = 1 << x`, `1 << x`, `int`},
320 {`package issue47243_d; var x int32; var _ = 1 << x`, `1`, `int`},
321 {`package issue47243_e; var x int32; var _ = 1 << 2`, `1`, `untyped int`},
322 {`package issue47243_f; var x int32; var _ = 1 << 2`, `2`, `untyped int`},
323 {`package issue47243_g; var x int32; var _ = int(1) << 2`, `2`, `untyped int`},
324 {`package issue47243_h; var x int32; var _ = 1 << (2 << x)`, `1`, `int`},
325 {`package issue47243_i; var x int32; var _ = 1 << (2 << x)`, `(2 << x)`, `untyped int`},
326 {`package issue47243_j; var x int32; var _ = 1 << (2 << x)`, `2`, `untyped int`},
328 // tests for broken code that doesn't type-check
329 {brokenPkg + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
330 {brokenPkg + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
331 {brokenPkg + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a, f: b,}}`, `b`, `string`},
332 {brokenPkg + `x3; var x = panic("");`, `panic`, `func(interface{})`},
333 {`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
334 {brokenPkg + `x5; func _() { var x map[string][...]int; x = map[string][...]int{"": {1,2,3}} }`, `x`, `map[string]invalid type`},
336 // parameterized functions
337 {`package p0; func f[T any](T) {}; var _ = f[int]`, `f`, `func[T any](T)`},
338 {`package p1; func f[T any](T) {}; var _ = f[int]`, `f[int]`, `func(int)`},
339 {`package p2; func f[T any](T) {}; func _() { f(42) }`, `f`, `func(int)`},
340 {`package p3; func f[T any](T) {}; func _() { f[int](42) }`, `f[int]`, `func(int)`},
341 {`package p4; func f[T any](T) {}; func _() { f[int](42) }`, `f`, `func[T any](T)`},
342 {`package p5; func f[T any](T) {}; func _() { f(42) }`, `f(42)`, `()`},
345 {`package t0; type t[] int; var _ t`, `t`, `t0.t`}, // t[] is a syntax error that is ignored in this test in favor of t
346 {`package t1; type t[P any] int; var _ t[int]`, `t`, `t1.t[P any]`},
347 {`package t2; type t[P interface{}] int; var _ t[int]`, `t`, `t2.t[P interface{}]`},
348 {`package t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `t3.t[P, Q interface{}]`},
349 {brokenPkg + `t4; type t[P, Q interface{ m() }] int; var _ t[int, int]`, `t`, `broken_t4.t[P, Q interface{m()}]`},
351 // instantiated types must be sanitized
352 {`package g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `g0.t[int]`},
354 // go.dev/issue/45096
355 {`package issue45096; func _[T interface{ ~int8 | ~int16 | ~int32 }](x T) { _ = x < 0 }`, `0`, `T`},
357 // go.dev/issue/47895
358 {`package p; import "unsafe"; type S struct { f int }; var s S; var _ = unsafe.Offsetof(s.f)`, `s.f`, `int`},
360 // go.dev/issue/50093
361 {`package u0a; func _[_ interface{int}]() {}`, `int`, `int`},
362 {`package u1a; func _[_ interface{~int}]() {}`, `~int`, `~int`},
363 {`package u2a; func _[_ interface{int | string}]() {}`, `int | string`, `int | string`},
364 {`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `int | string | ~bool`, `int | string | ~bool`},
365 {`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `int | string`, `int | string`},
366 {`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `~bool`, `~bool`},
367 {`package u3a; func _[_ interface{int | string | ~float64|~bool}]() {}`, `int | string | ~float64`, `int | string | ~float64`},
369 {`package u0b; func _[_ int]() {}`, `int`, `int`},
370 {`package u1b; func _[_ ~int]() {}`, `~int`, `~int`},
371 {`package u2b; func _[_ int | string]() {}`, `int | string`, `int | string`},
372 {`package u3b; func _[_ int | string | ~bool]() {}`, `int | string | ~bool`, `int | string | ~bool`},
373 {`package u3b; func _[_ int | string | ~bool]() {}`, `int | string`, `int | string`},
374 {`package u3b; func _[_ int | string | ~bool]() {}`, `~bool`, `~bool`},
375 {`package u3b; func _[_ int | string | ~float64|~bool]() {}`, `int | string | ~float64`, `int | string | ~float64`},
377 {`package u0c; type _ interface{int}`, `int`, `int`},
378 {`package u1c; type _ interface{~int}`, `~int`, `~int`},
379 {`package u2c; type _ interface{int | string}`, `int | string`, `int | string`},
380 {`package u3c; type _ interface{int | string | ~bool}`, `int | string | ~bool`, `int | string | ~bool`},
381 {`package u3c; type _ interface{int | string | ~bool}`, `int | string`, `int | string`},
382 {`package u3c; type _ interface{int | string | ~bool}`, `~bool`, `~bool`},
383 {`package u3c; type _ interface{int | string | ~float64|~bool}`, `int | string | ~float64`, `int | string | ~float64`},
386 for _, test := range tests {
387 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
389 if strings.HasPrefix(test.src, brokenPkg) {
390 pkg, err := typecheck(test.src, nil, &info)
392 t.Errorf("package %s: expected to fail but passed", pkg.Name())
399 name = mustTypecheck(test.src, nil, &info).Name()
402 // look for expression type
404 for e, tv := range info.Types {
405 if syntax.String(e) == test.expr {
411 t.Errorf("package %s: no type found for %s", name, test.expr)
415 // check that type is correct
416 if got := typ.String(); got != test.typ {
417 t.Errorf("package %s: got %s; want %s", name, got, test.typ)
422 func TestInstanceInfo(t *testing.T) {
423 const lib = `package lib
430 type testInst struct {
436 var tests = []struct {
438 instances []testInst // recorded instances in source order
440 {`package p0; func f[T any](T) {}; func _() { f(42) }`,
441 []testInst{{`f`, []string{`int`}, `func(int)`}},
443 {`package p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
444 []testInst{{`f`, []string{`rune`}, `func(rune) rune`}},
446 {`package p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
447 []testInst{{`f`, []string{`complex128`}, `func(...complex128) complex128`}},
449 {`package p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
450 []testInst{{`f`, []string{`float64`, `string`, `byte`}, `func(float64, *string, []byte)`}},
452 {`package p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
453 []testInst{{`f`, []string{`float64`, `byte`}, `func(float64, *byte, ...[]byte)`}},
456 {`package s1; func f[T any, P interface{*T}](x T) {}; func _(x string) { f(x) }`,
457 []testInst{{`f`, []string{`string`, `*string`}, `func(x string)`}},
459 {`package s2; func f[T any, P interface{*T}](x []T) {}; func _(x []int) { f(x) }`,
460 []testInst{{`f`, []string{`int`, `*int`}, `func(x []int)`}},
462 {`package s3; type C[T any] interface{chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
464 {`C`, []string{`T`}, `interface{chan<- T}`},
465 {`f`, []string{`int`, `chan<- int`}, `func(x []int)`},
468 {`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) }`,
470 {`C`, []string{`T`}, `interface{chan<- T}`},
471 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
472 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func(x []int)`},
476 {`package t1; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = f[string] }`,
477 []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
479 {`package t2; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = (f[string]) }`,
480 []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
482 {`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] }`,
484 {`C`, []string{`T`}, `interface{chan<- T}`},
485 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
486 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
489 {`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]) }`,
491 {`C`, []string{`T`}, `interface{chan<- T}`},
492 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
493 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
496 {`package i0; import "lib"; func _() { lib.F(42) }`,
497 []testInst{{`F`, []string{`int`}, `func(int)`}},
500 {`package duplfunc0; func f[T any](T) {}; func _() { f(42); f("foo"); f[int](3) }`,
502 {`f`, []string{`int`}, `func(int)`},
503 {`f`, []string{`string`}, `func(string)`},
504 {`f`, []string{`int`}, `func(int)`},
507 {`package duplfunc1; import "lib"; func _() { lib.F(42); lib.F("foo"); lib.F(3) }`,
509 {`F`, []string{`int`}, `func(int)`},
510 {`F`, []string{`string`}, `func(string)`},
511 {`F`, []string{`int`}, `func(int)`},
515 {`package type0; type T[P interface{~int}] struct{ x P }; var _ T[int]`,
516 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
518 {`package type1; type T[P interface{~int}] struct{ x P }; var _ (T[int])`,
519 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
521 {`package type2; type T[P interface{~int}] struct{ x P }; var _ T[(int)]`,
522 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
524 {`package type3; type T[P1 interface{~[]P2}, P2 any] struct{ x P1; y P2 }; var _ T[[]int, int]`,
525 []testInst{{`T`, []string{`[]int`, `int`}, `struct{x []int; y int}`}},
527 {`package type4; import "lib"; var _ lib.T[int]`,
528 []testInst{{`T`, []string{`int`}, `[]int`}},
531 {`package dupltype0; type T[P interface{~int}] struct{ x P }; var x T[int]; var y T[int]`,
533 {`T`, []string{`int`}, `struct{x int}`},
534 {`T`, []string{`int`}, `struct{x int}`},
537 {`package dupltype1; type T[P ~int] struct{ x P }; func (r *T[Q]) add(z T[Q]) { r.x += z.x }`,
539 {`T`, []string{`Q`}, `struct{x Q}`},
540 {`T`, []string{`Q`}, `struct{x Q}`},
543 {`package dupltype1; import "lib"; var x lib.T[int]; var y lib.T[int]; var z lib.T[string]`,
545 {`T`, []string{`int`}, `[]int`},
546 {`T`, []string{`int`}, `[]int`},
547 {`T`, []string{`string`}, `[]string`},
550 {`package issue51803; func foo[T any](T) {}; func _() { foo[int]( /* leave arg away on purpose */ ) }`,
551 []testInst{{`foo`, []string{`int`}, `func(int)`}},
554 // reverse type parameter inference
555 {`package reverse1a; var f func(int) = g; func g[P any](P) {}`,
556 []testInst{{`g`, []string{`int`}, `func(int)`}},
558 {`package reverse1b; func f(func(int)) {}; func g[P any](P) {}; func _() { f(g) }`,
559 []testInst{{`g`, []string{`int`}, `func(int)`}},
561 {`package reverse2a; var f func(int) string = g; func g[P, Q any](P) Q { var q Q; return q }`,
562 []testInst{{`g`, []string{`int`, `string`}, `func(int) string`}},
564 {`package reverse2b; func f(func(int) string) {}; func g[P, Q any](P) Q { var q Q; return q }; func _() { f(g) }`,
565 []testInst{{`g`, []string{`int`, `string`}, `func(int) string`}},
567 // reverse3a not possible (cannot assign to generic function outside of argument passing)
568 {`package reverse3b; func f[R any](func(int) R) {}; func g[P any](P) string { return "" }; func _() { f(g) }`,
570 {`f`, []string{`string`}, `func(func(int) string)`},
571 {`g`, []string{`int`}, `func(int) string`},
574 {`package reverse4a; var _, _ func([]int, *float32) = g, h; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}`,
576 {`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
577 {`h`, []string{`int`}, `func([]int, *float32)`},
580 {`package reverse4b; func f(_, _ func([]int, *float32)) {}; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}; func _() { f(g, h) }`,
582 {`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
583 {`h`, []string{`int`}, `func([]int, *float32)`},
586 {`package issue59956; func f(func(int), func(string), func(bool)) {}; func g[P any](P) {}; func _() { f(g, g, g) }`,
588 {`g`, []string{`int`}, `func(int)`},
589 {`g`, []string{`string`}, `func(string)`},
590 {`g`, []string{`bool`}, `func(bool)`},
595 for _, test := range tests {
596 imports := make(testImporter)
597 conf := Config{Importer: imports}
598 instMap := make(map[*syntax.Name]Instance)
599 useMap := make(map[*syntax.Name]Object)
600 makePkg := func(src string) *Package {
601 pkg, err := typecheck(src, &conf, &Info{Instances: instMap, Uses: useMap})
602 // allow error for issue51803
603 if err != nil && (pkg == nil || pkg.Name() != "issue51803") {
606 imports[pkg.Name()] = pkg
610 pkg := makePkg(test.src)
612 t.Run(pkg.Name(), func(t *testing.T) {
613 // Sort instances in source order for stability.
614 instances := sortedInstances(instMap)
615 if got, want := len(instances), len(test.instances); got != want {
616 t.Fatalf("got %d instances, want %d", got, want)
619 // Pairwise compare with the expected instances.
620 for ii, inst := range instances {
622 for i := 0; i < inst.Inst.TypeArgs.Len(); i++ {
623 targs = append(targs, inst.Inst.TypeArgs.At(i))
625 typ := inst.Inst.Type
627 testInst := test.instances[ii]
628 if got := inst.Name.Value; got != testInst.name {
629 t.Fatalf("got name %s, want %s", got, testInst.name)
632 if len(targs) != len(testInst.targs) {
633 t.Fatalf("got %d type arguments; want %d", len(targs), len(testInst.targs))
635 for i, targ := range targs {
636 if got := targ.String(); got != testInst.targs[i] {
637 t.Errorf("type argument %d: got %s; want %s", i, got, testInst.targs[i])
640 if got := typ.Underlying().String(); got != testInst.typ {
641 t.Errorf("package %s: got %s; want %s", pkg.Name(), got, testInst.typ)
644 // Verify the invariant that re-instantiating the corresponding generic
645 // type with TypeArgs results in an identical instance.
646 ptype := useMap[inst.Name].Type()
647 lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
648 if lister == nil || lister.TypeParams().Len() == 0 {
649 t.Fatalf("info.Types[%v] = %v, want parameterized type", inst.Name, ptype)
651 inst2, err := Instantiate(nil, ptype, targs, true)
653 t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
655 if !Identical(inst.Inst.Type, inst2) {
656 t.Errorf("%v and %v are not identical", inst.Inst.Type, inst2)
663 type recordedInstance struct {
668 func sortedInstances(m map[*syntax.Name]Instance) (instances []recordedInstance) {
669 for id, inst := range m {
670 instances = append(instances, recordedInstance{id, inst})
672 sort.Slice(instances, func(i, j int) bool {
673 return CmpPos(instances[i].Name.Pos(), instances[j].Name.Pos()) < 0
678 func TestDefsInfo(t *testing.T) {
679 var tests = []struct {
684 {`package p0; const x = 42`, `x`, `const p0.x untyped int`},
685 {`package p1; const x int = 42`, `x`, `const p1.x int`},
686 {`package p2; var x int`, `x`, `var p2.x int`},
687 {`package p3; type x int`, `x`, `type p3.x int`},
688 {`package p4; func f()`, `f`, `func p4.f()`},
689 {`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
691 // Tests using generics.
692 {`package g0; type x[T any] int`, `x`, `type g0.x[T any] int`},
693 {`package g1; func f[T any]() {}`, `f`, `func g1.f[T any]()`},
694 {`package g2; type x[T any] int; func (*x[_]) m() {}`, `m`, `func (*g2.x[_]).m()`},
697 for _, test := range tests {
699 Defs: make(map[*syntax.Name]Object),
701 name := mustTypecheck(test.src, nil, &info).Name()
705 for id, obj := range info.Defs {
706 if id.Value == test.obj {
712 t.Errorf("package %s: %s not found", name, test.obj)
716 if got := def.String(); got != test.want {
717 t.Errorf("package %s: got %s; want %s", name, got, test.want)
722 func TestUsesInfo(t *testing.T) {
723 var tests = []struct {
728 {`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
729 {`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
730 {`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
731 {`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
732 {`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
734 // Tests using generics.
735 {`package g0; func _[T any]() { _ = x }; const x = 42`, `x`, `const g0.x untyped int`},
736 {`package g1; func _[T any](x T) { }`, `T`, `type parameter T any`},
737 {`package g2; type N[A any] int; var _ N[int]`, `N`, `type g2.N[A any] int`},
738 {`package g3; type N[A any] int; func (N[_]) m() {}`, `N`, `type g3.N[A any] int`},
740 // Uses of fields are instantiated.
741 {`package s1; type N[A any] struct{ a A }; var f = N[int]{}.a`, `a`, `field a int`},
742 {`package s1; type N[A any] struct{ a A }; func (r N[B]) m(b B) { r.a = b }`, `a`, `field a B`},
744 // Uses of methods are uses of the instantiated method.
745 {`package m0; type N[A any] int; func (r N[B]) m() { r.n() }; func (N[C]) n() {}`, `n`, `func (m0.N[B]).n()`},
746 {`package m1; type N[A any] int; func (r N[B]) m() { }; var f = N[int].m`, `m`, `func (m1.N[int]).m()`},
747 {`package m2; func _[A any](v interface{ m() A }) { v.m() }`, `m`, `func (interface).m() A`},
748 {`package m3; func f[A any]() interface{ m() A } { return nil }; var _ = f[int]().m()`, `m`, `func (interface).m() int`},
749 {`package m4; type T[A any] func() interface{ m() A }; var x T[int]; var y = x().m`, `m`, `func (interface).m() int`},
750 {`package m5; type T[A any] interface{ m() A }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m5.T[B]).m() B`},
751 {`package m6; type T[A any] interface{ m() }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m6.T[B]).m()`},
752 {`package m7; type T[A any] interface{ m() A }; func _(t T[int]) { t.m() }`, `m`, `func (m7.T[int]).m() int`},
753 {`package m8; type T[A any] interface{ m() }; func _(t T[int]) { t.m() }`, `m`, `func (m8.T[int]).m()`},
754 {`package m9; type T[A any] interface{ m() }; func _(t T[int]) { _ = t.m }`, `m`, `func (m9.T[int]).m()`},
756 `package m10; type E[A any] interface{ m() }; type T[B any] interface{ E[B]; n() }; func _(t T[int]) { t.m() }`,
758 `func (m10.E[int]).m()`,
762 for _, test := range tests {
764 Uses: make(map[*syntax.Name]Object),
766 name := mustTypecheck(test.src, nil, &info).Name()
770 for id, obj := range info.Uses {
771 if id.Value == test.obj {
773 panic(fmt.Sprintf("multiple uses of %q", id.Value))
779 t.Errorf("package %s: %s not found", name, test.obj)
783 if got := use.String(); got != test.want {
784 t.Errorf("package %s: got %s; want %s", name, got, test.want)
789 func TestGenericMethodInfo(t *testing.T) {
794 func (r N[B]) m() { r.m(); r.n() }
796 func (r *N[C]) n() { }
800 Defs: make(map[*syntax.Name]Object),
801 Uses: make(map[*syntax.Name]Object),
802 Selections: make(map[*syntax.SelectorExpr]*Selection),
805 pkg, err := conf.Check("p", []*syntax.File{f}, &info)
810 N := pkg.Scope().Lookup("N").Type().(*Named)
812 // Find the generic methods stored on N.
813 gm, gn := N.Method(0), N.Method(1)
814 if gm.Name() == "n" {
818 // Collect objects from info.
819 var dm, dn *Func // the declared methods
820 var dmm, dmn *Func // the methods used in the body of m
821 for _, decl := range f.DeclList {
822 fdecl, ok := decl.(*syntax.FuncDecl)
826 def := info.Defs[fdecl.Name].(*Func)
827 switch fdecl.Name.Value {
830 syntax.Inspect(fdecl.Body, func(n syntax.Node) bool {
831 if call, ok := n.(*syntax.CallExpr); ok {
832 sel := call.Fun.(*syntax.SelectorExpr)
833 use := info.Uses[sel.Sel].(*Func)
834 selection := info.Selections[sel]
835 if selection.Kind() != MethodVal {
836 t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
838 if selection.Obj() != use {
839 t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
841 switch sel.Sel.Value {
856 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
859 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
862 t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
865 t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
869 func TestImplicitsInfo(t *testing.T) {
870 testenv.MustHaveGoBuild(t)
872 var tests = []struct {
876 {`package p2; import . "fmt"; var _ = Println`, ""}, // no Implicits entry
877 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
878 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
880 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
881 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
882 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
883 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
885 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
886 {`package p8; func f(int) {}`, "field: var int"},
887 {`package p9; func f() (complex64) { return 0 }`, "field: var complex64"},
888 {`package p10; type T struct{}; func (*T) f() {}`, "field: var *p10.T"},
890 // Tests using generics.
891 {`package f0; func f[T any](x int) {}`, ""}, // no Implicits entry
892 {`package f1; func f[T any](int) {}`, "field: var int"},
893 {`package f2; func f[T any](T) {}`, "field: var T"},
894 {`package f3; func f[T any]() (complex64) { return 0 }`, "field: var complex64"},
895 {`package f4; func f[T any](t T) (T) { return t }`, "field: var T"},
896 {`package t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var *t0.T[_]"},
897 {`package t1; type T[A any] struct{}; func _(x interface{}) { switch t := x.(type) { case T[int]: _ = t } }`, "caseClause: var t t1.T[int]"},
898 {`package t2; type T[A any] struct{}; func _[P any](x interface{}) { switch t := x.(type) { case T[P]: _ = t } }`, "caseClause: var t t2.T[P]"},
899 {`package t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
902 for _, test := range tests {
904 Implicits: make(map[syntax.Node]Object),
906 name := mustTypecheck(test.src, nil, &info).Name()
908 // the test cases expect at most one Implicits entry
909 if len(info.Implicits) > 1 {
910 t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
914 // extract Implicits entry, if any
916 for n, obj := range info.Implicits {
917 switch x := n.(type) {
918 case *syntax.ImportDecl:
920 case *syntax.CaseClause:
925 t.Fatalf("package %s: unexpected %T", name, x)
927 got += ": " + obj.String()
931 if got != test.want {
932 t.Errorf("package %s: got %q; want %q", name, got, test.want)
937 func predString(tv TypeAndValue) string {
938 var buf strings.Builder
939 pred := func(b bool, s string) {
942 buf.WriteString(", ")
948 pred(tv.IsVoid(), "void")
949 pred(tv.IsType(), "type")
950 pred(tv.IsBuiltin(), "builtin")
951 pred(tv.IsValue() && tv.Value != nil, "const")
952 pred(tv.IsValue() && tv.Value == nil, "value")
953 pred(tv.IsNil(), "nil")
954 pred(tv.Addressable(), "addressable")
955 pred(tv.Assignable(), "assignable")
956 pred(tv.HasOk(), "hasOk")
964 func TestPredicatesInfo(t *testing.T) {
965 testenv.MustHaveGoBuild(t)
967 var tests = []struct {
973 {`package n0; func f() { f() }`, `f()`, `void`},
976 {`package t0; type _ int`, `int`, `type`},
977 {`package t1; type _ []int`, `[]int`, `type`},
978 {`package t2; type _ func()`, `func()`, `type`},
979 {`package t3; type _ func(int)`, `int`, `type`},
980 {`package t3; type _ func(...int)`, `...int`, `type`},
983 {`package b0; var _ = len("")`, `len`, `builtin`},
984 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
987 {`package c0; var _ = 42`, `42`, `const`},
988 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
989 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
992 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
993 {`package v1; var _ = &[]int{1}`, `[]int{…}`, `value`},
994 {`package v2; var _ = func(){}`, `func() {}`, `value`},
995 {`package v4; func f() { _ = f }`, `f`, `value`},
996 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
997 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
999 // addressable (and thus assignable) operands
1000 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
1001 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
1002 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
1003 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
1004 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
1005 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
1006 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
1007 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
1008 // composite literals are not addressable
1010 // assignable but not addressable values
1011 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1012 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1014 // hasOk expressions
1015 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
1016 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
1019 // - package names are collected in the Uses map
1020 // - identifiers being declared are collected in the Defs map
1021 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
1022 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
1023 {`package m2; const c = 0`, `c`, `<missing>`},
1024 {`package m3; type T int`, `T`, `<missing>`},
1025 {`package m4; var v int`, `v`, `<missing>`},
1026 {`package m5; func f() {}`, `f`, `<missing>`},
1027 {`package m6; func _(x int) {}`, `x`, `<missing>`},
1028 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
1029 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
1032 for _, test := range tests {
1033 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
1034 name := mustTypecheck(test.src, nil, &info).Name()
1036 // look for expression predicates
1038 for e, tv := range info.Types {
1039 //println(name, syntax.String(e))
1040 if syntax.String(e) == test.expr {
1041 got = predString(tv)
1046 if got != test.pred {
1047 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
1052 func TestScopesInfo(t *testing.T) {
1053 testenv.MustHaveGoBuild(t)
1055 var tests = []struct {
1057 scopes []string // list of scope descriptors of the form kind:varlist
1059 {`package p0`, []string{
1062 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
1065 {`package p2; func _() {}`, []string{
1068 {`package p3; func _(x, y int) {}`, []string{
1069 "file:", "func:x y",
1071 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
1072 "file:", "func:x y z", // redeclaration of x
1074 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
1075 "file:", "func:u x y",
1077 {`package p6; func _() { { var x int; _ = x } }`, []string{
1078 "file:", "func:", "block:x",
1080 {`package p7; func _() { if true {} }`, []string{
1081 "file:", "func:", "if:", "block:",
1083 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
1084 "file:", "func:", "if:x", "block:y",
1086 {`package p9; func _() { switch x := 0; x {} }`, []string{
1087 "file:", "func:", "switch:x",
1089 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
1090 "file:", "func:", "switch:x", "case:y", "case:",
1092 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
1093 "file:", "func:t", "switch:",
1095 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
1096 "file:", "func:t", "switch:t",
1098 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
1099 "file:", "func:t", "switch:", "case:x", // x implicitly declared
1101 {`package p14; func _() { select{} }`, []string{
1104 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
1105 "file:", "func:c", "comm:",
1107 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
1108 "file:", "func:c", "comm:i x",
1110 {`package p17; func _() { for{} }`, []string{
1111 "file:", "func:", "for:", "block:",
1113 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
1114 "file:", "func:n", "for:i", "block:",
1116 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
1117 "file:", "func:a", "for:i", "block:",
1119 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
1120 "file:", "func:a", "for:i x", "block:",
1124 for _, test := range tests {
1125 info := Info{Scopes: make(map[syntax.Node]*Scope)}
1126 name := mustTypecheck(test.src, nil, &info).Name()
1128 // number of scopes must match
1129 if len(info.Scopes) != len(test.scopes) {
1130 t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
1133 // scope descriptions must match
1134 for node, scope := range info.Scopes {
1136 switch node.(type) {
1139 case *syntax.FuncType:
1141 case *syntax.BlockStmt:
1143 case *syntax.IfStmt:
1145 case *syntax.SwitchStmt:
1147 case *syntax.SelectStmt:
1149 case *syntax.CaseClause:
1151 case *syntax.CommClause:
1153 case *syntax.ForStmt:
1156 kind = fmt.Sprintf("%T", node)
1159 // look for matching scope description
1160 desc := kind + ":" + strings.Join(scope.Names(), " ")
1162 for _, d := range test.scopes {
1169 t.Errorf("package %s: no matching scope found for %s", name, desc)
1175 func TestInitOrderInfo(t *testing.T) {
1176 var tests = []struct {
1180 {`package p0; var (x = 1; y = x)`, []string{
1183 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
1184 "a = 1", "b = 2", "c = 3",
1186 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
1187 "a = 1", "b = 2", "c = 3",
1189 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
1190 "_ = f()", // blank var
1192 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
1193 "a = 0", "z = 0", "y = z", "x = y",
1195 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
1196 "a, _ = m[0]", // blank var
1198 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
1199 "z = 0", "a, b = f()",
1201 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
1202 "b = 1", "a = func() int {…}()",
1204 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
1205 "c = 1", "a, b = func() (_, _ int) {…}()",
1207 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1210 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1211 "a = 0", "b = 0", "c = 0", "d = c + b",
1213 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
1214 "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
1216 // emit an initializer for n:1 initializations only once (not for each node
1217 // on the lhs which may appear in different order in the dependency graph)
1218 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
1219 "b = 0", "x, y = m[0]", "a = x",
1221 // test case from spec section on package initialization
1235 "d = 3", "b = f()", "c = f()", "a = c + b",
1237 // test case for go.dev/issue/7131
1241 func next() int { counter++; return counter }
1244 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1247 var b, c = next(), next()
1248 var d, e, f = next(), next(), next()
1250 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1252 // test case for go.dev/issue/10709
1262 func (T) m() int { return 0 }
1264 func makeT(n int) T {
1270 "t = makeT(0)", "v = t.m()",
1272 // test case for go.dev/issue/10709: same as test before, but variable decls swapped
1282 func (T) m() int { return 0 }
1284 func makeT(n int) T {
1290 "t = makeT(0)", "v = t.m()",
1292 // another candidate possibly causing problems with go.dev/issue/10709
1297 func f1() int { return g1() }
1298 func g1() int { f1(); return x1 }
1304 func f2() int { return g2() }
1305 func g2() int { return x2 }
1307 var x2 = 0`, []string{
1308 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1312 for _, test := range tests {
1314 name := mustTypecheck(test.src, nil, &info).Name()
1316 // number of initializers must match
1317 if len(info.InitOrder) != len(test.inits) {
1318 t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1322 // initializers must match
1323 for i, want := range test.inits {
1324 got := info.InitOrder[i].String()
1326 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1333 func TestMultiFileInitOrder(t *testing.T) {
1334 fileA := mustParse(`package main; var a = 1`)
1335 fileB := mustParse(`package main; var b = 2`)
1337 // The initialization order must not depend on the parse
1338 // order of the files, only on the presentation order to
1339 // the type-checker.
1340 for _, test := range []struct {
1341 files []*syntax.File
1344 {[]*syntax.File{fileA, fileB}, "[a = 1 b = 2]"},
1345 {[]*syntax.File{fileB, fileA}, "[b = 2 a = 1]"},
1348 if _, err := new(Config).Check("main", test.files, &info); err != nil {
1351 if got := fmt.Sprint(info.InitOrder); got != test.want {
1352 t.Fatalf("got %s; want %s", got, test.want)
1357 func TestFiles(t *testing.T) {
1358 var sources = []string{
1359 "package p; type T struct{}; func (T) m1() {}",
1360 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1361 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1366 pkg := NewPackage("p", "p")
1368 check := NewChecker(&conf, pkg, &info)
1370 for _, src := range sources {
1371 if err := check.Files([]*syntax.File{mustParse(src)}); err != nil {
1376 // check InitOrder is [x y]
1378 for _, init := range info.InitOrder {
1379 for _, v := range init.Lhs {
1380 vars = append(vars, v.Name())
1383 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1384 t.Errorf("InitOrder == %s, want %s", got, want)
1388 type testImporter map[string]*Package
1390 func (m testImporter) Import(path string) (*Package, error) {
1391 if pkg := m[path]; pkg != nil {
1394 return nil, fmt.Errorf("package %q not found", path)
1397 func TestSelection(t *testing.T) {
1398 selections := make(map[*syntax.SelectorExpr]*Selection)
1400 imports := make(testImporter)
1401 conf := Config{Importer: imports}
1402 makePkg := func(path, src string) {
1403 pkg := mustTypecheck(src, &conf, &Info{Selections: selections})
1434 type G[P any] struct {
1446 // qualified identifiers
1484 // method expressions
1492 wantOut := map[string][2]string{
1493 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1495 "A{}.B": {"field (main.A) B *main.B", ".[0]"},
1496 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1497 "A{}.C": {"field (main.A) C main.C", ".[1]"},
1498 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1499 "A{}.b": {"field (main.A) b int", "->[0 0]"},
1500 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1501 "A{}.c": {"field (main.A) c int", ".[1 0]"},
1502 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1503 "Inst.p": {"field (main.G[int]) p int", ".[0]"},
1505 "A{}.f": {"method (main.A) f(int)", "->[0 0]"},
1506 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1507 "A{}.g": {"method (main.A) g()", ".[1 0]"},
1508 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1509 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1510 "B{}.f": {"method (main.B) f(int)", ".[0]"},
1511 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1512 "C{}.g": {"method (main.C) g()", ".[0]"},
1513 "new(C).g": {"method (*main.C) g()", "->[0]"},
1514 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1515 "Inst.m": {"method (main.G[int]) m(int)", ".[0]"},
1517 "A.f": {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1518 "(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1519 "B.f": {"method expr (main.B) f(main.B, int)", ".[0]"},
1520 "(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1521 "G[string].m": {"method expr (main.G[string]) m(main.G[string], string)", ".[0]"},
1522 "G[string]{}.p": {"field (main.G[string]) p string", ".[0]"},
1525 makePkg("lib", libSrc)
1526 makePkg("main", mainSrc)
1528 for e, sel := range selections {
1529 _ = sel.String() // assertion: must not panic
1531 start := indexFor(mainSrc, syntax.StartPos(e))
1532 end := indexFor(mainSrc, syntax.EndPos(e))
1533 segment := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1541 fmt.Sprintf("%s%v", direct, sel.Index()),
1543 want := wantOut[segment]
1545 t.Errorf("%s: got %q; want %q", segment, got, want)
1547 delete(wantOut, segment)
1549 // We must explicitly assert properties of the
1550 // Signature's receiver since it doesn't participate
1551 // in Identical() or String().
1552 sig, _ := sel.Type().(*Signature)
1553 if sel.Kind() == MethodVal {
1554 got := sig.Recv().Type()
1556 if !Identical(got, want) {
1557 t.Errorf("%s: Recv() = %s, want %s", segment, got, want)
1559 } else if sig != nil && sig.Recv() != nil {
1560 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1563 // Assert that all wantOut entries were used exactly once.
1564 for segment := range wantOut {
1565 t.Errorf("no syntax.Selection found with syntax %q", segment)
1569 // indexFor returns the index into s corresponding to the position pos.
1570 func indexFor(s string, pos syntax.Pos) int {
1571 i, line := 0, 1 // string index and corresponding line
1572 target := int(pos.Line())
1573 for line < target && i < len(s) {
1579 return i + int(pos.Col()-1) // columns are 1-based
1582 func TestIssue8518(t *testing.T) {
1583 imports := make(testImporter)
1585 Error: func(err error) { t.Log(err) }, // don't exit after first error
1588 makePkg := func(path, src string) {
1589 imports[path], _ = conf.Check(path, []*syntax.File{mustParse(src)}, nil) // errors logged via conf.Error
1596 const C2 = missing.C
1606 makePkg("a", libSrc)
1607 makePkg("main", mainSrc) // don't crash when type-checking this package
1610 func TestIssue59603(t *testing.T) {
1611 imports := make(testImporter)
1613 Error: func(err error) { t.Log(err) }, // don't exit after first error
1616 makePkg := func(path, src string) {
1617 imports[path], _ = conf.Check(path, []*syntax.File{mustParse(src)}, nil) // errors logged via conf.Error
1631 makePkg("a", libSrc)
1632 makePkg("main", mainSrc) // don't crash when type-checking this package
1635 func TestLookupFieldOrMethodOnNil(t *testing.T) {
1636 // LookupFieldOrMethod on a nil type is expected to produce a run-time panic.
1638 const want = "LookupFieldOrMethod on nil type"
1640 if s, ok := p.(string); !ok || s != want {
1641 t.Fatalf("got %v, want %s", p, want)
1644 LookupFieldOrMethod(nil, false, nil, "")
1647 func TestLookupFieldOrMethod(t *testing.T) {
1648 // Test cases assume a lookup of the form a.f or x.f, where a stands for an
1649 // addressable value, and x for a non-addressable value (even though a variable
1650 // for ease of test case writing).
1651 var tests = []struct {
1658 {"var x T; type T struct{}", false, nil, false},
1659 {"var x T; type T struct{ f int }", true, []int{0}, false},
1660 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1662 // field lookups on a generic type
1663 {"var x T[int]; type T[P any] struct{}", false, nil, false},
1664 {"var x T[int]; type T[P any] struct{ f P }", true, []int{0}, false},
1665 {"var x T[int]; type T[P any] struct{ a, b, f, c P }", true, []int{2}, false},
1668 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1669 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1670 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1671 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1673 // method lookups on a generic type
1674 {"var a T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, false},
1675 {"var a *T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, true},
1676 {"var a T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, false},
1677 {"var a *T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1680 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1681 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1683 // collisions on a generic type
1684 {"type ( E1[P any] struct{ f P }; E2[P any] struct{ f P }; x struct{ E1[int]; *E2[int] })", false, []int{1, 0}, false},
1685 {"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},
1687 // outside methodset
1688 // (*T).f method exists, but value of type T is not addressable
1689 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1691 // outside method set of a generic type
1692 {"var x T[int]; type T[P any] struct{}; func (*T[P]) f() {}", false, nil, true},
1694 // recursive generic types; see go.dev/issue/52715
1695 {"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},
1696 {"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},
1699 for _, test := range tests {
1700 pkg := mustTypecheck("package p;"+test.src, nil, nil)
1702 obj := pkg.Scope().Lookup("a")
1704 if obj = pkg.Scope().Lookup("x"); obj == nil {
1705 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1710 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1711 if (f != nil) != test.found {
1713 t.Errorf("%s: got no object; want one", test.src)
1715 t.Errorf("%s: got object = %v; want none", test.src, f)
1718 if !sameSlice(index, test.index) {
1719 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1721 if indirect != test.indirect {
1722 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1727 // Test for go.dev/issue/52715
1728 func TestLookupFieldOrMethod_RecursiveGeneric(t *testing.T) {
1732 type Tree[T any] struct {
1736 func (*Tree[R]) N(r R) R { return r }
1738 type Node[T any] struct {
1742 type Instance = *Tree[int]
1746 pkg := NewPackage("pkg", f.PkgName.Value)
1747 if err := NewChecker(nil, pkg, nil).Files([]*syntax.File{f}); err != nil {
1751 T := pkg.Scope().Lookup("Instance").Type()
1752 _, _, _ = LookupFieldOrMethod(T, false, pkg, "M") // verify that LookupFieldOrMethod terminates
1755 func sameSlice(a, b []int) bool {
1756 if len(a) != len(b) {
1759 for i, x := range a {
1767 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1768 // the correct result at various positions within the source.
1769 func TestScopeLookupParent(t *testing.T) {
1770 imports := make(testImporter)
1771 conf := Config{Importer: imports}
1773 makePkg := func(path, src string) {
1775 imports[path], err = conf.Check(path, []*syntax.File{mustParse(src)}, &info)
1781 makePkg("lib", "package lib; var X int")
1782 // Each /*name=kind:line*/ comment makes the test look up the
1783 // name at that point and checks that it resolves to a decl of
1784 // the specified kind and line number. "undef" means undefined.
1786 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1797 const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1798 type /*t=undef*/ t /*t=typename:14*/ *t
1799 print(Y) /*Y=var:10*/
1800 x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1801 var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1804 for i, x := range a /*i=undef*/ /*x=var:16*/ { _ = i; _ = x }
1807 switch y := i.(type) { /*y=undef*/
1808 case /*y=undef*/ int /*y=var:23*/ :
1809 case float32, /*y=undef*/ float64 /*y=var:23*/ :
1810 default /*y=var:23*/:
1815 switch int := i.(type) {
1816 case /*int=typename:0*/ int /*int=var:31*/ :
1818 default /*int=var:31*/ :
1824 info.Uses = make(map[*syntax.Name]Object)
1825 makePkg("main", mainSrc)
1826 mainScope := imports["main"].Scope()
1828 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1830 base := syntax.NewFileBase("main")
1831 syntax.CommentsDo(strings.NewReader(mainSrc), func(line, col uint, text string) {
1832 pos := syntax.MakePos(base, line, col)
1834 // Syntax errors are not comments.
1836 t.Errorf("%s: %s", pos, text)
1840 // Parse the assertion in the comment.
1841 m := rx.FindStringSubmatch(text)
1843 t.Errorf("%s: bad comment: %s", pos, text)
1846 name, want := m[1], m[2]
1848 // Look up the name in the innermost enclosing scope.
1849 inner := mainScope.Innermost(pos)
1851 t.Errorf("%s: at %s: can't find innermost scope", pos, text)
1855 if _, obj := inner.LookupParent(name, pos); obj != nil {
1856 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types2."))
1857 got = fmt.Sprintf("%s:%d", kind, obj.Pos().Line())
1860 t.Errorf("%s: at %s: %s resolved to %s, want %s", pos, text, name, got, want)
1864 // Check that for each referring identifier,
1865 // a lookup of its name on the innermost
1866 // enclosing scope returns the correct object.
1868 for id, wantObj := range info.Uses {
1869 inner := mainScope.Innermost(id.Pos())
1871 t.Errorf("%s: can't find innermost scope enclosing %q", id.Pos(), id.Value)
1875 // Exclude selectors and qualified identifiers---lexical
1876 // refs only. (Ideally, we'd see if the AST parent is a
1877 // SelectorExpr, but that requires PathEnclosingInterval
1878 // from golang.org/x/tools/go/ast/astutil.)
1879 if id.Value == "X" {
1883 _, gotObj := inner.LookupParent(id.Value, id.Pos())
1884 if gotObj != wantObj {
1885 t.Errorf("%s: got %v, want %v", id.Pos(), gotObj, wantObj)
1891 // newDefined creates a new defined type named T with the given underlying type.
1892 func newDefined(underlying Type) *Named {
1893 tname := NewTypeName(nopos, nil, "T", nil)
1894 return NewNamed(tname, underlying, nil)
1897 func TestConvertibleTo(t *testing.T) {
1898 for _, test := range []struct {
1902 {Typ[Int], Typ[Int], true},
1903 {Typ[Int], Typ[Float32], true},
1904 {Typ[Int], Typ[String], true},
1905 {newDefined(Typ[Int]), Typ[Int], true},
1906 {newDefined(new(Struct)), new(Struct), true},
1907 {newDefined(Typ[Int]), new(Struct), false},
1908 {Typ[UntypedInt], Typ[Int], true},
1909 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), true},
1910 {NewSlice(Typ[Int]), NewArray(Typ[Uint], 10), false},
1911 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
1912 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
1913 // Untyped string values are not permitted by the spec, so the behavior below is undefined.
1914 {Typ[UntypedString], Typ[String], true},
1916 if got := ConvertibleTo(test.v, test.t); got != test.want {
1917 t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1922 func TestAssignableTo(t *testing.T) {
1923 for _, test := range []struct {
1927 {Typ[Int], Typ[Int], true},
1928 {Typ[Int], Typ[Float32], false},
1929 {newDefined(Typ[Int]), Typ[Int], false},
1930 {newDefined(new(Struct)), new(Struct), true},
1931 {Typ[UntypedBool], Typ[Bool], true},
1932 {Typ[UntypedString], Typ[Bool], false},
1933 // Neither untyped string nor untyped numeric assignments arise during
1934 // normal type checking, so the below behavior is technically undefined by
1936 {Typ[UntypedString], Typ[String], true},
1937 {Typ[UntypedInt], Typ[Int], true},
1939 if got := AssignableTo(test.v, test.t); got != test.want {
1940 t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1945 func TestIdentical(t *testing.T) {
1946 // For each test, we compare the types of objects X and Y in the source.
1952 {"var X int; var Y int", true},
1953 {"var X int; var Y string", false},
1955 // TODO: add more tests for complex types.
1958 {"type X int; type Y int", false},
1961 {"type X = int; type Y = int", true},
1964 {`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
1965 {`func X() string { return "" }; func Y(int) string { return "" }`, false},
1966 {`func X(int) string { return "" }; func Y(int) {}`, false},
1968 // Generic functions. Type parameters should be considered identical modulo
1969 // renaming. See also go.dev/issue/49722.
1970 {`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
1971 {`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
1972 {`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
1973 {`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
1974 {`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
1975 {`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
1978 for _, test := range tests {
1979 pkg := mustTypecheck("package p;"+test.src, nil, nil)
1980 X := pkg.Scope().Lookup("X")
1981 Y := pkg.Scope().Lookup("Y")
1982 if X == nil || Y == nil {
1983 t.Fatal("test must declare both X and Y")
1985 if got := Identical(X.Type(), Y.Type()); got != test.want {
1986 t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
1991 func TestIdentical_issue15173(t *testing.T) {
1992 // Identical should allow nil arguments and be symmetric.
1993 for _, test := range []struct {
1997 {Typ[Int], Typ[Int], true},
1998 {Typ[Int], nil, false},
1999 {nil, Typ[Int], false},
2002 if got := Identical(test.x, test.y); got != test.want {
2003 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2008 func TestIdenticalUnions(t *testing.T) {
2009 tname := NewTypeName(nopos, nil, "myInt", nil)
2010 myInt := NewNamed(tname, Typ[Int], nil)
2011 tmap := map[string]*Term{
2012 "int": NewTerm(false, Typ[Int]),
2013 "~int": NewTerm(true, Typ[Int]),
2014 "string": NewTerm(false, Typ[String]),
2015 "~string": NewTerm(true, Typ[String]),
2016 "myInt": NewTerm(false, myInt),
2018 makeUnion := func(s string) *Union {
2019 parts := strings.Split(s, "|")
2021 for _, p := range parts {
2024 t.Fatalf("missing term %q", p)
2026 terms = append(terms, term)
2028 return NewUnion(terms)
2030 for _, test := range []struct {
2034 // These tests are just sanity checks. The tests for type sets and
2035 // interfaces provide much more test coverage.
2036 {"int|~int", "~int", true},
2037 {"myInt|~int", "~int", true},
2038 {"int|string", "string|int", true},
2039 {"int|int|string", "string|int", true},
2040 {"myInt|string", "int|string", false},
2042 x := makeUnion(test.x)
2043 y := makeUnion(test.y)
2044 if got := Identical(x, y); got != test.want {
2045 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2050 func TestIssue15305(t *testing.T) {
2051 const src = "package p; func f() int16; var _ = f(undef)"
2054 Error: func(err error) {}, // allow errors
2057 Types: make(map[syntax.Expr]TypeAndValue),
2059 conf.Check("p", []*syntax.File{f}, info) // ignore result
2060 for e, tv := range info.Types {
2061 if _, ok := e.(*syntax.CallExpr); ok {
2062 if tv.Type != Typ[Int16] {
2063 t.Errorf("CallExpr has type %v, want int16", tv.Type)
2068 t.Errorf("CallExpr has no type")
2071 // TestCompositeLitTypes verifies that Info.Types registers the correct
2072 // types for composite literal expressions and composite literal type
2074 func TestCompositeLitTypes(t *testing.T) {
2075 for i, test := range []struct {
2078 {`[16]byte{}`, `[16]byte`},
2079 {`[...]byte{}`, `[0]byte`}, // test for go.dev/issue/14092
2080 {`[...]int{1, 2, 3}`, `[3]int`}, // test for go.dev/issue/14092
2081 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for go.dev/issue/14092
2082 {`[]int{}`, `[]int`},
2083 {`map[string]bool{"foo": true}`, `map[string]bool`},
2084 {`struct{}{}`, `struct{}`},
2085 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
2087 f := mustParse(fmt.Sprintf("package p%d; var _ = %s", i, test.lit))
2088 types := make(map[syntax.Expr]TypeAndValue)
2089 if _, err := new(Config).Check("p", []*syntax.File{f}, &Info{Types: types}); err != nil {
2090 t.Fatalf("%s: %v", test.lit, err)
2093 cmptype := func(x syntax.Expr, want string) {
2096 t.Errorf("%s: no Types entry found", test.lit)
2100 t.Errorf("%s: type is nil", test.lit)
2103 if got := tv.Type.String(); got != want {
2104 t.Errorf("%s: got %v, want %s", test.lit, got, want)
2108 // test type of composite literal expression
2109 rhs := f.DeclList[0].(*syntax.VarDecl).Values
2110 cmptype(rhs, test.typ)
2112 // test type of composite literal type expression
2113 cmptype(rhs.(*syntax.CompositeLit).Type, test.typ)
2117 // TestObjectParents verifies that objects have parent scopes or not
2118 // as specified by the Object interface.
2119 func TestObjectParents(t *testing.T) {
2138 func f(x int) { y := x; print(y) }
2144 Defs: make(map[*syntax.Name]Object),
2146 if _, err := new(Config).Check("p", []*syntax.File{f}, info); err != nil {
2150 for ident, obj := range info.Defs {
2152 // only package names and implicit vars have a nil object
2153 // (in this test we only need to handle the package name)
2154 if ident.Value != "p" {
2155 t.Errorf("%v has nil object", ident)
2160 // struct fields, type-associated and interface methods
2161 // have no parent scope
2163 switch obj := obj.(type) {
2169 if obj.Type().(*Signature).Recv() != nil { // method
2174 gotParent := obj.Parent() != nil
2176 case gotParent && !wantParent:
2177 t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
2178 case !gotParent && wantParent:
2179 t.Errorf("%v: no parent found", ident)
2184 // TestFailedImport tests that we don't get follow-on errors
2185 // elsewhere in a package due to failing to import a package.
2186 func TestFailedImport(t *testing.T) {
2187 testenv.MustHaveGoBuild(t)
2192 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
2197 func f(x T) T { return foo.F(x) }
2200 files := []*syntax.File{f}
2202 // type-check using all possible importers
2203 for _, compiler := range []string{"gc", "gccgo", "source"} {
2206 Error: func(err error) {
2207 // we should only see the import error
2208 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
2209 t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
2213 //Importer: importer.For(compiler, nil),
2217 Uses: make(map[*syntax.Name]Object),
2219 pkg, _ := conf.Check("p", files, info)
2221 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
2225 imports := pkg.Imports()
2226 if len(imports) != 1 {
2227 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
2231 if imp.Name() != "foo" {
2232 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
2236 // verify that all uses of foo refer to the imported package foo (imp)
2237 for ident, obj := range info.Uses {
2238 if ident.Value == "foo" {
2239 if obj, ok := obj.(*PkgName); ok {
2240 if obj.Imported() != imp {
2241 t.Errorf("%s resolved to %v; want %v", ident.Value, obj.Imported(), imp)
2244 t.Errorf("%s resolved to %v; want package name", ident.Value, obj)
2251 func TestInstantiate(t *testing.T) {
2252 // eventually we like more tests but this is a start
2253 const src = "package p; type T[P any] *T[P]"
2254 pkg := mustTypecheck(src, nil, nil)
2256 // type T should have one type parameter
2257 T := pkg.Scope().Lookup("T").Type().(*Named)
2258 if n := T.TypeParams().Len(); n != 1 {
2259 t.Fatalf("expected 1 type parameter; found %d", n)
2262 // instantiation should succeed (no endless recursion)
2263 // even with a nil *Checker
2264 res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
2269 // instantiated type should point to itself
2270 if p := res.Underlying().(*Pointer).Elem(); p != res {
2271 t.Fatalf("unexpected result type: %s points to %s", res, p)
2275 func TestInstantiateErrors(t *testing.T) {
2277 src string // by convention, T must be the type being instantiated
2279 wantAt int // -1 indicates no error
2281 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
2282 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
2283 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
2284 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
2287 for _, test := range tests {
2288 src := "package p; " + test.src
2289 pkg := mustTypecheck(src, nil, nil)
2291 T := pkg.Scope().Lookup("T").Type().(*Named)
2293 _, err := Instantiate(nil, T, test.targs, true)
2295 t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
2298 var argErr *ArgumentError
2299 if !errors.As(err, &argErr) {
2300 t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
2303 if argErr.Index != test.wantAt {
2304 t.Errorf("Instantiate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2309 func TestArgumentErrorUnwrapping(t *testing.T) {
2310 var err error = &ArgumentError{
2312 Err: Error{Msg: "test"},
2315 if !errors.As(err, &e) {
2316 t.Fatalf("error %v does not wrap types.Error", err)
2318 if e.Msg != "test" {
2319 t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2323 func TestInstanceIdentity(t *testing.T) {
2324 imports := make(testImporter)
2325 conf := Config{Importer: imports}
2326 makePkg := func(src string) {
2328 name := f.PkgName.Value
2329 pkg, err := conf.Check(name, []*syntax.File{f}, nil)
2335 makePkg(`package lib; type T[P any] struct{}`)
2336 makePkg(`package a; import "lib"; var A lib.T[int]`)
2337 makePkg(`package b; import "lib"; var B lib.T[int]`)
2338 a := imports["a"].Scope().Lookup("A")
2339 b := imports["b"].Scope().Lookup("B")
2340 if !Identical(a.Type(), b.Type()) {
2341 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
2345 // TestInstantiatedObjects verifies properties of instantiated objects.
2346 func TestInstantiatedObjects(t *testing.T) {
2350 type T[P any] struct {
2354 func (recv *T[Q]) concreteMethod(mParam Q) (mResult Q) { return }
2356 type FT[P any] func(ftParam P) (ftResult P)
2358 func F[P any](fParam P) (fResult P){ return }
2360 type I[P any] interface {
2366 func (R[P]) m() {} // having a method triggers expansion of R
2381 Defs: make(map[*syntax.Name]Object),
2385 pkg, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
2390 lookup := func(name string) Type { return pkg.Scope().Lookup(name).Type() }
2391 fnScope := pkg.Scope().Lookup("fn").(*Func).Scope()
2398 {"field", lookup("t").Underlying().(*Struct).Field(0)},
2399 {"field", fnScope.Lookup("r").Type().Underlying().(*Struct).Field(0)},
2401 // Methods and method fields
2402 {"concreteMethod", lookup("t").(*Named).Method(0)},
2403 {"recv", lookup("t").(*Named).Method(0).Type().(*Signature).Recv()},
2404 {"mParam", lookup("t").(*Named).Method(0).Type().(*Signature).Params().At(0)},
2405 {"mResult", lookup("t").(*Named).Method(0).Type().(*Signature).Results().At(0)},
2407 // Interface methods
2408 {"interfaceMethod", lookup("i").Underlying().(*Interface).Method(0)},
2410 // Function type fields
2411 {"ftParam", lookup("ft").Underlying().(*Signature).Params().At(0)},
2412 {"ftResult", lookup("ft").Underlying().(*Signature).Results().At(0)},
2415 {"fParam", lookup("f").(*Signature).Params().At(0)},
2416 {"fResult", lookup("f").(*Signature).Results().At(0)},
2419 // Collect all identifiers by name.
2420 idents := make(map[string][]*syntax.Name)
2421 syntax.Inspect(f, func(n syntax.Node) bool {
2422 if id, ok := n.(*syntax.Name); ok {
2423 idents[id.Value] = append(idents[id.Value], id)
2428 for _, test := range tests {
2430 t.Run(test.name, func(t *testing.T) {
2431 if got := len(idents[test.name]); got != 1 {
2432 t.Fatalf("found %d identifiers named %s, want 1", got, test.name)
2434 ident := idents[test.name][0]
2435 def := info.Defs[ident]
2436 if def == test.obj {
2437 t.Fatalf("info.Defs[%s] contains the test object", test.name)
2439 if orig := originObject(test.obj); def != orig {
2440 t.Errorf("info.Defs[%s] does not match obj.Origin()", test.name)
2442 if def.Pkg() != test.obj.Pkg() {
2443 t.Errorf("Pkg() = %v, want %v", def.Pkg(), test.obj.Pkg())
2445 if def.Name() != test.obj.Name() {
2446 t.Errorf("Name() = %v, want %v", def.Name(), test.obj.Name())
2448 if def.Pos() != test.obj.Pos() {
2449 t.Errorf("Pos() = %v, want %v", def.Pos(), test.obj.Pos())
2451 if def.Parent() != test.obj.Parent() {
2452 t.Fatalf("Parent() = %v, want %v", def.Parent(), test.obj.Parent())
2454 if def.Exported() != test.obj.Exported() {
2455 t.Fatalf("Exported() = %v, want %v", def.Exported(), test.obj.Exported())
2457 if def.Id() != test.obj.Id() {
2458 t.Fatalf("Id() = %v, want %v", def.Id(), test.obj.Id())
2460 // String and Type are expected to differ.
2465 func originObject(obj Object) Object {
2466 switch obj := obj.(type) {
2475 func TestImplements(t *testing.T) {
2479 type EmptyIface interface{}
2490 type Integer interface{
2491 int8 | int16 | int32 | int64
2494 type EmptyTypeSet interface{
2511 type Bad Bad // invalid type
2515 conf := Config{Error: func(error) {}}
2516 pkg, _ := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
2518 lookup := func(tname string) Type { return pkg.Scope().Lookup(tname).Type() }
2520 EmptyIface = lookup("EmptyIface").Underlying().(*Interface)
2521 I = lookup("I").(*Named)
2522 II = I.Underlying().(*Interface)
2523 C = lookup("C").(*Named)
2524 CI = C.Underlying().(*Interface)
2525 Integer = lookup("Integer").Underlying().(*Interface)
2526 EmptyTypeSet = lookup("EmptyTypeSet").Underlying().(*Interface)
2528 N1p = NewPointer(N1)
2530 N2p = NewPointer(N2)
2545 {Typ[Int8], Integer, true},
2546 {Typ[Int64], Integer, true},
2547 {Typ[String], Integer, false},
2548 {EmptyTypeSet, II, true},
2549 {EmptyTypeSet, EmptyTypeSet, true},
2550 {Typ[Int], EmptyTypeSet, false},
2565 {Bad, EmptyIface, true},
2568 for _, test := range tests {
2569 if got := Implements(test.V, test.T); got != test.want {
2570 t.Errorf("Implements(%s, %s) = %t, want %t", test.V, test.T, got, test.want)
2573 // The type assertion x.(T) is valid if T is an interface or if T implements the type of x.
2574 // The assertion is never valid if T is a bad type.
2578 if _, ok := T.Underlying().(*Interface); (ok || Implements(T, V)) && T != Bad {
2581 if got := AssertableTo(V, T); got != want {
2582 t.Errorf("AssertableTo(%s, %s) = %t, want %t", V, T, got, want)
2587 func TestMissingMethodAlternative(t *testing.T) {
2609 pkg := mustTypecheck(src, nil, nil)
2611 T := pkg.Scope().Lookup("T").Type().Underlying().(*Interface)
2612 lookup := func(name string) (*Func, bool) {
2613 return MissingMethod(pkg.Scope().Lookup(name).Type(), T, true)
2616 // V0 has method m with correct signature. Should not report wrongType.
2617 method, wrongType := lookup("V0")
2618 if method != nil || wrongType {
2619 t.Fatalf("V0: got method = %v, wrongType = %v", method, wrongType)
2622 checkMissingMethod := func(tname string, reportWrongType bool) {
2623 method, wrongType := lookup(tname)
2624 if method == nil || method.Name() != "m" || wrongType != reportWrongType {
2625 t.Fatalf("%s: got method = %v, wrongType = %v", tname, method, wrongType)
2629 // V1 has no method m. Should not report wrongType.
2630 checkMissingMethod("V1", false)
2632 // V2 has method m with wrong signature type (ignoring receiver). Should report wrongType.
2633 checkMissingMethod("V2", true)
2635 // V3 has no method m but it exists on *V3. Should report wrongType.
2636 checkMissingMethod("V3", true)
2638 // V4 has no method m but has M. Should not report wrongType.
2639 checkMissingMethod("V4", false)