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`},
385 // reverse type inference
386 {`package r1; var _ func(int) = g; func g[P any](P) {}`, `g`, `func(int)`},
387 {`package r2; var _ func(int) = g[int]; func g[P any](P) {}`, `g`, `func[P any](P)`}, // go.dev/issues/60212
388 {`package r3; var _ func(int) = g[int]; func g[P any](P) {}`, `g[int]`, `func(int)`},
389 {`package r4; var _ func(int, string) = g; func g[P, Q any](P, Q) {}`, `g`, `func(int, string)`},
390 {`package r5; var _ func(int, string) = g[int]; func g[P, Q any](P, Q) {}`, `g`, `func[P, Q any](P, Q)`}, // go.dev/issues/60212
391 {`package r6; var _ func(int, string) = g[int]; func g[P, Q any](P, Q) {}`, `g[int]`, `func(int, string)`},
393 {`package s1; func _() { f(g) }; func f(func(int)) {}; func g[P any](P) {}`, `g`, `func(int)`},
394 {`package s2; func _() { f(g[int]) }; func f(func(int)) {}; func g[P any](P) {}`, `g`, `func[P any](P)`}, // go.dev/issues/60212
395 {`package s3; func _() { f(g[int]) }; func f(func(int)) {}; func g[P any](P) {}`, `g[int]`, `func(int)`},
396 {`package s4; func _() { f(g) }; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}`, `g`, `func(int, string)`},
397 {`package s5; func _() { f(g[int]) }; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}`, `g`, `func[P, Q any](P, Q)`}, // go.dev/issues/60212
398 {`package s6; func _() { f(g[int]) }; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}`, `g[int]`, `func(int, string)`},
400 {`package s7; func _() { f(g, h) }; func f[P any](func(int, P), func(P, string)) {}; func g[P any](P, P) {}; func h[P, Q any](P, Q) {}`, `g`, `func(int, int)`},
401 {`package s8; func _() { f(g, h) }; func f[P any](func(int, P), func(P, string)) {}; func g[P any](P, P) {}; func h[P, Q any](P, Q) {}`, `h`, `func(int, string)`},
402 {`package s9; func _() { f(g, h[int]) }; func f[P any](func(int, P), func(P, string)) {}; func g[P any](P, P) {}; func h[P, Q any](P, Q) {}`, `h`, `func[P, Q any](P, Q)`}, // go.dev/issues/60212
403 {`package s10; func _() { f(g, h[int]) }; func f[P any](func(int, P), func(P, string)) {}; func g[P any](P, P) {}; func h[P, Q any](P, Q) {}`, `h[int]`, `func(int, string)`},
406 for _, test := range tests {
407 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
409 if strings.HasPrefix(test.src, brokenPkg) {
410 pkg, err := typecheck(test.src, nil, &info)
412 t.Errorf("package %s: expected to fail but passed", pkg.Name())
419 name = mustTypecheck(test.src, nil, &info).Name()
422 // look for expression type
424 for e, tv := range info.Types {
425 if syntax.String(e) == test.expr {
431 t.Errorf("package %s: no type found for %s", name, test.expr)
435 // check that type is correct
436 if got := typ.String(); got != test.typ {
437 t.Errorf("package %s: expr = %s: got %s; want %s", name, test.expr, got, test.typ)
442 func TestInstanceInfo(t *testing.T) {
443 const lib = `package lib
450 type testInst struct {
456 var tests = []struct {
458 instances []testInst // recorded instances in source order
460 {`package p0; func f[T any](T) {}; func _() { f(42) }`,
461 []testInst{{`f`, []string{`int`}, `func(int)`}},
463 {`package p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
464 []testInst{{`f`, []string{`rune`}, `func(rune) rune`}},
466 {`package p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
467 []testInst{{`f`, []string{`complex128`}, `func(...complex128) complex128`}},
469 {`package p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
470 []testInst{{`f`, []string{`float64`, `string`, `byte`}, `func(float64, *string, []byte)`}},
472 {`package p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
473 []testInst{{`f`, []string{`float64`, `byte`}, `func(float64, *byte, ...[]byte)`}},
476 {`package s1; func f[T any, P interface{*T}](x T) {}; func _(x string) { f(x) }`,
477 []testInst{{`f`, []string{`string`, `*string`}, `func(x string)`}},
479 {`package s2; func f[T any, P interface{*T}](x []T) {}; func _(x []int) { f(x) }`,
480 []testInst{{`f`, []string{`int`, `*int`}, `func(x []int)`}},
482 {`package s3; type C[T any] interface{chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
484 {`C`, []string{`T`}, `interface{chan<- T}`},
485 {`f`, []string{`int`, `chan<- int`}, `func(x []int)`},
488 {`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) }`,
490 {`C`, []string{`T`}, `interface{chan<- T}`},
491 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
492 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func(x []int)`},
496 {`package t1; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = f[string] }`,
497 []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
499 {`package t2; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = (f[string]) }`,
500 []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
502 {`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] }`,
504 {`C`, []string{`T`}, `interface{chan<- T}`},
505 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
506 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
509 {`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]) }`,
511 {`C`, []string{`T`}, `interface{chan<- T}`},
512 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
513 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
516 {`package i0; import "lib"; func _() { lib.F(42) }`,
517 []testInst{{`F`, []string{`int`}, `func(int)`}},
520 {`package duplfunc0; func f[T any](T) {}; func _() { f(42); f("foo"); f[int](3) }`,
522 {`f`, []string{`int`}, `func(int)`},
523 {`f`, []string{`string`}, `func(string)`},
524 {`f`, []string{`int`}, `func(int)`},
527 {`package duplfunc1; import "lib"; func _() { lib.F(42); lib.F("foo"); lib.F(3) }`,
529 {`F`, []string{`int`}, `func(int)`},
530 {`F`, []string{`string`}, `func(string)`},
531 {`F`, []string{`int`}, `func(int)`},
535 {`package type0; type T[P interface{~int}] struct{ x P }; var _ T[int]`,
536 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
538 {`package type1; type T[P interface{~int}] struct{ x P }; var _ (T[int])`,
539 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
541 {`package type2; type T[P interface{~int}] struct{ x P }; var _ T[(int)]`,
542 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
544 {`package type3; type T[P1 interface{~[]P2}, P2 any] struct{ x P1; y P2 }; var _ T[[]int, int]`,
545 []testInst{{`T`, []string{`[]int`, `int`}, `struct{x []int; y int}`}},
547 {`package type4; import "lib"; var _ lib.T[int]`,
548 []testInst{{`T`, []string{`int`}, `[]int`}},
551 {`package dupltype0; type T[P interface{~int}] struct{ x P }; var x T[int]; var y T[int]`,
553 {`T`, []string{`int`}, `struct{x int}`},
554 {`T`, []string{`int`}, `struct{x int}`},
557 {`package dupltype1; type T[P ~int] struct{ x P }; func (r *T[Q]) add(z T[Q]) { r.x += z.x }`,
559 {`T`, []string{`Q`}, `struct{x Q}`},
560 {`T`, []string{`Q`}, `struct{x Q}`},
563 {`package dupltype1; import "lib"; var x lib.T[int]; var y lib.T[int]; var z lib.T[string]`,
565 {`T`, []string{`int`}, `[]int`},
566 {`T`, []string{`int`}, `[]int`},
567 {`T`, []string{`string`}, `[]string`},
570 {`package issue51803; func foo[T any](T) {}; func _() { foo[int]( /* leave arg away on purpose */ ) }`,
571 []testInst{{`foo`, []string{`int`}, `func(int)`}},
574 // reverse type inference
575 {`package reverse1a; var f func(int) = g; func g[P any](P) {}`,
576 []testInst{{`g`, []string{`int`}, `func(int)`}},
578 {`package reverse1b; func f(func(int)) {}; func g[P any](P) {}; func _() { f(g) }`,
579 []testInst{{`g`, []string{`int`}, `func(int)`}},
581 {`package reverse2a; var f func(int, string) = g; func g[P, Q any](P, Q) {}`,
582 []testInst{{`g`, []string{`int`, `string`}, `func(int, string)`}},
584 {`package reverse2b; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}; func _() { f(g) }`,
585 []testInst{{`g`, []string{`int`, `string`}, `func(int, string)`}},
587 {`package reverse2c; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}; func _() { f(g[int]) }`,
588 []testInst{{`g`, []string{`int`, `string`}, `func(int, string)`}},
590 // reverse3a not possible (cannot assign to generic function outside of argument passing)
591 {`package reverse3b; func f[R any](func(int) R) {}; func g[P any](P) string { return "" }; func _() { f(g) }`,
593 {`f`, []string{`string`}, `func(func(int) string)`},
594 {`g`, []string{`int`}, `func(int) string`},
597 {`package reverse4a; var _, _ func([]int, *float32) = g, h; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}`,
599 {`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
600 {`h`, []string{`int`}, `func([]int, *float32)`},
603 {`package reverse4b; func f(_, _ func([]int, *float32)) {}; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}; func _() { f(g, h) }`,
605 {`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
606 {`h`, []string{`int`}, `func([]int, *float32)`},
609 {`package issue59956; func f(func(int), func(string), func(bool)) {}; func g[P any](P) {}; func _() { f(g, g, g) }`,
611 {`g`, []string{`int`}, `func(int)`},
612 {`g`, []string{`string`}, `func(string)`},
613 {`g`, []string{`bool`}, `func(bool)`},
618 for _, test := range tests {
619 imports := make(testImporter)
620 conf := Config{Importer: imports}
621 instMap := make(map[*syntax.Name]Instance)
622 useMap := make(map[*syntax.Name]Object)
623 makePkg := func(src string) *Package {
624 pkg, err := typecheck(src, &conf, &Info{Instances: instMap, Uses: useMap})
625 // allow error for issue51803
626 if err != nil && (pkg == nil || pkg.Name() != "issue51803") {
629 imports[pkg.Name()] = pkg
633 pkg := makePkg(test.src)
635 t.Run(pkg.Name(), func(t *testing.T) {
636 // Sort instances in source order for stability.
637 instances := sortedInstances(instMap)
638 if got, want := len(instances), len(test.instances); got != want {
639 t.Fatalf("got %d instances, want %d", got, want)
642 // Pairwise compare with the expected instances.
643 for ii, inst := range instances {
645 for i := 0; i < inst.Inst.TypeArgs.Len(); i++ {
646 targs = append(targs, inst.Inst.TypeArgs.At(i))
648 typ := inst.Inst.Type
650 testInst := test.instances[ii]
651 if got := inst.Name.Value; got != testInst.name {
652 t.Fatalf("got name %s, want %s", got, testInst.name)
655 if len(targs) != len(testInst.targs) {
656 t.Fatalf("got %d type arguments; want %d", len(targs), len(testInst.targs))
658 for i, targ := range targs {
659 if got := targ.String(); got != testInst.targs[i] {
660 t.Errorf("type argument %d: got %s; want %s", i, got, testInst.targs[i])
663 if got := typ.Underlying().String(); got != testInst.typ {
664 t.Errorf("package %s: got %s; want %s", pkg.Name(), got, testInst.typ)
667 // Verify the invariant that re-instantiating the corresponding generic
668 // type with TypeArgs results in an identical instance.
669 ptype := useMap[inst.Name].Type()
670 lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
671 if lister == nil || lister.TypeParams().Len() == 0 {
672 t.Fatalf("info.Types[%v] = %v, want parameterized type", inst.Name, ptype)
674 inst2, err := Instantiate(nil, ptype, targs, true)
676 t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
678 if !Identical(inst.Inst.Type, inst2) {
679 t.Errorf("%v and %v are not identical", inst.Inst.Type, inst2)
686 type recordedInstance struct {
691 func sortedInstances(m map[*syntax.Name]Instance) (instances []recordedInstance) {
692 for id, inst := range m {
693 instances = append(instances, recordedInstance{id, inst})
695 sort.Slice(instances, func(i, j int) bool {
696 return CmpPos(instances[i].Name.Pos(), instances[j].Name.Pos()) < 0
701 func TestDefsInfo(t *testing.T) {
702 var tests = []struct {
707 {`package p0; const x = 42`, `x`, `const p0.x untyped int`},
708 {`package p1; const x int = 42`, `x`, `const p1.x int`},
709 {`package p2; var x int`, `x`, `var p2.x int`},
710 {`package p3; type x int`, `x`, `type p3.x int`},
711 {`package p4; func f()`, `f`, `func p4.f()`},
712 {`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
714 // Tests using generics.
715 {`package g0; type x[T any] int`, `x`, `type g0.x[T any] int`},
716 {`package g1; func f[T any]() {}`, `f`, `func g1.f[T any]()`},
717 {`package g2; type x[T any] int; func (*x[_]) m() {}`, `m`, `func (*g2.x[_]).m()`},
720 for _, test := range tests {
722 Defs: make(map[*syntax.Name]Object),
724 name := mustTypecheck(test.src, nil, &info).Name()
728 for id, obj := range info.Defs {
729 if id.Value == test.obj {
735 t.Errorf("package %s: %s not found", name, test.obj)
739 if got := def.String(); got != test.want {
740 t.Errorf("package %s: got %s; want %s", name, got, test.want)
745 func TestUsesInfo(t *testing.T) {
746 var tests = []struct {
751 {`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
752 {`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
753 {`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
754 {`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
755 {`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
757 // Tests using generics.
758 {`package g0; func _[T any]() { _ = x }; const x = 42`, `x`, `const g0.x untyped int`},
759 {`package g1; func _[T any](x T) { }`, `T`, `type parameter T any`},
760 {`package g2; type N[A any] int; var _ N[int]`, `N`, `type g2.N[A any] int`},
761 {`package g3; type N[A any] int; func (N[_]) m() {}`, `N`, `type g3.N[A any] int`},
763 // Uses of fields are instantiated.
764 {`package s1; type N[A any] struct{ a A }; var f = N[int]{}.a`, `a`, `field a int`},
765 {`package s1; type N[A any] struct{ a A }; func (r N[B]) m(b B) { r.a = b }`, `a`, `field a B`},
767 // Uses of methods are uses of the instantiated method.
768 {`package m0; type N[A any] int; func (r N[B]) m() { r.n() }; func (N[C]) n() {}`, `n`, `func (m0.N[B]).n()`},
769 {`package m1; type N[A any] int; func (r N[B]) m() { }; var f = N[int].m`, `m`, `func (m1.N[int]).m()`},
770 {`package m2; func _[A any](v interface{ m() A }) { v.m() }`, `m`, `func (interface).m() A`},
771 {`package m3; func f[A any]() interface{ m() A } { return nil }; var _ = f[int]().m()`, `m`, `func (interface).m() int`},
772 {`package m4; type T[A any] func() interface{ m() A }; var x T[int]; var y = x().m`, `m`, `func (interface).m() int`},
773 {`package m5; type T[A any] interface{ m() A }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m5.T[B]).m() B`},
774 {`package m6; type T[A any] interface{ m() }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m6.T[B]).m()`},
775 {`package m7; type T[A any] interface{ m() A }; func _(t T[int]) { t.m() }`, `m`, `func (m7.T[int]).m() int`},
776 {`package m8; type T[A any] interface{ m() }; func _(t T[int]) { t.m() }`, `m`, `func (m8.T[int]).m()`},
777 {`package m9; type T[A any] interface{ m() }; func _(t T[int]) { _ = t.m }`, `m`, `func (m9.T[int]).m()`},
779 `package m10; type E[A any] interface{ m() }; type T[B any] interface{ E[B]; n() }; func _(t T[int]) { t.m() }`,
781 `func (m10.E[int]).m()`,
785 for _, test := range tests {
787 Uses: make(map[*syntax.Name]Object),
789 name := mustTypecheck(test.src, nil, &info).Name()
793 for id, obj := range info.Uses {
794 if id.Value == test.obj {
796 panic(fmt.Sprintf("multiple uses of %q", id.Value))
802 t.Errorf("package %s: %s not found", name, test.obj)
806 if got := use.String(); got != test.want {
807 t.Errorf("package %s: got %s; want %s", name, got, test.want)
812 func TestGenericMethodInfo(t *testing.T) {
817 func (r N[B]) m() { r.m(); r.n() }
819 func (r *N[C]) n() { }
823 Defs: make(map[*syntax.Name]Object),
824 Uses: make(map[*syntax.Name]Object),
825 Selections: make(map[*syntax.SelectorExpr]*Selection),
828 pkg, err := conf.Check("p", []*syntax.File{f}, &info)
833 N := pkg.Scope().Lookup("N").Type().(*Named)
835 // Find the generic methods stored on N.
836 gm, gn := N.Method(0), N.Method(1)
837 if gm.Name() == "n" {
841 // Collect objects from info.
842 var dm, dn *Func // the declared methods
843 var dmm, dmn *Func // the methods used in the body of m
844 for _, decl := range f.DeclList {
845 fdecl, ok := decl.(*syntax.FuncDecl)
849 def := info.Defs[fdecl.Name].(*Func)
850 switch fdecl.Name.Value {
853 syntax.Inspect(fdecl.Body, func(n syntax.Node) bool {
854 if call, ok := n.(*syntax.CallExpr); ok {
855 sel := call.Fun.(*syntax.SelectorExpr)
856 use := info.Uses[sel.Sel].(*Func)
857 selection := info.Selections[sel]
858 if selection.Kind() != MethodVal {
859 t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
861 if selection.Obj() != use {
862 t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
864 switch sel.Sel.Value {
879 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
882 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
885 t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
888 t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
892 func TestImplicitsInfo(t *testing.T) {
893 testenv.MustHaveGoBuild(t)
895 var tests = []struct {
899 {`package p2; import . "fmt"; var _ = Println`, ""}, // no Implicits entry
900 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
901 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
903 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
904 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
905 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
906 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
908 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
909 {`package p8; func f(int) {}`, "field: var int"},
910 {`package p9; func f() (complex64) { return 0 }`, "field: var complex64"},
911 {`package p10; type T struct{}; func (*T) f() {}`, "field: var *p10.T"},
913 // Tests using generics.
914 {`package f0; func f[T any](x int) {}`, ""}, // no Implicits entry
915 {`package f1; func f[T any](int) {}`, "field: var int"},
916 {`package f2; func f[T any](T) {}`, "field: var T"},
917 {`package f3; func f[T any]() (complex64) { return 0 }`, "field: var complex64"},
918 {`package f4; func f[T any](t T) (T) { return t }`, "field: var T"},
919 {`package t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var *t0.T[_]"},
920 {`package t1; type T[A any] struct{}; func _(x interface{}) { switch t := x.(type) { case T[int]: _ = t } }`, "caseClause: var t t1.T[int]"},
921 {`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]"},
922 {`package t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
925 for _, test := range tests {
927 Implicits: make(map[syntax.Node]Object),
929 name := mustTypecheck(test.src, nil, &info).Name()
931 // the test cases expect at most one Implicits entry
932 if len(info.Implicits) > 1 {
933 t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
937 // extract Implicits entry, if any
939 for n, obj := range info.Implicits {
940 switch x := n.(type) {
941 case *syntax.ImportDecl:
943 case *syntax.CaseClause:
948 t.Fatalf("package %s: unexpected %T", name, x)
950 got += ": " + obj.String()
954 if got != test.want {
955 t.Errorf("package %s: got %q; want %q", name, got, test.want)
960 func predString(tv TypeAndValue) string {
961 var buf strings.Builder
962 pred := func(b bool, s string) {
965 buf.WriteString(", ")
971 pred(tv.IsVoid(), "void")
972 pred(tv.IsType(), "type")
973 pred(tv.IsBuiltin(), "builtin")
974 pred(tv.IsValue() && tv.Value != nil, "const")
975 pred(tv.IsValue() && tv.Value == nil, "value")
976 pred(tv.IsNil(), "nil")
977 pred(tv.Addressable(), "addressable")
978 pred(tv.Assignable(), "assignable")
979 pred(tv.HasOk(), "hasOk")
987 func TestPredicatesInfo(t *testing.T) {
988 testenv.MustHaveGoBuild(t)
990 var tests = []struct {
996 {`package n0; func f() { f() }`, `f()`, `void`},
999 {`package t0; type _ int`, `int`, `type`},
1000 {`package t1; type _ []int`, `[]int`, `type`},
1001 {`package t2; type _ func()`, `func()`, `type`},
1002 {`package t3; type _ func(int)`, `int`, `type`},
1003 {`package t3; type _ func(...int)`, `...int`, `type`},
1006 {`package b0; var _ = len("")`, `len`, `builtin`},
1007 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
1010 {`package c0; var _ = 42`, `42`, `const`},
1011 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
1012 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
1015 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
1016 {`package v1; var _ = &[]int{1}`, `[]int{…}`, `value`},
1017 {`package v2; var _ = func(){}`, `func() {}`, `value`},
1018 {`package v4; func f() { _ = f }`, `f`, `value`},
1019 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
1020 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
1022 // addressable (and thus assignable) operands
1023 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
1024 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
1025 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
1026 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
1027 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
1028 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
1029 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
1030 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
1031 // composite literals are not addressable
1033 // assignable but not addressable values
1034 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1035 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1037 // hasOk expressions
1038 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
1039 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
1042 // - package names are collected in the Uses map
1043 // - identifiers being declared are collected in the Defs map
1044 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
1045 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
1046 {`package m2; const c = 0`, `c`, `<missing>`},
1047 {`package m3; type T int`, `T`, `<missing>`},
1048 {`package m4; var v int`, `v`, `<missing>`},
1049 {`package m5; func f() {}`, `f`, `<missing>`},
1050 {`package m6; func _(x int) {}`, `x`, `<missing>`},
1051 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
1052 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
1055 for _, test := range tests {
1056 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
1057 name := mustTypecheck(test.src, nil, &info).Name()
1059 // look for expression predicates
1061 for e, tv := range info.Types {
1062 //println(name, syntax.String(e))
1063 if syntax.String(e) == test.expr {
1064 got = predString(tv)
1069 if got != test.pred {
1070 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
1075 func TestScopesInfo(t *testing.T) {
1076 testenv.MustHaveGoBuild(t)
1078 var tests = []struct {
1080 scopes []string // list of scope descriptors of the form kind:varlist
1082 {`package p0`, []string{
1085 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
1088 {`package p2; func _() {}`, []string{
1091 {`package p3; func _(x, y int) {}`, []string{
1092 "file:", "func:x y",
1094 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
1095 "file:", "func:x y z", // redeclaration of x
1097 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
1098 "file:", "func:u x y",
1100 {`package p6; func _() { { var x int; _ = x } }`, []string{
1101 "file:", "func:", "block:x",
1103 {`package p7; func _() { if true {} }`, []string{
1104 "file:", "func:", "if:", "block:",
1106 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
1107 "file:", "func:", "if:x", "block:y",
1109 {`package p9; func _() { switch x := 0; x {} }`, []string{
1110 "file:", "func:", "switch:x",
1112 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
1113 "file:", "func:", "switch:x", "case:y", "case:",
1115 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
1116 "file:", "func:t", "switch:",
1118 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
1119 "file:", "func:t", "switch:t",
1121 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
1122 "file:", "func:t", "switch:", "case:x", // x implicitly declared
1124 {`package p14; func _() { select{} }`, []string{
1127 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
1128 "file:", "func:c", "comm:",
1130 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
1131 "file:", "func:c", "comm:i x",
1133 {`package p17; func _() { for{} }`, []string{
1134 "file:", "func:", "for:", "block:",
1136 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
1137 "file:", "func:n", "for:i", "block:",
1139 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
1140 "file:", "func:a", "for:i", "block:",
1142 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
1143 "file:", "func:a", "for:i x", "block:",
1147 for _, test := range tests {
1148 info := Info{Scopes: make(map[syntax.Node]*Scope)}
1149 name := mustTypecheck(test.src, nil, &info).Name()
1151 // number of scopes must match
1152 if len(info.Scopes) != len(test.scopes) {
1153 t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
1156 // scope descriptions must match
1157 for node, scope := range info.Scopes {
1159 switch node.(type) {
1162 case *syntax.FuncType:
1164 case *syntax.BlockStmt:
1166 case *syntax.IfStmt:
1168 case *syntax.SwitchStmt:
1170 case *syntax.SelectStmt:
1172 case *syntax.CaseClause:
1174 case *syntax.CommClause:
1176 case *syntax.ForStmt:
1179 kind = fmt.Sprintf("%T", node)
1182 // look for matching scope description
1183 desc := kind + ":" + strings.Join(scope.Names(), " ")
1185 for _, d := range test.scopes {
1192 t.Errorf("package %s: no matching scope found for %s", name, desc)
1198 func TestInitOrderInfo(t *testing.T) {
1199 var tests = []struct {
1203 {`package p0; var (x = 1; y = x)`, []string{
1206 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
1207 "a = 1", "b = 2", "c = 3",
1209 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
1210 "a = 1", "b = 2", "c = 3",
1212 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
1213 "_ = f()", // blank var
1215 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
1216 "a = 0", "z = 0", "y = z", "x = y",
1218 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
1219 "a, _ = m[0]", // blank var
1221 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
1222 "z = 0", "a, b = f()",
1224 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
1225 "b = 1", "a = func() int {…}()",
1227 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
1228 "c = 1", "a, b = func() (_, _ int) {…}()",
1230 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1233 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1234 "a = 0", "b = 0", "c = 0", "d = c + b",
1236 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
1237 "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
1239 // emit an initializer for n:1 initializations only once (not for each node
1240 // on the lhs which may appear in different order in the dependency graph)
1241 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
1242 "b = 0", "x, y = m[0]", "a = x",
1244 // test case from spec section on package initialization
1258 "d = 3", "b = f()", "c = f()", "a = c + b",
1260 // test case for go.dev/issue/7131
1264 func next() int { counter++; return counter }
1267 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1270 var b, c = next(), next()
1271 var d, e, f = next(), next(), next()
1273 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1275 // test case for go.dev/issue/10709
1285 func (T) m() int { return 0 }
1287 func makeT(n int) T {
1293 "t = makeT(0)", "v = t.m()",
1295 // test case for go.dev/issue/10709: same as test before, but variable decls swapped
1305 func (T) m() int { return 0 }
1307 func makeT(n int) T {
1313 "t = makeT(0)", "v = t.m()",
1315 // another candidate possibly causing problems with go.dev/issue/10709
1320 func f1() int { return g1() }
1321 func g1() int { f1(); return x1 }
1327 func f2() int { return g2() }
1328 func g2() int { return x2 }
1330 var x2 = 0`, []string{
1331 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1335 for _, test := range tests {
1337 name := mustTypecheck(test.src, nil, &info).Name()
1339 // number of initializers must match
1340 if len(info.InitOrder) != len(test.inits) {
1341 t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1345 // initializers must match
1346 for i, want := range test.inits {
1347 got := info.InitOrder[i].String()
1349 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1356 func TestMultiFileInitOrder(t *testing.T) {
1357 fileA := mustParse(`package main; var a = 1`)
1358 fileB := mustParse(`package main; var b = 2`)
1360 // The initialization order must not depend on the parse
1361 // order of the files, only on the presentation order to
1362 // the type-checker.
1363 for _, test := range []struct {
1364 files []*syntax.File
1367 {[]*syntax.File{fileA, fileB}, "[a = 1 b = 2]"},
1368 {[]*syntax.File{fileB, fileA}, "[b = 2 a = 1]"},
1371 if _, err := new(Config).Check("main", test.files, &info); err != nil {
1374 if got := fmt.Sprint(info.InitOrder); got != test.want {
1375 t.Fatalf("got %s; want %s", got, test.want)
1380 func TestFiles(t *testing.T) {
1381 var sources = []string{
1382 "package p; type T struct{}; func (T) m1() {}",
1383 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1384 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1389 pkg := NewPackage("p", "p")
1391 check := NewChecker(&conf, pkg, &info)
1393 for _, src := range sources {
1394 if err := check.Files([]*syntax.File{mustParse(src)}); err != nil {
1399 // check InitOrder is [x y]
1401 for _, init := range info.InitOrder {
1402 for _, v := range init.Lhs {
1403 vars = append(vars, v.Name())
1406 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1407 t.Errorf("InitOrder == %s, want %s", got, want)
1411 type testImporter map[string]*Package
1413 func (m testImporter) Import(path string) (*Package, error) {
1414 if pkg := m[path]; pkg != nil {
1417 return nil, fmt.Errorf("package %q not found", path)
1420 func TestSelection(t *testing.T) {
1421 selections := make(map[*syntax.SelectorExpr]*Selection)
1423 imports := make(testImporter)
1424 conf := Config{Importer: imports}
1425 makePkg := func(path, src string) {
1426 pkg := mustTypecheck(src, &conf, &Info{Selections: selections})
1457 type G[P any] struct {
1469 // qualified identifiers
1507 // method expressions
1515 wantOut := map[string][2]string{
1516 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1518 "A{}.B": {"field (main.A) B *main.B", ".[0]"},
1519 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1520 "A{}.C": {"field (main.A) C main.C", ".[1]"},
1521 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1522 "A{}.b": {"field (main.A) b int", "->[0 0]"},
1523 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1524 "A{}.c": {"field (main.A) c int", ".[1 0]"},
1525 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1526 "Inst.p": {"field (main.G[int]) p int", ".[0]"},
1528 "A{}.f": {"method (main.A) f(int)", "->[0 0]"},
1529 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1530 "A{}.g": {"method (main.A) g()", ".[1 0]"},
1531 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1532 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1533 "B{}.f": {"method (main.B) f(int)", ".[0]"},
1534 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1535 "C{}.g": {"method (main.C) g()", ".[0]"},
1536 "new(C).g": {"method (*main.C) g()", "->[0]"},
1537 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1538 "Inst.m": {"method (main.G[int]) m(int)", ".[0]"},
1540 "A.f": {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1541 "(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1542 "B.f": {"method expr (main.B) f(main.B, int)", ".[0]"},
1543 "(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1544 "G[string].m": {"method expr (main.G[string]) m(main.G[string], string)", ".[0]"},
1545 "G[string]{}.p": {"field (main.G[string]) p string", ".[0]"},
1548 makePkg("lib", libSrc)
1549 makePkg("main", mainSrc)
1551 for e, sel := range selections {
1552 _ = sel.String() // assertion: must not panic
1554 start := indexFor(mainSrc, syntax.StartPos(e))
1555 end := indexFor(mainSrc, syntax.EndPos(e))
1556 segment := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1564 fmt.Sprintf("%s%v", direct, sel.Index()),
1566 want := wantOut[segment]
1568 t.Errorf("%s: got %q; want %q", segment, got, want)
1570 delete(wantOut, segment)
1572 // We must explicitly assert properties of the
1573 // Signature's receiver since it doesn't participate
1574 // in Identical() or String().
1575 sig, _ := sel.Type().(*Signature)
1576 if sel.Kind() == MethodVal {
1577 got := sig.Recv().Type()
1579 if !Identical(got, want) {
1580 t.Errorf("%s: Recv() = %s, want %s", segment, got, want)
1582 } else if sig != nil && sig.Recv() != nil {
1583 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1586 // Assert that all wantOut entries were used exactly once.
1587 for segment := range wantOut {
1588 t.Errorf("no syntax.Selection found with syntax %q", segment)
1592 // indexFor returns the index into s corresponding to the position pos.
1593 func indexFor(s string, pos syntax.Pos) int {
1594 i, line := 0, 1 // string index and corresponding line
1595 target := int(pos.Line())
1596 for line < target && i < len(s) {
1602 return i + int(pos.Col()-1) // columns are 1-based
1605 func TestIssue8518(t *testing.T) {
1606 imports := make(testImporter)
1608 Error: func(err error) { t.Log(err) }, // don't exit after first error
1611 makePkg := func(path, src string) {
1612 imports[path], _ = conf.Check(path, []*syntax.File{mustParse(src)}, nil) // errors logged via conf.Error
1619 const C2 = missing.C
1629 makePkg("a", libSrc)
1630 makePkg("main", mainSrc) // don't crash when type-checking this package
1633 func TestIssue59603(t *testing.T) {
1634 imports := make(testImporter)
1636 Error: func(err error) { t.Log(err) }, // don't exit after first error
1639 makePkg := func(path, src string) {
1640 imports[path], _ = conf.Check(path, []*syntax.File{mustParse(src)}, nil) // errors logged via conf.Error
1654 makePkg("a", libSrc)
1655 makePkg("main", mainSrc) // don't crash when type-checking this package
1658 func TestLookupFieldOrMethodOnNil(t *testing.T) {
1659 // LookupFieldOrMethod on a nil type is expected to produce a run-time panic.
1661 const want = "LookupFieldOrMethod on nil type"
1663 if s, ok := p.(string); !ok || s != want {
1664 t.Fatalf("got %v, want %s", p, want)
1667 LookupFieldOrMethod(nil, false, nil, "")
1670 func TestLookupFieldOrMethod(t *testing.T) {
1671 // Test cases assume a lookup of the form a.f or x.f, where a stands for an
1672 // addressable value, and x for a non-addressable value (even though a variable
1673 // for ease of test case writing).
1674 var tests = []struct {
1681 {"var x T; type T struct{}", false, nil, false},
1682 {"var x T; type T struct{ f int }", true, []int{0}, false},
1683 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1685 // field lookups on a generic type
1686 {"var x T[int]; type T[P any] struct{}", false, nil, false},
1687 {"var x T[int]; type T[P any] struct{ f P }", true, []int{0}, false},
1688 {"var x T[int]; type T[P any] struct{ a, b, f, c P }", true, []int{2}, false},
1691 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1692 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1693 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1694 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1696 // method lookups on a generic type
1697 {"var a T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, false},
1698 {"var a *T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, true},
1699 {"var a T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, false},
1700 {"var a *T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1703 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1704 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1706 // collisions on a generic type
1707 {"type ( E1[P any] struct{ f P }; E2[P any] struct{ f P }; x struct{ E1[int]; *E2[int] })", false, []int{1, 0}, false},
1708 {"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},
1710 // outside methodset
1711 // (*T).f method exists, but value of type T is not addressable
1712 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1714 // outside method set of a generic type
1715 {"var x T[int]; type T[P any] struct{}; func (*T[P]) f() {}", false, nil, true},
1717 // recursive generic types; see go.dev/issue/52715
1718 {"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},
1719 {"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},
1722 for _, test := range tests {
1723 pkg := mustTypecheck("package p;"+test.src, nil, nil)
1725 obj := pkg.Scope().Lookup("a")
1727 if obj = pkg.Scope().Lookup("x"); obj == nil {
1728 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1733 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1734 if (f != nil) != test.found {
1736 t.Errorf("%s: got no object; want one", test.src)
1738 t.Errorf("%s: got object = %v; want none", test.src, f)
1741 if !sameSlice(index, test.index) {
1742 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1744 if indirect != test.indirect {
1745 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1750 // Test for go.dev/issue/52715
1751 func TestLookupFieldOrMethod_RecursiveGeneric(t *testing.T) {
1755 type Tree[T any] struct {
1759 func (*Tree[R]) N(r R) R { return r }
1761 type Node[T any] struct {
1765 type Instance = *Tree[int]
1769 pkg := NewPackage("pkg", f.PkgName.Value)
1770 if err := NewChecker(nil, pkg, nil).Files([]*syntax.File{f}); err != nil {
1774 T := pkg.Scope().Lookup("Instance").Type()
1775 _, _, _ = LookupFieldOrMethod(T, false, pkg, "M") // verify that LookupFieldOrMethod terminates
1778 func sameSlice(a, b []int) bool {
1779 if len(a) != len(b) {
1782 for i, x := range a {
1790 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1791 // the correct result at various positions within the source.
1792 func TestScopeLookupParent(t *testing.T) {
1793 imports := make(testImporter)
1794 conf := Config{Importer: imports}
1796 makePkg := func(path, src string) {
1798 imports[path], err = conf.Check(path, []*syntax.File{mustParse(src)}, &info)
1804 makePkg("lib", "package lib; var X int")
1805 // Each /*name=kind:line*/ comment makes the test look up the
1806 // name at that point and checks that it resolves to a decl of
1807 // the specified kind and line number. "undef" means undefined.
1809 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1820 const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1821 type /*t=undef*/ t /*t=typename:14*/ *t
1822 print(Y) /*Y=var:10*/
1823 x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1824 var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1827 for i, x := range a /*i=undef*/ /*x=var:16*/ { _ = i; _ = x }
1830 switch y := i.(type) { /*y=undef*/
1831 case /*y=undef*/ int /*y=var:23*/ :
1832 case float32, /*y=undef*/ float64 /*y=var:23*/ :
1833 default /*y=var:23*/:
1838 switch int := i.(type) {
1839 case /*int=typename:0*/ int /*int=var:31*/ :
1841 default /*int=var:31*/ :
1847 info.Uses = make(map[*syntax.Name]Object)
1848 makePkg("main", mainSrc)
1849 mainScope := imports["main"].Scope()
1851 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1853 base := syntax.NewFileBase("main")
1854 syntax.CommentsDo(strings.NewReader(mainSrc), func(line, col uint, text string) {
1855 pos := syntax.MakePos(base, line, col)
1857 // Syntax errors are not comments.
1859 t.Errorf("%s: %s", pos, text)
1863 // Parse the assertion in the comment.
1864 m := rx.FindStringSubmatch(text)
1866 t.Errorf("%s: bad comment: %s", pos, text)
1869 name, want := m[1], m[2]
1871 // Look up the name in the innermost enclosing scope.
1872 inner := mainScope.Innermost(pos)
1874 t.Errorf("%s: at %s: can't find innermost scope", pos, text)
1878 if _, obj := inner.LookupParent(name, pos); obj != nil {
1879 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types2."))
1880 got = fmt.Sprintf("%s:%d", kind, obj.Pos().Line())
1883 t.Errorf("%s: at %s: %s resolved to %s, want %s", pos, text, name, got, want)
1887 // Check that for each referring identifier,
1888 // a lookup of its name on the innermost
1889 // enclosing scope returns the correct object.
1891 for id, wantObj := range info.Uses {
1892 inner := mainScope.Innermost(id.Pos())
1894 t.Errorf("%s: can't find innermost scope enclosing %q", id.Pos(), id.Value)
1898 // Exclude selectors and qualified identifiers---lexical
1899 // refs only. (Ideally, we'd see if the AST parent is a
1900 // SelectorExpr, but that requires PathEnclosingInterval
1901 // from golang.org/x/tools/go/ast/astutil.)
1902 if id.Value == "X" {
1906 _, gotObj := inner.LookupParent(id.Value, id.Pos())
1907 if gotObj != wantObj {
1908 t.Errorf("%s: got %v, want %v", id.Pos(), gotObj, wantObj)
1914 // newDefined creates a new defined type named T with the given underlying type.
1915 func newDefined(underlying Type) *Named {
1916 tname := NewTypeName(nopos, nil, "T", nil)
1917 return NewNamed(tname, underlying, nil)
1920 func TestConvertibleTo(t *testing.T) {
1921 for _, test := range []struct {
1925 {Typ[Int], Typ[Int], true},
1926 {Typ[Int], Typ[Float32], true},
1927 {Typ[Int], Typ[String], true},
1928 {newDefined(Typ[Int]), Typ[Int], true},
1929 {newDefined(new(Struct)), new(Struct), true},
1930 {newDefined(Typ[Int]), new(Struct), false},
1931 {Typ[UntypedInt], Typ[Int], true},
1932 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), true},
1933 {NewSlice(Typ[Int]), NewArray(Typ[Uint], 10), false},
1934 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
1935 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
1936 // Untyped string values are not permitted by the spec, so the behavior below is undefined.
1937 {Typ[UntypedString], Typ[String], true},
1939 if got := ConvertibleTo(test.v, test.t); got != test.want {
1940 t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1945 func TestAssignableTo(t *testing.T) {
1946 for _, test := range []struct {
1950 {Typ[Int], Typ[Int], true},
1951 {Typ[Int], Typ[Float32], false},
1952 {newDefined(Typ[Int]), Typ[Int], false},
1953 {newDefined(new(Struct)), new(Struct), true},
1954 {Typ[UntypedBool], Typ[Bool], true},
1955 {Typ[UntypedString], Typ[Bool], false},
1956 // Neither untyped string nor untyped numeric assignments arise during
1957 // normal type checking, so the below behavior is technically undefined by
1959 {Typ[UntypedString], Typ[String], true},
1960 {Typ[UntypedInt], Typ[Int], true},
1962 if got := AssignableTo(test.v, test.t); got != test.want {
1963 t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1968 func TestIdentical(t *testing.T) {
1969 // For each test, we compare the types of objects X and Y in the source.
1975 {"var X int; var Y int", true},
1976 {"var X int; var Y string", false},
1978 // TODO: add more tests for complex types.
1981 {"type X int; type Y int", false},
1984 {"type X = int; type Y = int", true},
1987 {`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
1988 {`func X() string { return "" }; func Y(int) string { return "" }`, false},
1989 {`func X(int) string { return "" }; func Y(int) {}`, false},
1991 // Generic functions. Type parameters should be considered identical modulo
1992 // renaming. See also go.dev/issue/49722.
1993 {`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
1994 {`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
1995 {`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
1996 {`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
1997 {`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
1998 {`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
2001 for _, test := range tests {
2002 pkg := mustTypecheck("package p;"+test.src, nil, nil)
2003 X := pkg.Scope().Lookup("X")
2004 Y := pkg.Scope().Lookup("Y")
2005 if X == nil || Y == nil {
2006 t.Fatal("test must declare both X and Y")
2008 if got := Identical(X.Type(), Y.Type()); got != test.want {
2009 t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
2014 func TestIdentical_issue15173(t *testing.T) {
2015 // Identical should allow nil arguments and be symmetric.
2016 for _, test := range []struct {
2020 {Typ[Int], Typ[Int], true},
2021 {Typ[Int], nil, false},
2022 {nil, Typ[Int], false},
2025 if got := Identical(test.x, test.y); got != test.want {
2026 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2031 func TestIdenticalUnions(t *testing.T) {
2032 tname := NewTypeName(nopos, nil, "myInt", nil)
2033 myInt := NewNamed(tname, Typ[Int], nil)
2034 tmap := map[string]*Term{
2035 "int": NewTerm(false, Typ[Int]),
2036 "~int": NewTerm(true, Typ[Int]),
2037 "string": NewTerm(false, Typ[String]),
2038 "~string": NewTerm(true, Typ[String]),
2039 "myInt": NewTerm(false, myInt),
2041 makeUnion := func(s string) *Union {
2042 parts := strings.Split(s, "|")
2044 for _, p := range parts {
2047 t.Fatalf("missing term %q", p)
2049 terms = append(terms, term)
2051 return NewUnion(terms)
2053 for _, test := range []struct {
2057 // These tests are just sanity checks. The tests for type sets and
2058 // interfaces provide much more test coverage.
2059 {"int|~int", "~int", true},
2060 {"myInt|~int", "~int", true},
2061 {"int|string", "string|int", true},
2062 {"int|int|string", "string|int", true},
2063 {"myInt|string", "int|string", false},
2065 x := makeUnion(test.x)
2066 y := makeUnion(test.y)
2067 if got := Identical(x, y); got != test.want {
2068 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2073 func TestIssue15305(t *testing.T) {
2074 const src = "package p; func f() int16; var _ = f(undef)"
2077 Error: func(err error) {}, // allow errors
2080 Types: make(map[syntax.Expr]TypeAndValue),
2082 conf.Check("p", []*syntax.File{f}, info) // ignore result
2083 for e, tv := range info.Types {
2084 if _, ok := e.(*syntax.CallExpr); ok {
2085 if tv.Type != Typ[Int16] {
2086 t.Errorf("CallExpr has type %v, want int16", tv.Type)
2091 t.Errorf("CallExpr has no type")
2094 // TestCompositeLitTypes verifies that Info.Types registers the correct
2095 // types for composite literal expressions and composite literal type
2097 func TestCompositeLitTypes(t *testing.T) {
2098 for i, test := range []struct {
2101 {`[16]byte{}`, `[16]byte`},
2102 {`[...]byte{}`, `[0]byte`}, // test for go.dev/issue/14092
2103 {`[...]int{1, 2, 3}`, `[3]int`}, // test for go.dev/issue/14092
2104 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for go.dev/issue/14092
2105 {`[]int{}`, `[]int`},
2106 {`map[string]bool{"foo": true}`, `map[string]bool`},
2107 {`struct{}{}`, `struct{}`},
2108 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
2110 f := mustParse(fmt.Sprintf("package p%d; var _ = %s", i, test.lit))
2111 types := make(map[syntax.Expr]TypeAndValue)
2112 if _, err := new(Config).Check("p", []*syntax.File{f}, &Info{Types: types}); err != nil {
2113 t.Fatalf("%s: %v", test.lit, err)
2116 cmptype := func(x syntax.Expr, want string) {
2119 t.Errorf("%s: no Types entry found", test.lit)
2123 t.Errorf("%s: type is nil", test.lit)
2126 if got := tv.Type.String(); got != want {
2127 t.Errorf("%s: got %v, want %s", test.lit, got, want)
2131 // test type of composite literal expression
2132 rhs := f.DeclList[0].(*syntax.VarDecl).Values
2133 cmptype(rhs, test.typ)
2135 // test type of composite literal type expression
2136 cmptype(rhs.(*syntax.CompositeLit).Type, test.typ)
2140 // TestObjectParents verifies that objects have parent scopes or not
2141 // as specified by the Object interface.
2142 func TestObjectParents(t *testing.T) {
2161 func f(x int) { y := x; print(y) }
2167 Defs: make(map[*syntax.Name]Object),
2169 if _, err := new(Config).Check("p", []*syntax.File{f}, info); err != nil {
2173 for ident, obj := range info.Defs {
2175 // only package names and implicit vars have a nil object
2176 // (in this test we only need to handle the package name)
2177 if ident.Value != "p" {
2178 t.Errorf("%v has nil object", ident)
2183 // struct fields, type-associated and interface methods
2184 // have no parent scope
2186 switch obj := obj.(type) {
2192 if obj.Type().(*Signature).Recv() != nil { // method
2197 gotParent := obj.Parent() != nil
2199 case gotParent && !wantParent:
2200 t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
2201 case !gotParent && wantParent:
2202 t.Errorf("%v: no parent found", ident)
2207 // TestFailedImport tests that we don't get follow-on errors
2208 // elsewhere in a package due to failing to import a package.
2209 func TestFailedImport(t *testing.T) {
2210 testenv.MustHaveGoBuild(t)
2215 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
2220 func f(x T) T { return foo.F(x) }
2223 files := []*syntax.File{f}
2225 // type-check using all possible importers
2226 for _, compiler := range []string{"gc", "gccgo", "source"} {
2229 Error: func(err error) {
2230 // we should only see the import error
2231 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
2232 t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
2236 //Importer: importer.For(compiler, nil),
2240 Uses: make(map[*syntax.Name]Object),
2242 pkg, _ := conf.Check("p", files, info)
2244 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
2248 imports := pkg.Imports()
2249 if len(imports) != 1 {
2250 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
2254 if imp.Name() != "foo" {
2255 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
2259 // verify that all uses of foo refer to the imported package foo (imp)
2260 for ident, obj := range info.Uses {
2261 if ident.Value == "foo" {
2262 if obj, ok := obj.(*PkgName); ok {
2263 if obj.Imported() != imp {
2264 t.Errorf("%s resolved to %v; want %v", ident.Value, obj.Imported(), imp)
2267 t.Errorf("%s resolved to %v; want package name", ident.Value, obj)
2274 func TestInstantiate(t *testing.T) {
2275 // eventually we like more tests but this is a start
2276 const src = "package p; type T[P any] *T[P]"
2277 pkg := mustTypecheck(src, nil, nil)
2279 // type T should have one type parameter
2280 T := pkg.Scope().Lookup("T").Type().(*Named)
2281 if n := T.TypeParams().Len(); n != 1 {
2282 t.Fatalf("expected 1 type parameter; found %d", n)
2285 // instantiation should succeed (no endless recursion)
2286 // even with a nil *Checker
2287 res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
2292 // instantiated type should point to itself
2293 if p := res.Underlying().(*Pointer).Elem(); p != res {
2294 t.Fatalf("unexpected result type: %s points to %s", res, p)
2298 func TestInstantiateErrors(t *testing.T) {
2300 src string // by convention, T must be the type being instantiated
2302 wantAt int // -1 indicates no error
2304 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
2305 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
2306 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
2307 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
2310 for _, test := range tests {
2311 src := "package p; " + test.src
2312 pkg := mustTypecheck(src, nil, nil)
2314 T := pkg.Scope().Lookup("T").Type().(*Named)
2316 _, err := Instantiate(nil, T, test.targs, true)
2318 t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
2321 var argErr *ArgumentError
2322 if !errors.As(err, &argErr) {
2323 t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
2326 if argErr.Index != test.wantAt {
2327 t.Errorf("Instantiate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2332 func TestArgumentErrorUnwrapping(t *testing.T) {
2333 var err error = &ArgumentError{
2335 Err: Error{Msg: "test"},
2338 if !errors.As(err, &e) {
2339 t.Fatalf("error %v does not wrap types.Error", err)
2341 if e.Msg != "test" {
2342 t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2346 func TestInstanceIdentity(t *testing.T) {
2347 imports := make(testImporter)
2348 conf := Config{Importer: imports}
2349 makePkg := func(src string) {
2351 name := f.PkgName.Value
2352 pkg, err := conf.Check(name, []*syntax.File{f}, nil)
2358 makePkg(`package lib; type T[P any] struct{}`)
2359 makePkg(`package a; import "lib"; var A lib.T[int]`)
2360 makePkg(`package b; import "lib"; var B lib.T[int]`)
2361 a := imports["a"].Scope().Lookup("A")
2362 b := imports["b"].Scope().Lookup("B")
2363 if !Identical(a.Type(), b.Type()) {
2364 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
2368 // TestInstantiatedObjects verifies properties of instantiated objects.
2369 func TestInstantiatedObjects(t *testing.T) {
2373 type T[P any] struct {
2377 func (recv *T[Q]) concreteMethod(mParam Q) (mResult Q) { return }
2379 type FT[P any] func(ftParam P) (ftResult P)
2381 func F[P any](fParam P) (fResult P){ return }
2383 type I[P any] interface {
2389 func (R[P]) m() {} // having a method triggers expansion of R
2404 Defs: make(map[*syntax.Name]Object),
2408 pkg, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
2413 lookup := func(name string) Type { return pkg.Scope().Lookup(name).Type() }
2414 fnScope := pkg.Scope().Lookup("fn").(*Func).Scope()
2421 {"field", lookup("t").Underlying().(*Struct).Field(0)},
2422 {"field", fnScope.Lookup("r").Type().Underlying().(*Struct).Field(0)},
2424 // Methods and method fields
2425 {"concreteMethod", lookup("t").(*Named).Method(0)},
2426 {"recv", lookup("t").(*Named).Method(0).Type().(*Signature).Recv()},
2427 {"mParam", lookup("t").(*Named).Method(0).Type().(*Signature).Params().At(0)},
2428 {"mResult", lookup("t").(*Named).Method(0).Type().(*Signature).Results().At(0)},
2430 // Interface methods
2431 {"interfaceMethod", lookup("i").Underlying().(*Interface).Method(0)},
2433 // Function type fields
2434 {"ftParam", lookup("ft").Underlying().(*Signature).Params().At(0)},
2435 {"ftResult", lookup("ft").Underlying().(*Signature).Results().At(0)},
2438 {"fParam", lookup("f").(*Signature).Params().At(0)},
2439 {"fResult", lookup("f").(*Signature).Results().At(0)},
2442 // Collect all identifiers by name.
2443 idents := make(map[string][]*syntax.Name)
2444 syntax.Inspect(f, func(n syntax.Node) bool {
2445 if id, ok := n.(*syntax.Name); ok {
2446 idents[id.Value] = append(idents[id.Value], id)
2451 for _, test := range tests {
2453 t.Run(test.name, func(t *testing.T) {
2454 if got := len(idents[test.name]); got != 1 {
2455 t.Fatalf("found %d identifiers named %s, want 1", got, test.name)
2457 ident := idents[test.name][0]
2458 def := info.Defs[ident]
2459 if def == test.obj {
2460 t.Fatalf("info.Defs[%s] contains the test object", test.name)
2462 if orig := originObject(test.obj); def != orig {
2463 t.Errorf("info.Defs[%s] does not match obj.Origin()", test.name)
2465 if def.Pkg() != test.obj.Pkg() {
2466 t.Errorf("Pkg() = %v, want %v", def.Pkg(), test.obj.Pkg())
2468 if def.Name() != test.obj.Name() {
2469 t.Errorf("Name() = %v, want %v", def.Name(), test.obj.Name())
2471 if def.Pos() != test.obj.Pos() {
2472 t.Errorf("Pos() = %v, want %v", def.Pos(), test.obj.Pos())
2474 if def.Parent() != test.obj.Parent() {
2475 t.Fatalf("Parent() = %v, want %v", def.Parent(), test.obj.Parent())
2477 if def.Exported() != test.obj.Exported() {
2478 t.Fatalf("Exported() = %v, want %v", def.Exported(), test.obj.Exported())
2480 if def.Id() != test.obj.Id() {
2481 t.Fatalf("Id() = %v, want %v", def.Id(), test.obj.Id())
2483 // String and Type are expected to differ.
2488 func originObject(obj Object) Object {
2489 switch obj := obj.(type) {
2498 func TestImplements(t *testing.T) {
2502 type EmptyIface interface{}
2513 type Integer interface{
2514 int8 | int16 | int32 | int64
2517 type EmptyTypeSet interface{
2534 type Bad Bad // invalid type
2538 conf := Config{Error: func(error) {}}
2539 pkg, _ := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
2541 lookup := func(tname string) Type { return pkg.Scope().Lookup(tname).Type() }
2543 EmptyIface = lookup("EmptyIface").Underlying().(*Interface)
2544 I = lookup("I").(*Named)
2545 II = I.Underlying().(*Interface)
2546 C = lookup("C").(*Named)
2547 CI = C.Underlying().(*Interface)
2548 Integer = lookup("Integer").Underlying().(*Interface)
2549 EmptyTypeSet = lookup("EmptyTypeSet").Underlying().(*Interface)
2551 N1p = NewPointer(N1)
2553 N2p = NewPointer(N2)
2568 {Typ[Int8], Integer, true},
2569 {Typ[Int64], Integer, true},
2570 {Typ[String], Integer, false},
2571 {EmptyTypeSet, II, true},
2572 {EmptyTypeSet, EmptyTypeSet, true},
2573 {Typ[Int], EmptyTypeSet, false},
2588 {Bad, EmptyIface, true},
2591 for _, test := range tests {
2592 if got := Implements(test.V, test.T); got != test.want {
2593 t.Errorf("Implements(%s, %s) = %t, want %t", test.V, test.T, got, test.want)
2596 // The type assertion x.(T) is valid if T is an interface or if T implements the type of x.
2597 // The assertion is never valid if T is a bad type.
2601 if _, ok := T.Underlying().(*Interface); (ok || Implements(T, V)) && T != Bad {
2604 if got := AssertableTo(V, T); got != want {
2605 t.Errorf("AssertableTo(%s, %s) = %t, want %t", V, T, got, want)
2610 func TestMissingMethodAlternative(t *testing.T) {
2632 pkg := mustTypecheck(src, nil, nil)
2634 T := pkg.Scope().Lookup("T").Type().Underlying().(*Interface)
2635 lookup := func(name string) (*Func, bool) {
2636 return MissingMethod(pkg.Scope().Lookup(name).Type(), T, true)
2639 // V0 has method m with correct signature. Should not report wrongType.
2640 method, wrongType := lookup("V0")
2641 if method != nil || wrongType {
2642 t.Fatalf("V0: got method = %v, wrongType = %v", method, wrongType)
2645 checkMissingMethod := func(tname string, reportWrongType bool) {
2646 method, wrongType := lookup(tname)
2647 if method == nil || method.Name() != "m" || wrongType != reportWrongType {
2648 t.Fatalf("%s: got method = %v, wrongType = %v", tname, method, wrongType)
2652 // V1 has no method m. Should not report wrongType.
2653 checkMissingMethod("V1", false)
2655 // V2 has method m with wrong signature type (ignoring receiver). Should report wrongType.
2656 checkMissingMethod("V2", true)
2658 // V3 has no method m but it exists on *V3. Should report wrongType.
2659 checkMissingMethod("V3", true)
2661 // V4 has no method m but has M. Should not report wrongType.
2662 checkMissingMethod("V4", false)