Source file
src/go/types/api_test.go
1
2
3
4
5 package types_test
6
7 import (
8 "errors"
9 "fmt"
10 "go/ast"
11 "go/importer"
12 "go/parser"
13 "go/token"
14 "internal/goversion"
15 "internal/testenv"
16 "reflect"
17 "regexp"
18 "slices"
19 "strings"
20 "sync"
21 "testing"
22
23 . "go/types"
24 )
25
26
27 var nopos token.Pos
28
29 func mustParse(fset *token.FileSet, src string) *ast.File {
30 f, err := parser.ParseFile(fset, pkgName(src), src, parser.ParseComments)
31 if err != nil {
32 panic(err)
33 }
34 return f
35 }
36
37 func typecheck(src string, conf *Config, info *Info) (*Package, error) {
38 fset := token.NewFileSet()
39 f := mustParse(fset, src)
40 if conf == nil {
41 conf = &Config{
42 Error: func(err error) {},
43 Importer: importer.Default(),
44 }
45 }
46 return conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
47 }
48
49 func mustTypecheck(src string, conf *Config, info *Info) *Package {
50 pkg, err := typecheck(src, conf, info)
51 if err != nil {
52 panic(err)
53 }
54 return pkg
55 }
56
57
58 func pkgName(src string) string {
59 const kw = "package "
60 if i := strings.Index(src, kw); i >= 0 {
61 after := src[i+len(kw):]
62 n := len(after)
63 if i := strings.IndexAny(after, "\n\t ;/"); i >= 0 {
64 n = i
65 }
66 return after[:n]
67 }
68 panic("missing package header: " + src)
69 }
70
71 func TestValuesInfo(t *testing.T) {
72 var tests = []struct {
73 src string
74 expr string
75 typ string
76 val string
77 }{
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"`},
84
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"`},
91
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`},
95
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`},
99
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`},
103
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`},
107
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)`},
111
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`},
118
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"`},
123
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)`},
132
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)`},
145
146 {`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`},
147 {`package g1; var(j int32; s int; n = 1.0<<s == j)`, `1.0`, `int32`, `1`},
148 }
149
150 for _, test := range tests {
151 info := Info{
152 Types: make(map[ast.Expr]TypeAndValue),
153 }
154 name := mustTypecheck(test.src, nil, &info).Name()
155
156
157 var expr ast.Expr
158 for e := range info.Types {
159 if ExprString(e) == test.expr {
160 expr = e
161 break
162 }
163 }
164 if expr == nil {
165 t.Errorf("package %s: no expression found for %s", name, test.expr)
166 continue
167 }
168 tv := info.Types[expr]
169
170
171 if got := tv.Type.String(); got != test.typ {
172 t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
173 continue
174 }
175
176
177 if tv.Value != nil {
178 if got := tv.Value.ExactString(); got != test.val {
179 t.Errorf("package %s: got value %s; want %s", name, got, test.val)
180 }
181 } else {
182 if test.val != "" {
183 t.Errorf("package %s: no constant found; want %s", name, test.val)
184 }
185 }
186 }
187 }
188
189 func TestTypesInfo(t *testing.T) {
190
191 const broken = "package broken_"
192
193 var tests = []struct {
194 src string
195 expr string
196 typ string
197 }{
198
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`},
204
205
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`},
213
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`},
221
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`},
229
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`},
237
238
239 {`package p0; var x interface{}; var _, _ = x.(int)`,
240 `x.(int)`,
241 `(int, bool)`,
242 },
243 {`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
244 `x.(int)`,
245 `(int, bool)`,
246 },
247 {`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
248 `m["foo"]`,
249 `(complex128, p2a.mybool)`,
250 },
251 {`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
252 `m["foo"]`,
253 `(complex128, bool)`,
254 },
255 {`package p3; var c chan string; var _, _ = <-c`,
256 `<-c`,
257 `(string, bool)`,
258 },
259
260
261 {`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
262 `x.(int)`,
263 `(int, bool)`,
264 },
265 {`package issue6796_b; var c chan string; var _, _ = (<-c)`,
266 `(<-c)`,
267 `(string, bool)`,
268 },
269 {`package issue6796_c; var c chan string; var _, _ = (<-c)`,
270 `<-c`,
271 `(string, bool)`,
272 },
273 {`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
274 `(<-c)`,
275 `(string, bool)`,
276 },
277 {`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
278 `(<-c)`,
279 `(string, bool)`,
280 },
281
282
283 {`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
284 `m[0]`,
285 `(string, bool)`,
286 },
287 {`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
288 `m[0]`,
289 `(string, bool)`,
290 },
291 {`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
292 `m[0]`,
293 `(string, bool)`,
294 },
295 {`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
296 `<-ch`,
297 `(string, bool)`,
298 },
299 {`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
300 `<-ch`,
301 `(string, bool)`,
302 },
303 {`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
304 `<-ch`,
305 `(string, bool)`,
306 },
307
308
309 {`package issue28277_a; func f(...int)`,
310 `...int`,
311 `[]int`,
312 },
313 {`package issue28277_b; func f(a, b int, c ...[]struct{})`,
314 `...[]struct{}`,
315 `[][]struct{}`,
316 },
317
318
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`},
329
330
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`},
337
338
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)`, `()`},
345
346
347 {`package t0; type t[] int; var _ t`, `t`, `t0.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()}]`},
352
353
354 {`package g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `g0.t[int]`},
355
356
357 {`package issue45096; func _[T interface{ ~int8 | ~int16 | ~int32 }](x T) { _ = x < 0 }`, `0`, `T`},
358
359
360 {`package p; import "unsafe"; type S struct { f int }; var s S; var _ = unsafe.Offsetof(s.f)`, `s.f`, `int`},
361
362
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`},
370
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`},
378
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`},
386
387
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)`},
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)`},
393 {`package r6; var _ func(int, string) = g[int]; func g[P, Q any](P, Q) {}`, `g[int]`, `func(int, string)`},
394
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)`},
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)`},
400 {`package s6; func _() { f(g[int]) }; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}`, `g[int]`, `func(int, string)`},
401
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)`},
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)`},
406 }
407
408 for _, test := range tests {
409 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
410 var name string
411 if strings.HasPrefix(test.src, broken) {
412 pkg, err := typecheck(test.src, nil, &info)
413 if err == nil {
414 t.Errorf("package %s: expected to fail but passed", pkg.Name())
415 continue
416 }
417 if pkg != nil {
418 name = pkg.Name()
419 }
420 } else {
421 name = mustTypecheck(test.src, nil, &info).Name()
422 }
423
424
425 var typ Type
426 for e, tv := range info.Types {
427 if ExprString(e) == test.expr {
428 typ = tv.Type
429 break
430 }
431 }
432 if typ == nil {
433 t.Errorf("package %s: no type found for %s", name, test.expr)
434 continue
435 }
436
437
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)
440 }
441 }
442 }
443
444 func TestInstanceInfo(t *testing.T) {
445 const lib = `package lib
446
447 func F[P any](P) {}
448
449 type T[P any] []P
450 `
451
452 type testInst struct {
453 name string
454 targs []string
455 typ string
456 }
457
458 var tests = []struct {
459 src string
460 instances []testInst
461 }{
462 {`package p0; func f[T any](T) {}; func _() { f(42) }`,
463 []testInst{{`f`, []string{`int`}, `func(int)`}},
464 },
465 {`package p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
466 []testInst{{`f`, []string{`rune`}, `func(rune) rune`}},
467 },
468 {`package p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
469 []testInst{{`f`, []string{`complex128`}, `func(...complex128) complex128`}},
470 },
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)`}},
473 },
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)`}},
476 },
477
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)`}},
480 },
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)`}},
483 },
484 {`package s3; type C[T any] interface{chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
485 []testInst{
486 {`C`, []string{`T`}, `interface{chan<- T}`},
487 {`f`, []string{`int`, `chan<- int`}, `func(x []int)`},
488 },
489 },
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) }`,
491 []testInst{
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)`},
495 },
496 },
497
498 {`package t1; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = f[string] }`,
499 []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
500 },
501 {`package t2; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = (f[string]) }`,
502 []testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
503 },
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] }`,
505 []testInst{
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`},
509 },
510 },
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]) }`,
512 []testInst{
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`},
516 },
517 },
518 {`package i0; import "lib"; func _() { lib.F(42) }`,
519 []testInst{{`F`, []string{`int`}, `func(int)`}},
520 },
521
522 {`package duplfunc0; func f[T any](T) {}; func _() { f(42); f("foo"); f[int](3) }`,
523 []testInst{
524 {`f`, []string{`int`}, `func(int)`},
525 {`f`, []string{`string`}, `func(string)`},
526 {`f`, []string{`int`}, `func(int)`},
527 },
528 },
529 {`package duplfunc1; import "lib"; func _() { lib.F(42); lib.F("foo"); lib.F(3) }`,
530 []testInst{
531 {`F`, []string{`int`}, `func(int)`},
532 {`F`, []string{`string`}, `func(string)`},
533 {`F`, []string{`int`}, `func(int)`},
534 },
535 },
536
537 {`package type0; type T[P interface{~int}] struct{ x P }; var _ T[int]`,
538 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
539 },
540 {`package type1; type T[P interface{~int}] struct{ x P }; var _ (T[int])`,
541 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
542 },
543 {`package type2; type T[P interface{~int}] struct{ x P }; var _ T[(int)]`,
544 []testInst{{`T`, []string{`int`}, `struct{x int}`}},
545 },
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}`}},
548 },
549 {`package type4; import "lib"; var _ lib.T[int]`,
550 []testInst{{`T`, []string{`int`}, `[]int`}},
551 },
552
553 {`package dupltype0; type T[P interface{~int}] struct{ x P }; var x T[int]; var y T[int]`,
554 []testInst{
555 {`T`, []string{`int`}, `struct{x int}`},
556 {`T`, []string{`int`}, `struct{x int}`},
557 },
558 },
559 {`package dupltype1; type T[P ~int] struct{ x P }; func (r *T[Q]) add(z T[Q]) { r.x += z.x }`,
560 []testInst{
561 {`T`, []string{`Q`}, `struct{x Q}`},
562 {`T`, []string{`Q`}, `struct{x Q}`},
563 },
564 },
565 {`package dupltype1; import "lib"; var x lib.T[int]; var y lib.T[int]; var z lib.T[string]`,
566 []testInst{
567 {`T`, []string{`int`}, `[]int`},
568 {`T`, []string{`int`}, `[]int`},
569 {`T`, []string{`string`}, `[]string`},
570 },
571 },
572 {`package issue51803; func foo[T any](T) {}; func _() { foo[int]( /* leave arg away on purpose */ ) }`,
573 []testInst{{`foo`, []string{`int`}, `func(int)`}},
574 },
575
576
577 {`package reverse1a; var f func(int) = g; func g[P any](P) {}`,
578 []testInst{{`g`, []string{`int`}, `func(int)`}},
579 },
580 {`package reverse1b; func f(func(int)) {}; func g[P any](P) {}; func _() { f(g) }`,
581 []testInst{{`g`, []string{`int`}, `func(int)`}},
582 },
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)`}},
585 },
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)`}},
588 },
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)`}},
591 },
592
593 {`package reverse3b; func f[R any](func(int) R) {}; func g[P any](P) string { return "" }; func _() { f(g) }`,
594 []testInst{
595 {`f`, []string{`string`}, `func(func(int) string)`},
596 {`g`, []string{`int`}, `func(int) string`},
597 },
598 },
599 {`package reverse4a; var _, _ func([]int, *float32) = g, h; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}`,
600 []testInst{
601 {`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
602 {`h`, []string{`int`}, `func([]int, *float32)`},
603 },
604 },
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) }`,
606 []testInst{
607 {`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
608 {`h`, []string{`int`}, `func([]int, *float32)`},
609 },
610 },
611 {`package issue59956; func f(func(int), func(string), func(bool)) {}; func g[P any](P) {}; func _() { f(g, g, g) }`,
612 []testInst{
613 {`g`, []string{`int`}, `func(int)`},
614 {`g`, []string{`string`}, `func(string)`},
615 {`g`, []string{`bool`}, `func(bool)`},
616 },
617 },
618 }
619
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
628 if err != nil && (pkg == nil || pkg.Name() != "issue51803") {
629 t.Fatal(err)
630 }
631 imports[pkg.Name()] = pkg
632 return pkg
633 }
634 makePkg(lib)
635 pkg := makePkg(test.src)
636
637 t.Run(pkg.Name(), func(t *testing.T) {
638
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)
642 }
643
644
645 for ii, inst := range instances {
646 var targs []Type
647 for i := 0; i < inst.Inst.TypeArgs.Len(); i++ {
648 targs = append(targs, inst.Inst.TypeArgs.At(i))
649 }
650 typ := inst.Inst.Type
651
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)
655 }
656 if len(targs) != len(testInst.targs) {
657 t.Fatalf("got %d type arguments; want %d", len(targs), len(testInst.targs))
658 }
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])
662 }
663 }
664 if got := typ.Underlying().String(); got != testInst.typ {
665 t.Errorf("package %s: got %s; want %s", pkg.Name(), got, testInst.typ)
666 }
667
668
669
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)
674 }
675 inst2, err := Instantiate(nil, ptype, targs, true)
676 if err != nil {
677 t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
678 }
679 if !Identical(inst.Inst.Type, inst2) {
680 t.Errorf("%v and %v are not identical", inst.Inst.Type, inst2)
681 }
682 }
683 })
684 }
685 }
686
687 type recordedInstance struct {
688 Ident *ast.Ident
689 Inst Instance
690 }
691
692 func sortedInstances(m map[*ast.Ident]Instance) (instances []recordedInstance) {
693 for id, inst := range m {
694 instances = append(instances, recordedInstance{id, inst})
695 }
696 slices.SortFunc(instances, func(a, b recordedInstance) int {
697 return CmpPos(a.Ident.Pos(), b.Ident.Pos())
698 })
699 return instances
700 }
701
702 func TestDefsInfo(t *testing.T) {
703 var tests = []struct {
704 src string
705 obj string
706 want string
707 }{
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`},
714
715
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()`},
719 }
720
721 for _, test := range tests {
722 info := Info{
723 Defs: make(map[*ast.Ident]Object),
724 }
725 name := mustTypecheck(test.src, nil, &info).Name()
726
727
728 var def Object
729 for id, obj := range info.Defs {
730 if id.Name == test.obj {
731 def = obj
732 break
733 }
734 }
735 if def == nil {
736 t.Errorf("package %s: %s not found", name, test.obj)
737 continue
738 }
739
740 if got := def.String(); got != test.want {
741 t.Errorf("package %s: got %s; want %s", name, got, test.want)
742 }
743 }
744 }
745
746 func TestUsesInfo(t *testing.T) {
747 var tests = []struct {
748 src string
749 obj string
750 want string
751 }{
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()`},
757
758
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`},
763
764
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`},
767
768
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()`},
779 {
780 `package m10; type E[A any] interface{ m() }; type T[B any] interface{ E[B]; n() }; func _(t T[int]) { t.m() }`,
781 `m`,
782 `func (m10.E[int]).m()`,
783 },
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()`},
786 }
787
788 for _, test := range tests {
789 info := Info{
790 Uses: make(map[*ast.Ident]Object),
791 }
792 name := mustTypecheck(test.src, nil, &info).Name()
793
794
795 var use Object
796 for id, obj := range info.Uses {
797 if id.Name == test.obj {
798 if use != nil {
799 panic(fmt.Sprintf("multiple uses of %q", id.Name))
800 }
801 use = obj
802 }
803 }
804 if use == nil {
805 t.Errorf("package %s: %s not found", name, test.obj)
806 continue
807 }
808
809 if got := use.String(); got != test.want {
810 t.Errorf("package %s: got %s; want %s", name, got, test.want)
811 }
812 }
813 }
814
815 func TestGenericMethodInfo(t *testing.T) {
816 src := `package p
817
818 type N[A any] int
819
820 func (r N[B]) m() { r.m(); r.n() }
821
822 func (r *N[C]) n() { }
823 `
824 fset := token.NewFileSet()
825 f := mustParse(fset, src)
826 info := Info{
827 Defs: make(map[*ast.Ident]Object),
828 Uses: make(map[*ast.Ident]Object),
829 Selections: make(map[*ast.SelectorExpr]*Selection),
830 }
831 var conf Config
832 pkg, err := conf.Check("p", fset, []*ast.File{f}, &info)
833 if err != nil {
834 t.Fatal(err)
835 }
836
837 N := pkg.Scope().Lookup("N").Type().(*Named)
838
839
840 gm, gn := N.Method(0), N.Method(1)
841 if gm.Name() == "n" {
842 gm, gn = gn, gm
843 }
844
845
846 var dm, dn *Func
847 var dmm, dmn *Func
848 for _, decl := range f.Decls {
849 fdecl, ok := decl.(*ast.FuncDecl)
850 if !ok {
851 continue
852 }
853 def := info.Defs[fdecl.Name].(*Func)
854 switch fdecl.Name.Name {
855 case "m":
856 dm = def
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)
864 }
865 if selection.Obj() != use {
866 t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
867 }
868 switch sel.Sel.Name {
869 case "m":
870 dmm = use
871 case "n":
872 dmn = use
873 }
874 }
875 return true
876 })
877 case "n":
878 dn = def
879 }
880 }
881
882 if gm != dm {
883 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
884 }
885 if gn != dn {
886 t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
887 }
888 if dmm != dm {
889 t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
890 }
891 if dmn == dn {
892 t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
893 }
894 }
895
896 func TestImplicitsInfo(t *testing.T) {
897 testenv.MustHaveGoBuild(t)
898
899 var tests = []struct {
900 src string
901 want string
902 }{
903 {`package p2; import . "fmt"; var _ = Println`, ""},
904 {`package p0; import local "fmt"; var _ = local.Println`, ""},
905 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
906
907 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""},
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{}"},
911
912 {`package p7; func f(x int) {}`, ""},
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"},
916
917
918 {`package f0; func f[T any](x int) {}`, ""},
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"},
927 }
928
929 for _, test := range tests {
930 info := Info{
931 Implicits: make(map[ast.Node]Object),
932 }
933 name := mustTypecheck(test.src, nil, &info).Name()
934
935
936 if len(info.Implicits) > 1 {
937 t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
938 continue
939 }
940
941
942 var got string
943 for n, obj := range info.Implicits {
944 switch x := n.(type) {
945 case *ast.ImportSpec:
946 got = "importSpec"
947 case *ast.CaseClause:
948 got = "caseClause"
949 case *ast.Field:
950 got = "field"
951 default:
952 t.Fatalf("package %s: unexpected %T", name, x)
953 }
954 got += ": " + obj.String()
955 }
956
957
958 if got != test.want {
959 t.Errorf("package %s: got %q; want %q", name, got, test.want)
960 }
961 }
962 }
963
964 func TestPkgNameOf(t *testing.T) {
965 testenv.MustHaveGoBuild(t)
966
967 const src = `
968 package p
969
970 import (
971 . "os"
972 _ "io"
973 "math"
974 "path/filepath"
975 snort "sort"
976 )
977
978 // avoid imported and not used errors
979 var (
980 _ = Open // os.Open
981 _ = math.Sin
982 _ = filepath.Abs
983 _ = snort.Ints
984 )
985 `
986
987 var tests = []struct {
988 path string
989 want string
990 }{
991 {`"os"`, "."},
992 {`"io"`, "_"},
993 {`"math"`, "math"},
994 {`"path/filepath"`, "filepath"},
995 {`"sort"`, "snort"},
996 }
997
998 fset := token.NewFileSet()
999 f := mustParse(fset, src)
1000 info := Info{
1001 Defs: make(map[*ast.Ident]Object),
1002 Implicits: make(map[ast.Node]Object),
1003 }
1004 var conf Config
1005 conf.Importer = importer.Default()
1006 _, err := conf.Check("p", fset, []*ast.File{f}, &info)
1007 if err != nil {
1008 t.Fatal(err)
1009 }
1010
1011
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
1016 }
1017 }
1018
1019 for _, test := range tests {
1020 imp := imports[test.path]
1021 if imp == nil {
1022 t.Fatalf("invalid test case: import path %s not found", test.path)
1023 }
1024 got := info.PkgNameOf(imp)
1025 if got == nil {
1026 t.Fatalf("import %s: package name not found", test.path)
1027 }
1028 if got.Name() != test.want {
1029 t.Errorf("import %s: got %s; want %s", test.path, got.Name(), test.want)
1030 }
1031 }
1032
1033
1034 if got := info.PkgNameOf(new(ast.ImportSpec)); got != nil {
1035 t.Errorf("got %s for non-existing import declaration", got.Name())
1036 }
1037 }
1038
1039 func predString(tv TypeAndValue) string {
1040 var buf strings.Builder
1041 pred := func(b bool, s string) {
1042 if b {
1043 if buf.Len() > 0 {
1044 buf.WriteString(", ")
1045 }
1046 buf.WriteString(s)
1047 }
1048 }
1049
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")
1059
1060 if buf.Len() == 0 {
1061 return "invalid"
1062 }
1063 return buf.String()
1064 }
1065
1066 func TestPredicatesInfo(t *testing.T) {
1067 testenv.MustHaveGoBuild(t)
1068
1069 var tests = []struct {
1070 src string
1071 expr string
1072 pred string
1073 }{
1074
1075 {`package n0; func f() { f() }`, `f()`, `void`},
1076
1077
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`},
1083
1084
1085 {`package b0; var _ = len("")`, `len`, `builtin`},
1086 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
1087
1088
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`},
1092
1093
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`},
1100
1101
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
1111
1112
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`},
1115
1116
1117 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
1118 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
1119
1120
1121
1122
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>`},
1132 }
1133
1134 for _, test := range tests {
1135 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
1136 name := mustTypecheck(test.src, nil, &info).Name()
1137
1138
1139 got := "<missing>"
1140 for e, tv := range info.Types {
1141
1142 if ExprString(e) == test.expr {
1143 got = predString(tv)
1144 break
1145 }
1146 }
1147
1148 if got != test.pred {
1149 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
1150 }
1151 }
1152 }
1153
1154 func TestScopesInfo(t *testing.T) {
1155 testenv.MustHaveGoBuild(t)
1156
1157 var tests = []struct {
1158 src string
1159 scopes []string
1160 }{
1161 {`package p0`, []string{
1162 "file:",
1163 }},
1164 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
1165 "file:fmt m",
1166 }},
1167 {`package p2; func _() {}`, []string{
1168 "file:", "func:",
1169 }},
1170 {`package p3; func _(x, y int) {}`, []string{
1171 "file:", "func:x y",
1172 }},
1173 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
1174 "file:", "func:x y z",
1175 }},
1176 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
1177 "file:", "func:u x y",
1178 }},
1179 {`package p6; func _() { { var x int; _ = x } }`, []string{
1180 "file:", "func:", "block:x",
1181 }},
1182 {`package p7; func _() { if true {} }`, []string{
1183 "file:", "func:", "if:", "block:",
1184 }},
1185 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
1186 "file:", "func:", "if:x", "block:y",
1187 }},
1188 {`package p9; func _() { switch x := 0; x {} }`, []string{
1189 "file:", "func:", "switch:x",
1190 }},
1191 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
1192 "file:", "func:", "switch:x", "case:y", "case:",
1193 }},
1194 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
1195 "file:", "func:t", "type switch:",
1196 }},
1197 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
1198 "file:", "func:t", "type switch:t",
1199 }},
1200 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
1201 "file:", "func:t", "type switch:", "case:x",
1202 }},
1203 {`package p14; func _() { select{} }`, []string{
1204 "file:", "func:",
1205 }},
1206 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
1207 "file:", "func:c", "comm:",
1208 }},
1209 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
1210 "file:", "func:c", "comm:i x",
1211 }},
1212 {`package p17; func _() { for{} }`, []string{
1213 "file:", "func:", "for:", "block:",
1214 }},
1215 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
1216 "file:", "func:n", "for:i", "block:",
1217 }},
1218 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
1219 "file:", "func:a", "range:i", "block:",
1220 }},
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:",
1223 }},
1224 }
1225
1226 for _, test := range tests {
1227 info := Info{Scopes: make(map[ast.Node]*Scope)}
1228 name := mustTypecheck(test.src, nil, &info).Name()
1229
1230
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))
1233 }
1234
1235
1236 for node, scope := range info.Scopes {
1237 kind := "<unknown node kind>"
1238 switch node.(type) {
1239 case *ast.File:
1240 kind = "file"
1241 case *ast.FuncType:
1242 kind = "func"
1243 case *ast.BlockStmt:
1244 kind = "block"
1245 case *ast.IfStmt:
1246 kind = "if"
1247 case *ast.SwitchStmt:
1248 kind = "switch"
1249 case *ast.TypeSwitchStmt:
1250 kind = "type switch"
1251 case *ast.CaseClause:
1252 kind = "case"
1253 case *ast.CommClause:
1254 kind = "comm"
1255 case *ast.ForStmt:
1256 kind = "for"
1257 case *ast.RangeStmt:
1258 kind = "range"
1259 }
1260
1261
1262 desc := kind + ":" + strings.Join(scope.Names(), " ")
1263 found := false
1264 for _, d := range test.scopes {
1265 if desc == d {
1266 found = true
1267 break
1268 }
1269 }
1270 if !found {
1271 t.Errorf("package %s: no matching scope found for %s", name, desc)
1272 }
1273 }
1274 }
1275 }
1276
1277 func TestInitOrderInfo(t *testing.T) {
1278 var tests = []struct {
1279 src string
1280 inits []string
1281 }{
1282 {`package p0; var (x = 1; y = x)`, []string{
1283 "x = 1", "y = x",
1284 }},
1285 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
1286 "a = 1", "b = 2", "c = 3",
1287 }},
1288 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
1289 "a = 1", "b = 2", "c = 3",
1290 }},
1291 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
1292 "_ = f()",
1293 }},
1294 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
1295 "a = 0", "z = 0", "y = z", "x = y",
1296 }},
1297 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
1298 "a, _ = m[0]",
1299 }},
1300 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
1301 "z = 0", "a, b = f()",
1302 }},
1303 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
1304 "b = 1", "a = (func() int literal)()",
1305 }},
1306 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
1307 "c = 1", "a, b = (func() (_, _ int) literal)()",
1308 }},
1309 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1310 "y = 1", "x = T.m",
1311 }},
1312 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1313 "a = 0", "b = 0", "c = 0", "d = c + b",
1314 }},
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",
1317 }},
1318
1319
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",
1322 }},
1323
1324 {`package p12
1325
1326 var (
1327 a = c + b
1328 b = f()
1329 c = f()
1330 d = 3
1331 )
1332
1333 func f() int {
1334 d++
1335 return d
1336 }`, []string{
1337 "d = 3", "b = f()", "c = f()", "a = c + b",
1338 }},
1339
1340 {`package main
1341
1342 var counter int
1343 func next() int { counter++; return counter }
1344
1345 var _ = makeOrder()
1346 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1347
1348 var a = next()
1349 var b, c = next(), next()
1350 var d, e, f = next(), next(), next()
1351 `, []string{
1352 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1353 }},
1354
1355 {`package p13
1356
1357 var (
1358 v = t.m()
1359 t = makeT(0)
1360 )
1361
1362 type T struct{}
1363
1364 func (T) m() int { return 0 }
1365
1366 func makeT(n int) T {
1367 if n > 0 {
1368 return makeT(n-1)
1369 }
1370 return T{}
1371 }`, []string{
1372 "t = makeT(0)", "v = t.m()",
1373 }},
1374
1375 {`package p14
1376
1377 var (
1378 t = makeT(0)
1379 v = t.m()
1380 )
1381
1382 type T struct{}
1383
1384 func (T) m() int { return 0 }
1385
1386 func makeT(n int) T {
1387 if n > 0 {
1388 return makeT(n-1)
1389 }
1390 return T{}
1391 }`, []string{
1392 "t = makeT(0)", "v = t.m()",
1393 }},
1394
1395 {`package p15
1396
1397 var y1 = f1()
1398
1399 func f1() int { return g1() }
1400 func g1() int { f1(); return x1 }
1401
1402 var x1 = 0
1403
1404 var y2 = f2()
1405
1406 func f2() int { return g2() }
1407 func g2() int { return x2 }
1408
1409 var x2 = 0`, []string{
1410 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1411 }},
1412 }
1413
1414 for _, test := range tests {
1415 info := Info{}
1416 name := mustTypecheck(test.src, nil, &info).Name()
1417
1418
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))
1421 continue
1422 }
1423
1424
1425 for i, want := range test.inits {
1426 got := info.InitOrder[i].String()
1427 if got != want {
1428 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1429 continue
1430 }
1431 }
1432 }
1433 }
1434
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`)
1439
1440
1441
1442
1443 for _, test := range []struct {
1444 files []*ast.File
1445 want string
1446 }{
1447 {[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
1448 {[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
1449 } {
1450 var info Info
1451 if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
1452 t.Fatal(err)
1453 }
1454 if got := fmt.Sprint(info.InitOrder); got != test.want {
1455 t.Fatalf("got %s; want %s", got, test.want)
1456 }
1457 }
1458 }
1459
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{}",
1465 "package p",
1466 }
1467
1468 var conf Config
1469 fset := token.NewFileSet()
1470 pkg := NewPackage("p", "p")
1471 var info Info
1472 check := NewChecker(&conf, fset, pkg, &info)
1473
1474 for _, src := range sources {
1475 if err := check.Files([]*ast.File{mustParse(fset, src)}); err != nil {
1476 t.Error(err)
1477 }
1478 }
1479
1480
1481 var vars []string
1482 for _, init := range info.InitOrder {
1483 for _, v := range init.Lhs {
1484 vars = append(vars, v.Name())
1485 }
1486 }
1487 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1488 t.Errorf("InitOrder == %s, want %s", got, want)
1489 }
1490 }
1491
1492 type testImporter map[string]*Package
1493
1494 func (m testImporter) Import(path string) (*Package, error) {
1495 if pkg := m[path]; pkg != nil {
1496 return pkg, nil
1497 }
1498 return nil, fmt.Errorf("package %q not found", path)
1499 }
1500
1501 func TestSelection(t *testing.T) {
1502 selections := make(map[*ast.SelectorExpr]*Selection)
1503
1504
1505
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})
1511 if err != nil {
1512 t.Fatal(err)
1513 }
1514 imports[path] = pkg
1515 }
1516
1517 const libSrc = `
1518 package lib
1519 type T float64
1520 const C T = 3
1521 var V T
1522 func F() {}
1523 func (T) M() {}
1524 `
1525 const mainSrc = `
1526 package main
1527 import "lib"
1528
1529 type A struct {
1530 *B
1531 C
1532 }
1533
1534 type B struct {
1535 b int
1536 }
1537
1538 func (B) f(int)
1539
1540 type C struct {
1541 c int
1542 }
1543
1544 type G[P any] struct {
1545 p P
1546 }
1547
1548 func (G[P]) m(P) {}
1549
1550 var Inst G[int]
1551
1552 func (C) g()
1553 func (*C) h()
1554
1555 func main() {
1556 // qualified identifiers
1557 var _ lib.T
1558 _ = lib.C
1559 _ = lib.F
1560 _ = lib.V
1561 _ = lib.T.M
1562
1563 // fields
1564 _ = A{}.B
1565 _ = new(A).B
1566
1567 _ = A{}.C
1568 _ = new(A).C
1569
1570 _ = A{}.b
1571 _ = new(A).b
1572
1573 _ = A{}.c
1574 _ = new(A).c
1575
1576 _ = Inst.p
1577 _ = G[string]{}.p
1578
1579 // methods
1580 _ = A{}.f
1581 _ = new(A).f
1582 _ = A{}.g
1583 _ = new(A).g
1584 _ = new(A).h
1585
1586 _ = B{}.f
1587 _ = new(B).f
1588
1589 _ = C{}.g
1590 _ = new(C).g
1591 _ = new(C).h
1592 _ = Inst.m
1593
1594 // method expressions
1595 _ = A.f
1596 _ = (*A).f
1597 _ = B.f
1598 _ = (*B).f
1599 _ = G[string].m
1600 }`
1601
1602 wantOut := map[string][2]string{
1603 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1604
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]"},
1614
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]"},
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]"},
1625 "Inst.m": {"method (main.G[int]) m(int)", ".[0]"},
1626
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]"},
1633 }
1634
1635 makePkg("lib", libSrc)
1636 makePkg("main", mainSrc)
1637
1638 for e, sel := range selections {
1639 _ = sel.String()
1640
1641 start := fset.Position(e.Pos()).Offset
1642 end := fset.Position(e.End()).Offset
1643 syntax := mainSrc[start:end]
1644
1645 direct := "."
1646 if sel.Indirect() {
1647 direct = "->"
1648 }
1649 got := [2]string{
1650 sel.String(),
1651 fmt.Sprintf("%s%v", direct, sel.Index()),
1652 }
1653 want := wantOut[syntax]
1654 if want != got {
1655 t.Errorf("%s: got %q; want %q", syntax, got, want)
1656 }
1657 delete(wantOut, syntax)
1658
1659
1660
1661
1662 sig, _ := sel.Type().(*Signature)
1663 if sel.Kind() == MethodVal {
1664 got := sig.Recv().Type()
1665 want := sel.Recv()
1666 if !Identical(got, want) {
1667 t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
1668 }
1669 } else if sig != nil && sig.Recv() != nil {
1670 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1671 }
1672 }
1673
1674 for syntax := range wantOut {
1675 t.Errorf("no ast.Selection found with syntax %q", syntax)
1676 }
1677 }
1678
1679 func TestIssue8518(t *testing.T) {
1680 fset := token.NewFileSet()
1681 imports := make(testImporter)
1682 conf := Config{
1683 Error: func(err error) { t.Log(err) },
1684 Importer: imports,
1685 }
1686 makePkg := func(path, src string) {
1687 imports[path], _ = conf.Check(path, fset, []*ast.File{mustParse(fset, src)}, nil)
1688 }
1689
1690 const libSrc = `
1691 package a
1692 import "missing"
1693 const C1 = foo
1694 const C2 = missing.C
1695 `
1696
1697 const mainSrc = `
1698 package main
1699 import "a"
1700 var _ = a.C1
1701 var _ = a.C2
1702 `
1703
1704 makePkg("a", libSrc)
1705 makePkg("main", mainSrc)
1706 }
1707
1708 func TestIssue59603(t *testing.T) {
1709 fset := token.NewFileSet()
1710 imports := make(testImporter)
1711 conf := Config{
1712 Error: func(err error) { t.Log(err) },
1713 Importer: imports,
1714 }
1715 makePkg := func(path, src string) {
1716 imports[path], _ = conf.Check(path, fset, []*ast.File{mustParse(fset, src)}, nil)
1717 }
1718
1719 const libSrc = `
1720 package a
1721 const C = foo
1722 `
1723
1724 const mainSrc = `
1725 package main
1726 import "a"
1727 const _ = a.C
1728 `
1729
1730 makePkg("a", libSrc)
1731 makePkg("main", mainSrc)
1732 }
1733
1734 func TestLookupFieldOrMethodOnNil(t *testing.T) {
1735
1736 defer func() {
1737 const want = "LookupFieldOrMethod on nil type"
1738 p := recover()
1739 if s, ok := p.(string); !ok || s != want {
1740 t.Fatalf("got %v, want %s", p, want)
1741 }
1742 }()
1743 LookupFieldOrMethod(nil, false, nil, "")
1744 }
1745
1746 func TestLookupFieldOrMethod(t *testing.T) {
1747
1748
1749
1750
1751
1752 var tests = []struct {
1753 src string
1754 found bool
1755 index []int
1756 indirect bool
1757 }{
1758
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},
1762
1763
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},
1767
1768
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},
1773
1774
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},
1779
1780
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},
1783
1784
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},
1787
1788
1789
1790 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1791
1792
1793 {"var x T[int]; type T[P any] struct{}; func (*T[P]) f() {}", false, nil, true},
1794
1795
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},
1798 }
1799
1800 for _, test := range tests {
1801 pkg := mustTypecheck("package p;"+test.src, nil, nil)
1802
1803 obj := pkg.Scope().Lookup("a")
1804 if obj == nil {
1805 if obj = pkg.Scope().Lookup("x"); obj == nil {
1806 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1807 continue
1808 }
1809 }
1810
1811 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1812 if (f != nil) != test.found {
1813 if f == nil {
1814 t.Errorf("%s: got no object; want one", test.src)
1815 } else {
1816 t.Errorf("%s: got object = %v; want none", test.src, f)
1817 }
1818 }
1819 if !sameSlice(index, test.index) {
1820 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1821 }
1822 if indirect != test.indirect {
1823 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1824 }
1825 }
1826 }
1827
1828
1829 func TestLookupFieldOrMethod_RecursiveGeneric(t *testing.T) {
1830 const src = `
1831 package pkg
1832
1833 type Tree[T any] struct {
1834 *Node[T]
1835 }
1836
1837 func (*Tree[R]) N(r R) R { return r }
1838
1839 type Node[T any] struct {
1840 *Tree[T]
1841 }
1842
1843 type Instance = *Tree[int]
1844 `
1845
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 {
1850 panic(err)
1851 }
1852
1853 T := pkg.Scope().Lookup("Instance").Type()
1854 _, _, _ = LookupFieldOrMethod(T, false, pkg, "M")
1855 }
1856
1857 func sameSlice(a, b []int) bool {
1858 if len(a) != len(b) {
1859 return false
1860 }
1861 for i, x := range a {
1862 if x != b[i] {
1863 return false
1864 }
1865 }
1866 return true
1867 }
1868
1869
1870
1871 func TestScopeLookupParent(t *testing.T) {
1872 fset := token.NewFileSet()
1873 imports := make(testImporter)
1874 conf := Config{Importer: imports}
1875 var info Info
1876 makePkg := func(path string, files ...*ast.File) {
1877 var err error
1878 imports[path], err = conf.Check(path, fset, files, &info)
1879 if err != nil {
1880 t.Fatal(err)
1881 }
1882 }
1883
1884 makePkg("lib", mustParse(fset, "package lib; var X int"))
1885
1886
1887
1888 mainSrc := `
1889 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1890 package main
1891
1892 import "lib"
1893 import . "lib"
1894
1895 const Pi = 3.1415
1896 type T struct{}
1897 var Y, _ = lib.X, X
1898
1899 func F[T *U, U any](param1, param2 int) /*param1=undef*/ (res1 /*res1=undef*/, res2 int) /*param1=var:12*/ /*res1=var:12*/ /*U=typename: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[*int, int] /*F=var:17*/ ; _ = F
1905
1906 var a []int
1907 for i, x := range a /*i=undef*/ /*x=var:16*/ { _ = i; _ = x }
1908
1909 var i interface{}
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*/:
1914 println(y)
1915 }
1916 /*y=undef*/
1917
1918 switch int := i.(type) {
1919 case /*int=typename:0*/ int /*int=var:31*/ :
1920 println(int)
1921 default /*int=var:31*/ :
1922 }
1923
1924 _ = param1
1925 _ = res1
1926 return
1927 }
1928 /*main=undef*/
1929 `
1930
1931 info.Uses = make(map[*ast.Ident]Object)
1932 f := mustParse(fset, mainSrc)
1933 makePkg("main", f)
1934 mainScope := imports["main"].Scope()
1935 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1936 for _, group := range f.Comments {
1937 for _, comment := range group.List {
1938
1939 m := rx.FindStringSubmatch(comment.Text)
1940 if m == nil {
1941 t.Errorf("%s: bad comment: %s",
1942 fset.Position(comment.Pos()), comment.Text)
1943 continue
1944 }
1945 name, want := m[1], m[2]
1946
1947
1948 inner := mainScope.Innermost(comment.Pos())
1949 if inner == nil {
1950 t.Errorf("%s: at %s: can't find innermost scope",
1951 fset.Position(comment.Pos()), comment.Text)
1952 continue
1953 }
1954 got := "undef"
1955 if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil {
1956 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
1957 got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line)
1958 }
1959 if got != want {
1960 t.Errorf("%s: at %s: %s resolved to %s, want %s",
1961 fset.Position(comment.Pos()), comment.Text, name, got, want)
1962 }
1963 }
1964 }
1965
1966
1967
1968
1969
1970 for id, wantObj := range info.Uses {
1971 inner := mainScope.Innermost(id.Pos())
1972 if inner == nil {
1973 t.Errorf("%s: can't find innermost scope enclosing %q",
1974 fset.Position(id.Pos()), id.Name)
1975 continue
1976 }
1977
1978
1979
1980
1981
1982 if id.Name == "X" {
1983 continue
1984 }
1985
1986 _, gotObj := inner.LookupParent(id.Name, id.Pos())
1987 if gotObj != wantObj {
1988
1989 var printScopeTree func(indent string, s *Scope)
1990 printScopeTree = func(indent string, s *Scope) {
1991 t.Logf("%sscope %s %v-%v = %v",
1992 indent,
1993 ScopeComment(s),
1994 s.Pos(),
1995 s.End(),
1996 s.Names())
1997 for i := range s.NumChildren() {
1998 printScopeTree(indent+" ", s.Child(i))
1999 }
2000 }
2001 printScopeTree("", mainScope)
2002
2003 t.Errorf("%s: Scope(%s).LookupParent(%s@%v) got %v, want %v [scopePos=%v]",
2004 fset.Position(id.Pos()),
2005 ScopeComment(inner),
2006 id.Name,
2007 id.Pos(),
2008 gotObj,
2009 wantObj,
2010 ObjectScopePos(wantObj))
2011 continue
2012 }
2013 }
2014 }
2015
2016
2017
2018 func newDefined(underlying Type) *Named {
2019 tname := NewTypeName(nopos, nil, "T", nil)
2020 return NewNamed(tname, underlying, nil)
2021 }
2022
2023 func TestConvertibleTo(t *testing.T) {
2024 for _, test := range []struct {
2025 v, t Type
2026 want bool
2027 }{
2028 {Typ[Int], Typ[Int], true},
2029 {Typ[Int], Typ[Float32], true},
2030 {Typ[Int], Typ[String], true},
2031 {newDefined(Typ[Int]), Typ[Int], true},
2032 {newDefined(new(Struct)), new(Struct), true},
2033 {newDefined(Typ[Int]), new(Struct), false},
2034 {Typ[UntypedInt], Typ[Int], true},
2035 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), true},
2036 {NewSlice(Typ[Int]), NewArray(Typ[Uint], 10), false},
2037 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
2038 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
2039
2040 {Typ[UntypedString], Typ[String], true},
2041 } {
2042 if got := ConvertibleTo(test.v, test.t); got != test.want {
2043 t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
2044 }
2045 }
2046 }
2047
2048 func TestAssignableTo(t *testing.T) {
2049 for _, test := range []struct {
2050 v, t Type
2051 want bool
2052 }{
2053 {Typ[Int], Typ[Int], true},
2054 {Typ[Int], Typ[Float32], false},
2055 {newDefined(Typ[Int]), Typ[Int], false},
2056 {newDefined(new(Struct)), new(Struct), true},
2057 {Typ[UntypedBool], Typ[Bool], true},
2058 {Typ[UntypedString], Typ[Bool], false},
2059
2060
2061
2062 {Typ[UntypedString], Typ[String], true},
2063 {Typ[UntypedInt], Typ[Int], true},
2064 } {
2065 if got := AssignableTo(test.v, test.t); got != test.want {
2066 t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
2067 }
2068 }
2069 }
2070
2071 func TestIdentical(t *testing.T) {
2072
2073 tests := []struct {
2074 src string
2075 want bool
2076 }{
2077
2078 {"var X int; var Y int", true},
2079 {"var X int; var Y string", false},
2080
2081
2082
2083
2084 {"type X int; type Y int", false},
2085
2086
2087 {"type X = int; type Y = int", true},
2088
2089
2090 {`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
2091 {`func X() string { return "" }; func Y(int) string { return "" }`, false},
2092 {`func X(int) string { return "" }; func Y(int) {}`, false},
2093
2094
2095
2096 {`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
2097 {`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
2098 {`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
2099 {`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
2100 {`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
2101 {`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
2102 }
2103
2104 for _, test := range tests {
2105 pkg := mustTypecheck("package p;"+test.src, nil, nil)
2106 X := pkg.Scope().Lookup("X")
2107 Y := pkg.Scope().Lookup("Y")
2108 if X == nil || Y == nil {
2109 t.Fatal("test must declare both X and Y")
2110 }
2111 if got := Identical(X.Type(), Y.Type()); got != test.want {
2112 t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
2113 }
2114 }
2115 }
2116
2117 func TestIdentical_issue15173(t *testing.T) {
2118
2119 for _, test := range []struct {
2120 x, y Type
2121 want bool
2122 }{
2123 {Typ[Int], Typ[Int], true},
2124 {Typ[Int], nil, false},
2125 {nil, Typ[Int], false},
2126 {nil, nil, true},
2127 } {
2128 if got := Identical(test.x, test.y); got != test.want {
2129 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2130 }
2131 }
2132 }
2133
2134 func TestIdenticalUnions(t *testing.T) {
2135 tname := NewTypeName(nopos, nil, "myInt", nil)
2136 myInt := NewNamed(tname, Typ[Int], nil)
2137 tmap := map[string]*Term{
2138 "int": NewTerm(false, Typ[Int]),
2139 "~int": NewTerm(true, Typ[Int]),
2140 "string": NewTerm(false, Typ[String]),
2141 "~string": NewTerm(true, Typ[String]),
2142 "myInt": NewTerm(false, myInt),
2143 }
2144 makeUnion := func(s string) *Union {
2145 parts := strings.Split(s, "|")
2146 var terms []*Term
2147 for _, p := range parts {
2148 term := tmap[p]
2149 if term == nil {
2150 t.Fatalf("missing term %q", p)
2151 }
2152 terms = append(terms, term)
2153 }
2154 return NewUnion(terms)
2155 }
2156 for _, test := range []struct {
2157 x, y string
2158 want bool
2159 }{
2160
2161
2162 {"int|~int", "~int", true},
2163 {"myInt|~int", "~int", true},
2164 {"int|string", "string|int", true},
2165 {"int|int|string", "string|int", true},
2166 {"myInt|string", "int|string", false},
2167 } {
2168 x := makeUnion(test.x)
2169 y := makeUnion(test.y)
2170 if got := Identical(x, y); got != test.want {
2171 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
2172 }
2173 }
2174 }
2175
2176 func TestIssue61737(t *testing.T) {
2177
2178
2179
2180
2181
2182
2183 sig1 := NewSignatureType(nil, nil, nil, NewTuple(NewParam(nopos, nil, "", Typ[Int])), nil, false)
2184 sig2 := NewSignatureType(nil, nil, nil, NewTuple(NewParam(nopos, nil, "", Typ[String])), nil, false)
2185
2186 methods := []*Func{
2187 NewFunc(nopos, nil, "M", sig1),
2188 NewFunc(nopos, nil, "M", sig2),
2189 }
2190
2191 embeddedMethods := []*Func{
2192 NewFunc(nopos, nil, "M", sig2),
2193 }
2194 embedded := NewInterfaceType(embeddedMethods, nil)
2195 iface := NewInterfaceType(methods, []Type{embedded})
2196 iface.Complete()
2197 }
2198
2199 func TestNewAlias_Issue65455(t *testing.T) {
2200 obj := NewTypeName(nopos, nil, "A", nil)
2201 alias := NewAlias(obj, Typ[Int])
2202 alias.Underlying()
2203 }
2204
2205 func TestIssue15305(t *testing.T) {
2206 const src = "package p; func f() int16; var _ = f(undef)"
2207 fset := token.NewFileSet()
2208 f := mustParse(fset, src)
2209 conf := Config{
2210 Error: func(err error) {},
2211 }
2212 info := &Info{
2213 Types: make(map[ast.Expr]TypeAndValue),
2214 }
2215 conf.Check("p", fset, []*ast.File{f}, info)
2216 for e, tv := range info.Types {
2217 if _, ok := e.(*ast.CallExpr); ok {
2218 if tv.Type != Typ[Int16] {
2219 t.Errorf("CallExpr has type %v, want int16", tv.Type)
2220 }
2221 return
2222 }
2223 }
2224 t.Errorf("CallExpr has no type")
2225 }
2226
2227
2228
2229
2230 func TestCompositeLitTypes(t *testing.T) {
2231 for i, test := range []struct {
2232 lit, typ string
2233 }{
2234 {`[16]byte{}`, `[16]byte`},
2235 {`[...]byte{}`, `[0]byte`},
2236 {`[...]int{1, 2, 3}`, `[3]int`},
2237 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`},
2238 {`[]int{}`, `[]int`},
2239 {`map[string]bool{"foo": true}`, `map[string]bool`},
2240 {`struct{}{}`, `struct{}`},
2241 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
2242 } {
2243 fset := token.NewFileSet()
2244 f := mustParse(fset, fmt.Sprintf("package p%d; var _ = %s", i, test.lit))
2245 types := make(map[ast.Expr]TypeAndValue)
2246 if _, err := new(Config).Check("p", fset, []*ast.File{f}, &Info{Types: types}); err != nil {
2247 t.Fatalf("%s: %v", test.lit, err)
2248 }
2249
2250 cmptype := func(x ast.Expr, want string) {
2251 tv, ok := types[x]
2252 if !ok {
2253 t.Errorf("%s: no Types entry found", test.lit)
2254 return
2255 }
2256 if tv.Type == nil {
2257 t.Errorf("%s: type is nil", test.lit)
2258 return
2259 }
2260 if got := tv.Type.String(); got != want {
2261 t.Errorf("%s: got %v, want %s", test.lit, got, want)
2262 }
2263 }
2264
2265
2266 rhs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0]
2267 cmptype(rhs, test.typ)
2268
2269
2270 cmptype(rhs.(*ast.CompositeLit).Type, test.typ)
2271 }
2272 }
2273
2274
2275
2276 func TestObjectParents(t *testing.T) {
2277 const src = `
2278 package p
2279
2280 const C = 0
2281
2282 type T1 struct {
2283 a, b int
2284 T2
2285 }
2286
2287 type T2 interface {
2288 im1()
2289 im2()
2290 }
2291
2292 func (T1) m1() {}
2293 func (*T1) m2() {}
2294
2295 func f(x int) { y := x; print(y) }
2296 `
2297
2298 fset := token.NewFileSet()
2299 f := mustParse(fset, src)
2300
2301 info := &Info{
2302 Defs: make(map[*ast.Ident]Object),
2303 }
2304 if _, err := new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
2305 t.Fatal(err)
2306 }
2307
2308 for ident, obj := range info.Defs {
2309 if obj == nil {
2310
2311
2312 if ident.Name != "p" {
2313 t.Errorf("%v has nil object", ident)
2314 }
2315 continue
2316 }
2317
2318
2319
2320 wantParent := true
2321 switch obj := obj.(type) {
2322 case *Var:
2323 if obj.IsField() {
2324 wantParent = false
2325 }
2326 case *Func:
2327 if obj.Signature().Recv() != nil {
2328 wantParent = false
2329 }
2330 }
2331
2332 gotParent := obj.Parent() != nil
2333 switch {
2334 case gotParent && !wantParent:
2335 t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
2336 case !gotParent && wantParent:
2337 t.Errorf("%v: no parent found", ident)
2338 }
2339 }
2340 }
2341
2342
2343
2344 func TestFailedImport(t *testing.T) {
2345 testenv.MustHaveGoBuild(t)
2346
2347 const src = `
2348 package p
2349
2350 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
2351
2352 const c = foo.C
2353 type T = foo.T
2354 var v T = c
2355 func f(x T) T { return foo.F(x) }
2356 `
2357 fset := token.NewFileSet()
2358 f := mustParse(fset, src)
2359 files := []*ast.File{f}
2360
2361
2362 for _, compiler := range []string{"gc", "gccgo", "source"} {
2363 errcount := 0
2364 conf := Config{
2365 Error: func(err error) {
2366
2367 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
2368 t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
2369 }
2370 errcount++
2371 },
2372 Importer: importer.For(compiler, nil),
2373 }
2374
2375 info := &Info{
2376 Uses: make(map[*ast.Ident]Object),
2377 }
2378 pkg, _ := conf.Check("p", fset, files, info)
2379 if pkg == nil {
2380 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
2381 continue
2382 }
2383
2384 imports := pkg.Imports()
2385 if len(imports) != 1 {
2386 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
2387 continue
2388 }
2389 imp := imports[0]
2390 if imp.Name() != "foo" {
2391 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
2392 continue
2393 }
2394
2395
2396 for ident, obj := range info.Uses {
2397 if ident.Name == "foo" {
2398 if obj, ok := obj.(*PkgName); ok {
2399 if obj.Imported() != imp {
2400 t.Errorf("%s resolved to %v; want %v", ident, obj.Imported(), imp)
2401 }
2402 } else {
2403 t.Errorf("%s resolved to %v; want package name", ident, obj)
2404 }
2405 }
2406 }
2407 }
2408 }
2409
2410 func TestInstantiate(t *testing.T) {
2411
2412 const src = "package p; type T[P any] *T[P]"
2413 pkg := mustTypecheck(src, nil, nil)
2414
2415
2416 T := pkg.Scope().Lookup("T").Type().(*Named)
2417 if n := T.TypeParams().Len(); n != 1 {
2418 t.Fatalf("expected 1 type parameter; found %d", n)
2419 }
2420
2421
2422
2423 res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
2424 if err != nil {
2425 t.Fatal(err)
2426 }
2427
2428
2429 if p := res.Underlying().(*Pointer).Elem(); p != res {
2430 t.Fatalf("unexpected result type: %s points to %s", res, p)
2431 }
2432 }
2433
2434 func TestInstantiateConcurrent(t *testing.T) {
2435 const src = `package p
2436
2437 type I[P any] interface {
2438 m(P)
2439 n() P
2440 }
2441
2442 type J = I[int]
2443
2444 type Nested[P any] *interface{b(P)}
2445
2446 type K = Nested[string]
2447 `
2448 pkg := mustTypecheck(src, nil, nil)
2449
2450 insts := []*Interface{
2451 pkg.Scope().Lookup("J").Type().Underlying().(*Interface),
2452 pkg.Scope().Lookup("K").Type().Underlying().(*Pointer).Elem().(*Interface),
2453 }
2454
2455
2456 for _, inst := range insts {
2457 var (
2458 counts [2]int
2459 methods [2][]string
2460 )
2461 var wg sync.WaitGroup
2462 for i := 0; i < 2; i++ {
2463 i := i
2464 wg.Add(1)
2465 go func() {
2466 defer wg.Done()
2467
2468 counts[i] = inst.NumMethods()
2469 for mi := 0; mi < counts[i]; mi++ {
2470 methods[i] = append(methods[i], inst.Method(mi).String())
2471 }
2472 }()
2473 }
2474 wg.Wait()
2475
2476 if counts[0] != counts[1] {
2477 t.Errorf("mismatching method counts for %s: %d vs %d", inst, counts[0], counts[1])
2478 continue
2479 }
2480 for i := 0; i < counts[0]; i++ {
2481 if m0, m1 := methods[0][i], methods[1][i]; m0 != m1 {
2482 t.Errorf("mismatching methods for %s: %s vs %s", inst, m0, m1)
2483 }
2484 }
2485 }
2486 }
2487
2488 func TestInstantiateErrors(t *testing.T) {
2489 tests := []struct {
2490 src string
2491 targs []Type
2492 wantAt int
2493 }{
2494 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
2495 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
2496 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
2497 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
2498 }
2499
2500 for _, test := range tests {
2501 src := "package p; " + test.src
2502 pkg := mustTypecheck(src, nil, nil)
2503
2504 T := pkg.Scope().Lookup("T").Type().(*Named)
2505
2506 _, err := Instantiate(nil, T, test.targs, true)
2507 if err == nil {
2508 t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
2509 }
2510
2511 var argErr *ArgumentError
2512 if !errors.As(err, &argErr) {
2513 t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
2514 }
2515
2516 if argErr.Index != test.wantAt {
2517 t.Errorf("Instantiate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2518 }
2519 }
2520 }
2521
2522 func TestArgumentErrorUnwrapping(t *testing.T) {
2523 var err error = &ArgumentError{
2524 Index: 1,
2525 Err: Error{Msg: "test"},
2526 }
2527 var e Error
2528 if !errors.As(err, &e) {
2529 t.Fatalf("error %v does not wrap types.Error", err)
2530 }
2531 if e.Msg != "test" {
2532 t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2533 }
2534 }
2535
2536 func TestInstanceIdentity(t *testing.T) {
2537 imports := make(testImporter)
2538 conf := Config{Importer: imports}
2539 makePkg := func(src string) {
2540 fset := token.NewFileSet()
2541 f := mustParse(fset, src)
2542 name := f.Name.Name
2543 pkg, err := conf.Check(name, fset, []*ast.File{f}, nil)
2544 if err != nil {
2545 t.Fatal(err)
2546 }
2547 imports[name] = pkg
2548 }
2549 makePkg(`package lib; type T[P any] struct{}`)
2550 makePkg(`package a; import "lib"; var A lib.T[int]`)
2551 makePkg(`package b; import "lib"; var B lib.T[int]`)
2552 a := imports["a"].Scope().Lookup("A")
2553 b := imports["b"].Scope().Lookup("B")
2554 if !Identical(a.Type(), b.Type()) {
2555 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
2556 }
2557 }
2558
2559
2560 func TestInstantiatedObjects(t *testing.T) {
2561 const src = `
2562 package p
2563
2564 type T[P any] struct {
2565 field P
2566 }
2567
2568 func (recv *T[Q]) concreteMethod(mParam Q) (mResult Q) { return }
2569
2570 type FT[P any] func(ftParam P) (ftResult P)
2571
2572 func F[P any](fParam P) (fResult P){ return }
2573
2574 type I[P any] interface {
2575 interfaceMethod(P)
2576 }
2577
2578 type R[P any] T[P]
2579
2580 func (R[P]) m() {} // having a method triggers expansion of R
2581
2582 var (
2583 t T[int]
2584 ft FT[int]
2585 f = F[int]
2586 i I[int]
2587 )
2588
2589 func fn() {
2590 var r R[int]
2591 _ = r
2592 }
2593 `
2594 info := &Info{
2595 Defs: make(map[*ast.Ident]Object),
2596 }
2597 fset := token.NewFileSet()
2598 f := mustParse(fset, src)
2599 conf := Config{}
2600 pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
2601 if err != nil {
2602 t.Fatal(err)
2603 }
2604
2605 lookup := func(name string) Type { return pkg.Scope().Lookup(name).Type() }
2606 fnScope := pkg.Scope().Lookup("fn").(*Func).Scope()
2607
2608 tests := []struct {
2609 name string
2610 obj Object
2611 }{
2612
2613 {"field", lookup("t").Underlying().(*Struct).Field(0)},
2614 {"field", fnScope.Lookup("r").Type().Underlying().(*Struct).Field(0)},
2615
2616
2617 {"concreteMethod", lookup("t").(*Named).Method(0)},
2618 {"recv", lookup("t").(*Named).Method(0).Signature().Recv()},
2619 {"mParam", lookup("t").(*Named).Method(0).Signature().Params().At(0)},
2620 {"mResult", lookup("t").(*Named).Method(0).Signature().Results().At(0)},
2621
2622
2623 {"interfaceMethod", lookup("i").Underlying().(*Interface).Method(0)},
2624
2625
2626 {"ftParam", lookup("ft").Underlying().(*Signature).Params().At(0)},
2627 {"ftResult", lookup("ft").Underlying().(*Signature).Results().At(0)},
2628
2629
2630 {"fParam", lookup("f").(*Signature).Params().At(0)},
2631 {"fResult", lookup("f").(*Signature).Results().At(0)},
2632 }
2633
2634
2635 idents := make(map[string][]*ast.Ident)
2636 ast.Inspect(f, func(n ast.Node) bool {
2637 if id, ok := n.(*ast.Ident); ok {
2638 idents[id.Name] = append(idents[id.Name], id)
2639 }
2640 return true
2641 })
2642
2643 for _, test := range tests {
2644 test := test
2645 t.Run(test.name, func(t *testing.T) {
2646 if got := len(idents[test.name]); got != 1 {
2647 t.Fatalf("found %d identifiers named %s, want 1", got, test.name)
2648 }
2649 ident := idents[test.name][0]
2650 def := info.Defs[ident]
2651 if def == test.obj {
2652 t.Fatalf("info.Defs[%s] contains the test object", test.name)
2653 }
2654 if orig := originObject(test.obj); def != orig {
2655 t.Errorf("info.Defs[%s] does not match obj.Origin()", test.name)
2656 }
2657 if def.Pkg() != test.obj.Pkg() {
2658 t.Errorf("Pkg() = %v, want %v", def.Pkg(), test.obj.Pkg())
2659 }
2660 if def.Name() != test.obj.Name() {
2661 t.Errorf("Name() = %v, want %v", def.Name(), test.obj.Name())
2662 }
2663 if def.Pos() != test.obj.Pos() {
2664 t.Errorf("Pos() = %v, want %v", def.Pos(), test.obj.Pos())
2665 }
2666 if def.Parent() != test.obj.Parent() {
2667 t.Fatalf("Parent() = %v, want %v", def.Parent(), test.obj.Parent())
2668 }
2669 if def.Exported() != test.obj.Exported() {
2670 t.Fatalf("Exported() = %v, want %v", def.Exported(), test.obj.Exported())
2671 }
2672 if def.Id() != test.obj.Id() {
2673 t.Fatalf("Id() = %v, want %v", def.Id(), test.obj.Id())
2674 }
2675
2676 })
2677 }
2678 }
2679
2680 func originObject(obj Object) Object {
2681 switch obj := obj.(type) {
2682 case *Var:
2683 return obj.Origin()
2684 case *Func:
2685 return obj.Origin()
2686 }
2687 return obj
2688 }
2689
2690 func TestImplements(t *testing.T) {
2691 const src = `
2692 package p
2693
2694 type EmptyIface interface{}
2695
2696 type I interface {
2697 m()
2698 }
2699
2700 type C interface {
2701 m()
2702 ~int
2703 }
2704
2705 type Integer interface{
2706 int8 | int16 | int32 | int64
2707 }
2708
2709 type EmptyTypeSet interface{
2710 Integer
2711 ~string
2712 }
2713
2714 type N1 int
2715 func (N1) m() {}
2716
2717 type N2 int
2718 func (*N2) m() {}
2719
2720 type N3 int
2721 func (N3) m(int) {}
2722
2723 type N4 string
2724 func (N4) m()
2725
2726 type Bad Bad // invalid type
2727 `
2728
2729 fset := token.NewFileSet()
2730 f := mustParse(fset, src)
2731 conf := Config{Error: func(error) {}}
2732 pkg, _ := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
2733
2734 lookup := func(tname string) Type { return pkg.Scope().Lookup(tname).Type() }
2735 var (
2736 EmptyIface = lookup("EmptyIface").Underlying().(*Interface)
2737 I = lookup("I").(*Named)
2738 II = I.Underlying().(*Interface)
2739 C = lookup("C").(*Named)
2740 CI = C.Underlying().(*Interface)
2741 Integer = lookup("Integer").Underlying().(*Interface)
2742 EmptyTypeSet = lookup("EmptyTypeSet").Underlying().(*Interface)
2743 N1 = lookup("N1")
2744 N1p = NewPointer(N1)
2745 N2 = lookup("N2")
2746 N2p = NewPointer(N2)
2747 N3 = lookup("N3")
2748 N4 = lookup("N4")
2749 Bad = lookup("Bad")
2750 )
2751
2752 tests := []struct {
2753 V Type
2754 T *Interface
2755 want bool
2756 }{
2757 {I, II, true},
2758 {I, CI, false},
2759 {C, II, true},
2760 {C, CI, true},
2761 {Typ[Int8], Integer, true},
2762 {Typ[Int64], Integer, true},
2763 {Typ[String], Integer, false},
2764 {EmptyTypeSet, II, true},
2765 {EmptyTypeSet, EmptyTypeSet, true},
2766 {Typ[Int], EmptyTypeSet, false},
2767 {N1, II, true},
2768 {N1, CI, true},
2769 {N1p, II, true},
2770 {N1p, CI, false},
2771 {N2, II, false},
2772 {N2, CI, false},
2773 {N2p, II, true},
2774 {N2p, CI, false},
2775 {N3, II, false},
2776 {N3, CI, false},
2777 {N4, II, true},
2778 {N4, CI, false},
2779 {Bad, II, false},
2780 {Bad, CI, false},
2781 {Bad, EmptyIface, true},
2782 }
2783
2784 for _, test := range tests {
2785 if got := Implements(test.V, test.T); got != test.want {
2786 t.Errorf("Implements(%s, %s) = %t, want %t", test.V, test.T, got, test.want)
2787 }
2788
2789
2790
2791 V := test.T
2792 T := test.V
2793 want := false
2794 if _, ok := T.Underlying().(*Interface); (ok || Implements(T, V)) && T != Bad {
2795 want = true
2796 }
2797 if got := AssertableTo(V, T); got != want {
2798 t.Errorf("AssertableTo(%s, %s) = %t, want %t", V, T, got, want)
2799 }
2800 }
2801 }
2802
2803 func TestMissingMethodAlternative(t *testing.T) {
2804 const src = `
2805 package p
2806 type T interface {
2807 m()
2808 }
2809
2810 type V0 struct{}
2811 func (V0) m() {}
2812
2813 type V1 struct{}
2814
2815 type V2 struct{}
2816 func (V2) m() int
2817
2818 type V3 struct{}
2819 func (*V3) m()
2820
2821 type V4 struct{}
2822 func (V4) M()
2823 `
2824
2825 pkg := mustTypecheck(src, nil, nil)
2826
2827 T := pkg.Scope().Lookup("T").Type().Underlying().(*Interface)
2828 lookup := func(name string) (*Func, bool) {
2829 return MissingMethod(pkg.Scope().Lookup(name).Type(), T, true)
2830 }
2831
2832
2833 method, wrongType := lookup("V0")
2834 if method != nil || wrongType {
2835 t.Fatalf("V0: got method = %v, wrongType = %v", method, wrongType)
2836 }
2837
2838 checkMissingMethod := func(tname string, reportWrongType bool) {
2839 method, wrongType := lookup(tname)
2840 if method == nil || method.Name() != "m" || wrongType != reportWrongType {
2841 t.Fatalf("%s: got method = %v, wrongType = %v", tname, method, wrongType)
2842 }
2843 }
2844
2845
2846 checkMissingMethod("V1", false)
2847
2848
2849 checkMissingMethod("V2", true)
2850
2851
2852 checkMissingMethod("V3", true)
2853
2854
2855 checkMissingMethod("V4", false)
2856 }
2857
2858 func TestErrorURL(t *testing.T) {
2859 var conf Config
2860 *stringFieldAddr(&conf, "_ErrorURL") = " [go.dev/e/%s]"
2861
2862
2863 const src1 = `
2864 package p
2865 var _ T
2866 `
2867 _, err := typecheck(src1, &conf, nil)
2868 if err == nil || !strings.HasSuffix(err.Error(), " [go.dev/e/UndeclaredName]") {
2869 t.Errorf("src1: unexpected error: got %v", err)
2870 }
2871
2872
2873 const src2 = `
2874 package p
2875 func f() int { return 0 }
2876 var _ = f(1, 2)
2877 `
2878 _, err = typecheck(src2, &conf, nil)
2879 if err == nil || !strings.Contains(err.Error(), " [go.dev/e/WrongArgCount]\n") {
2880 t.Errorf("src1: unexpected error: got %v", err)
2881 }
2882 }
2883
2884 func TestModuleVersion(t *testing.T) {
2885
2886 goversion := fmt.Sprintf("go1.%d", goversion.Version)
2887 for _, v := range []string{
2888 goversion,
2889 goversion + ".0",
2890 goversion + ".1",
2891 goversion + ".rc",
2892 } {
2893 conf := Config{GoVersion: v}
2894 pkg := mustTypecheck("package p", &conf, nil)
2895 if pkg.GoVersion() != conf.GoVersion {
2896 t.Errorf("got %s; want %s", pkg.GoVersion(), conf.GoVersion)
2897 }
2898 }
2899 }
2900
2901 func TestFileVersions(t *testing.T) {
2902 for _, test := range []struct {
2903 goVersion string
2904 fileVersion string
2905 wantVersion string
2906 }{
2907 {"", "", ""},
2908 {"go1.19", "", "go1.19"},
2909 {"", "go1.20", "go1.21"},
2910 {"go1", "", "go1"},
2911 {"go1", "goo1.22", "go1"},
2912 {"go1", "go1.19", "go1.21"},
2913 {"go1", "go1.20", "go1.21"},
2914 {"go1", "go1.21", "go1.21"},
2915 {"go1", "go1.22", "go1.22"},
2916 {"go1.19", "", "go1.19"},
2917 {"go1.19", "goo1.22", "go1.19"},
2918 {"go1.19", "go1.20", "go1.21"},
2919 {"go1.19", "go1.21", "go1.21"},
2920 {"go1.19", "go1.22", "go1.22"},
2921 {"go1.20", "", "go1.20"},
2922 {"go1.20", "goo1.22", "go1.20"},
2923 {"go1.20", "go1.19", "go1.21"},
2924 {"go1.20", "go1.20", "go1.21"},
2925 {"go1.20", "go1.21", "go1.21"},
2926 {"go1.20", "go1.22", "go1.22"},
2927 {"go1.21", "", "go1.21"},
2928 {"go1.21", "goo1.22", "go1.21"},
2929 {"go1.21", "go1.19", "go1.21"},
2930 {"go1.21", "go1.20", "go1.21"},
2931 {"go1.21", "go1.21", "go1.21"},
2932 {"go1.21", "go1.22", "go1.22"},
2933 {"go1.22", "", "go1.22"},
2934 {"go1.22", "goo1.22", "go1.22"},
2935 {"go1.22", "go1.19", "go1.21"},
2936 {"go1.22", "go1.20", "go1.21"},
2937 {"go1.22", "go1.21", "go1.21"},
2938 {"go1.22", "go1.22", "go1.22"},
2939
2940
2941
2942 {"go1.19.0", "", "go1.19.0"},
2943 {"go1.20.1", "go1.19.1", "go1.20.1"},
2944 {"go1.20.1", "go1.21.1", "go1.20.1"},
2945 {"go1.21.1", "go1.19.1", "go1.21.1"},
2946 {"go1.21.1", "go1.21.1", "go1.21.1"},
2947 {"go1.22.1", "go1.19.1", "go1.22.1"},
2948 {"go1.22.1", "go1.21.1", "go1.22.1"},
2949 } {
2950 var src string
2951 if test.fileVersion != "" {
2952 src = "//go:build " + test.fileVersion + "\n"
2953 }
2954 src += "package p"
2955
2956 conf := Config{GoVersion: test.goVersion}
2957 versions := make(map[*ast.File]string)
2958 var info Info
2959 info.FileVersions = versions
2960 mustTypecheck(src, &conf, &info)
2961
2962 n := 0
2963 for _, v := range versions {
2964 want := test.wantVersion
2965 if v != want {
2966 t.Errorf("%q: unexpected file version: got %q, want %q", src, v, want)
2967 }
2968 n++
2969 }
2970 if n != 1 {
2971 t.Errorf("%q: incorrect number of map entries: got %d", src, n)
2972 }
2973 }
2974 }
2975
2976
2977
2978 func TestTooNew(t *testing.T) {
2979 for _, test := range []struct {
2980 goVersion string
2981 fileVersion string
2982 wantErr string
2983 }{
2984 {"go1.98", "", "package requires newer Go version go1.98"},
2985 {"", "go1.99", "p:2:9: file requires newer Go version go1.99"},
2986 {"go1.98", "go1.99", "package requires newer Go version go1.98"},
2987 {"go1.98", "go1.99", "file requires newer Go version go1.99"},
2988 } {
2989 var src string
2990 if test.fileVersion != "" {
2991 src = "//go:build " + test.fileVersion + "\n"
2992 }
2993 src += "package p; func f()"
2994
2995 var errs []error
2996 conf := Config{
2997 GoVersion: test.goVersion,
2998 Error: func(err error) { errs = append(errs, err) },
2999 }
3000 info := &Info{Defs: make(map[*ast.Ident]Object)}
3001 typecheck(src, &conf, info)
3002 got := fmt.Sprint(errs)
3003 if !strings.Contains(got, test.wantErr) {
3004 t.Errorf("%q: unexpected error: got %q, want substring %q",
3005 src, got, test.wantErr)
3006 }
3007
3008
3009 var gotObjs []string
3010 for id, obj := range info.Defs {
3011 if obj != nil {
3012 objStr := strings.ReplaceAll(fmt.Sprintf("%s:%T", id.Name, obj), "types2", "types")
3013 gotObjs = append(gotObjs, objStr)
3014 }
3015 }
3016 wantObjs := "f:*types.Func"
3017 if !strings.Contains(fmt.Sprint(gotObjs), wantObjs) {
3018 t.Errorf("%q: got %s, want substring %q",
3019 src, gotObjs, wantObjs)
3020 }
3021 }
3022 }
3023
3024
3025 func TestUnaliasTooSoonInCycle(t *testing.T) {
3026 setGotypesalias(t, true)
3027 const src = `package a
3028
3029 var x T[B] // this appears to cause Unalias to be called on B while still Invalid
3030
3031 type T[_ any] struct{}
3032 type A T[B]
3033 type B = T[A]
3034 `
3035 pkg := mustTypecheck(src, nil, nil)
3036 B := pkg.Scope().Lookup("B")
3037
3038 got, want := Unalias(B.Type()).String(), "a.T[a.A]"
3039 if got != want {
3040 t.Errorf("Unalias(type B = T[A]) = %q, want %q", got, want)
3041 }
3042 }
3043
3044 func TestAlias_Rhs(t *testing.T) {
3045 setGotypesalias(t, true)
3046 const src = `package p
3047
3048 type A = B
3049 type B = C
3050 type C = int
3051 `
3052
3053 pkg := mustTypecheck(src, nil, nil)
3054 A := pkg.Scope().Lookup("A")
3055
3056 got, want := A.Type().(*Alias).Rhs().String(), "p.B"
3057 if got != want {
3058 t.Errorf("A.Rhs = %s, want %s", got, want)
3059 }
3060 }
3061
3062
3063
3064 func TestAnyHijacking_Check(t *testing.T) {
3065 for _, enableAlias := range []bool{false, true} {
3066 t.Run(fmt.Sprintf("EnableAlias=%t", enableAlias), func(t *testing.T) {
3067 setGotypesalias(t, enableAlias)
3068 var wg sync.WaitGroup
3069 for i := 0; i < 10; i++ {
3070 wg.Add(1)
3071 go func() {
3072 defer wg.Done()
3073 pkg := mustTypecheck("package p; var x any", nil, nil)
3074 x := pkg.Scope().Lookup("x")
3075 if _, gotAlias := x.Type().(*Alias); gotAlias != enableAlias {
3076 t.Errorf(`Lookup("x").Type() is %T: got Alias: %t, want %t`, x.Type(), gotAlias, enableAlias)
3077 }
3078 }()
3079 }
3080 wg.Wait()
3081 })
3082 }
3083 }
3084
3085
3086
3087 func TestAnyHijacking_Lookup(t *testing.T) {
3088 for _, enableAlias := range []bool{false, true} {
3089 t.Run(fmt.Sprintf("EnableAlias=%t", enableAlias), func(t *testing.T) {
3090 setGotypesalias(t, enableAlias)
3091 a := Universe.Lookup("any")
3092 if _, gotAlias := a.Type().(*Alias); gotAlias != enableAlias {
3093 t.Errorf(`Lookup("x").Type() is %T: got Alias: %t, want %t`, a.Type(), gotAlias, enableAlias)
3094 }
3095 })
3096 }
3097 }
3098
3099 func setGotypesalias(t *testing.T, enable bool) {
3100 if enable {
3101 t.Setenv("GODEBUG", "gotypesalias=1")
3102 } else {
3103 t.Setenv("GODEBUG", "gotypesalias=0")
3104 }
3105 }
3106
View as plain text