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"
20 . "cmd/compile/internal/types2"
23 // nopos indicates an unknown position
26 func mustParse(src string) *syntax.File {
27 f, err := syntax.Parse(syntax.NewFileBase(pkgName(src)), strings.NewReader(src), nil, nil, 0)
29 panic(err) // so we don't need to pass *testing.T
34 func typecheck(src string, conf *Config, info *Info) (*Package, error) {
38 Error: func(err error) {}, // collect all errors
39 Importer: defaultImporter(),
42 return conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
45 func mustTypecheck(src string, conf *Config, info *Info) *Package {
46 pkg, err := typecheck(src, conf, info)
48 panic(err) // so we don't need to pass *testing.T
53 // pkgName extracts the package name from src, which must contain a package header.
54 func pkgName(src string) string {
56 if i := strings.Index(src, kw); i >= 0 {
57 after := src[i+len(kw):]
59 if i := strings.IndexAny(after, "\n\t ;/"); i >= 0 {
64 panic("missing package header: " + src)
67 func TestValuesInfo(t *testing.T) {
68 var tests = []struct {
70 expr string // constant expression
71 typ string // constant type
72 val string // constant value
74 {`package a0; const _ = false`, `false`, `untyped bool`, `false`},
75 {`package a1; const _ = 0`, `0`, `untyped int`, `0`},
76 {`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
77 {`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
78 {`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
79 {`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
81 {`package b0; var _ = false`, `false`, `bool`, `false`},
82 {`package b1; var _ = 0`, `0`, `int`, `0`},
83 {`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
84 {`package b3; var _ = 0.`, `0.`, `float64`, `0`},
85 {`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
86 {`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
88 {`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
89 {`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
90 {`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
92 {`package c1a; var _ = int(0)`, `0`, `int`, `0`},
93 {`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
94 {`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
96 {`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
97 {`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
98 {`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
100 {`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
101 {`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
102 {`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
104 {`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
105 {`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
106 {`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
108 {`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
109 {`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
110 {`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
111 {`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
112 {`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
113 {`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
115 {`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
116 {`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
117 {`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
118 {`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
120 {`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
121 {`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
122 {`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
123 {`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
124 {`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
125 {`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
126 {`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
127 {`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
129 {`package f0 ; var _ float32 = 1e-200`, `1e-200`, `float32`, `0`},
130 {`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
131 {`package f2a; var _ float64 = 1e-2000`, `1e-2000`, `float64`, `0`},
132 {`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
133 {`package f2b; var _ = 1e-2000`, `1e-2000`, `float64`, `0`},
134 {`package f3b; var _ = -1e-2000`, `-1e-2000`, `float64`, `0`},
135 {`package f4 ; var _ complex64 = 1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
136 {`package f5 ; var _ complex64 = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
137 {`package f6a; var _ complex128 = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
138 {`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
139 {`package f6b; var _ = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
140 {`package f7b; var _ = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
142 {`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // go.dev/issue/22341
143 {`package g1; var(j int32; s int; n = 1.0<<s == j)`, `1.0`, `int32`, `1`}, // go.dev/issue/48422
146 for _, test := range tests {
148 Types: make(map[syntax.Expr]TypeAndValue),
150 name := mustTypecheck(test.src, nil, &info).Name()
152 // look for expression
154 for e := range info.Types {
155 if syntax.String(e) == test.expr {
161 t.Errorf("package %s: no expression found for %s", name, test.expr)
164 tv := info.Types[expr]
166 // check that type is correct
167 if got := tv.Type.String(); got != test.typ {
168 t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
172 // if we have a constant, check that value is correct
174 if got := tv.Value.ExactString(); got != test.val {
175 t.Errorf("package %s: got value %s; want %s", name, got, test.val)
179 t.Errorf("package %s: no constant found; want %s", name, test.val)
185 func TestTypesInfo(t *testing.T) {
186 // Test sources that are not expected to typecheck must start with the broken prefix.
187 const brokenPkg = "package broken_"
189 var tests = []struct {
191 expr string // expression
192 typ string // value type
194 // single-valued expressions of untyped constants
195 {`package b0; var x interface{} = false`, `false`, `bool`},
196 {`package b1; var x interface{} = 0`, `0`, `int`},
197 {`package b2; var x interface{} = 0.`, `0.`, `float64`},
198 {`package b3; var x interface{} = 0i`, `0i`, `complex128`},
199 {`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
202 {`package n0; var _ *int = nil`, `nil`, `*int`},
203 {`package n1; var _ func() = nil`, `nil`, `func()`},
204 {`package n2; var _ []byte = nil`, `nil`, `[]byte`},
205 {`package n3; var _ map[int]int = nil`, `nil`, `map[int]int`},
206 {`package n4; var _ chan int = nil`, `nil`, `chan int`},
207 {`package n5a; var _ interface{} = (*int)(nil)`, `nil`, `*int`},
208 {`package n5b; var _ interface{m()} = nil`, `nil`, `interface{m()}`},
209 {`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `unsafe.Pointer`},
211 {`package n10; var (x *int; _ = x == nil)`, `nil`, `*int`},
212 {`package n11; var (x func(); _ = x == nil)`, `nil`, `func()`},
213 {`package n12; var (x []byte; _ = x == nil)`, `nil`, `[]byte`},
214 {`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `map[int]int`},
215 {`package n14; var (x chan int; _ = x == nil)`, `nil`, `chan int`},
216 {`package n15a; var (x interface{}; _ = x == (*int)(nil))`, `nil`, `*int`},
217 {`package n15b; var (x interface{m()}; _ = x == nil)`, `nil`, `interface{m()}`},
218 {`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `unsafe.Pointer`},
220 {`package n20; var _ = (*int)(nil)`, `nil`, `*int`},
221 {`package n21; var _ = (func())(nil)`, `nil`, `func()`},
222 {`package n22; var _ = ([]byte)(nil)`, `nil`, `[]byte`},
223 {`package n23; var _ = (map[int]int)(nil)`, `nil`, `map[int]int`},
224 {`package n24; var _ = (chan int)(nil)`, `nil`, `chan int`},
225 {`package n25a; var _ = (interface{})((*int)(nil))`, `nil`, `*int`},
226 {`package n25b; var _ = (interface{m()})(nil)`, `nil`, `interface{m()}`},
227 {`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `unsafe.Pointer`},
229 {`package n30; func f(*int) { f(nil) }`, `nil`, `*int`},
230 {`package n31; func f(func()) { f(nil) }`, `nil`, `func()`},
231 {`package n32; func f([]byte) { f(nil) }`, `nil`, `[]byte`},
232 {`package n33; func f(map[int]int) { f(nil) }`, `nil`, `map[int]int`},
233 {`package n34; func f(chan int) { f(nil) }`, `nil`, `chan int`},
234 {`package n35a; func f(interface{}) { f((*int)(nil)) }`, `nil`, `*int`},
235 {`package n35b; func f(interface{m()}) { f(nil) }`, `nil`, `interface{m()}`},
236 {`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `unsafe.Pointer`},
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 {brokenPkg + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
332 {brokenPkg + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
333 {brokenPkg + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a, f: b,}}`, `b`, `string`},
334 {brokenPkg + `x3; var x = panic("");`, `panic`, `func(interface{})`},
335 {`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
336 {brokenPkg + `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 {brokenPkg + `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[syntax.Expr]TypeAndValue)}
411 if strings.HasPrefix(test.src, brokenPkg) {
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 syntax.String(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[*syntax.Name]Instance)
624 useMap := make(map[*syntax.Name]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.Name.Value; got != testInst.name {
654 t.Fatalf("got name %s, want %s", got, testInst.name)
657 if len(targs) != len(testInst.targs) {
658 t.Fatalf("got %d type arguments; want %d", len(targs), len(testInst.targs))
660 for i, targ := range targs {
661 if got := targ.String(); got != testInst.targs[i] {
662 t.Errorf("type argument %d: got %s; want %s", i, got, testInst.targs[i])
665 if got := typ.Underlying().String(); got != testInst.typ {
666 t.Errorf("package %s: got %s; want %s", pkg.Name(), got, testInst.typ)
669 // Verify the invariant that re-instantiating the corresponding generic
670 // type with TypeArgs results in an identical instance.
671 ptype := useMap[inst.Name].Type()
672 lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
673 if lister == nil || lister.TypeParams().Len() == 0 {
674 t.Fatalf("info.Types[%v] = %v, want parameterized type", inst.Name, ptype)
676 inst2, err := Instantiate(nil, ptype, targs, true)
678 t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
680 if !Identical(inst.Inst.Type, inst2) {
681 t.Errorf("%v and %v are not identical", inst.Inst.Type, inst2)
688 type recordedInstance struct {
693 func sortedInstances(m map[*syntax.Name]Instance) (instances []recordedInstance) {
694 for id, inst := range m {
695 instances = append(instances, recordedInstance{id, inst})
697 sort.Slice(instances, func(i, j int) bool {
698 return CmpPos(instances[i].Name.Pos(), instances[j].Name.Pos()) < 0
703 func TestDefsInfo(t *testing.T) {
704 var tests = []struct {
709 {`package p0; const x = 42`, `x`, `const p0.x untyped int`},
710 {`package p1; const x int = 42`, `x`, `const p1.x int`},
711 {`package p2; var x int`, `x`, `var p2.x int`},
712 {`package p3; type x int`, `x`, `type p3.x int`},
713 {`package p4; func f()`, `f`, `func p4.f()`},
714 {`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
716 // Tests using generics.
717 {`package g0; type x[T any] int`, `x`, `type g0.x[T any] int`},
718 {`package g1; func f[T any]() {}`, `f`, `func g1.f[T any]()`},
719 {`package g2; type x[T any] int; func (*x[_]) m() {}`, `m`, `func (*g2.x[_]).m()`},
722 for _, test := range tests {
724 Defs: make(map[*syntax.Name]Object),
726 name := mustTypecheck(test.src, nil, &info).Name()
730 for id, obj := range info.Defs {
731 if id.Value == test.obj {
737 t.Errorf("package %s: %s not found", name, test.obj)
741 if got := def.String(); got != test.want {
742 t.Errorf("package %s: got %s; want %s", name, got, test.want)
747 func TestUsesInfo(t *testing.T) {
748 var tests = []struct {
753 {`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
754 {`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
755 {`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
756 {`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
757 {`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
759 // Tests using generics.
760 {`package g0; func _[T any]() { _ = x }; const x = 42`, `x`, `const g0.x untyped int`},
761 {`package g1; func _[T any](x T) { }`, `T`, `type parameter T any`},
762 {`package g2; type N[A any] int; var _ N[int]`, `N`, `type g2.N[A any] int`},
763 {`package g3; type N[A any] int; func (N[_]) m() {}`, `N`, `type g3.N[A any] int`},
765 // Uses of fields are instantiated.
766 {`package s1; type N[A any] struct{ a A }; var f = N[int]{}.a`, `a`, `field a int`},
767 {`package s1; type N[A any] struct{ a A }; func (r N[B]) m(b B) { r.a = b }`, `a`, `field a B`},
769 // Uses of methods are uses of the instantiated method.
770 {`package m0; type N[A any] int; func (r N[B]) m() { r.n() }; func (N[C]) n() {}`, `n`, `func (m0.N[B]).n()`},
771 {`package m1; type N[A any] int; func (r N[B]) m() { }; var f = N[int].m`, `m`, `func (m1.N[int]).m()`},
772 {`package m2; func _[A any](v interface{ m() A }) { v.m() }`, `m`, `func (interface).m() A`},
773 {`package m3; func f[A any]() interface{ m() A } { return nil }; var _ = f[int]().m()`, `m`, `func (interface).m() int`},
774 {`package m4; type T[A any] func() interface{ m() A }; var x T[int]; var y = x().m`, `m`, `func (interface).m() int`},
775 {`package m5; type T[A any] interface{ m() A }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m5.T[B]).m() B`},
776 {`package m6; type T[A any] interface{ m() }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m6.T[B]).m()`},
777 {`package m7; type T[A any] interface{ m() A }; func _(t T[int]) { t.m() }`, `m`, `func (m7.T[int]).m() int`},
778 {`package m8; type T[A any] interface{ m() }; func _(t T[int]) { t.m() }`, `m`, `func (m8.T[int]).m()`},
779 {`package m9; type T[A any] interface{ m() }; func _(t T[int]) { _ = t.m }`, `m`, `func (m9.T[int]).m()`},
781 `package m10; type E[A any] interface{ m() }; type T[B any] interface{ E[B]; n() }; func _(t T[int]) { t.m() }`,
783 `func (m10.E[int]).m()`,
787 for _, test := range tests {
789 Uses: make(map[*syntax.Name]Object),
791 name := mustTypecheck(test.src, nil, &info).Name()
795 for id, obj := range info.Uses {
796 if id.Value == test.obj {
798 panic(fmt.Sprintf("multiple uses of %q", id.Value))
804 t.Errorf("package %s: %s not found", name, test.obj)
808 if got := use.String(); got != test.want {
809 t.Errorf("package %s: got %s; want %s", name, got, test.want)
814 func TestGenericMethodInfo(t *testing.T) {
819 func (r N[B]) m() { r.m(); r.n() }
821 func (r *N[C]) n() { }
825 Defs: make(map[*syntax.Name]Object),
826 Uses: make(map[*syntax.Name]Object),
827 Selections: make(map[*syntax.SelectorExpr]*Selection),
830 pkg, err := conf.Check("p", []*syntax.File{f}, &info)
835 N := pkg.Scope().Lookup("N").Type().(*Named)
837 // Find the generic methods stored on N.
838 gm, gn := N.Method(0), N.Method(1)
839 if gm.Name() == "n" {
843 // Collect objects from info.
844 var dm, dn *Func // the declared methods
845 var dmm, dmn *Func // the methods used in the body of m
846 for _, decl := range f.DeclList {
847 fdecl, ok := decl.(*syntax.FuncDecl)
851 def := info.Defs[fdecl.Name].(*Func)
852 switch fdecl.Name.Value {
855 syntax.Inspect(fdecl.Body, func(n syntax.Node) bool {
856 if call, ok := n.(*syntax.CallExpr); ok {
857 sel := call.Fun.(*syntax.SelectorExpr)
858 use := info.Uses[sel.Sel].(*Func)
859 selection := info.Selections[sel]
860 if selection.Kind() != MethodVal {
861 t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
863 if selection.Obj() != use {
864 t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
866 switch sel.Sel.Value {
881 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
884 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
887 t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
890 t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
894 func TestImplicitsInfo(t *testing.T) {
895 testenv.MustHaveGoBuild(t)
897 var tests = []struct {
901 {`package p2; import . "fmt"; var _ = Println`, ""}, // no Implicits entry
902 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
903 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
905 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
906 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
907 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
908 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
910 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
911 {`package p8; func f(int) {}`, "field: var int"},
912 {`package p9; func f() (complex64) { return 0 }`, "field: var complex64"},
913 {`package p10; type T struct{}; func (*T) f() {}`, "field: var *p10.T"},
915 // Tests using generics.
916 {`package f0; func f[T any](x int) {}`, ""}, // no Implicits entry
917 {`package f1; func f[T any](int) {}`, "field: var int"},
918 {`package f2; func f[T any](T) {}`, "field: var T"},
919 {`package f3; func f[T any]() (complex64) { return 0 }`, "field: var complex64"},
920 {`package f4; func f[T any](t T) (T) { return t }`, "field: var T"},
921 {`package t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var *t0.T[_]"},
922 {`package t1; type T[A any] struct{}; func _(x interface{}) { switch t := x.(type) { case T[int]: _ = t } }`, "caseClause: var t t1.T[int]"},
923 {`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]"},
924 {`package t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
927 for _, test := range tests {
929 Implicits: make(map[syntax.Node]Object),
931 name := mustTypecheck(test.src, nil, &info).Name()
933 // the test cases expect at most one Implicits entry
934 if len(info.Implicits) > 1 {
935 t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
939 // extract Implicits entry, if any
941 for n, obj := range info.Implicits {
942 switch x := n.(type) {
943 case *syntax.ImportDecl:
945 case *syntax.CaseClause:
950 t.Fatalf("package %s: unexpected %T", name, x)
952 got += ": " + obj.String()
956 if got != test.want {
957 t.Errorf("package %s: got %q; want %q", name, got, test.want)
962 func TestPkgNameOf(t *testing.T) {
963 testenv.MustHaveGoBuild(t)
976 // avoid imported and not used errors
985 var tests = []struct {
986 path string // path string enclosed in "'s
992 {`"path/filepath"`, "filepath"},
998 Defs: make(map[*syntax.Name]Object),
999 Implicits: make(map[syntax.Node]Object),
1002 conf.Importer = defaultImporter()
1003 _, err := conf.Check("p", []*syntax.File{f}, &info)
1008 // map import paths to importDecl
1009 imports := make(map[string]*syntax.ImportDecl)
1010 for _, d := range f.DeclList {
1011 if imp, _ := d.(*syntax.ImportDecl); imp != nil {
1012 imports[imp.Path.Value] = imp
1016 for _, test := range tests {
1017 imp := imports[test.path]
1019 t.Fatalf("invalid test case: import path %s not found", test.path)
1021 got := info.PkgNameOf(imp)
1023 t.Fatalf("import %s: package name not found", test.path)
1025 if got.Name() != test.want {
1026 t.Errorf("import %s: got %s; want %s", test.path, got.Name(), test.want)
1030 // test non-existing importDecl
1031 if got := info.PkgNameOf(new(syntax.ImportDecl)); got != nil {
1032 t.Errorf("got %s for non-existing import declaration", got.Name())
1036 func predString(tv TypeAndValue) string {
1037 var buf strings.Builder
1038 pred := func(b bool, s string) {
1041 buf.WriteString(", ")
1047 pred(tv.IsVoid(), "void")
1048 pred(tv.IsType(), "type")
1049 pred(tv.IsBuiltin(), "builtin")
1050 pred(tv.IsValue() && tv.Value != nil, "const")
1051 pred(tv.IsValue() && tv.Value == nil, "value")
1052 pred(tv.IsNil(), "nil")
1053 pred(tv.Addressable(), "addressable")
1054 pred(tv.Assignable(), "assignable")
1055 pred(tv.HasOk(), "hasOk")
1063 func TestPredicatesInfo(t *testing.T) {
1064 testenv.MustHaveGoBuild(t)
1066 var tests = []struct {
1072 {`package n0; func f() { f() }`, `f()`, `void`},
1075 {`package t0; type _ int`, `int`, `type`},
1076 {`package t1; type _ []int`, `[]int`, `type`},
1077 {`package t2; type _ func()`, `func()`, `type`},
1078 {`package t3; type _ func(int)`, `int`, `type`},
1079 {`package t3; type _ func(...int)`, `...int`, `type`},
1082 {`package b0; var _ = len("")`, `len`, `builtin`},
1083 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
1086 {`package c0; var _ = 42`, `42`, `const`},
1087 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
1088 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
1091 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
1092 {`package v1; var _ = &[]int{1}`, `[]int{…}`, `value`},
1093 {`package v2; var _ = func(){}`, `func() {}`, `value`},
1094 {`package v4; func f() { _ = f }`, `f`, `value`},
1095 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
1096 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
1098 // addressable (and thus assignable) operands
1099 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
1100 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
1101 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
1102 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
1103 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
1104 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
1105 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
1106 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
1107 // composite literals are not addressable
1109 // assignable but not addressable values
1110 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1111 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
1113 // hasOk expressions
1114 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
1115 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
1118 // - package names are collected in the Uses map
1119 // - identifiers being declared are collected in the Defs map
1120 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
1121 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
1122 {`package m2; const c = 0`, `c`, `<missing>`},
1123 {`package m3; type T int`, `T`, `<missing>`},
1124 {`package m4; var v int`, `v`, `<missing>`},
1125 {`package m5; func f() {}`, `f`, `<missing>`},
1126 {`package m6; func _(x int) {}`, `x`, `<missing>`},
1127 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
1128 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
1131 for _, test := range tests {
1132 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
1133 name := mustTypecheck(test.src, nil, &info).Name()
1135 // look for expression predicates
1137 for e, tv := range info.Types {
1138 //println(name, syntax.String(e))
1139 if syntax.String(e) == test.expr {
1140 got = predString(tv)
1145 if got != test.pred {
1146 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
1151 func TestScopesInfo(t *testing.T) {
1152 testenv.MustHaveGoBuild(t)
1154 var tests = []struct {
1156 scopes []string // list of scope descriptors of the form kind:varlist
1158 {`package p0`, []string{
1161 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
1164 {`package p2; func _() {}`, []string{
1167 {`package p3; func _(x, y int) {}`, []string{
1168 "file:", "func:x y",
1170 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
1171 "file:", "func:x y z", // redeclaration of x
1173 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
1174 "file:", "func:u x y",
1176 {`package p6; func _() { { var x int; _ = x } }`, []string{
1177 "file:", "func:", "block:x",
1179 {`package p7; func _() { if true {} }`, []string{
1180 "file:", "func:", "if:", "block:",
1182 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
1183 "file:", "func:", "if:x", "block:y",
1185 {`package p9; func _() { switch x := 0; x {} }`, []string{
1186 "file:", "func:", "switch:x",
1188 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
1189 "file:", "func:", "switch:x", "case:y", "case:",
1191 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
1192 "file:", "func:t", "switch:",
1194 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
1195 "file:", "func:t", "switch:t",
1197 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
1198 "file:", "func:t", "switch:", "case:x", // x implicitly declared
1200 {`package p14; func _() { select{} }`, []string{
1203 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
1204 "file:", "func:c", "comm:",
1206 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
1207 "file:", "func:c", "comm:i x",
1209 {`package p17; func _() { for{} }`, []string{
1210 "file:", "func:", "for:", "block:",
1212 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
1213 "file:", "func:n", "for:i", "block:",
1215 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
1216 "file:", "func:a", "for:i", "block:",
1218 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
1219 "file:", "func:a", "for:i x", "block:",
1223 for _, test := range tests {
1224 info := Info{Scopes: make(map[syntax.Node]*Scope)}
1225 name := mustTypecheck(test.src, nil, &info).Name()
1227 // number of scopes must match
1228 if len(info.Scopes) != len(test.scopes) {
1229 t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
1232 // scope descriptions must match
1233 for node, scope := range info.Scopes {
1235 switch node.(type) {
1238 case *syntax.FuncType:
1240 case *syntax.BlockStmt:
1242 case *syntax.IfStmt:
1244 case *syntax.SwitchStmt:
1246 case *syntax.SelectStmt:
1248 case *syntax.CaseClause:
1250 case *syntax.CommClause:
1252 case *syntax.ForStmt:
1255 kind = fmt.Sprintf("%T", node)
1258 // look for matching scope description
1259 desc := kind + ":" + strings.Join(scope.Names(), " ")
1261 for _, d := range test.scopes {
1268 t.Errorf("package %s: no matching scope found for %s", name, desc)
1274 func TestInitOrderInfo(t *testing.T) {
1275 var tests = []struct {
1279 {`package p0; var (x = 1; y = x)`, []string{
1282 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
1283 "a = 1", "b = 2", "c = 3",
1285 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
1286 "a = 1", "b = 2", "c = 3",
1288 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
1289 "_ = f()", // blank var
1291 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
1292 "a = 0", "z = 0", "y = z", "x = y",
1294 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
1295 "a, _ = m[0]", // blank var
1297 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
1298 "z = 0", "a, b = f()",
1300 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
1301 "b = 1", "a = func() int {…}()",
1303 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
1304 "c = 1", "a, b = func() (_, _ int) {…}()",
1306 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1309 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1310 "a = 0", "b = 0", "c = 0", "d = c + b",
1312 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
1313 "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
1315 // emit an initializer for n:1 initializations only once (not for each node
1316 // on the lhs which may appear in different order in the dependency graph)
1317 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
1318 "b = 0", "x, y = m[0]", "a = x",
1320 // test case from spec section on package initialization
1334 "d = 3", "b = f()", "c = f()", "a = c + b",
1336 // test case for go.dev/issue/7131
1340 func next() int { counter++; return counter }
1343 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1346 var b, c = next(), next()
1347 var d, e, f = next(), next(), next()
1349 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1351 // test case for go.dev/issue/10709
1361 func (T) m() int { return 0 }
1363 func makeT(n int) T {
1369 "t = makeT(0)", "v = t.m()",
1371 // test case for go.dev/issue/10709: same as test before, but variable decls swapped
1381 func (T) m() int { return 0 }
1383 func makeT(n int) T {
1389 "t = makeT(0)", "v = t.m()",
1391 // another candidate possibly causing problems with go.dev/issue/10709
1396 func f1() int { return g1() }
1397 func g1() int { f1(); return x1 }
1403 func f2() int { return g2() }
1404 func g2() int { return x2 }
1406 var x2 = 0`, []string{
1407 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1411 for _, test := range tests {
1413 name := mustTypecheck(test.src, nil, &info).Name()
1415 // number of initializers must match
1416 if len(info.InitOrder) != len(test.inits) {
1417 t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1421 // initializers must match
1422 for i, want := range test.inits {
1423 got := info.InitOrder[i].String()
1425 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1432 func TestMultiFileInitOrder(t *testing.T) {
1433 fileA := mustParse(`package main; var a = 1`)
1434 fileB := mustParse(`package main; var b = 2`)
1436 // The initialization order must not depend on the parse
1437 // order of the files, only on the presentation order to
1438 // the type-checker.
1439 for _, test := range []struct {
1440 files []*syntax.File
1443 {[]*syntax.File{fileA, fileB}, "[a = 1 b = 2]"},
1444 {[]*syntax.File{fileB, fileA}, "[b = 2 a = 1]"},
1447 if _, err := new(Config).Check("main", test.files, &info); err != nil {
1450 if got := fmt.Sprint(info.InitOrder); got != test.want {
1451 t.Fatalf("got %s; want %s", got, test.want)
1456 func TestFiles(t *testing.T) {
1457 var sources = []string{
1458 "package p; type T struct{}; func (T) m1() {}",
1459 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1460 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1465 pkg := NewPackage("p", "p")
1467 check := NewChecker(&conf, pkg, &info)
1469 for _, src := range sources {
1470 if err := check.Files([]*syntax.File{mustParse(src)}); err != nil {
1475 // check InitOrder is [x y]
1477 for _, init := range info.InitOrder {
1478 for _, v := range init.Lhs {
1479 vars = append(vars, v.Name())
1482 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1483 t.Errorf("InitOrder == %s, want %s", got, want)
1487 type testImporter map[string]*Package
1489 func (m testImporter) Import(path string) (*Package, error) {
1490 if pkg := m[path]; pkg != nil {
1493 return nil, fmt.Errorf("package %q not found", path)
1496 func TestSelection(t *testing.T) {
1497 selections := make(map[*syntax.SelectorExpr]*Selection)
1499 imports := make(testImporter)
1500 conf := Config{Importer: imports}
1501 makePkg := func(path, src string) {
1502 pkg := mustTypecheck(src, &conf, &Info{Selections: selections})
1533 type G[P any] struct {
1545 // qualified identifiers
1583 // method expressions
1591 wantOut := map[string][2]string{
1592 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1594 "A{}.B": {"field (main.A) B *main.B", ".[0]"},
1595 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1596 "A{}.C": {"field (main.A) C main.C", ".[1]"},
1597 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1598 "A{}.b": {"field (main.A) b int", "->[0 0]"},
1599 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1600 "A{}.c": {"field (main.A) c int", ".[1 0]"},
1601 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1602 "Inst.p": {"field (main.G[int]) p int", ".[0]"},
1604 "A{}.f": {"method (main.A) f(int)", "->[0 0]"},
1605 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1606 "A{}.g": {"method (main.A) g()", ".[1 0]"},
1607 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1608 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1609 "B{}.f": {"method (main.B) f(int)", ".[0]"},
1610 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1611 "C{}.g": {"method (main.C) g()", ".[0]"},
1612 "new(C).g": {"method (*main.C) g()", "->[0]"},
1613 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1614 "Inst.m": {"method (main.G[int]) m(int)", ".[0]"},
1616 "A.f": {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1617 "(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1618 "B.f": {"method expr (main.B) f(main.B, int)", ".[0]"},
1619 "(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1620 "G[string].m": {"method expr (main.G[string]) m(main.G[string], string)", ".[0]"},
1621 "G[string]{}.p": {"field (main.G[string]) p string", ".[0]"},
1624 makePkg("lib", libSrc)
1625 makePkg("main", mainSrc)
1627 for e, sel := range selections {
1628 _ = sel.String() // assertion: must not panic
1630 start := indexFor(mainSrc, syntax.StartPos(e))
1631 end := indexFor(mainSrc, syntax.EndPos(e))
1632 segment := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1640 fmt.Sprintf("%s%v", direct, sel.Index()),
1642 want := wantOut[segment]
1644 t.Errorf("%s: got %q; want %q", segment, got, want)
1646 delete(wantOut, segment)
1648 // We must explicitly assert properties of the
1649 // Signature's receiver since it doesn't participate
1650 // in Identical() or String().
1651 sig, _ := sel.Type().(*Signature)
1652 if sel.Kind() == MethodVal {
1653 got := sig.Recv().Type()
1655 if !Identical(got, want) {
1656 t.Errorf("%s: Recv() = %s, want %s", segment, got, want)
1658 } else if sig != nil && sig.Recv() != nil {
1659 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1662 // Assert that all wantOut entries were used exactly once.
1663 for segment := range wantOut {
1664 t.Errorf("no syntax.Selection found with syntax %q", segment)
1668 // indexFor returns the index into s corresponding to the position pos.
1669 func indexFor(s string, pos syntax.Pos) int {
1670 i, line := 0, 1 // string index and corresponding line
1671 target := int(pos.Line())
1672 for line < target && i < len(s) {
1678 return i + int(pos.Col()-1) // columns are 1-based
1681 func TestIssue8518(t *testing.T) {
1682 imports := make(testImporter)
1684 Error: func(err error) { t.Log(err) }, // don't exit after first error
1687 makePkg := func(path, src string) {
1688 imports[path], _ = conf.Check(path, []*syntax.File{mustParse(src)}, nil) // errors logged via conf.Error
1695 const C2 = missing.C
1705 makePkg("a", libSrc)
1706 makePkg("main", mainSrc) // don't crash when type-checking this package
1709 func TestIssue59603(t *testing.T) {
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, []*syntax.File{mustParse(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).
1750 var tests = []struct {
1757 {"var x T; type T struct{}", false, nil, false},
1758 {"var x T; type T struct{ f int }", true, []int{0}, false},
1759 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1761 // field lookups on a generic type
1762 {"var x T[int]; type T[P any] struct{}", false, nil, false},
1763 {"var x T[int]; type T[P any] struct{ f P }", true, []int{0}, false},
1764 {"var x T[int]; type T[P any] struct{ a, b, f, c P }", true, []int{2}, false},
1767 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1768 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
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}, // TODO(gri) should this report indirect = false?
1772 // method lookups on a generic type
1773 {"var a T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, false},
1774 {"var a *T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, true},
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}, // TODO(gri) should this report indirect = false?
1779 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1780 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1782 // collisions on a generic type
1783 {"type ( E1[P any] struct{ f P }; E2[P any] struct{ f P }; x struct{ E1[int]; *E2[int] })", false, []int{1, 0}, false},
1784 {"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},
1786 // outside methodset
1787 // (*T).f method exists, but value of type T is not addressable
1788 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1790 // outside method set of a generic type
1791 {"var x T[int]; type T[P any] struct{}; func (*T[P]) f() {}", false, nil, true},
1793 // recursive generic types; see go.dev/issue/52715
1794 {"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},
1795 {"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},
1798 for _, test := range tests {
1799 pkg := mustTypecheck("package p;"+test.src, nil, nil)
1801 obj := pkg.Scope().Lookup("a")
1803 if obj = pkg.Scope().Lookup("x"); obj == nil {
1804 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1809 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1810 if (f != nil) != test.found {
1812 t.Errorf("%s: got no object; want one", test.src)
1814 t.Errorf("%s: got object = %v; want none", test.src, f)
1817 if !sameSlice(index, test.index) {
1818 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1820 if indirect != test.indirect {
1821 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1826 // Test for go.dev/issue/52715
1827 func TestLookupFieldOrMethod_RecursiveGeneric(t *testing.T) {
1831 type Tree[T any] struct {
1835 func (*Tree[R]) N(r R) R { return r }
1837 type Node[T any] struct {
1841 type Instance = *Tree[int]
1845 pkg := NewPackage("pkg", f.PkgName.Value)
1846 if err := NewChecker(nil, pkg, nil).Files([]*syntax.File{f}); err != nil {
1850 T := pkg.Scope().Lookup("Instance").Type()
1851 _, _, _ = LookupFieldOrMethod(T, false, pkg, "M") // verify that LookupFieldOrMethod terminates
1854 func sameSlice(a, b []int) bool {
1855 if len(a) != len(b) {
1858 for i, x := range a {
1866 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1867 // the correct result at various positions within the source.
1868 func TestScopeLookupParent(t *testing.T) {
1869 imports := make(testImporter)
1870 conf := Config{Importer: imports}
1872 makePkg := func(path, src string) {
1874 imports[path], err = conf.Check(path, []*syntax.File{mustParse(src)}, &info)
1880 makePkg("lib", "package lib; var X int")
1881 // Each /*name=kind:line*/ comment makes the test look up the
1882 // name at that point and checks that it resolves to a decl of
1883 // the specified kind and line number. "undef" means undefined.
1885 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1896 const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1897 type /*t=undef*/ t /*t=typename:14*/ *t
1898 print(Y) /*Y=var:10*/
1899 x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1900 var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1903 for i, x := range a /*i=undef*/ /*x=var:16*/ { _ = i; _ = x }
1906 switch y := i.(type) { /*y=undef*/
1907 case /*y=undef*/ int /*y=var:23*/ :
1908 case float32, /*y=undef*/ float64 /*y=var:23*/ :
1909 default /*y=var:23*/:
1914 switch int := i.(type) {
1915 case /*int=typename:0*/ int /*int=var:31*/ :
1917 default /*int=var:31*/ :
1923 info.Uses = make(map[*syntax.Name]Object)
1924 makePkg("main", mainSrc)
1925 mainScope := imports["main"].Scope()
1927 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1929 base := syntax.NewFileBase("main")
1930 syntax.CommentsDo(strings.NewReader(mainSrc), func(line, col uint, text string) {
1931 pos := syntax.MakePos(base, line, col)
1933 // Syntax errors are not comments.
1935 t.Errorf("%s: %s", pos, text)
1939 // Parse the assertion in the comment.
1940 m := rx.FindStringSubmatch(text)
1942 t.Errorf("%s: bad comment: %s", pos, text)
1945 name, want := m[1], m[2]
1947 // Look up the name in the innermost enclosing scope.
1948 inner := mainScope.Innermost(pos)
1950 t.Errorf("%s: at %s: can't find innermost scope", pos, text)
1954 if _, obj := inner.LookupParent(name, pos); obj != nil {
1955 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types2."))
1956 got = fmt.Sprintf("%s:%d", kind, obj.Pos().Line())
1959 t.Errorf("%s: at %s: %s resolved to %s, want %s", pos, text, name, got, want)
1963 // Check that for each referring identifier,
1964 // a lookup of its name on the innermost
1965 // enclosing scope returns the correct object.
1967 for id, wantObj := range info.Uses {
1968 inner := mainScope.Innermost(id.Pos())
1970 t.Errorf("%s: can't find innermost scope enclosing %q", id.Pos(), id.Value)
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.)
1978 if id.Value == "X" {
1982 _, gotObj := inner.LookupParent(id.Value, id.Pos())
1983 if gotObj != wantObj {
1984 t.Errorf("%s: got %v, want %v", id.Pos(), gotObj, wantObj)
1990 // newDefined creates a new defined type named T with the given underlying type.
1991 func newDefined(underlying Type) *Named {
1992 tname := NewTypeName(nopos, nil, "T", nil)
1993 return NewNamed(tname, underlying, nil)
1996 func TestConvertibleTo(t *testing.T) {
1997 for _, test := range []struct {
2001 {Typ[Int], Typ[Int], true},
2002 {Typ[Int], Typ[Float32], true},
2003 {Typ[Int], Typ[String], true},
2004 {newDefined(Typ[Int]), Typ[Int], true},
2005 {newDefined(new(Struct)), new(Struct), true},
2006 {newDefined(Typ[Int]), new(Struct), false},
2007 {Typ[UntypedInt], Typ[Int], true},
2008 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), true},
2009 {NewSlice(Typ[Int]), NewArray(Typ[Uint], 10), false},
2010 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
2011 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
2012 // Untyped string values are not permitted by the spec, so the behavior below is undefined.
2013 {Typ[UntypedString], Typ[String], true},
2015 if got := ConvertibleTo(test.v, test.t); got != test.want {
2016 t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
2021 func TestAssignableTo(t *testing.T) {
2022 for _, test := range []struct {
2026 {Typ[Int], Typ[Int], true},
2027 {Typ[Int], Typ[Float32], false},
2028 {newDefined(Typ[Int]), Typ[Int], false},
2029 {newDefined(new(Struct)), new(Struct), true},
2030 {Typ[UntypedBool], Typ[Bool], true},
2031 {Typ[UntypedString], Typ[Bool], false},
2032 // Neither untyped string nor untyped numeric assignments arise during
2033 // normal type checking, so the below behavior is technically undefined by
2035 {Typ[UntypedString], Typ[String], true},
2036 {Typ[UntypedInt], Typ[Int], true},
2038 if got := AssignableTo(test.v, test.t); got != test.want {
2039 t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
2044 func TestIdentical(t *testing.T) {
2045 // For each test, we compare the types of objects X and Y in the source.
2051 {"var X int; var Y int", true},
2052 {"var X int; var Y string", false},
2054 // TODO: add more tests for complex types.
2057 {"type X int; type Y int", false},
2060 {"type X = int; type Y = int", true},
2063 {`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
2064 {`func X() string { return "" }; func Y(int) string { return "" }`, false},
2065 {`func X(int) string { return "" }; func Y(int) {}`, false},
2067 // Generic functions. Type parameters should be considered identical modulo
2068 // renaming. See also go.dev/issue/49722.
2069 {`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
2070 {`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
2071 {`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
2072 {`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
2073 {`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
2074 {`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
2077 for _, test := range tests {
2078 pkg := mustTypecheck("package p;"+test.src, nil, nil)
2079 X := pkg.Scope().Lookup("X")
2080 Y := pkg.Scope().Lookup("Y")
2081 if X == nil || Y == nil {
2082 t.Fatal("test must declare both X and Y")
2084 if got := Identical(X.Type(), Y.Type()); got != test.want {
2085 t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
2090 func TestIdentical_issue15173(t *testing.T) {
2091 // Identical should allow nil arguments and be symmetric.
2092 for _, test := range []struct {
2096 {Typ[Int], Typ[Int], true},
2097 {Typ[Int], nil, false},
2098 {nil, Typ[Int], false},
2101 if got := Identical(test.x, test.y); got != test.want {
2102 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2107 func TestIdenticalUnions(t *testing.T) {
2108 tname := NewTypeName(nopos, nil, "myInt", nil)
2109 myInt := NewNamed(tname, Typ[Int], nil)
2110 tmap := map[string]*Term{
2111 "int": NewTerm(false, Typ[Int]),
2112 "~int": NewTerm(true, Typ[Int]),
2113 "string": NewTerm(false, Typ[String]),
2114 "~string": NewTerm(true, Typ[String]),
2115 "myInt": NewTerm(false, myInt),
2117 makeUnion := func(s string) *Union {
2118 parts := strings.Split(s, "|")
2120 for _, p := range parts {
2123 t.Fatalf("missing term %q", p)
2125 terms = append(terms, term)
2127 return NewUnion(terms)
2129 for _, test := range []struct {
2133 // These tests are just sanity checks. The tests for type sets and
2134 // interfaces provide much more test coverage.
2135 {"int|~int", "~int", true},
2136 {"myInt|~int", "~int", true},
2137 {"int|string", "string|int", true},
2138 {"int|int|string", "string|int", true},
2139 {"myInt|string", "int|string", false},
2141 x := makeUnion(test.x)
2142 y := makeUnion(test.y)
2143 if got := Identical(x, y); got != test.want {
2144 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2149 func TestIssue61737(t *testing.T) {
2150 // This test verifies that it is possible to construct invalid interfaces
2151 // containing duplicate methods using the go/types API.
2153 // It must be possible for importers to construct such invalid interfaces.
2154 // Previously, this panicked.
2156 sig1 := NewSignatureType(nil, nil, nil, NewTuple(NewParam(nopos, nil, "", Typ[Int])), nil, false)
2157 sig2 := NewSignatureType(nil, nil, nil, NewTuple(NewParam(nopos, nil, "", Typ[String])), nil, false)
2160 NewFunc(nopos, nil, "M", sig1),
2161 NewFunc(nopos, nil, "M", sig2),
2164 embeddedMethods := []*Func{
2165 NewFunc(nopos, nil, "M", sig2),
2167 embedded := NewInterfaceType(embeddedMethods, nil)
2168 iface := NewInterfaceType(methods, []Type{embedded})
2169 iface.NumMethods() // unlike go/types, there is no Complete() method, so we complete implicitly
2172 func TestIssue15305(t *testing.T) {
2173 const src = "package p; func f() int16; var _ = f(undef)"
2176 Error: func(err error) {}, // allow errors
2179 Types: make(map[syntax.Expr]TypeAndValue),
2181 conf.Check("p", []*syntax.File{f}, info) // ignore result
2182 for e, tv := range info.Types {
2183 if _, ok := e.(*syntax.CallExpr); ok {
2184 if tv.Type != Typ[Int16] {
2185 t.Errorf("CallExpr has type %v, want int16", tv.Type)
2190 t.Errorf("CallExpr has no type")
2193 // TestCompositeLitTypes verifies that Info.Types registers the correct
2194 // types for composite literal expressions and composite literal type
2196 func TestCompositeLitTypes(t *testing.T) {
2197 for i, test := range []struct {
2200 {`[16]byte{}`, `[16]byte`},
2201 {`[...]byte{}`, `[0]byte`}, // test for go.dev/issue/14092
2202 {`[...]int{1, 2, 3}`, `[3]int`}, // test for go.dev/issue/14092
2203 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for go.dev/issue/14092
2204 {`[]int{}`, `[]int`},
2205 {`map[string]bool{"foo": true}`, `map[string]bool`},
2206 {`struct{}{}`, `struct{}`},
2207 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
2209 f := mustParse(fmt.Sprintf("package p%d; var _ = %s", i, test.lit))
2210 types := make(map[syntax.Expr]TypeAndValue)
2211 if _, err := new(Config).Check("p", []*syntax.File{f}, &Info{Types: types}); err != nil {
2212 t.Fatalf("%s: %v", test.lit, err)
2215 cmptype := func(x syntax.Expr, want string) {
2218 t.Errorf("%s: no Types entry found", test.lit)
2222 t.Errorf("%s: type is nil", test.lit)
2225 if got := tv.Type.String(); got != want {
2226 t.Errorf("%s: got %v, want %s", test.lit, got, want)
2230 // test type of composite literal expression
2231 rhs := f.DeclList[0].(*syntax.VarDecl).Values
2232 cmptype(rhs, test.typ)
2234 // test type of composite literal type expression
2235 cmptype(rhs.(*syntax.CompositeLit).Type, test.typ)
2239 // TestObjectParents verifies that objects have parent scopes or not
2240 // as specified by the Object interface.
2241 func TestObjectParents(t *testing.T) {
2260 func f(x int) { y := x; print(y) }
2266 Defs: make(map[*syntax.Name]Object),
2268 if _, err := new(Config).Check("p", []*syntax.File{f}, info); err != nil {
2272 for ident, obj := range info.Defs {
2274 // only package names and implicit vars have a nil object
2275 // (in this test we only need to handle the package name)
2276 if ident.Value != "p" {
2277 t.Errorf("%v has nil object", ident)
2282 // struct fields, type-associated and interface methods
2283 // have no parent scope
2285 switch obj := obj.(type) {
2291 if obj.Type().(*Signature).Recv() != nil { // method
2296 gotParent := obj.Parent() != nil
2298 case gotParent && !wantParent:
2299 t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
2300 case !gotParent && wantParent:
2301 t.Errorf("%v: no parent found", ident)
2306 // TestFailedImport tests that we don't get follow-on errors
2307 // elsewhere in a package due to failing to import a package.
2308 func TestFailedImport(t *testing.T) {
2309 testenv.MustHaveGoBuild(t)
2314 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
2319 func f(x T) T { return foo.F(x) }
2322 files := []*syntax.File{f}
2324 // type-check using all possible importers
2325 for _, compiler := range []string{"gc", "gccgo", "source"} {
2328 Error: func(err error) {
2329 // we should only see the import error
2330 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
2331 t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
2335 //Importer: importer.For(compiler, nil),
2339 Uses: make(map[*syntax.Name]Object),
2341 pkg, _ := conf.Check("p", files, info)
2343 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
2347 imports := pkg.Imports()
2348 if len(imports) != 1 {
2349 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
2353 if imp.Name() != "foo" {
2354 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
2358 // verify that all uses of foo refer to the imported package foo (imp)
2359 for ident, obj := range info.Uses {
2360 if ident.Value == "foo" {
2361 if obj, ok := obj.(*PkgName); ok {
2362 if obj.Imported() != imp {
2363 t.Errorf("%s resolved to %v; want %v", ident.Value, obj.Imported(), imp)
2366 t.Errorf("%s resolved to %v; want package name", ident.Value, obj)
2373 func TestInstantiate(t *testing.T) {
2374 // eventually we like more tests but this is a start
2375 const src = "package p; type T[P any] *T[P]"
2376 pkg := mustTypecheck(src, nil, nil)
2378 // type T should have one type parameter
2379 T := pkg.Scope().Lookup("T").Type().(*Named)
2380 if n := T.TypeParams().Len(); n != 1 {
2381 t.Fatalf("expected 1 type parameter; found %d", n)
2384 // instantiation should succeed (no endless recursion)
2385 // even with a nil *Checker
2386 res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
2391 // instantiated type should point to itself
2392 if p := res.Underlying().(*Pointer).Elem(); p != res {
2393 t.Fatalf("unexpected result type: %s points to %s", res, p)
2397 func TestInstantiateConcurrent(t *testing.T) {
2398 const src = `package p
2400 type I[P any] interface {
2407 type Nested[P any] *interface{b(P)}
2409 type K = Nested[string]
2411 pkg := mustTypecheck(src, nil, nil)
2413 insts := []*Interface{
2414 pkg.Scope().Lookup("J").Type().Underlying().(*Interface),
2415 pkg.Scope().Lookup("K").Type().Underlying().(*Pointer).Elem().(*Interface),
2418 // Use the interface instances concurrently.
2419 for _, inst := range insts {
2421 counts [2]int // method counts
2422 methods [2][]string // method strings
2424 var wg sync.WaitGroup
2425 for i := 0; i < 2; i++ {
2431 counts[i] = inst.NumMethods()
2432 for mi := 0; mi < counts[i]; mi++ {
2433 methods[i] = append(methods[i], inst.Method(mi).String())
2439 if counts[0] != counts[1] {
2440 t.Errorf("mismatching method counts for %s: %d vs %d", inst, counts[0], counts[1])
2443 for i := 0; i < counts[0]; i++ {
2444 if m0, m1 := methods[0][i], methods[1][i]; m0 != m1 {
2445 t.Errorf("mismatching methods for %s: %s vs %s", inst, m0, m1)
2451 func TestInstantiateErrors(t *testing.T) {
2453 src string // by convention, T must be the type being instantiated
2455 wantAt int // -1 indicates no error
2457 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
2458 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
2459 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
2460 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
2463 for _, test := range tests {
2464 src := "package p; " + test.src
2465 pkg := mustTypecheck(src, nil, nil)
2467 T := pkg.Scope().Lookup("T").Type().(*Named)
2469 _, err := Instantiate(nil, T, test.targs, true)
2471 t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
2474 var argErr *ArgumentError
2475 if !errors.As(err, &argErr) {
2476 t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
2479 if argErr.Index != test.wantAt {
2480 t.Errorf("Instantiate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2485 func TestArgumentErrorUnwrapping(t *testing.T) {
2486 var err error = &ArgumentError{
2488 Err: Error{Msg: "test"},
2491 if !errors.As(err, &e) {
2492 t.Fatalf("error %v does not wrap types.Error", err)
2494 if e.Msg != "test" {
2495 t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2499 func TestInstanceIdentity(t *testing.T) {
2500 imports := make(testImporter)
2501 conf := Config{Importer: imports}
2502 makePkg := func(src string) {
2504 name := f.PkgName.Value
2505 pkg, err := conf.Check(name, []*syntax.File{f}, nil)
2511 makePkg(`package lib; type T[P any] struct{}`)
2512 makePkg(`package a; import "lib"; var A lib.T[int]`)
2513 makePkg(`package b; import "lib"; var B lib.T[int]`)
2514 a := imports["a"].Scope().Lookup("A")
2515 b := imports["b"].Scope().Lookup("B")
2516 if !Identical(a.Type(), b.Type()) {
2517 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
2521 // TestInstantiatedObjects verifies properties of instantiated objects.
2522 func TestInstantiatedObjects(t *testing.T) {
2526 type T[P any] struct {
2530 func (recv *T[Q]) concreteMethod(mParam Q) (mResult Q) { return }
2532 type FT[P any] func(ftParam P) (ftResult P)
2534 func F[P any](fParam P) (fResult P){ return }
2536 type I[P any] interface {
2542 func (R[P]) m() {} // having a method triggers expansion of R
2557 Defs: make(map[*syntax.Name]Object),
2561 pkg, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
2566 lookup := func(name string) Type { return pkg.Scope().Lookup(name).Type() }
2567 fnScope := pkg.Scope().Lookup("fn").(*Func).Scope()
2574 {"field", lookup("t").Underlying().(*Struct).Field(0)},
2575 {"field", fnScope.Lookup("r").Type().Underlying().(*Struct).Field(0)},
2577 // Methods and method fields
2578 {"concreteMethod", lookup("t").(*Named).Method(0)},
2579 {"recv", lookup("t").(*Named).Method(0).Type().(*Signature).Recv()},
2580 {"mParam", lookup("t").(*Named).Method(0).Type().(*Signature).Params().At(0)},
2581 {"mResult", lookup("t").(*Named).Method(0).Type().(*Signature).Results().At(0)},
2583 // Interface methods
2584 {"interfaceMethod", lookup("i").Underlying().(*Interface).Method(0)},
2586 // Function type fields
2587 {"ftParam", lookup("ft").Underlying().(*Signature).Params().At(0)},
2588 {"ftResult", lookup("ft").Underlying().(*Signature).Results().At(0)},
2591 {"fParam", lookup("f").(*Signature).Params().At(0)},
2592 {"fResult", lookup("f").(*Signature).Results().At(0)},
2595 // Collect all identifiers by name.
2596 idents := make(map[string][]*syntax.Name)
2597 syntax.Inspect(f, func(n syntax.Node) bool {
2598 if id, ok := n.(*syntax.Name); ok {
2599 idents[id.Value] = append(idents[id.Value], id)
2604 for _, test := range tests {
2606 t.Run(test.name, func(t *testing.T) {
2607 if got := len(idents[test.name]); got != 1 {
2608 t.Fatalf("found %d identifiers named %s, want 1", got, test.name)
2610 ident := idents[test.name][0]
2611 def := info.Defs[ident]
2612 if def == test.obj {
2613 t.Fatalf("info.Defs[%s] contains the test object", test.name)
2615 if orig := originObject(test.obj); def != orig {
2616 t.Errorf("info.Defs[%s] does not match obj.Origin()", test.name)
2618 if def.Pkg() != test.obj.Pkg() {
2619 t.Errorf("Pkg() = %v, want %v", def.Pkg(), test.obj.Pkg())
2621 if def.Name() != test.obj.Name() {
2622 t.Errorf("Name() = %v, want %v", def.Name(), test.obj.Name())
2624 if def.Pos() != test.obj.Pos() {
2625 t.Errorf("Pos() = %v, want %v", def.Pos(), test.obj.Pos())
2627 if def.Parent() != test.obj.Parent() {
2628 t.Fatalf("Parent() = %v, want %v", def.Parent(), test.obj.Parent())
2630 if def.Exported() != test.obj.Exported() {
2631 t.Fatalf("Exported() = %v, want %v", def.Exported(), test.obj.Exported())
2633 if def.Id() != test.obj.Id() {
2634 t.Fatalf("Id() = %v, want %v", def.Id(), test.obj.Id())
2636 // String and Type are expected to differ.
2641 func originObject(obj Object) Object {
2642 switch obj := obj.(type) {
2651 func TestImplements(t *testing.T) {
2655 type EmptyIface interface{}
2666 type Integer interface{
2667 int8 | int16 | int32 | int64
2670 type EmptyTypeSet interface{
2687 type Bad Bad // invalid type
2691 conf := Config{Error: func(error) {}}
2692 pkg, _ := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
2694 lookup := func(tname string) Type { return pkg.Scope().Lookup(tname).Type() }
2696 EmptyIface = lookup("EmptyIface").Underlying().(*Interface)
2697 I = lookup("I").(*Named)
2698 II = I.Underlying().(*Interface)
2699 C = lookup("C").(*Named)
2700 CI = C.Underlying().(*Interface)
2701 Integer = lookup("Integer").Underlying().(*Interface)
2702 EmptyTypeSet = lookup("EmptyTypeSet").Underlying().(*Interface)
2704 N1p = NewPointer(N1)
2706 N2p = NewPointer(N2)
2721 {Typ[Int8], Integer, true},
2722 {Typ[Int64], Integer, true},
2723 {Typ[String], Integer, false},
2724 {EmptyTypeSet, II, true},
2725 {EmptyTypeSet, EmptyTypeSet, true},
2726 {Typ[Int], EmptyTypeSet, false},
2741 {Bad, EmptyIface, true},
2744 for _, test := range tests {
2745 if got := Implements(test.V, test.T); got != test.want {
2746 t.Errorf("Implements(%s, %s) = %t, want %t", test.V, test.T, got, test.want)
2749 // The type assertion x.(T) is valid if T is an interface or if T implements the type of x.
2750 // The assertion is never valid if T is a bad type.
2754 if _, ok := T.Underlying().(*Interface); (ok || Implements(T, V)) && T != Bad {
2757 if got := AssertableTo(V, T); got != want {
2758 t.Errorf("AssertableTo(%s, %s) = %t, want %t", V, T, got, want)
2763 func TestMissingMethodAlternative(t *testing.T) {
2785 pkg := mustTypecheck(src, nil, nil)
2787 T := pkg.Scope().Lookup("T").Type().Underlying().(*Interface)
2788 lookup := func(name string) (*Func, bool) {
2789 return MissingMethod(pkg.Scope().Lookup(name).Type(), T, true)
2792 // V0 has method m with correct signature. Should not report wrongType.
2793 method, wrongType := lookup("V0")
2794 if method != nil || wrongType {
2795 t.Fatalf("V0: got method = %v, wrongType = %v", method, wrongType)
2798 checkMissingMethod := func(tname string, reportWrongType bool) {
2799 method, wrongType := lookup(tname)
2800 if method == nil || method.Name() != "m" || wrongType != reportWrongType {
2801 t.Fatalf("%s: got method = %v, wrongType = %v", tname, method, wrongType)
2805 // V1 has no method m. Should not report wrongType.
2806 checkMissingMethod("V1", false)
2808 // V2 has method m with wrong signature type (ignoring receiver). Should report wrongType.
2809 checkMissingMethod("V2", true)
2811 // V3 has no method m but it exists on *V3. Should report wrongType.
2812 checkMissingMethod("V3", true)
2814 // V4 has no method m but has M. Should not report wrongType.
2815 checkMissingMethod("V4", false)
2818 func TestErrorURL(t *testing.T) {
2819 conf := Config{ErrorURL: " [go.dev/e/%s]"}
2821 // test case for a one-line error
2826 _, err := typecheck(src1, &conf, nil)
2827 if err == nil || !strings.HasSuffix(err.Error(), " [go.dev/e/UndeclaredName]") {
2828 t.Errorf("src1: unexpected error: got %v", err)
2831 // test case for a multi-line error
2834 func f() int { return 0 }
2837 _, err = typecheck(src2, &conf, nil)
2838 if err == nil || !strings.Contains(err.Error(), " [go.dev/e/WrongArgCount]\n") {
2839 t.Errorf("src1: unexpected error: got %v", err)
2843 func TestModuleVersion(t *testing.T) {
2844 // version go1.dd must be able to typecheck go1.dd.0, go1.dd.1, etc.
2845 goversion := fmt.Sprintf("go1.%d", goversion.Version)
2846 for _, v := range []string{
2852 conf := Config{GoVersion: v}
2853 pkg := mustTypecheck("package p", &conf, nil)
2854 if pkg.GoVersion() != conf.GoVersion {
2855 t.Errorf("got %s; want %s", pkg.GoVersion(), conf.GoVersion)
2860 func TestFileVersions(t *testing.T) {
2861 for _, test := range []struct {
2866 {"", "", ""}, // no versions specified
2867 {"go1.19", "", "go1.19"}, // module version specified
2868 {"", "go1.20", ""}, // file upgrade ignored
2869 {"go1.19", "go1.20", "go1.20"}, // file upgrade permitted
2870 {"go1.20", "go1.19", "go1.20"}, // file downgrade not permitted
2871 {"go1.21", "go1.19", "go1.19"}, // file downgrade permitted (module version is >= go1.21)
2873 // versions containing release numbers
2874 // (file versions containing release numbers are considered invalid)
2875 {"go1.19.0", "", "go1.19.0"}, // no file version specified
2876 {"go1.20", "go1.20.1", "go1.20"}, // file upgrade ignored
2877 {"go1.20.1", "go1.20", "go1.20.1"}, // file upgrade ignored
2878 {"go1.20.1", "go1.21", "go1.21"}, // file upgrade permitted
2879 {"go1.20.1", "go1.19", "go1.20.1"}, // file downgrade not permitted
2880 {"go1.21.1", "go1.19.1", "go1.21.1"}, // file downgrade not permitted (invalid file version)
2881 {"go1.21.1", "go1.19", "go1.19"}, // file downgrade permitted (module version is >= go1.21)
2884 if test.fileVersion != "" {
2885 src = "//go:build " + test.fileVersion + "\n"
2889 conf := Config{GoVersion: test.goVersion}
2890 versions := make(map[*syntax.PosBase]string)
2892 info.FileVersions = versions
2893 mustTypecheck(src, &conf, &info)
2896 for _, v := range info.FileVersions {
2897 want := test.wantVersion
2899 t.Errorf("%q: unexpected file version: got %v, want %v", src, v, want)
2904 t.Errorf("%q: incorrect number of map entries: got %d", src, n)