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