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