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.
26 // nopos indicates an unknown position
29 func mustParse(fset *token.FileSet, src string) *ast.File {
30 f, err := parser.ParseFile(fset, pkgName(src), src, 0)
32 panic(err) // so we don't need to pass *testing.T
37 func typecheck(src string, conf *Config, info *Info) (*Package, error) {
38 fset := token.NewFileSet()
39 f := mustParse(fset, src)
42 Error: func(err error) {}, // collect all errors
43 Importer: importer.Default(),
46 return conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
49 func mustTypecheck(src string, conf *Config, info *Info) *Package {
50 pkg, err := typecheck(src, conf, info)
52 panic(err) // so we don't need to pass *testing.T
57 // pkgName extracts the package name from src, which must contain a package header.
58 func pkgName(src string) string {
60 if i := strings.Index(src, kw); i >= 0 {
61 after := src[i+len(kw):]
63 if i := strings.IndexAny(after, "\n\t ;/"); i >= 0 {
68 panic("missing package header: " + src)
71 func TestValuesInfo(t *testing.T) {
72 var tests = []struct {
74 expr string // constant expression
75 typ string // constant type
76 val string // constant value
78 {`package a0; const _ = false`, `false`, `untyped bool`, `false`},
79 {`package a1; const _ = 0`, `0`, `untyped int`, `0`},
80 {`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
81 {`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
82 {`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
83 {`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
85 {`package b0; var _ = false`, `false`, `bool`, `false`},
86 {`package b1; var _ = 0`, `0`, `int`, `0`},
87 {`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
88 {`package b3; var _ = 0.`, `0.`, `float64`, `0`},
89 {`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
90 {`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
92 {`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
93 {`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
94 {`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
96 {`package c1a; var _ = int(0)`, `0`, `int`, `0`},
97 {`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
98 {`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
100 {`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
101 {`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
102 {`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
104 {`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
105 {`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
106 {`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
108 {`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
109 {`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
110 {`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
112 {`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
113 {`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
114 {`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
115 {`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
116 {`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
117 {`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
119 {`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
120 {`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
121 {`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
122 {`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
124 {`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
125 {`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
126 {`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
127 {`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
128 {`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
129 {`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
130 {`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
131 {`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
133 {`package f0 ; var _ float32 = 1e-200`, `1e-200`, `float32`, `0`},
134 {`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
135 {`package f2a; var _ float64 = 1e-2000`, `1e-2000`, `float64`, `0`},
136 {`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
137 {`package f2b; var _ = 1e-2000`, `1e-2000`, `float64`, `0`},
138 {`package f3b; var _ = -1e-2000`, `-1e-2000`, `float64`, `0`},
139 {`package f4 ; var _ complex64 = 1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
140 {`package f5 ; var _ complex64 = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
141 {`package f6a; var _ complex128 = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
142 {`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
143 {`package f6b; var _ = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
144 {`package f7b; var _ = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
146 {`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // go.dev/issue/22341
147 {`package g1; var(j int32; s int; n = 1.0<<s == j)`, `1.0`, `int32`, `1`}, // go.dev/issue/48422
150 for _, test := range tests {
152 Types: make(map[ast.Expr]TypeAndValue),
154 name := mustTypecheck(test.src, nil, &info).Name()
156 // look for expression
158 for e := range info.Types {
159 if ExprString(e) == test.expr {
165 t.Errorf("package %s: no expression found for %s", name, test.expr)
168 tv := info.Types[expr]
170 // check that type is correct
171 if got := tv.Type.String(); got != test.typ {
172 t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
176 // if we have a constant, check that value is correct
178 if got := tv.Value.ExactString(); got != test.val {
179 t.Errorf("package %s: got value %s; want %s", name, got, test.val)
183 t.Errorf("package %s: no constant found; want %s", name, test.val)
189 func TestTypesInfo(t *testing.T) {
190 // Test sources that are not expected to typecheck must start with the broken prefix.
191 const broken = "package broken_"
193 var tests = []struct {
195 expr string // expression
196 typ string // value type
198 // single-valued expressions of untyped constants
199 {`package b0; var x interface{} = false`, `false`, `bool`},
200 {`package b1; var x interface{} = 0`, `0`, `int`},
201 {`package b2; var x interface{} = 0.`, `0.`, `float64`},
202 {`package b3; var x interface{} = 0i`, `0i`, `complex128`},
203 {`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
206 {`package n0; var _ *int = nil`, `nil`, `untyped nil`},
207 {`package n1; var _ func() = nil`, `nil`, `untyped nil`},
208 {`package n2; var _ []byte = nil`, `nil`, `untyped nil`},
209 {`package n3; var _ map[int]int = nil`, `nil`, `untyped nil`},
210 {`package n4; var _ chan int = nil`, `nil`, `untyped nil`},
211 {`package n5; var _ interface{} = nil`, `nil`, `untyped nil`},
212 {`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `untyped nil`},
214 {`package n10; var (x *int; _ = x == nil)`, `nil`, `untyped nil`},
215 {`package n11; var (x func(); _ = x == nil)`, `nil`, `untyped nil`},
216 {`package n12; var (x []byte; _ = x == nil)`, `nil`, `untyped nil`},
217 {`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `untyped nil`},
218 {`package n14; var (x chan int; _ = x == nil)`, `nil`, `untyped nil`},
219 {`package n15; var (x interface{}; _ = x == nil)`, `nil`, `untyped nil`},
220 {`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `untyped nil`},
222 {`package n20; var _ = (*int)(nil)`, `nil`, `untyped nil`},
223 {`package n21; var _ = (func())(nil)`, `nil`, `untyped nil`},
224 {`package n22; var _ = ([]byte)(nil)`, `nil`, `untyped nil`},
225 {`package n23; var _ = (map[int]int)(nil)`, `nil`, `untyped nil`},
226 {`package n24; var _ = (chan int)(nil)`, `nil`, `untyped nil`},
227 {`package n25; var _ = (interface{})(nil)`, `nil`, `untyped nil`},
228 {`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `untyped nil`},
230 {`package n30; func f(*int) { f(nil) }`, `nil`, `untyped nil`},
231 {`package n31; func f(func()) { f(nil) }`, `nil`, `untyped nil`},
232 {`package n32; func f([]byte) { f(nil) }`, `nil`, `untyped nil`},
233 {`package n33; func f(map[int]int) { f(nil) }`, `nil`, `untyped nil`},
234 {`package n34; func f(chan int) { f(nil) }`, `nil`, `untyped nil`},
235 {`package n35; func f(interface{}) { f(nil) }`, `nil`, `untyped nil`},
236 {`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `untyped nil`},
238 // comma-ok expressions
239 {`package p0; var x interface{}; var _, _ = x.(int)`,
243 {`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
247 {`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
249 `(complex128, p2a.mybool)`,
251 {`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
253 `(complex128, bool)`,
255 {`package p3; var c chan string; var _, _ = <-c`,
261 {`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
265 {`package issue6796_b; var c chan string; var _, _ = (<-c)`,
269 {`package issue6796_c; var c chan string; var _, _ = (<-c)`,
273 {`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
277 {`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
283 {`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
287 {`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
291 {`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
295 {`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
299 {`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
303 {`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
308 // go.dev/issue/28277
309 {`package issue28277_a; func f(...int)`,
313 {`package issue28277_b; func f(a, b int, c ...[]struct{})`,
318 // go.dev/issue/47243
319 {`package issue47243_a; var x int32; var _ = x << 3`, `3`, `untyped int`},
320 {`package issue47243_b; var x int32; var _ = x << 3.`, `3.`, `untyped float`},
321 {`package issue47243_c; var x int32; var _ = 1 << x`, `1 << x`, `int`},
322 {`package issue47243_d; var x int32; var _ = 1 << x`, `1`, `int`},
323 {`package issue47243_e; var x int32; var _ = 1 << 2`, `1`, `untyped int`},
324 {`package issue47243_f; var x int32; var _ = 1 << 2`, `2`, `untyped int`},
325 {`package issue47243_g; var x int32; var _ = int(1) << 2`, `2`, `untyped int`},
326 {`package issue47243_h; var x int32; var _ = 1 << (2 << x)`, `1`, `int`},
327 {`package issue47243_i; var x int32; var _ = 1 << (2 << x)`, `(2 << x)`, `untyped int`},
328 {`package issue47243_j; var x int32; var _ = 1 << (2 << x)`, `2`, `untyped int`},
330 // tests for broken code that doesn't type-check
331 {broken + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
332 {broken + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
333 {broken + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a, f: b,}}`, `b`, `string`},
334 {broken + `x3; var x = panic("");`, `panic`, `func(interface{})`},
335 {`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
336 {broken + `x5; func _() { var x map[string][...]int; x = map[string][...]int{"": {1,2,3}} }`, `x`, `map[string]invalid type`},
338 // parameterized functions
339 {`package p0; func f[T any](T) {}; var _ = f[int]`, `f`, `func[T any](T)`},
340 {`package p1; func f[T any](T) {}; var _ = f[int]`, `f[int]`, `func(int)`},
341 {`package p2; func f[T any](T) {}; func _() { f(42) }`, `f`, `func(int)`},
342 {`package p3; func f[T any](T) {}; func _() { f[int](42) }`, `f[int]`, `func(int)`},
343 {`package p4; func f[T any](T) {}; func _() { f[int](42) }`, `f`, `func[T any](T)`},
344 {`package p5; func f[T any](T) {}; func _() { f(42) }`, `f(42)`, `()`},
347 {`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
348 {`package t1; type t[P any] int; var _ t[int]`, `t`, `t1.t[P any]`},
349 {`package t2; type t[P interface{}] int; var _ t[int]`, `t`, `t2.t[P interface{}]`},
350 {`package t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `t3.t[P, Q interface{}]`},
351 {broken + `t4; type t[P, Q interface{ m() }] int; var _ t[int, int]`, `t`, `broken_t4.t[P, Q interface{m()}]`},
353 // instantiated types must be sanitized
354 {`package g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `g0.t[int]`},
356 // go.dev/issue/45096
357 {`package issue45096; func _[T interface{ ~int8 | ~int16 | ~int32 }](x T) { _ = x < 0 }`, `0`, `T`},
359 // go.dev/issue/47895
360 {`package p; import "unsafe"; type S struct { f int }; var s S; var _ = unsafe.Offsetof(s.f)`, `s.f`, `int`},
362 // go.dev/issue/50093
363 {`package u0a; func _[_ interface{int}]() {}`, `int`, `int`},
364 {`package u1a; func _[_ interface{~int}]() {}`, `~int`, `~int`},
365 {`package u2a; func _[_ interface{int | string}]() {}`, `int | string`, `int | string`},
366 {`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `int | string | ~bool`, `int | string | ~bool`},
367 {`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `int | string`, `int | string`},
368 {`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `~bool`, `~bool`},
369 {`package u3a; func _[_ interface{int | string | ~float64|~bool}]() {}`, `int | string | ~float64`, `int | string | ~float64`},
371 {`package u0b; func _[_ int]() {}`, `int`, `int`},
372 {`package u1b; func _[_ ~int]() {}`, `~int`, `~int`},
373 {`package u2b; func _[_ int | string]() {}`, `int | string`, `int | string`},
374 {`package u3b; func _[_ int | string | ~bool]() {}`, `int | string | ~bool`, `int | string | ~bool`},
375 {`package u3b; func _[_ int | string | ~bool]() {}`, `int | string`, `int | string`},
376 {`package u3b; func _[_ int | string | ~bool]() {}`, `~bool`, `~bool`},
377 {`package u3b; func _[_ int | string | ~float64|~bool]() {}`, `int | string | ~float64`, `int | string | ~float64`},
379 {`package u0c; type _ interface{int}`, `int`, `int`},
380 {`package u1c; type _ interface{~int}`, `~int`, `~int`},
381 {`package u2c; type _ interface{int | string}`, `int | string`, `int | string`},
382 {`package u3c; type _ interface{int | string | ~bool}`, `int | string | ~bool`, `int | string | ~bool`},
383 {`package u3c; type _ interface{int | string | ~bool}`, `int | string`, `int | string`},
384 {`package u3c; type _ interface{int | string | ~bool}`, `~bool`, `~bool`},
385 {`package u3c; type _ interface{int | string | ~float64|~bool}`, `int | string | ~float64`, `int | string | ~float64`},
387 // reverse type inference
388 {`package r1; var _ func(int) = g; func g[P any](P) {}`, `g`, `func(int)`},
389 {`package r2; var _ func(int) = g[int]; func g[P any](P) {}`, `g`, `func[P any](P)`}, // go.dev/issues/60212
390 {`package r3; var _ func(int) = g[int]; func g[P any](P) {}`, `g[int]`, `func(int)`},
391 {`package r4; var _ func(int, string) = g; func g[P, Q any](P, Q) {}`, `g`, `func(int, string)`},
392 {`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
393 {`package r6; var _ func(int, string) = g[int]; func g[P, Q any](P, Q) {}`, `g[int]`, `func(int, string)`},
395 {`package s1; func _() { f(g) }; func f(func(int)) {}; func g[P any](P) {}`, `g`, `func(int)`},
396 {`package s2; func _() { f(g[int]) }; func f(func(int)) {}; func g[P any](P) {}`, `g`, `func[P any](P)`}, // go.dev/issues/60212
397 {`package s3; func _() { f(g[int]) }; func f(func(int)) {}; func g[P any](P) {}`, `g[int]`, `func(int)`},
398 {`package s4; func _() { f(g) }; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}`, `g`, `func(int, string)`},
399 {`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
400 {`package s6; func _() { f(g[int]) }; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}`, `g[int]`, `func(int, string)`},
402 {`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)`},
403 {`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)`},
404 {`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
405 {`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)`},
408 for _, test := range tests {
409 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
411 if strings.HasPrefix(test.src, broken) {
412 pkg, err := typecheck(test.src, nil, &info)
414 t.Errorf("package %s: expected to fail but passed", pkg.Name())
421 name = mustTypecheck(test.src, nil, &info).Name()
424 // look for expression type
426 for e, tv := range info.Types {
427 if ExprString(e) == test.expr {
433 t.Errorf("package %s: no type found for %s", name, test.expr)
437 // check that type is correct
438 if got := typ.String(); got != test.typ {
439 t.Errorf("package %s: expr = %s: got %s; want %s", name, test.expr, got, test.typ)
444 func TestInstanceInfo(t *testing.T) {
445 const lib = `package lib
452 type testInst struct {
458 var tests = []struct {
460 instances []testInst // recorded instances in source order
462 {`package p0; func f[T any](T) {}; func _() { f(42) }`,
463 []testInst{{`f`, []string{`int`}, `func(int)`}},
465 {`package p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
466 []testInst{{`f`, []string{`rune`}, `func(rune) rune`}},
468 {`package p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
469 []testInst{{`f`, []string{`complex128`}, `func(...complex128) complex128`}},
471 {`package p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
472 []testInst{{`f`, []string{`float64`, `string`, `byte`}, `func(float64, *string, []byte)`}},
474 {`package p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
475 []testInst{{`f`, []string{`float64`, `byte`}, `func(float64, *byte, ...[]byte)`}},
478 {`package s1; func f[T any, P interface{*T}](x T) {}; func _(x string) { f(x) }`,
479 []testInst{{`f`, []string{`string`, `*string`}, `func(x string)`}},
481 {`package s2; func f[T any, P interface{*T}](x []T) {}; func _(x []int) { f(x) }`,
482 []testInst{{`f`, []string{`int`, `*int`}, `func(x []int)`}},
484 {`package s3; type C[T any] interface{chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
486 {`C`, []string{`T`}, `interface{chan<- T}`},
487 {`f`, []string{`int`, `chan<- int`}, `func(x []int)`},
490 {`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) }`,
492 {`C`, []string{`T`}, `interface{chan<- T}`},
493 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
494 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func(x []int)`},
498 {`package t1; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = f[string] }`,
499 []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
501 {`package t2; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = (f[string]) }`,
502 []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
504 {`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] }`,
506 {`C`, []string{`T`}, `interface{chan<- T}`},
507 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
508 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
511 {`package t4; type C[T any] interface{chan<- T}; func f[T any, P C[T], Q C[[]*P]]() []T { return nil }; func _() { _ = (f[int]) }`,
513 {`C`, []string{`T`}, `interface{chan<- T}`},
514 {`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
515 {`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
518 {`package i0; import "lib"; func _() { lib.F(42) }`,
519 []testInst{{`F`, []string{`int`}, `func(int)`}},
522 {`package duplfunc0; func f[T any](T) {}; func _() { f(42); f("foo"); f[int](3) }`,
524 {`f`, []string{`int`}, `func(int)`},
525 {`f`, []string{`string`}, `func(string)`},
526 {`f`, []string{`int`}, `func(int)`},
529 {`package duplfunc1; import "lib"; func _() { lib.F(42); lib.F("foo"); lib.F(3) }`,
531 {`F`, []string{`int`}, `func(int)`},
532 {`F`, []string{`string`}, `func(string)`},
533 {`F`, []string{`int`}, `func(int)`},
537 {`package type0; type T[P interface{~int}] struct{ x P }; var _ T[int]`,
538 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
540 {`package type1; type T[P interface{~int}] struct{ x P }; var _ (T[int])`,
541 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
543 {`package type2; type T[P interface{~int}] struct{ x P }; var _ T[(int)]`,
544 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
546 {`package type3; type T[P1 interface{~[]P2}, P2 any] struct{ x P1; y P2 }; var _ T[[]int, int]`,
547 []testInst{{`T`, []string{`[]int`, `int`}, `struct{x []int; y int}`}},
549 {`package type4; import "lib"; var _ lib.T[int]`,
550 []testInst{{`T`, []string{`int`}, `[]int`}},
553 {`package dupltype0; type T[P interface{~int}] struct{ x P }; var x T[int]; var y T[int]`,
555 {`T`, []string{`int`}, `struct{x int}`},
556 {`T`, []string{`int`}, `struct{x int}`},
559 {`package dupltype1; type T[P ~int] struct{ x P }; func (r *T[Q]) add(z T[Q]) { r.x += z.x }`,
561 {`T`, []string{`Q`}, `struct{x Q}`},
562 {`T`, []string{`Q`}, `struct{x Q}`},
565 {`package dupltype1; import "lib"; var x lib.T[int]; var y lib.T[int]; var z lib.T[string]`,
567 {`T`, []string{`int`}, `[]int`},
568 {`T`, []string{`int`}, `[]int`},
569 {`T`, []string{`string`}, `[]string`},
572 {`package issue51803; func foo[T any](T) {}; func _() { foo[int]( /* leave arg away on purpose */ ) }`,
573 []testInst{{`foo`, []string{`int`}, `func(int)`}},
576 // reverse type inference
577 {`package reverse1a; var f func(int) = g; func g[P any](P) {}`,
578 []testInst{{`g`, []string{`int`}, `func(int)`}},
580 {`package reverse1b; func f(func(int)) {}; func g[P any](P) {}; func _() { f(g) }`,
581 []testInst{{`g`, []string{`int`}, `func(int)`}},
583 {`package reverse2a; var f func(int, string) = g; func g[P, Q any](P, Q) {}`,
584 []testInst{{`g`, []string{`int`, `string`}, `func(int, string)`}},
586 {`package reverse2b; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}; func _() { f(g) }`,
587 []testInst{{`g`, []string{`int`, `string`}, `func(int, string)`}},
589 {`package reverse2c; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}; func _() { f(g[int]) }`,
590 []testInst{{`g`, []string{`int`, `string`}, `func(int, string)`}},
592 // reverse3a not possible (cannot assign to generic function outside of argument passing)
593 {`package reverse3b; func f[R any](func(int) R) {}; func g[P any](P) string { return "" }; func _() { f(g) }`,
595 {`f`, []string{`string`}, `func(func(int) string)`},
596 {`g`, []string{`int`}, `func(int) string`},
599 {`package reverse4a; var _, _ func([]int, *float32) = g, h; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}`,
601 {`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
602 {`h`, []string{`int`}, `func([]int, *float32)`},
605 {`package reverse4b; func f(_, _ func([]int, *float32)) {}; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}; func _() { f(g, h) }`,
607 {`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
608 {`h`, []string{`int`}, `func([]int, *float32)`},
611 {`package issue59956; func f(func(int), func(string), func(bool)) {}; func g[P any](P) {}; func _() { f(g, g, g) }`,
613 {`g`, []string{`int`}, `func(int)`},
614 {`g`, []string{`string`}, `func(string)`},
615 {`g`, []string{`bool`}, `func(bool)`},
620 for _, test := range tests {
621 imports := make(testImporter)
622 conf := Config{Importer: imports}
623 instMap := make(map[*ast.Ident]Instance)
624 useMap := make(map[*ast.Ident]Object)
625 makePkg := func(src string) *Package {
626 pkg, err := typecheck(src, &conf, &Info{Instances: instMap, Uses: useMap})
627 // allow error for issue51803
628 if err != nil && (pkg == nil || pkg.Name() != "issue51803") {
631 imports[pkg.Name()] = pkg
635 pkg := makePkg(test.src)
637 t.Run(pkg.Name(), func(t *testing.T) {
638 // Sort instances in source order for stability.
639 instances := sortedInstances(instMap)
640 if got, want := len(instances), len(test.instances); got != want {
641 t.Fatalf("got %d instances, want %d", got, want)
644 // Pairwise compare with the expected instances.
645 for ii, inst := range instances {
647 for i := 0; i < inst.Inst.TypeArgs.Len(); i++ {
648 targs = append(targs, inst.Inst.TypeArgs.At(i))
650 typ := inst.Inst.Type
652 testInst := test.instances[ii]
653 if got := inst.Ident.Name; got != testInst.name {
654 t.Fatalf("got name %s, want %s", got, testInst.name)
656 if len(targs) != len(testInst.targs) {
657 t.Fatalf("got %d type arguments; want %d", len(targs), len(testInst.targs))
659 for i, targ := range targs {
660 if got := targ.String(); got != testInst.targs[i] {
661 t.Errorf("type argument %d: got %s; want %s", i, got, testInst.targs[i])
664 if got := typ.Underlying().String(); got != testInst.typ {
665 t.Errorf("package %s: got %s; want %s", pkg.Name(), got, testInst.typ)
668 // Verify the invariant that re-instantiating the corresponding generic
669 // type with TypeArgs results in an identical instance.
670 ptype := useMap[inst.Ident].Type()
671 lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
672 if lister == nil || lister.TypeParams().Len() == 0 {
673 t.Fatalf("info.Types[%v] = %v, want parameterized type", inst.Ident, ptype)
675 inst2, err := Instantiate(nil, ptype, targs, true)
677 t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
679 if !Identical(inst.Inst.Type, inst2) {
680 t.Errorf("%v and %v are not identical", inst.Inst.Type, inst2)
687 type recordedInstance struct {
692 func sortedInstances(m map[*ast.Ident]Instance) (instances []recordedInstance) {
693 for id, inst := range m {
694 instances = append(instances, recordedInstance{id, inst})
696 sort.Slice(instances, func(i, j int) bool {
697 return CmpPos(instances[i].Ident.Pos(), instances[j].Ident.Pos()) < 0
702 func TestDefsInfo(t *testing.T) {
703 var tests = []struct {
708 {`package p0; const x = 42`, `x`, `const p0.x untyped int`},
709 {`package p1; const x int = 42`, `x`, `const p1.x int`},
710 {`package p2; var x int`, `x`, `var p2.x int`},
711 {`package p3; type x int`, `x`, `type p3.x int`},
712 {`package p4; func f()`, `f`, `func p4.f()`},
713 {`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
715 // Tests using generics.
716 {`package g0; type x[T any] int`, `x`, `type g0.x[T any] int`},
717 {`package g1; func f[T any]() {}`, `f`, `func g1.f[T any]()`},
718 {`package g2; type x[T any] int; func (*x[_]) m() {}`, `m`, `func (*g2.x[_]).m()`},
721 for _, test := range tests {
723 Defs: make(map[*ast.Ident]Object),
725 name := mustTypecheck(test.src, nil, &info).Name()
729 for id, obj := range info.Defs {
730 if id.Name == test.obj {
736 t.Errorf("package %s: %s not found", name, test.obj)
740 if got := def.String(); got != test.want {
741 t.Errorf("package %s: got %s; want %s", name, got, test.want)
746 func TestUsesInfo(t *testing.T) {
747 var tests = []struct {
752 {`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
753 {`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
754 {`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
755 {`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
756 {`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
758 // Tests using generics.
759 {`package g0; func _[T any]() { _ = x }; const x = 42`, `x`, `const g0.x untyped int`},
760 {`package g1; func _[T any](x T) { }`, `T`, `type parameter T any`},
761 {`package g2; type N[A any] int; var _ N[int]`, `N`, `type g2.N[A any] int`},
762 {`package g3; type N[A any] int; func (N[_]) m() {}`, `N`, `type g3.N[A any] int`},
764 // Uses of fields are instantiated.
765 {`package s1; type N[A any] struct{ a A }; var f = N[int]{}.a`, `a`, `field a int`},
766 {`package s1; type N[A any] struct{ a A }; func (r N[B]) m(b B) { r.a = b }`, `a`, `field a B`},
768 // Uses of methods are uses of the instantiated method.
769 {`package m0; type N[A any] int; func (r N[B]) m() { r.n() }; func (N[C]) n() {}`, `n`, `func (m0.N[B]).n()`},
770 {`package m1; type N[A any] int; func (r N[B]) m() { }; var f = N[int].m`, `m`, `func (m1.N[int]).m()`},
771 {`package m2; func _[A any](v interface{ m() A }) { v.m() }`, `m`, `func (interface).m() A`},
772 {`package m3; func f[A any]() interface{ m() A } { return nil }; var _ = f[int]().m()`, `m`, `func (interface).m() int`},
773 {`package m4; type T[A any] func() interface{ m() A }; var x T[int]; var y = x().m`, `m`, `func (interface).m() int`},
774 {`package m5; type T[A any] interface{ m() A }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m5.T[B]).m() B`},
775 {`package m6; type T[A any] interface{ m() }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m6.T[B]).m()`},
776 {`package m7; type T[A any] interface{ m() A }; func _(t T[int]) { t.m() }`, `m`, `func (m7.T[int]).m() int`},
777 {`package m8; type T[A any] interface{ m() }; func _(t T[int]) { t.m() }`, `m`, `func (m8.T[int]).m()`},
778 {`package m9; type T[A any] interface{ m() }; func _(t T[int]) { _ = t.m }`, `m`, `func (m9.T[int]).m()`},
780 `package m10; type E[A any] interface{ m() }; type T[B any] interface{ E[B]; n() }; func _(t T[int]) { t.m() }`,
782 `func (m10.E[int]).m()`,
784 {`package m11; type T[A any] interface{ m(); n() }; func _(t1 T[int], t2 T[string]) { t1.m(); t2.n() }`, `m`, `func (m11.T[int]).m()`},
785 {`package m12; type T[A any] interface{ m(); n() }; func _(t1 T[int], t2 T[string]) { t1.m(); t2.n() }`, `n`, `func (m12.T[string]).n()`},
788 for _, test := range tests {
790 Uses: make(map[*ast.Ident]Object),
792 name := mustTypecheck(test.src, nil, &info).Name()
796 for id, obj := range info.Uses {
797 if id.Name == test.obj {
799 panic(fmt.Sprintf("multiple uses of %q", id.Name))
805 t.Errorf("package %s: %s not found", name, test.obj)
809 if got := use.String(); got != test.want {
810 t.Errorf("package %s: got %s; want %s", name, got, test.want)
815 func TestGenericMethodInfo(t *testing.T) {
820 func (r N[B]) m() { r.m(); r.n() }
822 func (r *N[C]) n() { }
824 fset := token.NewFileSet()
825 f := mustParse(fset, src)
827 Defs: make(map[*ast.Ident]Object),
828 Uses: make(map[*ast.Ident]Object),
829 Selections: make(map[*ast.SelectorExpr]*Selection),
832 pkg, err := conf.Check("p", fset, []*ast.File{f}, &info)
837 N := pkg.Scope().Lookup("N").Type().(*Named)
839 // Find the generic methods stored on N.
840 gm, gn := N.Method(0), N.Method(1)
841 if gm.Name() == "n" {
845 // Collect objects from info.
846 var dm, dn *Func // the declared methods
847 var dmm, dmn *Func // the methods used in the body of m
848 for _, decl := range f.Decls {
849 fdecl, ok := decl.(*ast.FuncDecl)
853 def := info.Defs[fdecl.Name].(*Func)
854 switch fdecl.Name.Name {
857 ast.Inspect(fdecl.Body, func(n ast.Node) bool {
858 if call, ok := n.(*ast.CallExpr); ok {
859 sel := call.Fun.(*ast.SelectorExpr)
860 use := info.Uses[sel.Sel].(*Func)
861 selection := info.Selections[sel]
862 if selection.Kind() != MethodVal {
863 t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
865 if selection.Obj() != use {
866 t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
868 switch sel.Sel.Name {
883 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
886 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
889 t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
892 t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
896 func TestImplicitsInfo(t *testing.T) {
897 testenv.MustHaveGoBuild(t)
899 var tests = []struct {
903 {`package p2; import . "fmt"; var _ = Println`, ""}, // no Implicits entry
904 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
905 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
907 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
908 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
909 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
910 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
912 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
913 {`package p8; func f(int) {}`, "field: var int"},
914 {`package p9; func f() (complex64) { return 0 }`, "field: var complex64"},
915 {`package p10; type T struct{}; func (*T) f() {}`, "field: var *p10.T"},
917 // Tests using generics.
918 {`package f0; func f[T any](x int) {}`, ""}, // no Implicits entry
919 {`package f1; func f[T any](int) {}`, "field: var int"},
920 {`package f2; func f[T any](T) {}`, "field: var T"},
921 {`package f3; func f[T any]() (complex64) { return 0 }`, "field: var complex64"},
922 {`package f4; func f[T any](t T) (T) { return t }`, "field: var T"},
923 {`package t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var *t0.T[_]"},
924 {`package t1; type T[A any] struct{}; func _(x interface{}) { switch t := x.(type) { case T[int]: _ = t } }`, "caseClause: var t t1.T[int]"},
925 {`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]"},
926 {`package t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
929 for _, test := range tests {
931 Implicits: make(map[ast.Node]Object),
933 name := mustTypecheck(test.src, nil, &info).Name()
935 // the test cases expect at most one Implicits entry
936 if len(info.Implicits) > 1 {
937 t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
941 // extract Implicits entry, if any
943 for n, obj := range info.Implicits {
944 switch x := n.(type) {
945 case *ast.ImportSpec:
947 case *ast.CaseClause:
952 t.Fatalf("package %s: unexpected %T", name, x)
954 got += ": " + obj.String()
958 if got != test.want {
959 t.Errorf("package %s: got %q; want %q", name, got, test.want)
964 func TestPkgNameOf(t *testing.T) {
965 testenv.MustHaveGoBuild(t)
978 // avoid imported and not used errors
987 var tests = []struct {
988 path string // path string enclosed in "'s
994 {`"path/filepath"`, "filepath"},
998 fset := token.NewFileSet()
999 f := mustParse(fset, src)
1001 Defs: make(map[*ast.Ident]Object),
1002 Implicits: make(map[ast.Node]Object),
1005 conf.Importer = importer.Default()
1006 _, err := conf.Check("p", fset, []*ast.File{f}, &info)
1011 // map import paths to importDecl
1012 imports := make(map[string]*ast.ImportSpec)
1013 for _, s := range f.Decls[0].(*ast.GenDecl).Specs {
1014 if imp, _ := s.(*ast.ImportSpec); imp != nil {
1015 imports[imp.Path.Value] = imp
1019 for _, test := range tests {
1020 imp := imports[test.path]
1022 t.Fatalf("invalid test case: import path %s not found", test.path)
1024 got := info.PkgNameOf(imp)
1026 t.Fatalf("import %s: package name not found", test.path)
1028 if got.Name() != test.want {
1029 t.Errorf("import %s: got %s; want %s", test.path, got.Name(), test.want)
1033 // test non-existing importDecl
1034 if got := info.PkgNameOf(new(ast.ImportSpec)); got != nil {
1035 t.Errorf("got %s for non-existing import declaration", got.Name())
1039 func predString(tv TypeAndValue) string {
1040 var buf strings.Builder
1041 pred := func(b bool, s string) {
1044 buf.WriteString(", ")
1050 pred(tv.IsVoid(), "void")
1051 pred(tv.IsType(), "type")
1052 pred(tv.IsBuiltin(), "builtin")
1053 pred(tv.IsValue() && tv.Value != nil, "const")
1054 pred(tv.IsValue() && tv.Value == nil, "value")
1055 pred(tv.IsNil(), "nil")
1056 pred(tv.Addressable(), "addressable")
1057 pred(tv.Assignable(), "assignable")
1058 pred(tv.HasOk(), "hasOk")
1066 func TestPredicatesInfo(t *testing.T) {
1067 testenv.MustHaveGoBuild(t)
1069 var tests = []struct {
1075 {`package n0; func f() { f() }`, `f()`, `void`},
1078 {`package t0; type _ int`, `int`, `type`},
1079 {`package t1; type _ []int`, `[]int`, `type`},
1080 {`package t2; type _ func()`, `func()`, `type`},
1081 {`package t3; type _ func(int)`, `int`, `type`},
1082 {`package t3; type _ func(...int)`, `...int`, `type`},
1085 {`package b0; var _ = len("")`, `len`, `builtin`},
1086 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
1089 {`package c0; var _ = 42`, `42`, `const`},
1090 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
1091 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
1094 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
1095 {`package v1; var _ = &[]int{1}`, `[]int{…}`, `value`},
1096 {`package v2; var _ = func(){}`, `(func() literal)`, `value`},
1097 {`package v4; func f() { _ = f }`, `f`, `value`},
1098 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
1099 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
1101 // addressable (and thus assignable) operands
1102 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
1103 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
1104 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
1105 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
1106 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
1107 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
1108 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
1109 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
1110 // composite literals are not addressable
1112 // assignable but not addressable values
1113 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1114 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1116 // hasOk expressions
1117 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
1118 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
1121 // - package names are collected in the Uses map
1122 // - identifiers being declared are collected in the Defs map
1123 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
1124 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
1125 {`package m2; const c = 0`, `c`, `<missing>`},
1126 {`package m3; type T int`, `T`, `<missing>`},
1127 {`package m4; var v int`, `v`, `<missing>`},
1128 {`package m5; func f() {}`, `f`, `<missing>`},
1129 {`package m6; func _(x int) {}`, `x`, `<missing>`},
1130 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
1131 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
1134 for _, test := range tests {
1135 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
1136 name := mustTypecheck(test.src, nil, &info).Name()
1138 // look for expression predicates
1140 for e, tv := range info.Types {
1141 //println(name, ExprString(e))
1142 if ExprString(e) == test.expr {
1143 got = predString(tv)
1148 if got != test.pred {
1149 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
1154 func TestScopesInfo(t *testing.T) {
1155 testenv.MustHaveGoBuild(t)
1157 var tests = []struct {
1159 scopes []string // list of scope descriptors of the form kind:varlist
1161 {`package p0`, []string{
1164 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
1167 {`package p2; func _() {}`, []string{
1170 {`package p3; func _(x, y int) {}`, []string{
1171 "file:", "func:x y",
1173 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
1174 "file:", "func:x y z", // redeclaration of x
1176 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
1177 "file:", "func:u x y",
1179 {`package p6; func _() { { var x int; _ = x } }`, []string{
1180 "file:", "func:", "block:x",
1182 {`package p7; func _() { if true {} }`, []string{
1183 "file:", "func:", "if:", "block:",
1185 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
1186 "file:", "func:", "if:x", "block:y",
1188 {`package p9; func _() { switch x := 0; x {} }`, []string{
1189 "file:", "func:", "switch:x",
1191 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
1192 "file:", "func:", "switch:x", "case:y", "case:",
1194 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
1195 "file:", "func:t", "type switch:",
1197 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
1198 "file:", "func:t", "type switch:t",
1200 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
1201 "file:", "func:t", "type switch:", "case:x", // x implicitly declared
1203 {`package p14; func _() { select{} }`, []string{
1206 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
1207 "file:", "func:c", "comm:",
1209 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
1210 "file:", "func:c", "comm:i x",
1212 {`package p17; func _() { for{} }`, []string{
1213 "file:", "func:", "for:", "block:",
1215 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
1216 "file:", "func:n", "for:i", "block:",
1218 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
1219 "file:", "func:a", "range:i", "block:",
1221 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
1222 "file:", "func:a", "range:i x", "block:",
1226 for _, test := range tests {
1227 info := Info{Scopes: make(map[ast.Node]*Scope)}
1228 name := mustTypecheck(test.src, nil, &info).Name()
1230 // number of scopes must match
1231 if len(info.Scopes) != len(test.scopes) {
1232 t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
1235 // scope descriptions must match
1236 for node, scope := range info.Scopes {
1237 kind := "<unknown node kind>"
1238 switch node.(type) {
1243 case *ast.BlockStmt:
1247 case *ast.SwitchStmt:
1249 case *ast.TypeSwitchStmt:
1250 kind = "type switch"
1251 case *ast.CaseClause:
1253 case *ast.CommClause:
1257 case *ast.RangeStmt:
1261 // look for matching scope description
1262 desc := kind + ":" + strings.Join(scope.Names(), " ")
1264 for _, d := range test.scopes {
1271 t.Errorf("package %s: no matching scope found for %s", name, desc)
1277 func TestInitOrderInfo(t *testing.T) {
1278 var tests = []struct {
1282 {`package p0; var (x = 1; y = x)`, []string{
1285 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
1286 "a = 1", "b = 2", "c = 3",
1288 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
1289 "a = 1", "b = 2", "c = 3",
1291 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
1292 "_ = f()", // blank var
1294 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
1295 "a = 0", "z = 0", "y = z", "x = y",
1297 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
1298 "a, _ = m[0]", // blank var
1300 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
1301 "z = 0", "a, b = f()",
1303 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
1304 "b = 1", "a = (func() int literal)()",
1306 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
1307 "c = 1", "a, b = (func() (_, _ int) literal)()",
1309 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1312 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1313 "a = 0", "b = 0", "c = 0", "d = c + b",
1315 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
1316 "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
1318 // emit an initializer for n:1 initializations only once (not for each node
1319 // on the lhs which may appear in different order in the dependency graph)
1320 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
1321 "b = 0", "x, y = m[0]", "a = x",
1323 // test case from spec section on package initialization
1337 "d = 3", "b = f()", "c = f()", "a = c + b",
1339 // test case for go.dev/issue/7131
1343 func next() int { counter++; return counter }
1346 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1349 var b, c = next(), next()
1350 var d, e, f = next(), next(), next()
1352 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1354 // test case for go.dev/issue/10709
1364 func (T) m() int { return 0 }
1366 func makeT(n int) T {
1372 "t = makeT(0)", "v = t.m()",
1374 // test case for go.dev/issue/10709: same as test before, but variable decls swapped
1384 func (T) m() int { return 0 }
1386 func makeT(n int) T {
1392 "t = makeT(0)", "v = t.m()",
1394 // another candidate possibly causing problems with go.dev/issue/10709
1399 func f1() int { return g1() }
1400 func g1() int { f1(); return x1 }
1406 func f2() int { return g2() }
1407 func g2() int { return x2 }
1409 var x2 = 0`, []string{
1410 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1414 for _, test := range tests {
1416 name := mustTypecheck(test.src, nil, &info).Name()
1418 // number of initializers must match
1419 if len(info.InitOrder) != len(test.inits) {
1420 t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1424 // initializers must match
1425 for i, want := range test.inits {
1426 got := info.InitOrder[i].String()
1428 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1435 func TestMultiFileInitOrder(t *testing.T) {
1436 fset := token.NewFileSet()
1437 fileA := mustParse(fset, `package main; var a = 1`)
1438 fileB := mustParse(fset, `package main; var b = 2`)
1440 // The initialization order must not depend on the parse
1441 // order of the files, only on the presentation order to
1442 // the type-checker.
1443 for _, test := range []struct {
1447 {[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
1448 {[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
1451 if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
1454 if got := fmt.Sprint(info.InitOrder); got != test.want {
1455 t.Fatalf("got %s; want %s", got, test.want)
1460 func TestFiles(t *testing.T) {
1461 var sources = []string{
1462 "package p; type T struct{}; func (T) m1() {}",
1463 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1464 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1469 fset := token.NewFileSet()
1470 pkg := NewPackage("p", "p")
1472 check := NewChecker(&conf, fset, pkg, &info)
1474 for _, src := range sources {
1475 if err := check.Files([]*ast.File{mustParse(fset, src)}); err != nil {
1480 // check InitOrder is [x y]
1482 for _, init := range info.InitOrder {
1483 for _, v := range init.Lhs {
1484 vars = append(vars, v.Name())
1487 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1488 t.Errorf("InitOrder == %s, want %s", got, want)
1492 type testImporter map[string]*Package
1494 func (m testImporter) Import(path string) (*Package, error) {
1495 if pkg := m[path]; pkg != nil {
1498 return nil, fmt.Errorf("package %q not found", path)
1501 func TestSelection(t *testing.T) {
1502 selections := make(map[*ast.SelectorExpr]*Selection)
1504 // We need a specific fileset in this test below for positions.
1505 // Cannot use typecheck helper.
1506 fset := token.NewFileSet()
1507 imports := make(testImporter)
1508 conf := Config{Importer: imports}
1509 makePkg := func(path, src string) {
1510 pkg, err := conf.Check(path, fset, []*ast.File{mustParse(fset, src)}, &Info{Selections: selections})
1544 type G[P any] struct {
1556 // qualified identifiers
1594 // method expressions
1602 wantOut := map[string][2]string{
1603 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1605 "A{}.B": {"field (main.A) B *main.B", ".[0]"},
1606 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1607 "A{}.C": {"field (main.A) C main.C", ".[1]"},
1608 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1609 "A{}.b": {"field (main.A) b int", "->[0 0]"},
1610 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1611 "A{}.c": {"field (main.A) c int", ".[1 0]"},
1612 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1613 "Inst.p": {"field (main.G[int]) p int", ".[0]"},
1615 "A{}.f": {"method (main.A) f(int)", "->[0 0]"},
1616 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1617 "A{}.g": {"method (main.A) g()", ".[1 0]"},
1618 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1619 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1620 "B{}.f": {"method (main.B) f(int)", ".[0]"},
1621 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1622 "C{}.g": {"method (main.C) g()", ".[0]"},
1623 "new(C).g": {"method (*main.C) g()", "->[0]"},
1624 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1625 "Inst.m": {"method (main.G[int]) m(int)", ".[0]"},
1627 "A.f": {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1628 "(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1629 "B.f": {"method expr (main.B) f(main.B, int)", ".[0]"},
1630 "(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1631 "G[string].m": {"method expr (main.G[string]) m(main.G[string], string)", ".[0]"},
1632 "G[string]{}.p": {"field (main.G[string]) p string", ".[0]"},
1635 makePkg("lib", libSrc)
1636 makePkg("main", mainSrc)
1638 for e, sel := range selections {
1639 _ = sel.String() // assertion: must not panic
1641 start := fset.Position(e.Pos()).Offset
1642 end := fset.Position(e.End()).Offset
1643 syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1651 fmt.Sprintf("%s%v", direct, sel.Index()),
1653 want := wantOut[syntax]
1655 t.Errorf("%s: got %q; want %q", syntax, got, want)
1657 delete(wantOut, syntax)
1659 // We must explicitly assert properties of the
1660 // Signature's receiver since it doesn't participate
1661 // in Identical() or String().
1662 sig, _ := sel.Type().(*Signature)
1663 if sel.Kind() == MethodVal {
1664 got := sig.Recv().Type()
1666 if !Identical(got, want) {
1667 t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
1669 } else if sig != nil && sig.Recv() != nil {
1670 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1673 // Assert that all wantOut entries were used exactly once.
1674 for syntax := range wantOut {
1675 t.Errorf("no ast.Selection found with syntax %q", syntax)
1679 func TestIssue8518(t *testing.T) {
1680 fset := token.NewFileSet()
1681 imports := make(testImporter)
1683 Error: func(err error) { t.Log(err) }, // don't exit after first error
1686 makePkg := func(path, src string) {
1687 imports[path], _ = conf.Check(path, fset, []*ast.File{mustParse(fset, src)}, nil) // errors logged via conf.Error
1694 const C2 = missing.C
1704 makePkg("a", libSrc)
1705 makePkg("main", mainSrc) // don't crash when type-checking this package
1708 func TestIssue59603(t *testing.T) {
1709 fset := token.NewFileSet()
1710 imports := make(testImporter)
1712 Error: func(err error) { t.Log(err) }, // don't exit after first error
1715 makePkg := func(path, src string) {
1716 imports[path], _ = conf.Check(path, fset, []*ast.File{mustParse(fset, src)}, nil) // errors logged via conf.Error
1730 makePkg("a", libSrc)
1731 makePkg("main", mainSrc) // don't crash when type-checking this package
1734 func TestLookupFieldOrMethodOnNil(t *testing.T) {
1735 // LookupFieldOrMethod on a nil type is expected to produce a run-time panic.
1737 const want = "LookupFieldOrMethod on nil type"
1739 if s, ok := p.(string); !ok || s != want {
1740 t.Fatalf("got %v, want %s", p, want)
1743 LookupFieldOrMethod(nil, false, nil, "")
1746 func TestLookupFieldOrMethod(t *testing.T) {
1747 // Test cases assume a lookup of the form a.f or x.f, where a stands for an
1748 // addressable value, and x for a non-addressable value (even though a variable
1749 // for ease of test case writing).
1751 // Should be kept in sync with TestMethodSet.
1752 var tests = []struct {
1759 {"var x T; type T struct{}", false, nil, false},
1760 {"var x T; type T struct{ f int }", true, []int{0}, false},
1761 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1763 // field lookups on a generic type
1764 {"var x T[int]; type T[P any] struct{}", false, nil, false},
1765 {"var x T[int]; type T[P any] struct{ f P }", true, []int{0}, false},
1766 {"var x T[int]; type T[P any] struct{ a, b, f, c P }", true, []int{2}, false},
1769 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1770 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1771 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1772 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1774 // method lookups on a generic type
1775 {"var a T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, false},
1776 {"var a *T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, true},
1777 {"var a T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, false},
1778 {"var a *T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1781 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1782 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1784 // collisions on a generic type
1785 {"type ( E1[P any] struct{ f P }; E2[P any] struct{ f P }; x struct{ E1[int]; *E2[int] })", false, []int{1, 0}, false},
1786 {"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},
1788 // outside methodset
1789 // (*T).f method exists, but value of type T is not addressable
1790 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1792 // outside method set of a generic type
1793 {"var x T[int]; type T[P any] struct{}; func (*T[P]) f() {}", false, nil, true},
1795 // recursive generic types; see go.dev/issue/52715
1796 {"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},
1797 {"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},
1800 for _, test := range tests {
1801 pkg := mustTypecheck("package p;"+test.src, nil, nil)
1803 obj := pkg.Scope().Lookup("a")
1805 if obj = pkg.Scope().Lookup("x"); obj == nil {
1806 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1811 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1812 if (f != nil) != test.found {
1814 t.Errorf("%s: got no object; want one", test.src)
1816 t.Errorf("%s: got object = %v; want none", test.src, f)
1819 if !sameSlice(index, test.index) {
1820 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1822 if indirect != test.indirect {
1823 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1828 // Test for go.dev/issue/52715
1829 func TestLookupFieldOrMethod_RecursiveGeneric(t *testing.T) {
1833 type Tree[T any] struct {
1837 func (*Tree[R]) N(r R) R { return r }
1839 type Node[T any] struct {
1843 type Instance = *Tree[int]
1846 fset := token.NewFileSet()
1847 f := mustParse(fset, src)
1848 pkg := NewPackage("pkg", f.Name.Name)
1849 if err := NewChecker(nil, fset, pkg, nil).Files([]*ast.File{f}); err != nil {
1853 T := pkg.Scope().Lookup("Instance").Type()
1854 _, _, _ = LookupFieldOrMethod(T, false, pkg, "M") // verify that LookupFieldOrMethod terminates
1857 func sameSlice(a, b []int) bool {
1858 if len(a) != len(b) {
1861 for i, x := range a {
1869 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1870 // the correct result at various positions with the source.
1871 func TestScopeLookupParent(t *testing.T) {
1872 fset := token.NewFileSet()
1873 imports := make(testImporter)
1874 conf := Config{Importer: imports}
1876 makePkg := func(path string, files ...*ast.File) {
1878 imports[path], err = conf.Check(path, fset, files, &info)
1884 makePkg("lib", mustParse(fset, "package lib; var X int"))
1885 // Each /*name=kind:line*/ comment makes the test look up the
1886 // name at that point and checks that it resolves to a decl of
1887 // the specified kind and line number. "undef" means undefined.
1889 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1900 const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1901 type /*t=undef*/ t /*t=typename:14*/ *t
1902 print(Y) /*Y=var:10*/
1903 x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1904 var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1907 for i, x := range a /*i=undef*/ /*x=var:16*/ { _ = i; _ = x }
1910 switch y := i.(type) { /*y=undef*/
1911 case /*y=undef*/ int /*y=var:23*/ :
1912 case float32, /*y=undef*/ float64 /*y=var:23*/ :
1913 default /*y=var:23*/:
1918 switch int := i.(type) {
1919 case /*int=typename:0*/ int /*int=var:31*/ :
1921 default /*int=var:31*/ :
1927 info.Uses = make(map[*ast.Ident]Object)
1928 f := mustParse(fset, mainSrc)
1930 mainScope := imports["main"].Scope()
1931 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1932 for _, group := range f.Comments {
1933 for _, comment := range group.List {
1934 // Parse the assertion in the comment.
1935 m := rx.FindStringSubmatch(comment.Text)
1937 t.Errorf("%s: bad comment: %s",
1938 fset.Position(comment.Pos()), comment.Text)
1941 name, want := m[1], m[2]
1943 // Look up the name in the innermost enclosing scope.
1944 inner := mainScope.Innermost(comment.Pos())
1946 t.Errorf("%s: at %s: can't find innermost scope",
1947 fset.Position(comment.Pos()), comment.Text)
1951 if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil {
1952 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
1953 got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line)
1956 t.Errorf("%s: at %s: %s resolved to %s, want %s",
1957 fset.Position(comment.Pos()), comment.Text, name, got, want)
1962 // Check that for each referring identifier,
1963 // a lookup of its name on the innermost
1964 // enclosing scope returns the correct object.
1966 for id, wantObj := range info.Uses {
1967 inner := mainScope.Innermost(id.Pos())
1969 t.Errorf("%s: can't find innermost scope enclosing %q",
1970 fset.Position(id.Pos()), id.Name)
1974 // Exclude selectors and qualified identifiers---lexical
1975 // refs only. (Ideally, we'd see if the AST parent is a
1976 // SelectorExpr, but that requires PathEnclosingInterval
1977 // from golang.org/x/tools/go/ast/astutil.)
1982 _, gotObj := inner.LookupParent(id.Name, id.Pos())
1983 if gotObj != wantObj {
1984 t.Errorf("%s: got %v, want %v",
1985 fset.Position(id.Pos()), gotObj, wantObj)
1991 // newDefined creates a new defined type named T with the given underlying type.
1992 // Helper function for use with TestIncompleteInterfaces only.
1993 func newDefined(underlying Type) *Named {
1994 tname := NewTypeName(nopos, nil, "T", nil)
1995 return NewNamed(tname, underlying, nil)
1998 func TestConvertibleTo(t *testing.T) {
1999 for _, test := range []struct {
2003 {Typ[Int], Typ[Int], true},
2004 {Typ[Int], Typ[Float32], true},
2005 {Typ[Int], Typ[String], true},
2006 {newDefined(Typ[Int]), Typ[Int], true},
2007 {newDefined(new(Struct)), new(Struct), true},
2008 {newDefined(Typ[Int]), new(Struct), false},
2009 {Typ[UntypedInt], Typ[Int], true},
2010 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), true},
2011 {NewSlice(Typ[Int]), NewArray(Typ[Uint], 10), false},
2012 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
2013 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
2014 // Untyped string values are not permitted by the spec, so the behavior below is undefined.
2015 {Typ[UntypedString], Typ[String], true},
2017 if got := ConvertibleTo(test.v, test.t); got != test.want {
2018 t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
2023 func TestAssignableTo(t *testing.T) {
2024 for _, test := range []struct {
2028 {Typ[Int], Typ[Int], true},
2029 {Typ[Int], Typ[Float32], false},
2030 {newDefined(Typ[Int]), Typ[Int], false},
2031 {newDefined(new(Struct)), new(Struct), true},
2032 {Typ[UntypedBool], Typ[Bool], true},
2033 {Typ[UntypedString], Typ[Bool], false},
2034 // Neither untyped string nor untyped numeric assignments arise during
2035 // normal type checking, so the below behavior is technically undefined by
2037 {Typ[UntypedString], Typ[String], true},
2038 {Typ[UntypedInt], Typ[Int], true},
2040 if got := AssignableTo(test.v, test.t); got != test.want {
2041 t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
2046 func TestIdentical(t *testing.T) {
2047 // For each test, we compare the types of objects X and Y in the source.
2053 {"var X int; var Y int", true},
2054 {"var X int; var Y string", false},
2056 // TODO: add more tests for complex types.
2059 {"type X int; type Y int", false},
2062 {"type X = int; type Y = int", true},
2065 {`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
2066 {`func X() string { return "" }; func Y(int) string { return "" }`, false},
2067 {`func X(int) string { return "" }; func Y(int) {}`, false},
2069 // Generic functions. Type parameters should be considered identical modulo
2070 // renaming. See also go.dev/issue/49722.
2071 {`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
2072 {`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
2073 {`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
2074 {`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
2075 {`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
2076 {`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
2079 for _, test := range tests {
2080 pkg := mustTypecheck("package p;"+test.src, nil, nil)
2081 X := pkg.Scope().Lookup("X")
2082 Y := pkg.Scope().Lookup("Y")
2083 if X == nil || Y == nil {
2084 t.Fatal("test must declare both X and Y")
2086 if got := Identical(X.Type(), Y.Type()); got != test.want {
2087 t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
2092 func TestIdentical_issue15173(t *testing.T) {
2093 // Identical should allow nil arguments and be symmetric.
2094 for _, test := range []struct {
2098 {Typ[Int], Typ[Int], true},
2099 {Typ[Int], nil, false},
2100 {nil, Typ[Int], false},
2103 if got := Identical(test.x, test.y); got != test.want {
2104 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2109 func TestIdenticalUnions(t *testing.T) {
2110 tname := NewTypeName(nopos, nil, "myInt", nil)
2111 myInt := NewNamed(tname, Typ[Int], nil)
2112 tmap := map[string]*Term{
2113 "int": NewTerm(false, Typ[Int]),
2114 "~int": NewTerm(true, Typ[Int]),
2115 "string": NewTerm(false, Typ[String]),
2116 "~string": NewTerm(true, Typ[String]),
2117 "myInt": NewTerm(false, myInt),
2119 makeUnion := func(s string) *Union {
2120 parts := strings.Split(s, "|")
2122 for _, p := range parts {
2125 t.Fatalf("missing term %q", p)
2127 terms = append(terms, term)
2129 return NewUnion(terms)
2131 for _, test := range []struct {
2135 // These tests are just sanity checks. The tests for type sets and
2136 // interfaces provide much more test coverage.
2137 {"int|~int", "~int", true},
2138 {"myInt|~int", "~int", true},
2139 {"int|string", "string|int", true},
2140 {"int|int|string", "string|int", true},
2141 {"myInt|string", "int|string", false},
2143 x := makeUnion(test.x)
2144 y := makeUnion(test.y)
2145 if got := Identical(x, y); got != test.want {
2146 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2151 func TestIssue61737(t *testing.T) {
2152 // This test verifies that it is possible to construct invalid interfaces
2153 // containing duplicate methods using the go/types API.
2155 // It must be possible for importers to construct such invalid interfaces.
2156 // Previously, this panicked.
2158 sig1 := NewSignatureType(nil, nil, nil, NewTuple(NewParam(nopos, nil, "", Typ[Int])), nil, false)
2159 sig2 := NewSignatureType(nil, nil, nil, NewTuple(NewParam(nopos, nil, "", Typ[String])), nil, false)
2162 NewFunc(nopos, nil, "M", sig1),
2163 NewFunc(nopos, nil, "M", sig2),
2166 embeddedMethods := []*Func{
2167 NewFunc(nopos, nil, "M", sig2),
2169 embedded := NewInterfaceType(embeddedMethods, nil)
2170 iface := NewInterfaceType(methods, []Type{embedded})
2174 func TestIssue15305(t *testing.T) {
2175 const src = "package p; func f() int16; var _ = f(undef)"
2176 fset := token.NewFileSet()
2177 f := mustParse(fset, src)
2179 Error: func(err error) {}, // allow errors
2182 Types: make(map[ast.Expr]TypeAndValue),
2184 conf.Check("p", fset, []*ast.File{f}, info) // ignore result
2185 for e, tv := range info.Types {
2186 if _, ok := e.(*ast.CallExpr); ok {
2187 if tv.Type != Typ[Int16] {
2188 t.Errorf("CallExpr has type %v, want int16", tv.Type)
2193 t.Errorf("CallExpr has no type")
2196 // TestCompositeLitTypes verifies that Info.Types registers the correct
2197 // types for composite literal expressions and composite literal type
2199 func TestCompositeLitTypes(t *testing.T) {
2200 for i, test := range []struct {
2203 {`[16]byte{}`, `[16]byte`},
2204 {`[...]byte{}`, `[0]byte`}, // test for go.dev/issue/14092
2205 {`[...]int{1, 2, 3}`, `[3]int`}, // test for go.dev/issue/14092
2206 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for go.dev/issue/14092
2207 {`[]int{}`, `[]int`},
2208 {`map[string]bool{"foo": true}`, `map[string]bool`},
2209 {`struct{}{}`, `struct{}`},
2210 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
2212 fset := token.NewFileSet()
2213 f := mustParse(fset, fmt.Sprintf("package p%d; var _ = %s", i, test.lit))
2214 types := make(map[ast.Expr]TypeAndValue)
2215 if _, err := new(Config).Check("p", fset, []*ast.File{f}, &Info{Types: types}); err != nil {
2216 t.Fatalf("%s: %v", test.lit, err)
2219 cmptype := func(x ast.Expr, want string) {
2222 t.Errorf("%s: no Types entry found", test.lit)
2226 t.Errorf("%s: type is nil", test.lit)
2229 if got := tv.Type.String(); got != want {
2230 t.Errorf("%s: got %v, want %s", test.lit, got, want)
2234 // test type of composite literal expression
2235 rhs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0]
2236 cmptype(rhs, test.typ)
2238 // test type of composite literal type expression
2239 cmptype(rhs.(*ast.CompositeLit).Type, test.typ)
2243 // TestObjectParents verifies that objects have parent scopes or not
2244 // as specified by the Object interface.
2245 func TestObjectParents(t *testing.T) {
2264 func f(x int) { y := x; print(y) }
2267 fset := token.NewFileSet()
2268 f := mustParse(fset, src)
2271 Defs: make(map[*ast.Ident]Object),
2273 if _, err := new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
2277 for ident, obj := range info.Defs {
2279 // only package names and implicit vars have a nil object
2280 // (in this test we only need to handle the package name)
2281 if ident.Name != "p" {
2282 t.Errorf("%v has nil object", ident)
2287 // struct fields, type-associated and interface methods
2288 // have no parent scope
2290 switch obj := obj.(type) {
2296 if obj.Type().(*Signature).Recv() != nil { // method
2301 gotParent := obj.Parent() != nil
2303 case gotParent && !wantParent:
2304 t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
2305 case !gotParent && wantParent:
2306 t.Errorf("%v: no parent found", ident)
2311 // TestFailedImport tests that we don't get follow-on errors
2312 // elsewhere in a package due to failing to import a package.
2313 func TestFailedImport(t *testing.T) {
2314 testenv.MustHaveGoBuild(t)
2319 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
2324 func f(x T) T { return foo.F(x) }
2326 fset := token.NewFileSet()
2327 f := mustParse(fset, src)
2328 files := []*ast.File{f}
2330 // type-check using all possible importers
2331 for _, compiler := range []string{"gc", "gccgo", "source"} {
2334 Error: func(err error) {
2335 // we should only see the import error
2336 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
2337 t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
2341 Importer: importer.For(compiler, nil),
2345 Uses: make(map[*ast.Ident]Object),
2347 pkg, _ := conf.Check("p", fset, files, info)
2349 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
2353 imports := pkg.Imports()
2354 if len(imports) != 1 {
2355 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
2359 if imp.Name() != "foo" {
2360 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
2364 // verify that all uses of foo refer to the imported package foo (imp)
2365 for ident, obj := range info.Uses {
2366 if ident.Name == "foo" {
2367 if obj, ok := obj.(*PkgName); ok {
2368 if obj.Imported() != imp {
2369 t.Errorf("%s resolved to %v; want %v", ident, obj.Imported(), imp)
2372 t.Errorf("%s resolved to %v; want package name", ident, obj)
2379 func TestInstantiate(t *testing.T) {
2380 // eventually we like more tests but this is a start
2381 const src = "package p; type T[P any] *T[P]"
2382 pkg := mustTypecheck(src, nil, nil)
2384 // type T should have one type parameter
2385 T := pkg.Scope().Lookup("T").Type().(*Named)
2386 if n := T.TypeParams().Len(); n != 1 {
2387 t.Fatalf("expected 1 type parameter; found %d", n)
2390 // instantiation should succeed (no endless recursion)
2391 // even with a nil *Checker
2392 res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
2397 // instantiated type should point to itself
2398 if p := res.Underlying().(*Pointer).Elem(); p != res {
2399 t.Fatalf("unexpected result type: %s points to %s", res, p)
2403 func TestInstantiateConcurrent(t *testing.T) {
2404 const src = `package p
2406 type I[P any] interface {
2413 type Nested[P any] *interface{b(P)}
2415 type K = Nested[string]
2417 pkg := mustTypecheck(src, nil, nil)
2419 insts := []*Interface{
2420 pkg.Scope().Lookup("J").Type().Underlying().(*Interface),
2421 pkg.Scope().Lookup("K").Type().Underlying().(*Pointer).Elem().(*Interface),
2424 // Use the interface instances concurrently.
2425 for _, inst := range insts {
2427 counts [2]int // method counts
2428 methods [2][]string // method strings
2430 var wg sync.WaitGroup
2431 for i := 0; i < 2; i++ {
2437 counts[i] = inst.NumMethods()
2438 for mi := 0; mi < counts[i]; mi++ {
2439 methods[i] = append(methods[i], inst.Method(mi).String())
2445 if counts[0] != counts[1] {
2446 t.Errorf("mismatching method counts for %s: %d vs %d", inst, counts[0], counts[1])
2449 for i := 0; i < counts[0]; i++ {
2450 if m0, m1 := methods[0][i], methods[1][i]; m0 != m1 {
2451 t.Errorf("mismatching methods for %s: %s vs %s", inst, m0, m1)
2457 func TestInstantiateErrors(t *testing.T) {
2459 src string // by convention, T must be the type being instantiated
2461 wantAt int // -1 indicates no error
2463 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
2464 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
2465 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
2466 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
2469 for _, test := range tests {
2470 src := "package p; " + test.src
2471 pkg := mustTypecheck(src, nil, nil)
2473 T := pkg.Scope().Lookup("T").Type().(*Named)
2475 _, err := Instantiate(nil, T, test.targs, true)
2477 t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
2480 var argErr *ArgumentError
2481 if !errors.As(err, &argErr) {
2482 t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
2485 if argErr.Index != test.wantAt {
2486 t.Errorf("Instantiate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2491 func TestArgumentErrorUnwrapping(t *testing.T) {
2492 var err error = &ArgumentError{
2494 Err: Error{Msg: "test"},
2497 if !errors.As(err, &e) {
2498 t.Fatalf("error %v does not wrap types.Error", err)
2500 if e.Msg != "test" {
2501 t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2505 func TestInstanceIdentity(t *testing.T) {
2506 imports := make(testImporter)
2507 conf := Config{Importer: imports}
2508 makePkg := func(src string) {
2509 fset := token.NewFileSet()
2510 f := mustParse(fset, src)
2512 pkg, err := conf.Check(name, fset, []*ast.File{f}, nil)
2518 makePkg(`package lib; type T[P any] struct{}`)
2519 makePkg(`package a; import "lib"; var A lib.T[int]`)
2520 makePkg(`package b; import "lib"; var B lib.T[int]`)
2521 a := imports["a"].Scope().Lookup("A")
2522 b := imports["b"].Scope().Lookup("B")
2523 if !Identical(a.Type(), b.Type()) {
2524 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
2528 // TestInstantiatedObjects verifies properties of instantiated objects.
2529 func TestInstantiatedObjects(t *testing.T) {
2533 type T[P any] struct {
2537 func (recv *T[Q]) concreteMethod(mParam Q) (mResult Q) { return }
2539 type FT[P any] func(ftParam P) (ftResult P)
2541 func F[P any](fParam P) (fResult P){ return }
2543 type I[P any] interface {
2549 func (R[P]) m() {} // having a method triggers expansion of R
2564 Defs: make(map[*ast.Ident]Object),
2566 fset := token.NewFileSet()
2567 f := mustParse(fset, src)
2569 pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
2574 lookup := func(name string) Type { return pkg.Scope().Lookup(name).Type() }
2575 fnScope := pkg.Scope().Lookup("fn").(*Func).Scope()
2582 {"field", lookup("t").Underlying().(*Struct).Field(0)},
2583 {"field", fnScope.Lookup("r").Type().Underlying().(*Struct).Field(0)},
2585 // Methods and method fields
2586 {"concreteMethod", lookup("t").(*Named).Method(0)},
2587 {"recv", lookup("t").(*Named).Method(0).Type().(*Signature).Recv()},
2588 {"mParam", lookup("t").(*Named).Method(0).Type().(*Signature).Params().At(0)},
2589 {"mResult", lookup("t").(*Named).Method(0).Type().(*Signature).Results().At(0)},
2591 // Interface methods
2592 {"interfaceMethod", lookup("i").Underlying().(*Interface).Method(0)},
2594 // Function type fields
2595 {"ftParam", lookup("ft").Underlying().(*Signature).Params().At(0)},
2596 {"ftResult", lookup("ft").Underlying().(*Signature).Results().At(0)},
2599 {"fParam", lookup("f").(*Signature).Params().At(0)},
2600 {"fResult", lookup("f").(*Signature).Results().At(0)},
2603 // Collect all identifiers by name.
2604 idents := make(map[string][]*ast.Ident)
2605 ast.Inspect(f, func(n ast.Node) bool {
2606 if id, ok := n.(*ast.Ident); ok {
2607 idents[id.Name] = append(idents[id.Name], id)
2612 for _, test := range tests {
2614 t.Run(test.name, func(t *testing.T) {
2615 if got := len(idents[test.name]); got != 1 {
2616 t.Fatalf("found %d identifiers named %s, want 1", got, test.name)
2618 ident := idents[test.name][0]
2619 def := info.Defs[ident]
2620 if def == test.obj {
2621 t.Fatalf("info.Defs[%s] contains the test object", test.name)
2623 if orig := originObject(test.obj); def != orig {
2624 t.Errorf("info.Defs[%s] does not match obj.Origin()", test.name)
2626 if def.Pkg() != test.obj.Pkg() {
2627 t.Errorf("Pkg() = %v, want %v", def.Pkg(), test.obj.Pkg())
2629 if def.Name() != test.obj.Name() {
2630 t.Errorf("Name() = %v, want %v", def.Name(), test.obj.Name())
2632 if def.Pos() != test.obj.Pos() {
2633 t.Errorf("Pos() = %v, want %v", def.Pos(), test.obj.Pos())
2635 if def.Parent() != test.obj.Parent() {
2636 t.Fatalf("Parent() = %v, want %v", def.Parent(), test.obj.Parent())
2638 if def.Exported() != test.obj.Exported() {
2639 t.Fatalf("Exported() = %v, want %v", def.Exported(), test.obj.Exported())
2641 if def.Id() != test.obj.Id() {
2642 t.Fatalf("Id() = %v, want %v", def.Id(), test.obj.Id())
2644 // String and Type are expected to differ.
2649 func originObject(obj Object) Object {
2650 switch obj := obj.(type) {
2659 func TestImplements(t *testing.T) {
2663 type EmptyIface interface{}
2674 type Integer interface{
2675 int8 | int16 | int32 | int64
2678 type EmptyTypeSet interface{
2695 type Bad Bad // invalid type
2698 fset := token.NewFileSet()
2699 f := mustParse(fset, src)
2700 conf := Config{Error: func(error) {}}
2701 pkg, _ := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
2703 lookup := func(tname string) Type { return pkg.Scope().Lookup(tname).Type() }
2705 EmptyIface = lookup("EmptyIface").Underlying().(*Interface)
2706 I = lookup("I").(*Named)
2707 II = I.Underlying().(*Interface)
2708 C = lookup("C").(*Named)
2709 CI = C.Underlying().(*Interface)
2710 Integer = lookup("Integer").Underlying().(*Interface)
2711 EmptyTypeSet = lookup("EmptyTypeSet").Underlying().(*Interface)
2713 N1p = NewPointer(N1)
2715 N2p = NewPointer(N2)
2730 {Typ[Int8], Integer, true},
2731 {Typ[Int64], Integer, true},
2732 {Typ[String], Integer, false},
2733 {EmptyTypeSet, II, true},
2734 {EmptyTypeSet, EmptyTypeSet, true},
2735 {Typ[Int], EmptyTypeSet, false},
2750 {Bad, EmptyIface, true},
2753 for _, test := range tests {
2754 if got := Implements(test.V, test.T); got != test.want {
2755 t.Errorf("Implements(%s, %s) = %t, want %t", test.V, test.T, got, test.want)
2758 // The type assertion x.(T) is valid if T is an interface or if T implements the type of x.
2759 // The assertion is never valid if T is a bad type.
2763 if _, ok := T.Underlying().(*Interface); (ok || Implements(T, V)) && T != Bad {
2766 if got := AssertableTo(V, T); got != want {
2767 t.Errorf("AssertableTo(%s, %s) = %t, want %t", V, T, got, want)
2772 func TestMissingMethodAlternative(t *testing.T) {
2794 pkg := mustTypecheck(src, nil, nil)
2796 T := pkg.Scope().Lookup("T").Type().Underlying().(*Interface)
2797 lookup := func(name string) (*Func, bool) {
2798 return MissingMethod(pkg.Scope().Lookup(name).Type(), T, true)
2801 // V0 has method m with correct signature. Should not report wrongType.
2802 method, wrongType := lookup("V0")
2803 if method != nil || wrongType {
2804 t.Fatalf("V0: got method = %v, wrongType = %v", method, wrongType)
2807 checkMissingMethod := func(tname string, reportWrongType bool) {
2808 method, wrongType := lookup(tname)
2809 if method == nil || method.Name() != "m" || wrongType != reportWrongType {
2810 t.Fatalf("%s: got method = %v, wrongType = %v", tname, method, wrongType)
2814 // V1 has no method m. Should not report wrongType.
2815 checkMissingMethod("V1", false)
2817 // V2 has method m with wrong signature type (ignoring receiver). Should report wrongType.
2818 checkMissingMethod("V2", true)
2820 // V3 has no method m but it exists on *V3. Should report wrongType.
2821 checkMissingMethod("V3", true)
2823 // V4 has no method m but has M. Should not report wrongType.
2824 checkMissingMethod("V4", false)
2827 func TestErrorURL(t *testing.T) {
2829 *stringFieldAddr(&conf, "_ErrorURL") = " [go.dev/e/%s]"
2831 // test case for a one-line error
2836 _, err := typecheck(src1, &conf, nil)
2837 if err == nil || !strings.HasSuffix(err.Error(), " [go.dev/e/UndeclaredName]") {
2838 t.Errorf("src1: unexpected error: got %v", err)
2841 // test case for a multi-line error
2844 func f() int { return 0 }
2847 _, err = typecheck(src2, &conf, nil)
2848 if err == nil || !strings.Contains(err.Error(), " [go.dev/e/WrongArgCount]\n") {
2849 t.Errorf("src1: unexpected error: got %v", err)
2853 func TestModuleVersion(t *testing.T) {
2854 // version go1.dd must be able to typecheck go1.dd.0, go1.dd.1, etc.
2855 goversion := fmt.Sprintf("go1.%d", goversion.Version)
2856 for _, v := range []string{
2862 conf := Config{GoVersion: v}
2863 pkg := mustTypecheck("package p", &conf, nil)
2864 if pkg.GoVersion() != conf.GoVersion {
2865 t.Errorf("got %s; want %s", pkg.GoVersion(), conf.GoVersion)
2870 func TestFileVersions(t *testing.T) {
2871 for _, test := range []struct {
2876 {"", "", ""}, // no versions specified
2877 {"go1.19", "", "go1.19"}, // module version specified
2878 {"", "go1.20", ""}, // file upgrade ignored
2879 {"go1.19", "go1.20", "go1.20"}, // file upgrade permitted
2880 {"go1.20", "go1.19", "go1.20"}, // file downgrade not permitted
2881 {"go1.21", "go1.19", "go1.19"}, // file downgrade permitted (module version is >= go1.21)
2883 // versions containing release numbers
2884 // (file versions containing release numbers are considered invalid)
2885 {"go1.19.0", "", "go1.19.0"}, // no file version specified
2886 {"go1.20", "go1.20.1", "go1.20"}, // file upgrade ignored
2887 {"go1.20.1", "go1.20", "go1.20.1"}, // file upgrade ignored
2888 {"go1.20.1", "go1.21", "go1.21"}, // file upgrade permitted
2889 {"go1.20.1", "go1.19", "go1.20.1"}, // file downgrade not permitted
2890 {"go1.21.1", "go1.19.1", "go1.21.1"}, // file downgrade not permitted (invalid file version)
2891 {"go1.21.1", "go1.19", "go1.19"}, // file downgrade permitted (module version is >= go1.21)
2894 if test.fileVersion != "" {
2895 src = "//go:build " + test.fileVersion + "\n"
2899 conf := Config{GoVersion: test.goVersion}
2900 versions := make(map[*ast.File]string)
2902 info.FileVersions = versions
2903 mustTypecheck(src, &conf, &info)
2906 for _, v := range versions {
2907 want := test.wantVersion
2909 t.Errorf("%q: unexpected file version: got %q, want %q", src, v, want)
2914 t.Errorf("%q: incorrect number of map entries: got %d", src, n)