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 parse(path, src string) (*syntax.File, error) {
25 errh := func(error) {} // dummy error handler so that parsing continues in presence of errors
26 return syntax.Parse(syntax.NewFileBase(path), strings.NewReader(src), errh, nil, 0)
29 func mustParse(path, src string) *syntax.File {
30 f, err := parse(path, src)
32 panic(err) // so we don't need to pass *testing.T
37 func typecheck(path, src string, info *Info) (*Package, error) {
38 f, err := parse(path, src)
39 if f == nil { // ignore errors unless f is nil
43 Error: func(err error) {}, // collect all errors
44 Importer: defaultImporter(),
46 return conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
49 func mustTypecheck(path, src string, info *Info) *Package {
50 pkg, err := typecheck(path, src, info)
52 panic(err) // so we don't need to pass *testing.T
57 func TestValuesInfo(t *testing.T) {
58 var tests = []struct {
60 expr string // constant expression
61 typ string // constant type
62 val string // constant value
64 {`package a0; const _ = false`, `false`, `untyped bool`, `false`},
65 {`package a1; const _ = 0`, `0`, `untyped int`, `0`},
66 {`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
67 {`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
68 {`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
69 {`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
71 {`package b0; var _ = false`, `false`, `bool`, `false`},
72 {`package b1; var _ = 0`, `0`, `int`, `0`},
73 {`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
74 {`package b3; var _ = 0.`, `0.`, `float64`, `0`},
75 {`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
76 {`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
78 {`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
79 {`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
80 {`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
82 {`package c1a; var _ = int(0)`, `0`, `int`, `0`},
83 {`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
84 {`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
86 {`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
87 {`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
88 {`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
90 {`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
91 {`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
92 {`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
94 {`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
95 {`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
96 {`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
98 {`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
99 {`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
100 {`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
101 {`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
102 {`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
103 {`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
105 {`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
106 {`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
107 {`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
108 {`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
110 {`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
111 {`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
112 {`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
113 {`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
114 {`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
115 {`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
116 {`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
117 {`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
119 {`package f0 ; var _ float32 = 1e-200`, `1e-200`, `float32`, `0`},
120 {`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
121 {`package f2a; var _ float64 = 1e-2000`, `1e-2000`, `float64`, `0`},
122 {`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
123 {`package f2b; var _ = 1e-2000`, `1e-2000`, `float64`, `0`},
124 {`package f3b; var _ = -1e-2000`, `-1e-2000`, `float64`, `0`},
125 {`package f4 ; var _ complex64 = 1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
126 {`package f5 ; var _ complex64 = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
127 {`package f6a; var _ complex128 = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
128 {`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
129 {`package f6b; var _ = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
130 {`package f7b; var _ = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
132 {`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // issue #22341
133 {`package g1; var(j int32; s int; n = 1.0<<s == j)`, `1.0`, `int32`, `1`}, // issue #48422
136 for _, test := range tests {
138 Types: make(map[syntax.Expr]TypeAndValue),
140 name := mustTypecheck("ValuesInfo", test.src, &info).Name()
142 // look for expression
144 for e := range info.Types {
145 if syntax.String(e) == test.expr {
151 t.Errorf("package %s: no expression found for %s", name, test.expr)
154 tv := info.Types[expr]
156 // check that type is correct
157 if got := tv.Type.String(); got != test.typ {
158 t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
162 // if we have a constant, check that value is correct
164 if got := tv.Value.ExactString(); got != test.val {
165 t.Errorf("package %s: got value %s; want %s", name, got, test.val)
169 t.Errorf("package %s: no constant found; want %s", name, test.val)
175 func TestTypesInfo(t *testing.T) {
176 // Test sources that are not expected to typecheck must start with the broken prefix.
177 const brokenPkg = "package broken_"
179 var tests = []struct {
181 expr string // expression
182 typ string // value type
184 // single-valued expressions of untyped constants
185 {`package b0; var x interface{} = false`, `false`, `bool`},
186 {`package b1; var x interface{} = 0`, `0`, `int`},
187 {`package b2; var x interface{} = 0.`, `0.`, `float64`},
188 {`package b3; var x interface{} = 0i`, `0i`, `complex128`},
189 {`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
192 {`package n0; var _ *int = nil`, `nil`, `*int`},
193 {`package n1; var _ func() = nil`, `nil`, `func()`},
194 {`package n2; var _ []byte = nil`, `nil`, `[]byte`},
195 {`package n3; var _ map[int]int = nil`, `nil`, `map[int]int`},
196 {`package n4; var _ chan int = nil`, `nil`, `chan int`},
197 {`package n5a; var _ interface{} = (*int)(nil)`, `nil`, `*int`},
198 {`package n5b; var _ interface{m()} = nil`, `nil`, `interface{m()}`},
199 {`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `unsafe.Pointer`},
201 {`package n10; var (x *int; _ = x == nil)`, `nil`, `*int`},
202 {`package n11; var (x func(); _ = x == nil)`, `nil`, `func()`},
203 {`package n12; var (x []byte; _ = x == nil)`, `nil`, `[]byte`},
204 {`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `map[int]int`},
205 {`package n14; var (x chan int; _ = x == nil)`, `nil`, `chan int`},
206 {`package n15a; var (x interface{}; _ = x == (*int)(nil))`, `nil`, `*int`},
207 {`package n15b; var (x interface{m()}; _ = x == nil)`, `nil`, `interface{m()}`},
208 {`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `unsafe.Pointer`},
210 {`package n20; var _ = (*int)(nil)`, `nil`, `*int`},
211 {`package n21; var _ = (func())(nil)`, `nil`, `func()`},
212 {`package n22; var _ = ([]byte)(nil)`, `nil`, `[]byte`},
213 {`package n23; var _ = (map[int]int)(nil)`, `nil`, `map[int]int`},
214 {`package n24; var _ = (chan int)(nil)`, `nil`, `chan int`},
215 {`package n25a; var _ = (interface{})((*int)(nil))`, `nil`, `*int`},
216 {`package n25b; var _ = (interface{m()})(nil)`, `nil`, `interface{m()}`},
217 {`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `unsafe.Pointer`},
219 {`package n30; func f(*int) { f(nil) }`, `nil`, `*int`},
220 {`package n31; func f(func()) { f(nil) }`, `nil`, `func()`},
221 {`package n32; func f([]byte) { f(nil) }`, `nil`, `[]byte`},
222 {`package n33; func f(map[int]int) { f(nil) }`, `nil`, `map[int]int`},
223 {`package n34; func f(chan int) { f(nil) }`, `nil`, `chan int`},
224 {`package n35a; func f(interface{}) { f((*int)(nil)) }`, `nil`, `*int`},
225 {`package n35b; func f(interface{m()}) { f(nil) }`, `nil`, `interface{m()}`},
226 {`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `unsafe.Pointer`},
228 // comma-ok expressions
229 {`package p0; var x interface{}; var _, _ = x.(int)`,
233 {`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
237 {`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
239 `(complex128, p2a.mybool)`,
241 {`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
243 `(complex128, bool)`,
245 {`package p3; var c chan string; var _, _ = <-c`,
251 {`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
255 {`package issue6796_b; var c chan string; var _, _ = (<-c)`,
259 {`package issue6796_c; var c chan string; var _, _ = (<-c)`,
263 {`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
267 {`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
273 {`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
277 {`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
281 {`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
285 {`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
289 {`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
293 {`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
299 {`package issue28277_a; func f(...int)`,
303 {`package issue28277_b; func f(a, b int, c ...[]struct{})`,
309 {`package issue47243_a; var x int32; var _ = x << 3`, `3`, `untyped int`},
310 {`package issue47243_b; var x int32; var _ = x << 3.`, `3.`, `untyped float`},
311 {`package issue47243_c; var x int32; var _ = 1 << x`, `1 << x`, `int`},
312 {`package issue47243_d; var x int32; var _ = 1 << x`, `1`, `int`},
313 {`package issue47243_e; var x int32; var _ = 1 << 2`, `1`, `untyped int`},
314 {`package issue47243_f; var x int32; var _ = 1 << 2`, `2`, `untyped int`},
315 {`package issue47243_g; var x int32; var _ = int(1) << 2`, `2`, `untyped int`},
316 {`package issue47243_h; var x int32; var _ = 1 << (2 << x)`, `1`, `int`},
317 {`package issue47243_i; var x int32; var _ = 1 << (2 << x)`, `(2 << x)`, `untyped int`},
318 {`package issue47243_j; var x int32; var _ = 1 << (2 << x)`, `2`, `untyped int`},
320 // tests for broken code that doesn't parse or type-check
321 {brokenPkg + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
322 {brokenPkg + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
323 {brokenPkg + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a, f: b,}}`, `b`, `string`},
324 {brokenPkg + `x3; var x = panic("");`, `panic`, `func(interface{})`},
325 {`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
326 {brokenPkg + `x5; func _() { var x map[string][...]int; x = map[string][...]int{"": {1,2,3}} }`, `x`, `map[string]invalid type`},
328 // parameterized functions
329 {`package p0; func f[T any](T) {}; var _ = f[int]`, `f`, `func[T any](T)`},
330 {`package p1; func f[T any](T) {}; var _ = f[int]`, `f[int]`, `func(int)`},
331 {`package p2; func f[T any](T) {}; func _() { f(42) }`, `f`, `func(int)`},
332 {`package p3; func f[T any](T) {}; func _() { f[int](42) }`, `f[int]`, `func(int)`},
333 {`package p4; func f[T any](T) {}; func _() { f[int](42) }`, `f`, `func[T any](T)`},
334 {`package p5; func f[T any](T) {}; func _() { f(42) }`, `f(42)`, `()`},
337 {`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
338 {`package t1; type t[P any] int; var _ t[int]`, `t`, `t1.t[P any]`},
339 {`package t2; type t[P interface{}] int; var _ t[int]`, `t`, `t2.t[P interface{}]`},
340 {`package t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `t3.t[P, Q interface{}]`},
341 {brokenPkg + `t4; type t[P, Q interface{ m() }] int; var _ t[int, int]`, `t`, `broken_t4.t[P, Q interface{m()}]`},
343 // instantiated types must be sanitized
344 {`package g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `g0.t[int]`},
347 {`package issue45096; func _[T interface{ ~int8 | ~int16 | ~int32 }](x T) { _ = x < 0 }`, `0`, `T`},
350 {`package p; import "unsafe"; type S struct { f int }; var s S; var _ = unsafe.Offsetof(s.f)`, `s.f`, `int`},
353 {`package u0a; func _[_ interface{int}]() {}`, `int`, `int`},
354 {`package u1a; func _[_ interface{~int}]() {}`, `~int`, `~int`},
355 {`package u2a; func _[_ interface{int | string}]() {}`, `int | string`, `int | string`},
356 {`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `int | string | ~bool`, `int | string | ~bool`},
357 {`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `int | string`, `int | string`},
358 {`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `~bool`, `~bool`},
359 {`package u3a; func _[_ interface{int | string | ~float64|~bool}]() {}`, `int | string | ~float64`, `int | string | ~float64`},
361 {`package u0b; func _[_ int]() {}`, `int`, `int`},
362 {`package u1b; func _[_ ~int]() {}`, `~int`, `~int`},
363 {`package u2b; func _[_ int | string]() {}`, `int | string`, `int | string`},
364 {`package u3b; func _[_ int | string | ~bool]() {}`, `int | string | ~bool`, `int | string | ~bool`},
365 {`package u3b; func _[_ int | string | ~bool]() {}`, `int | string`, `int | string`},
366 {`package u3b; func _[_ int | string | ~bool]() {}`, `~bool`, `~bool`},
367 {`package u3b; func _[_ int | string | ~float64|~bool]() {}`, `int | string | ~float64`, `int | string | ~float64`},
369 {`package u0c; type _ interface{int}`, `int`, `int`},
370 {`package u1c; type _ interface{~int}`, `~int`, `~int`},
371 {`package u2c; type _ interface{int | string}`, `int | string`, `int | string`},
372 {`package u3c; type _ interface{int | string | ~bool}`, `int | string | ~bool`, `int | string | ~bool`},
373 {`package u3c; type _ interface{int | string | ~bool}`, `int | string`, `int | string`},
374 {`package u3c; type _ interface{int | string | ~bool}`, `~bool`, `~bool`},
375 {`package u3c; type _ interface{int | string | ~float64|~bool}`, `int | string | ~float64`, `int | string | ~float64`},
378 for _, test := range tests {
379 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
381 if strings.HasPrefix(test.src, brokenPkg) {
382 pkg, err := typecheck("TypesInfo", test.src, &info)
384 t.Errorf("package %s: expected to fail but passed", pkg.Name())
391 name = mustTypecheck("TypesInfo", test.src, &info).Name()
394 // look for expression type
396 for e, tv := range info.Types {
397 if syntax.String(e) == test.expr {
403 t.Errorf("package %s: no type found for %s", name, test.expr)
407 // check that type is correct
408 if got := typ.String(); got != test.typ {
409 t.Errorf("package %s: got %s; want %s", name, got, test.typ)
414 func TestInstanceInfo(t *testing.T) {
415 const lib = `package lib
422 type testInst struct {
428 var tests = []struct {
430 instances []testInst // recorded instances in source order
432 {`package p0; func f[T any](T) {}; func _() { f(42) }`,
433 []testInst{{`f`, []string{`int`}, `func(int)`}},
435 {`package p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
436 []testInst{{`f`, []string{`rune`}, `func(rune) rune`}},
438 {`package p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
439 []testInst{{`f`, []string{`complex128`}, `func(...complex128) complex128`}},
441 {`package p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
442 []testInst{{`f`, []string{`float64`, `string`, `byte`}, `func(float64, *string, []byte)`}},
444 {`package p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
445 []testInst{{`f`, []string{`float64`, `byte`}, `func(float64, *byte, ...[]byte)`}},
448 {`package s1; func f[T any, P interface{*T}](x T) {}; func _(x string) { f(x) }`,
449 []testInst{{`f`, []string{`string`, `*string`}, `func(x string)`}},
451 {`package s2; func f[T any, P interface{*T}](x []T) {}; func _(x []int) { f(x) }`,
452 []testInst{{`f`, []string{`int`, `*int`}, `func(x []int)`}},
454 {`package s3; type C[T any] interface{chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
456 {`C`, []string{`T`}, `interface{chan<- T}`},
457 {`f`, []string{`int`, `chan<- int`}, `func(x []int)`},
460 {`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) }`,
462 {`C`, []string{`T`}, `interface{chan<- T}`},
463 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
464 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func(x []int)`},
468 {`package t1; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = f[string] }`,
469 []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
471 {`package t2; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = (f[string]) }`,
472 []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
474 {`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] }`,
476 {`C`, []string{`T`}, `interface{chan<- T}`},
477 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
478 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
481 {`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]) }`,
483 {`C`, []string{`T`}, `interface{chan<- T}`},
484 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
485 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
488 {`package i0; import "lib"; func _() { lib.F(42) }`,
489 []testInst{{`F`, []string{`int`}, `func(int)`}},
492 {`package duplfunc0; func f[T any](T) {}; func _() { f(42); f("foo"); f[int](3) }`,
494 {`f`, []string{`int`}, `func(int)`},
495 {`f`, []string{`string`}, `func(string)`},
496 {`f`, []string{`int`}, `func(int)`},
499 {`package duplfunc1; import "lib"; func _() { lib.F(42); lib.F("foo"); lib.F(3) }`,
501 {`F`, []string{`int`}, `func(int)`},
502 {`F`, []string{`string`}, `func(string)`},
503 {`F`, []string{`int`}, `func(int)`},
507 {`package type0; type T[P interface{~int}] struct{ x P }; var _ T[int]`,
508 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
510 {`package type1; type T[P interface{~int}] struct{ x P }; var _ (T[int])`,
511 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
513 {`package type2; type T[P interface{~int}] struct{ x P }; var _ T[(int)]`,
514 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
516 {`package type3; type T[P1 interface{~[]P2}, P2 any] struct{ x P1; y P2 }; var _ T[[]int, int]`,
517 []testInst{{`T`, []string{`[]int`, `int`}, `struct{x []int; y int}`}},
519 {`package type4; import "lib"; var _ lib.T[int]`,
520 []testInst{{`T`, []string{`int`}, `[]int`}},
523 {`package dupltype0; type T[P interface{~int}] struct{ x P }; var x T[int]; var y T[int]`,
525 {`T`, []string{`int`}, `struct{x int}`},
526 {`T`, []string{`int`}, `struct{x int}`},
529 {`package dupltype1; type T[P ~int] struct{ x P }; func (r *T[Q]) add(z T[Q]) { r.x += z.x }`,
531 {`T`, []string{`Q`}, `struct{x Q}`},
532 {`T`, []string{`Q`}, `struct{x Q}`},
535 {`package dupltype1; import "lib"; var x lib.T[int]; var y lib.T[int]; var z lib.T[string]`,
537 {`T`, []string{`int`}, `[]int`},
538 {`T`, []string{`int`}, `[]int`},
539 {`T`, []string{`string`}, `[]string`},
542 {`package issue51803; func foo[T any](T) {}; func _() { foo[int]( /* leave arg away on purpose */ ) }`,
543 []testInst{{`foo`, []string{`int`}, `func(int)`}},
547 for _, test := range tests {
548 imports := make(testImporter)
551 Error: func(error) {}, // ignore errors
553 instMap := make(map[*syntax.Name]Instance)
554 useMap := make(map[*syntax.Name]Object)
555 makePkg := func(src string) *Package {
556 f := mustParse("p.go", src)
557 pkg, _ := conf.Check("", []*syntax.File{f}, &Info{Instances: instMap, Uses: useMap})
558 imports[pkg.Name()] = pkg
562 pkg := makePkg(test.src)
564 t.Run(pkg.Name(), func(t *testing.T) {
565 // Sort instances in source order for stability.
566 instances := sortedInstances(instMap)
567 if got, want := len(instances), len(test.instances); got != want {
568 t.Fatalf("got %d instances, want %d", got, want)
571 // Pairwise compare with the expected instances.
572 for ii, inst := range instances {
574 for i := 0; i < inst.Inst.TypeArgs.Len(); i++ {
575 targs = append(targs, inst.Inst.TypeArgs.At(i))
577 typ := inst.Inst.Type
579 testInst := test.instances[ii]
580 if got := inst.Name.Value; got != testInst.name {
581 t.Fatalf("got name %s, want %s", got, testInst.name)
584 if len(targs) != len(testInst.targs) {
585 t.Fatalf("got %d type arguments; want %d", len(targs), len(testInst.targs))
587 for i, targ := range targs {
588 if got := targ.String(); got != testInst.targs[i] {
589 t.Errorf("type argument %d: got %s; want %s", i, got, testInst.targs[i])
592 if got := typ.Underlying().String(); got != testInst.typ {
593 t.Errorf("package %s: got %s; want %s", pkg.Name(), got, testInst.typ)
596 // Verify the invariant that re-instantiating the corresponding generic
597 // type with TypeArgs results in an identical instance.
598 ptype := useMap[inst.Name].Type()
599 lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
600 if lister == nil || lister.TypeParams().Len() == 0 {
601 t.Fatalf("info.Types[%v] = %v, want parameterized type", inst.Name, ptype)
603 inst2, err := Instantiate(nil, ptype, targs, true)
605 t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
607 if !Identical(inst.Inst.Type, inst2) {
608 t.Errorf("%v and %v are not identical", inst.Inst.Type, inst2)
615 type recordedInstance struct {
620 func sortedInstances(m map[*syntax.Name]Instance) (instances []recordedInstance) {
621 for id, inst := range m {
622 instances = append(instances, recordedInstance{id, inst})
624 sort.Slice(instances, func(i, j int) bool {
625 return instances[i].Name.Pos().Cmp(instances[j].Name.Pos()) < 0
630 func TestDefsInfo(t *testing.T) {
631 var tests = []struct {
636 {`package p0; const x = 42`, `x`, `const p0.x untyped int`},
637 {`package p1; const x int = 42`, `x`, `const p1.x int`},
638 {`package p2; var x int`, `x`, `var p2.x int`},
639 {`package p3; type x int`, `x`, `type p3.x int`},
640 {`package p4; func f()`, `f`, `func p4.f()`},
641 {`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
643 // Tests using generics.
644 {`package g0; type x[T any] int`, `x`, `type g0.x[T any] int`},
645 {`package g1; func f[T any]() {}`, `f`, `func g1.f[T any]()`},
646 {`package g2; type x[T any] int; func (*x[_]) m() {}`, `m`, `func (*g2.x[_]).m()`},
649 for _, test := range tests {
651 Defs: make(map[*syntax.Name]Object),
653 name := mustTypecheck("DefsInfo", test.src, &info).Name()
657 for id, obj := range info.Defs {
658 if id.Value == test.obj {
664 t.Errorf("package %s: %s not found", name, test.obj)
668 if got := def.String(); got != test.want {
669 t.Errorf("package %s: got %s; want %s", name, got, test.want)
674 func TestUsesInfo(t *testing.T) {
675 var tests = []struct {
680 {`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
681 {`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
682 {`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
683 {`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
684 {`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
686 // Tests using generics.
687 {`package g0; func _[T any]() { _ = x }; const x = 42`, `x`, `const g0.x untyped int`},
688 {`package g1; func _[T any](x T) { }`, `T`, `type parameter T any`},
689 {`package g2; type N[A any] int; var _ N[int]`, `N`, `type g2.N[A any] int`},
690 {`package g3; type N[A any] int; func (N[_]) m() {}`, `N`, `type g3.N[A any] int`},
692 // Uses of fields are instantiated.
693 {`package s1; type N[A any] struct{ a A }; var f = N[int]{}.a`, `a`, `field a int`},
694 {`package s1; type N[A any] struct{ a A }; func (r N[B]) m(b B) { r.a = b }`, `a`, `field a B`},
696 // Uses of methods are uses of the instantiated method.
697 {`package m0; type N[A any] int; func (r N[B]) m() { r.n() }; func (N[C]) n() {}`, `n`, `func (m0.N[B]).n()`},
698 {`package m1; type N[A any] int; func (r N[B]) m() { }; var f = N[int].m`, `m`, `func (m1.N[int]).m()`},
699 {`package m2; func _[A any](v interface{ m() A }) { v.m() }`, `m`, `func (interface).m() A`},
700 {`package m3; func f[A any]() interface{ m() A } { return nil }; var _ = f[int]().m()`, `m`, `func (interface).m() int`},
701 {`package m4; type T[A any] func() interface{ m() A }; var x T[int]; var y = x().m`, `m`, `func (interface).m() int`},
702 {`package m5; type T[A any] interface{ m() A }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m5.T[B]).m() B`},
703 {`package m6; type T[A any] interface{ m() }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m6.T[B]).m()`},
704 {`package m7; type T[A any] interface{ m() A }; func _(t T[int]) { t.m() }`, `m`, `func (m7.T[int]).m() int`},
705 {`package m8; type T[A any] interface{ m() }; func _(t T[int]) { t.m() }`, `m`, `func (m8.T[int]).m()`},
706 {`package m9; type T[A any] interface{ m() }; func _(t T[int]) { _ = t.m }`, `m`, `func (m9.T[int]).m()`},
708 `package m10; type E[A any] interface{ m() }; type T[B any] interface{ E[B]; n() }; func _(t T[int]) { t.m() }`,
710 `func (m10.E[int]).m()`,
714 for _, test := range tests {
716 Uses: make(map[*syntax.Name]Object),
718 name := mustTypecheck("UsesInfo", test.src, &info).Name()
722 for id, obj := range info.Uses {
723 if id.Value == test.obj {
725 panic(fmt.Sprintf("multiple uses of %q", id.Value))
731 t.Errorf("package %s: %s not found", name, test.obj)
735 if got := use.String(); got != test.want {
736 t.Errorf("package %s: got %s; want %s", name, got, test.want)
741 func TestGenericMethodInfo(t *testing.T) {
746 func (r N[B]) m() { r.m(); r.n() }
748 func (r *N[C]) n() { }
750 f := mustParse("p.go", src)
752 Defs: make(map[*syntax.Name]Object),
753 Uses: make(map[*syntax.Name]Object),
754 Selections: make(map[*syntax.SelectorExpr]*Selection),
757 pkg, err := conf.Check("p", []*syntax.File{f}, &info)
762 N := pkg.Scope().Lookup("N").Type().(*Named)
764 // Find the generic methods stored on N.
765 gm, gn := N.Method(0), N.Method(1)
766 if gm.Name() == "n" {
770 // Collect objects from info.
771 var dm, dn *Func // the declared methods
772 var dmm, dmn *Func // the methods used in the body of m
773 for _, decl := range f.DeclList {
774 fdecl, ok := decl.(*syntax.FuncDecl)
778 def := info.Defs[fdecl.Name].(*Func)
779 switch fdecl.Name.Value {
782 syntax.Inspect(fdecl.Body, func(n syntax.Node) bool {
783 if call, ok := n.(*syntax.CallExpr); ok {
784 sel := call.Fun.(*syntax.SelectorExpr)
785 use := info.Uses[sel.Sel].(*Func)
786 selection := info.Selections[sel]
787 if selection.Kind() != MethodVal {
788 t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
790 if selection.Obj() != use {
791 t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
793 switch sel.Sel.Value {
808 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
811 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
814 t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
817 t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
821 func TestImplicitsInfo(t *testing.T) {
822 testenv.MustHaveGoBuild(t)
824 var tests = []struct {
828 {`package p2; import . "fmt"; var _ = Println`, ""}, // no Implicits entry
829 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
830 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
832 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
833 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
834 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
835 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
837 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
838 {`package p8; func f(int) {}`, "field: var int"},
839 {`package p9; func f() (complex64) { return 0 }`, "field: var complex64"},
840 {`package p10; type T struct{}; func (*T) f() {}`, "field: var *p10.T"},
842 // Tests using generics.
843 {`package f0; func f[T any](x int) {}`, ""}, // no Implicits entry
844 {`package f1; func f[T any](int) {}`, "field: var int"},
845 {`package f2; func f[T any](T) {}`, "field: var T"},
846 {`package f3; func f[T any]() (complex64) { return 0 }`, "field: var complex64"},
847 {`package f4; func f[T any](t T) (T) { return t }`, "field: var T"},
848 {`package t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var *t0.T[_]"},
849 {`package t1; type T[A any] struct{}; func _(x interface{}) { switch t := x.(type) { case T[int]: _ = t } }`, "caseClause: var t t1.T[int]"},
850 {`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]"},
851 {`package t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
854 for _, test := range tests {
856 Implicits: make(map[syntax.Node]Object),
858 name := mustTypecheck("ImplicitsInfo", test.src, &info).Name()
860 // the test cases expect at most one Implicits entry
861 if len(info.Implicits) > 1 {
862 t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
866 // extract Implicits entry, if any
868 for n, obj := range info.Implicits {
869 switch x := n.(type) {
870 case *syntax.ImportDecl:
872 case *syntax.CaseClause:
877 t.Fatalf("package %s: unexpected %T", name, x)
879 got += ": " + obj.String()
883 if got != test.want {
884 t.Errorf("package %s: got %q; want %q", name, got, test.want)
889 func predString(tv TypeAndValue) string {
890 var buf strings.Builder
891 pred := func(b bool, s string) {
894 buf.WriteString(", ")
900 pred(tv.IsVoid(), "void")
901 pred(tv.IsType(), "type")
902 pred(tv.IsBuiltin(), "builtin")
903 pred(tv.IsValue() && tv.Value != nil, "const")
904 pred(tv.IsValue() && tv.Value == nil, "value")
905 pred(tv.IsNil(), "nil")
906 pred(tv.Addressable(), "addressable")
907 pred(tv.Assignable(), "assignable")
908 pred(tv.HasOk(), "hasOk")
916 func TestPredicatesInfo(t *testing.T) {
917 testenv.MustHaveGoBuild(t)
919 var tests = []struct {
925 {`package n0; func f() { f() }`, `f()`, `void`},
928 {`package t0; type _ int`, `int`, `type`},
929 {`package t1; type _ []int`, `[]int`, `type`},
930 {`package t2; type _ func()`, `func()`, `type`},
931 {`package t3; type _ func(int)`, `int`, `type`},
932 {`package t3; type _ func(...int)`, `...int`, `type`},
935 {`package b0; var _ = len("")`, `len`, `builtin`},
936 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
939 {`package c0; var _ = 42`, `42`, `const`},
940 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
941 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
944 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
945 {`package v1; var _ = &[]int{1}`, `[]int{…}`, `value`},
946 {`package v2; var _ = func(){}`, `func() {}`, `value`},
947 {`package v4; func f() { _ = f }`, `f`, `value`},
948 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
949 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
951 // addressable (and thus assignable) operands
952 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
953 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
954 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
955 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
956 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
957 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
958 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
959 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
960 // composite literals are not addressable
962 // assignable but not addressable values
963 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
964 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
967 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
968 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
971 // - package names are collected in the Uses map
972 // - identifiers being declared are collected in the Defs map
973 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
974 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
975 {`package m2; const c = 0`, `c`, `<missing>`},
976 {`package m3; type T int`, `T`, `<missing>`},
977 {`package m4; var v int`, `v`, `<missing>`},
978 {`package m5; func f() {}`, `f`, `<missing>`},
979 {`package m6; func _(x int) {}`, `x`, `<missing>`},
980 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
981 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
984 for _, test := range tests {
985 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
986 name := mustTypecheck("PredicatesInfo", test.src, &info).Name()
988 // look for expression predicates
990 for e, tv := range info.Types {
991 //println(name, syntax.String(e))
992 if syntax.String(e) == test.expr {
998 if got != test.pred {
999 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
1004 func TestScopesInfo(t *testing.T) {
1005 testenv.MustHaveGoBuild(t)
1007 var tests = []struct {
1009 scopes []string // list of scope descriptors of the form kind:varlist
1011 {`package p0`, []string{
1014 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
1017 {`package p2; func _() {}`, []string{
1020 {`package p3; func _(x, y int) {}`, []string{
1021 "file:", "func:x y",
1023 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
1024 "file:", "func:x y z", // redeclaration of x
1026 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
1027 "file:", "func:u x y",
1029 {`package p6; func _() { { var x int; _ = x } }`, []string{
1030 "file:", "func:", "block:x",
1032 {`package p7; func _() { if true {} }`, []string{
1033 "file:", "func:", "if:", "block:",
1035 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
1036 "file:", "func:", "if:x", "block:y",
1038 {`package p9; func _() { switch x := 0; x {} }`, []string{
1039 "file:", "func:", "switch:x",
1041 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
1042 "file:", "func:", "switch:x", "case:y", "case:",
1044 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
1045 "file:", "func:t", "switch:",
1047 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
1048 "file:", "func:t", "switch:t",
1050 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
1051 "file:", "func:t", "switch:", "case:x", // x implicitly declared
1053 {`package p14; func _() { select{} }`, []string{
1056 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
1057 "file:", "func:c", "comm:",
1059 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
1060 "file:", "func:c", "comm:i x",
1062 {`package p17; func _() { for{} }`, []string{
1063 "file:", "func:", "for:", "block:",
1065 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
1066 "file:", "func:n", "for:i", "block:",
1068 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
1069 "file:", "func:a", "for:i", "block:",
1071 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
1072 "file:", "func:a", "for:i x", "block:",
1076 for _, test := range tests {
1077 info := Info{Scopes: make(map[syntax.Node]*Scope)}
1078 name := mustTypecheck("ScopesInfo", test.src, &info).Name()
1080 // number of scopes must match
1081 if len(info.Scopes) != len(test.scopes) {
1082 t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
1085 // scope descriptions must match
1086 for node, scope := range info.Scopes {
1088 switch node.(type) {
1091 case *syntax.FuncType:
1093 case *syntax.BlockStmt:
1095 case *syntax.IfStmt:
1097 case *syntax.SwitchStmt:
1099 case *syntax.SelectStmt:
1101 case *syntax.CaseClause:
1103 case *syntax.CommClause:
1105 case *syntax.ForStmt:
1108 kind = fmt.Sprintf("%T", node)
1111 // look for matching scope description
1112 desc := kind + ":" + strings.Join(scope.Names(), " ")
1114 for _, d := range test.scopes {
1121 t.Errorf("package %s: no matching scope found for %s", name, desc)
1127 func TestInitOrderInfo(t *testing.T) {
1128 var tests = []struct {
1132 {`package p0; var (x = 1; y = x)`, []string{
1135 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
1136 "a = 1", "b = 2", "c = 3",
1138 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
1139 "a = 1", "b = 2", "c = 3",
1141 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
1142 "_ = f()", // blank var
1144 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
1145 "a = 0", "z = 0", "y = z", "x = y",
1147 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
1148 "a, _ = m[0]", // blank var
1150 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
1151 "z = 0", "a, b = f()",
1153 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
1154 "b = 1", "a = func() int {…}()",
1156 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
1157 "c = 1", "a, b = func() (_, _ int) {…}()",
1159 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1162 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1163 "a = 0", "b = 0", "c = 0", "d = c + b",
1165 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
1166 "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
1168 // emit an initializer for n:1 initializations only once (not for each node
1169 // on the lhs which may appear in different order in the dependency graph)
1170 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
1171 "b = 0", "x, y = m[0]", "a = x",
1173 // test case from spec section on package initialization
1187 "d = 3", "b = f()", "c = f()", "a = c + b",
1189 // test case for issue 7131
1193 func next() int { counter++; return counter }
1196 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1199 var b, c = next(), next()
1200 var d, e, f = next(), next(), next()
1202 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1204 // test case for issue 10709
1214 func (T) m() int { return 0 }
1216 func makeT(n int) T {
1222 "t = makeT(0)", "v = t.m()",
1224 // test case for issue 10709: same as test before, but variable decls swapped
1234 func (T) m() int { return 0 }
1236 func makeT(n int) T {
1242 "t = makeT(0)", "v = t.m()",
1244 // another candidate possibly causing problems with issue 10709
1249 func f1() int { return g1() }
1250 func g1() int { f1(); return x1 }
1256 func f2() int { return g2() }
1257 func g2() int { return x2 }
1259 var x2 = 0`, []string{
1260 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1264 for _, test := range tests {
1266 name := mustTypecheck("InitOrderInfo", test.src, &info).Name()
1268 // number of initializers must match
1269 if len(info.InitOrder) != len(test.inits) {
1270 t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1274 // initializers must match
1275 for i, want := range test.inits {
1276 got := info.InitOrder[i].String()
1278 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1285 func TestMultiFileInitOrder(t *testing.T) {
1286 fileA := mustParse("", `package main; var a = 1`)
1287 fileB := mustParse("", `package main; var b = 2`)
1289 // The initialization order must not depend on the parse
1290 // order of the files, only on the presentation order to
1291 // the type-checker.
1292 for _, test := range []struct {
1293 files []*syntax.File
1296 {[]*syntax.File{fileA, fileB}, "[a = 1 b = 2]"},
1297 {[]*syntax.File{fileB, fileA}, "[b = 2 a = 1]"},
1300 if _, err := new(Config).Check("main", test.files, &info); err != nil {
1303 if got := fmt.Sprint(info.InitOrder); got != test.want {
1304 t.Fatalf("got %s; want %s", got, test.want)
1309 func TestFiles(t *testing.T) {
1310 var sources = []string{
1311 "package p; type T struct{}; func (T) m1() {}",
1312 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1313 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1318 pkg := NewPackage("p", "p")
1320 check := NewChecker(&conf, pkg, &info)
1322 for i, src := range sources {
1323 filename := fmt.Sprintf("sources%d", i)
1324 f := mustParse(filename, src)
1325 if err := check.Files([]*syntax.File{f}); err != nil {
1330 // check InitOrder is [x y]
1332 for _, init := range info.InitOrder {
1333 for _, v := range init.Lhs {
1334 vars = append(vars, v.Name())
1337 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1338 t.Errorf("InitOrder == %s, want %s", got, want)
1342 type testImporter map[string]*Package
1344 func (m testImporter) Import(path string) (*Package, error) {
1345 if pkg := m[path]; pkg != nil {
1348 return nil, fmt.Errorf("package %q not found", path)
1351 func TestSelection(t *testing.T) {
1352 selections := make(map[*syntax.SelectorExpr]*Selection)
1354 imports := make(testImporter)
1355 conf := Config{Importer: imports}
1356 makePkg := func(path, src string) {
1357 f := mustParse(path+".go", src)
1358 pkg, err := conf.Check(path, []*syntax.File{f}, &Info{Selections: selections})
1392 type G[P any] struct {
1404 // qualified identifiers
1442 // method expressions
1450 wantOut := map[string][2]string{
1451 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1453 "A{}.B": {"field (main.A) B *main.B", ".[0]"},
1454 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1455 "A{}.C": {"field (main.A) C main.C", ".[1]"},
1456 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1457 "A{}.b": {"field (main.A) b int", "->[0 0]"},
1458 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1459 "A{}.c": {"field (main.A) c int", ".[1 0]"},
1460 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1461 "Inst.p": {"field (main.G[int]) p int", ".[0]"},
1463 "A{}.f": {"method (main.A) f(int)", "->[0 0]"},
1464 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1465 "A{}.g": {"method (main.A) g()", ".[1 0]"},
1466 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1467 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1468 "B{}.f": {"method (main.B) f(int)", ".[0]"},
1469 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1470 "C{}.g": {"method (main.C) g()", ".[0]"},
1471 "new(C).g": {"method (*main.C) g()", "->[0]"},
1472 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1473 "Inst.m": {"method (main.G[int]) m(int)", ".[0]"},
1475 "A.f": {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1476 "(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1477 "B.f": {"method expr (main.B) f(main.B, int)", ".[0]"},
1478 "(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1479 "G[string].m": {"method expr (main.G[string]) m(main.G[string], string)", ".[0]"},
1480 "G[string]{}.p": {"field (main.G[string]) p string", ".[0]"},
1483 makePkg("lib", libSrc)
1484 makePkg("main", mainSrc)
1486 for e, sel := range selections {
1487 _ = sel.String() // assertion: must not panic
1489 start := indexFor(mainSrc, syntax.StartPos(e))
1490 end := indexFor(mainSrc, syntax.EndPos(e))
1491 segment := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1499 fmt.Sprintf("%s%v", direct, sel.Index()),
1501 want := wantOut[segment]
1503 t.Errorf("%s: got %q; want %q", segment, got, want)
1505 delete(wantOut, segment)
1507 // We must explicitly assert properties of the
1508 // Signature's receiver since it doesn't participate
1509 // in Identical() or String().
1510 sig, _ := sel.Type().(*Signature)
1511 if sel.Kind() == MethodVal {
1512 got := sig.Recv().Type()
1514 if !Identical(got, want) {
1515 t.Errorf("%s: Recv() = %s, want %s", segment, got, want)
1517 } else if sig != nil && sig.Recv() != nil {
1518 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1521 // Assert that all wantOut entries were used exactly once.
1522 for segment := range wantOut {
1523 t.Errorf("no syntax.Selection found with syntax %q", segment)
1527 // indexFor returns the index into s corresponding to the position pos.
1528 func indexFor(s string, pos syntax.Pos) int {
1529 i, line := 0, 1 // string index and corresponding line
1530 target := int(pos.Line())
1531 for line < target && i < len(s) {
1537 return i + int(pos.Col()-1) // columns are 1-based
1540 func TestIssue8518(t *testing.T) {
1541 imports := make(testImporter)
1543 Error: func(err error) { t.Log(err) }, // don't exit after first error
1546 makePkg := func(path, src string) {
1547 f := mustParse(path, src)
1548 pkg, _ := conf.Check(path, []*syntax.File{f}, nil) // errors logged via conf.Error
1556 const C2 = missing.C
1566 makePkg("a", libSrc)
1567 makePkg("main", mainSrc) // don't crash when type-checking this package
1570 func TestLookupFieldOrMethodOnNil(t *testing.T) {
1571 // LookupFieldOrMethod on a nil type is expected to produce a run-time panic.
1573 const want = "LookupFieldOrMethod on nil type"
1575 if s, ok := p.(string); !ok || s != want {
1576 t.Fatalf("got %v, want %s", p, want)
1579 LookupFieldOrMethod(nil, false, nil, "")
1582 func TestLookupFieldOrMethod(t *testing.T) {
1583 // Test cases assume a lookup of the form a.f or x.f, where a stands for an
1584 // addressable value, and x for a non-addressable value (even though a variable
1585 // for ease of test case writing).
1586 var tests = []struct {
1593 {"var x T; type T struct{}", false, nil, false},
1594 {"var x T; type T struct{ f int }", true, []int{0}, false},
1595 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1597 // field lookups on a generic type
1598 {"var x T[int]; type T[P any] struct{}", false, nil, false},
1599 {"var x T[int]; type T[P any] struct{ f P }", true, []int{0}, false},
1600 {"var x T[int]; type T[P any] struct{ a, b, f, c P }", true, []int{2}, false},
1603 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1604 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1605 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1606 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1608 // method lookups on a generic type
1609 {"var a T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, false},
1610 {"var a *T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, true},
1611 {"var a T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, false},
1612 {"var a *T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1615 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1616 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1618 // collisions on a generic type
1619 {"type ( E1[P any] struct{ f P }; E2[P any] struct{ f P }; x struct{ E1[int]; *E2[int] })", false, []int{1, 0}, false},
1620 {"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},
1622 // outside methodset
1623 // (*T).f method exists, but value of type T is not addressable
1624 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1626 // outside method set of a generic type
1627 {"var x T[int]; type T[P any] struct{}; func (*T[P]) f() {}", false, nil, true},
1629 // recursive generic types; see golang/go#52715
1630 {"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},
1631 {"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},
1634 for _, test := range tests {
1635 pkg := mustTypecheck("test", "package p;"+test.src, nil)
1637 obj := pkg.Scope().Lookup("a")
1639 if obj = pkg.Scope().Lookup("x"); obj == nil {
1640 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1645 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1646 if (f != nil) != test.found {
1648 t.Errorf("%s: got no object; want one", test.src)
1650 t.Errorf("%s: got object = %v; want none", test.src, f)
1653 if !sameSlice(index, test.index) {
1654 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1656 if indirect != test.indirect {
1657 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1662 // Test for golang/go#52715
1663 func TestLookupFieldOrMethod_RecursiveGeneric(t *testing.T) {
1667 type Tree[T any] struct {
1671 func (*Tree[R]) N(r R) R { return r }
1673 type Node[T any] struct {
1677 type Instance = *Tree[int]
1680 f := mustParse("foo.go", src)
1681 pkg := NewPackage("pkg", f.PkgName.Value)
1682 if err := NewChecker(nil, pkg, nil).Files([]*syntax.File{f}); err != nil {
1686 T := pkg.Scope().Lookup("Instance").Type()
1687 _, _, _ = LookupFieldOrMethod(T, false, pkg, "M") // verify that LookupFieldOrMethod terminates
1690 func sameSlice(a, b []int) bool {
1691 if len(a) != len(b) {
1694 for i, x := range a {
1702 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1703 // the correct result at various positions within the source.
1704 func TestScopeLookupParent(t *testing.T) {
1705 imports := make(testImporter)
1706 conf := Config{Importer: imports}
1708 makePkg := func(path, src string) {
1709 f := mustParse(path, src)
1711 imports[path], err = conf.Check(path, []*syntax.File{f}, &info)
1717 makePkg("lib", "package lib; var X int")
1718 // Each /*name=kind:line*/ comment makes the test look up the
1719 // name at that point and checks that it resolves to a decl of
1720 // the specified kind and line number. "undef" means undefined.
1722 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1733 const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1734 type /*t=undef*/ t /*t=typename:14*/ *t
1735 print(Y) /*Y=var:10*/
1736 x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1737 var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1740 for i, x := range a /*i=undef*/ /*x=var:16*/ { _ = i; _ = x }
1743 switch y := i.(type) { /*y=undef*/
1744 case /*y=undef*/ int /*y=var:23*/ :
1745 case float32, /*y=undef*/ float64 /*y=var:23*/ :
1746 default /*y=var:23*/:
1751 switch int := i.(type) {
1752 case /*int=typename:0*/ int /*int=var:31*/ :
1754 default /*int=var:31*/ :
1760 info.Uses = make(map[*syntax.Name]Object)
1761 makePkg("main", mainSrc)
1762 mainScope := imports["main"].Scope()
1764 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1766 base := syntax.NewFileBase("main")
1767 syntax.CommentsDo(strings.NewReader(mainSrc), func(line, col uint, text string) {
1768 pos := syntax.MakePos(base, line, col)
1770 // Syntax errors are not comments.
1772 t.Errorf("%s: %s", pos, text)
1776 // Parse the assertion in the comment.
1777 m := rx.FindStringSubmatch(text)
1779 t.Errorf("%s: bad comment: %s", pos, text)
1782 name, want := m[1], m[2]
1784 // Look up the name in the innermost enclosing scope.
1785 inner := mainScope.Innermost(pos)
1787 t.Errorf("%s: at %s: can't find innermost scope", pos, text)
1791 if _, obj := inner.LookupParent(name, pos); obj != nil {
1792 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types2."))
1793 got = fmt.Sprintf("%s:%d", kind, obj.Pos().Line())
1796 t.Errorf("%s: at %s: %s resolved to %s, want %s", pos, text, name, got, want)
1800 // Check that for each referring identifier,
1801 // a lookup of its name on the innermost
1802 // enclosing scope returns the correct object.
1804 for id, wantObj := range info.Uses {
1805 inner := mainScope.Innermost(id.Pos())
1807 t.Errorf("%s: can't find innermost scope enclosing %q", id.Pos(), id.Value)
1811 // Exclude selectors and qualified identifiers---lexical
1812 // refs only. (Ideally, we'd see if the AST parent is a
1813 // SelectorExpr, but that requires PathEnclosingInterval
1814 // from golang.org/x/tools/go/ast/astutil.)
1815 if id.Value == "X" {
1819 _, gotObj := inner.LookupParent(id.Value, id.Pos())
1820 if gotObj != wantObj {
1821 t.Errorf("%s: got %v, want %v", id.Pos(), gotObj, wantObj)
1827 // newDefined creates a new defined type named T with the given underlying type.
1828 func newDefined(underlying Type) *Named {
1829 tname := NewTypeName(nopos, nil, "T", nil)
1830 return NewNamed(tname, underlying, nil)
1833 func TestConvertibleTo(t *testing.T) {
1834 for _, test := range []struct {
1838 {Typ[Int], Typ[Int], true},
1839 {Typ[Int], Typ[Float32], true},
1840 {Typ[Int], Typ[String], true},
1841 {newDefined(Typ[Int]), Typ[Int], true},
1842 {newDefined(new(Struct)), new(Struct), true},
1843 {newDefined(Typ[Int]), new(Struct), false},
1844 {Typ[UntypedInt], Typ[Int], true},
1845 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), true},
1846 {NewSlice(Typ[Int]), NewArray(Typ[Uint], 10), false},
1847 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
1848 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
1849 // Untyped string values are not permitted by the spec, so the behavior below is undefined.
1850 {Typ[UntypedString], Typ[String], true},
1852 if got := ConvertibleTo(test.v, test.t); got != test.want {
1853 t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1858 func TestAssignableTo(t *testing.T) {
1859 for _, test := range []struct {
1863 {Typ[Int], Typ[Int], true},
1864 {Typ[Int], Typ[Float32], false},
1865 {newDefined(Typ[Int]), Typ[Int], false},
1866 {newDefined(new(Struct)), new(Struct), true},
1867 {Typ[UntypedBool], Typ[Bool], true},
1868 {Typ[UntypedString], Typ[Bool], false},
1869 // Neither untyped string nor untyped numeric assignments arise during
1870 // normal type checking, so the below behavior is technically undefined by
1872 {Typ[UntypedString], Typ[String], true},
1873 {Typ[UntypedInt], Typ[Int], true},
1875 if got := AssignableTo(test.v, test.t); got != test.want {
1876 t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1881 func TestIdentical(t *testing.T) {
1882 // For each test, we compare the types of objects X and Y in the source.
1888 {"var X int; var Y int", true},
1889 {"var X int; var Y string", false},
1891 // TODO: add more tests for complex types.
1894 {"type X int; type Y int", false},
1897 {"type X = int; type Y = int", true},
1900 {`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
1901 {`func X() string { return "" }; func Y(int) string { return "" }`, false},
1902 {`func X(int) string { return "" }; func Y(int) {}`, false},
1904 // Generic functions. Type parameters should be considered identical modulo
1905 // renaming. See also issue #49722.
1906 {`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
1907 {`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
1908 {`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
1909 {`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
1910 {`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
1911 {`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
1914 for _, test := range tests {
1915 pkg := mustTypecheck("test", "package p;"+test.src, nil)
1916 X := pkg.Scope().Lookup("X")
1917 Y := pkg.Scope().Lookup("Y")
1918 if X == nil || Y == nil {
1919 t.Fatal("test must declare both X and Y")
1921 if got := Identical(X.Type(), Y.Type()); got != test.want {
1922 t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
1927 func TestIdentical_issue15173(t *testing.T) {
1928 // Identical should allow nil arguments and be symmetric.
1929 for _, test := range []struct {
1933 {Typ[Int], Typ[Int], true},
1934 {Typ[Int], nil, false},
1935 {nil, Typ[Int], false},
1938 if got := Identical(test.x, test.y); got != test.want {
1939 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
1944 func TestIdenticalUnions(t *testing.T) {
1945 tname := NewTypeName(nopos, nil, "myInt", nil)
1946 myInt := NewNamed(tname, Typ[Int], nil)
1947 tmap := map[string]*Term{
1948 "int": NewTerm(false, Typ[Int]),
1949 "~int": NewTerm(true, Typ[Int]),
1950 "string": NewTerm(false, Typ[String]),
1951 "~string": NewTerm(true, Typ[String]),
1952 "myInt": NewTerm(false, myInt),
1954 makeUnion := func(s string) *Union {
1955 parts := strings.Split(s, "|")
1957 for _, p := range parts {
1960 t.Fatalf("missing term %q", p)
1962 terms = append(terms, term)
1964 return NewUnion(terms)
1966 for _, test := range []struct {
1970 // These tests are just sanity checks. The tests for type sets and
1971 // interfaces provide much more test coverage.
1972 {"int|~int", "~int", true},
1973 {"myInt|~int", "~int", true},
1974 {"int|string", "string|int", true},
1975 {"int|int|string", "string|int", true},
1976 {"myInt|string", "int|string", false},
1978 x := makeUnion(test.x)
1979 y := makeUnion(test.y)
1980 if got := Identical(x, y); got != test.want {
1981 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
1986 func TestIssue15305(t *testing.T) {
1987 const src = "package p; func f() int16; var _ = f(undef)"
1988 f := mustParse("issue15305.go", src)
1990 Error: func(err error) {}, // allow errors
1993 Types: make(map[syntax.Expr]TypeAndValue),
1995 conf.Check("p", []*syntax.File{f}, info) // ignore result
1996 for e, tv := range info.Types {
1997 if _, ok := e.(*syntax.CallExpr); ok {
1998 if tv.Type != Typ[Int16] {
1999 t.Errorf("CallExpr has type %v, want int16", tv.Type)
2004 t.Errorf("CallExpr has no type")
2007 // TestCompositeLitTypes verifies that Info.Types registers the correct
2008 // types for composite literal expressions and composite literal type
2010 func TestCompositeLitTypes(t *testing.T) {
2011 for _, test := range []struct {
2014 {`[16]byte{}`, `[16]byte`},
2015 {`[...]byte{}`, `[0]byte`}, // test for issue #14092
2016 {`[...]int{1, 2, 3}`, `[3]int`}, // test for issue #14092
2017 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for issue #14092
2018 {`[]int{}`, `[]int`},
2019 {`map[string]bool{"foo": true}`, `map[string]bool`},
2020 {`struct{}{}`, `struct{}`},
2021 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
2023 f := mustParse(test.lit, "package p; var _ = "+test.lit)
2024 types := make(map[syntax.Expr]TypeAndValue)
2025 if _, err := new(Config).Check("p", []*syntax.File{f}, &Info{Types: types}); err != nil {
2026 t.Fatalf("%s: %v", test.lit, err)
2029 cmptype := func(x syntax.Expr, want string) {
2032 t.Errorf("%s: no Types entry found", test.lit)
2036 t.Errorf("%s: type is nil", test.lit)
2039 if got := tv.Type.String(); got != want {
2040 t.Errorf("%s: got %v, want %s", test.lit, got, want)
2044 // test type of composite literal expression
2045 rhs := f.DeclList[0].(*syntax.VarDecl).Values
2046 cmptype(rhs, test.typ)
2048 // test type of composite literal type expression
2049 cmptype(rhs.(*syntax.CompositeLit).Type, test.typ)
2053 // TestObjectParents verifies that objects have parent scopes or not
2054 // as specified by the Object interface.
2055 func TestObjectParents(t *testing.T) {
2074 func f(x int) { y := x; print(y) }
2077 f := mustParse("src", src)
2080 Defs: make(map[*syntax.Name]Object),
2082 if _, err := new(Config).Check("p", []*syntax.File{f}, info); err != nil {
2086 for ident, obj := range info.Defs {
2088 // only package names and implicit vars have a nil object
2089 // (in this test we only need to handle the package name)
2090 if ident.Value != "p" {
2091 t.Errorf("%v has nil object", ident)
2096 // struct fields, type-associated and interface methods
2097 // have no parent scope
2099 switch obj := obj.(type) {
2105 if obj.Type().(*Signature).Recv() != nil { // method
2110 gotParent := obj.Parent() != nil
2112 case gotParent && !wantParent:
2113 t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
2114 case !gotParent && wantParent:
2115 t.Errorf("%v: no parent found", ident)
2120 // TestFailedImport tests that we don't get follow-on errors
2121 // elsewhere in a package due to failing to import a package.
2122 func TestFailedImport(t *testing.T) {
2123 testenv.MustHaveGoBuild(t)
2128 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
2133 func f(x T) T { return foo.F(x) }
2135 f := mustParse("src", src)
2136 files := []*syntax.File{f}
2138 // type-check using all possible importers
2139 for _, compiler := range []string{"gc", "gccgo", "source"} {
2142 Error: func(err error) {
2143 // we should only see the import error
2144 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
2145 t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
2149 //Importer: importer.For(compiler, nil),
2153 Uses: make(map[*syntax.Name]Object),
2155 pkg, _ := conf.Check("p", files, info)
2157 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
2161 imports := pkg.Imports()
2162 if len(imports) != 1 {
2163 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
2167 if imp.Name() != "foo" {
2168 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
2172 // verify that all uses of foo refer to the imported package foo (imp)
2173 for ident, obj := range info.Uses {
2174 if ident.Value == "foo" {
2175 if obj, ok := obj.(*PkgName); ok {
2176 if obj.Imported() != imp {
2177 t.Errorf("%s resolved to %v; want %v", ident.Value, obj.Imported(), imp)
2180 t.Errorf("%s resolved to %v; want package name", ident.Value, obj)
2187 func TestInstantiate(t *testing.T) {
2188 // eventually we like more tests but this is a start
2189 const src = "package p; type T[P any] *T[P]"
2190 pkg := mustTypecheck(".", src, nil)
2192 // type T should have one type parameter
2193 T := pkg.Scope().Lookup("T").Type().(*Named)
2194 if n := T.TypeParams().Len(); n != 1 {
2195 t.Fatalf("expected 1 type parameter; found %d", n)
2198 // instantiation should succeed (no endless recursion)
2199 // even with a nil *Checker
2200 res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
2205 // instantiated type should point to itself
2206 if p := res.Underlying().(*Pointer).Elem(); p != res {
2207 t.Fatalf("unexpected result type: %s points to %s", res, p)
2211 func TestInstantiateErrors(t *testing.T) {
2213 src string // by convention, T must be the type being instantiated
2215 wantAt int // -1 indicates no error
2217 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
2218 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
2219 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
2220 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
2223 for _, test := range tests {
2224 src := "package p; " + test.src
2225 pkg := mustTypecheck(".", src, nil)
2227 T := pkg.Scope().Lookup("T").Type().(*Named)
2229 _, err := Instantiate(nil, T, test.targs, true)
2231 t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
2234 var argErr *ArgumentError
2235 if !errors.As(err, &argErr) {
2236 t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
2239 if argErr.Index != test.wantAt {
2240 t.Errorf("Instantiate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2245 func TestArgumentErrorUnwrapping(t *testing.T) {
2246 var err error = &ArgumentError{
2248 Err: Error{Msg: "test"},
2251 if !errors.As(err, &e) {
2252 t.Fatalf("error %v does not wrap types.Error", err)
2254 if e.Msg != "test" {
2255 t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2259 func TestInstanceIdentity(t *testing.T) {
2260 imports := make(testImporter)
2261 conf := Config{Importer: imports}
2262 makePkg := func(src string) {
2263 f := mustParse("", src)
2264 name := f.PkgName.Value
2265 pkg, err := conf.Check(name, []*syntax.File{f}, nil)
2271 makePkg(`package lib; type T[P any] struct{}`)
2272 makePkg(`package a; import "lib"; var A lib.T[int]`)
2273 makePkg(`package b; import "lib"; var B lib.T[int]`)
2274 a := imports["a"].Scope().Lookup("A")
2275 b := imports["b"].Scope().Lookup("B")
2276 if !Identical(a.Type(), b.Type()) {
2277 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
2281 // TestInstantiatedObjects verifies properties of instantiated objects.
2282 func TestInstantiatedObjects(t *testing.T) {
2286 type T[P any] struct {
2290 func (recv *T[Q]) concreteMethod(mParam Q) (mResult Q) { return }
2292 type FT[P any] func(ftParam P) (ftResult P)
2294 func F[P any](fParam P) (fResult P){ return }
2296 type I[P any] interface {
2302 func (R[P]) m() {} // having a method triggers expansion of R
2317 Defs: make(map[*syntax.Name]Object),
2319 f := mustParse("p.go", src)
2321 pkg, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
2326 lookup := func(name string) Type { return pkg.Scope().Lookup(name).Type() }
2327 fnScope := pkg.Scope().Lookup("fn").(*Func).Scope()
2334 {"field", lookup("t").Underlying().(*Struct).Field(0)},
2335 {"field", fnScope.Lookup("r").Type().Underlying().(*Struct).Field(0)},
2337 // Methods and method fields
2338 {"concreteMethod", lookup("t").(*Named).Method(0)},
2339 {"recv", lookup("t").(*Named).Method(0).Type().(*Signature).Recv()},
2340 {"mParam", lookup("t").(*Named).Method(0).Type().(*Signature).Params().At(0)},
2341 {"mResult", lookup("t").(*Named).Method(0).Type().(*Signature).Results().At(0)},
2343 // Interface methods
2344 {"interfaceMethod", lookup("i").Underlying().(*Interface).Method(0)},
2346 // Function type fields
2347 {"ftParam", lookup("ft").Underlying().(*Signature).Params().At(0)},
2348 {"ftResult", lookup("ft").Underlying().(*Signature).Results().At(0)},
2351 {"fParam", lookup("f").(*Signature).Params().At(0)},
2352 {"fResult", lookup("f").(*Signature).Results().At(0)},
2355 // Collect all identifiers by name.
2356 idents := make(map[string][]*syntax.Name)
2357 syntax.Inspect(f, func(n syntax.Node) bool {
2358 if id, ok := n.(*syntax.Name); ok {
2359 idents[id.Value] = append(idents[id.Value], id)
2364 for _, test := range tests {
2366 t.Run(test.name, func(t *testing.T) {
2367 if got := len(idents[test.name]); got != 1 {
2368 t.Fatalf("found %d identifiers named %s, want 1", got, test.name)
2370 ident := idents[test.name][0]
2371 def := info.Defs[ident]
2372 if def == test.obj {
2373 t.Fatalf("info.Defs[%s] contains the test object", test.name)
2375 if orig := originObject(test.obj); def != orig {
2376 t.Errorf("info.Defs[%s] does not match obj.Origin()", test.name)
2378 if def.Pkg() != test.obj.Pkg() {
2379 t.Errorf("Pkg() = %v, want %v", def.Pkg(), test.obj.Pkg())
2381 if def.Name() != test.obj.Name() {
2382 t.Errorf("Name() = %v, want %v", def.Name(), test.obj.Name())
2384 if def.Pos() != test.obj.Pos() {
2385 t.Errorf("Pos() = %v, want %v", def.Pos(), test.obj.Pos())
2387 if def.Parent() != test.obj.Parent() {
2388 t.Fatalf("Parent() = %v, want %v", def.Parent(), test.obj.Parent())
2390 if def.Exported() != test.obj.Exported() {
2391 t.Fatalf("Exported() = %v, want %v", def.Exported(), test.obj.Exported())
2393 if def.Id() != test.obj.Id() {
2394 t.Fatalf("Id() = %v, want %v", def.Id(), test.obj.Id())
2396 // String and Type are expected to differ.
2401 func originObject(obj Object) Object {
2402 switch obj := obj.(type) {
2411 func TestImplements(t *testing.T) {
2415 type EmptyIface interface{}
2426 type Integer interface{
2427 int8 | int16 | int32 | int64
2430 type EmptyTypeSet interface{
2447 type Bad Bad // invalid type
2450 f := mustParse("p.go", src)
2451 conf := Config{Error: func(error) {}}
2452 pkg, _ := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
2454 lookup := func(tname string) Type { return pkg.Scope().Lookup(tname).Type() }
2456 EmptyIface = lookup("EmptyIface").Underlying().(*Interface)
2457 I = lookup("I").(*Named)
2458 II = I.Underlying().(*Interface)
2459 C = lookup("C").(*Named)
2460 CI = C.Underlying().(*Interface)
2461 Integer = lookup("Integer").Underlying().(*Interface)
2462 EmptyTypeSet = lookup("EmptyTypeSet").Underlying().(*Interface)
2464 N1p = NewPointer(N1)
2466 N2p = NewPointer(N2)
2481 {Typ[Int8], Integer, true},
2482 {Typ[Int64], Integer, true},
2483 {Typ[String], Integer, false},
2484 {EmptyTypeSet, II, true},
2485 {EmptyTypeSet, EmptyTypeSet, true},
2486 {Typ[Int], EmptyTypeSet, false},
2501 {Bad, EmptyIface, true},
2504 for _, test := range tests {
2505 if got := Implements(test.V, test.T); got != test.want {
2506 t.Errorf("Implements(%s, %s) = %t, want %t", test.V, test.T, got, test.want)
2509 // The type assertion x.(T) is valid if T is an interface or if T implements the type of x.
2510 // The assertion is never valid if T is a bad type.
2514 if _, ok := T.Underlying().(*Interface); (ok || Implements(T, V)) && T != Bad {
2517 if got := AssertableTo(V, T); got != want {
2518 t.Errorf("AssertableTo(%s, %s) = %t, want %t", V, T, got, want)
2523 func TestMissingMethodAlternative(t *testing.T) {
2545 pkg := mustTypecheck("p.go", src, nil)
2547 T := pkg.Scope().Lookup("T").Type().Underlying().(*Interface)
2548 lookup := func(name string) (*Func, bool) {
2549 return MissingMethod(pkg.Scope().Lookup(name).Type(), T, true)
2552 // V0 has method m with correct signature. Should not report wrongType.
2553 method, wrongType := lookup("V0")
2554 if method != nil || wrongType {
2555 t.Fatalf("V0: got method = %v, wrongType = %v", method, wrongType)
2558 checkMissingMethod := func(tname string, reportWrongType bool) {
2559 method, wrongType := lookup(tname)
2560 if method == nil || method.Name() != "m" || wrongType != reportWrongType {
2561 t.Fatalf("%s: got method = %v, wrongType = %v", tname, method, wrongType)
2565 // V1 has no method m. Should not report wrongType.
2566 checkMissingMethod("V1", false)
2568 // V2 has method m with wrong signature type (ignoring receiver). Should report wrongType.
2569 checkMissingMethod("V2", true)
2571 // V3 has no method m but it exists on *V3. Should report wrongType.
2572 checkMissingMethod("V3", true)
2574 // V4 has no method m but has M. Should not report wrongType.
2575 checkMissingMethod("V4", false)