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