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