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