Repository navigation
Expand file tree
/
Copy pathinstantiate_test.go
More file actions
334 lines (284 loc) · 7.75 KB
/
Copy pathinstantiate_test.go
File metadata and controls
334 lines (284 loc) · 7.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ir_test
import (
"fmt"
"go/types"
"reflect"
"sort"
"strings"
"testing"
"honnef.co/go/tools/go/ir"
"honnef.co/go/tools/go/ir/irutil"
)
// TestNeedsInstance ensures that new method instances can be created via MethodValue.
func TestNeedsInstance(t *testing.T) {
const input = `
package p
import "unsafe"
type Pointer[T any] struct {
v unsafe.Pointer
}
func (x *Pointer[T]) Load() *T {
return (*T)(LoadPointer(&x.v))
}
func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer)
`
// The SSA members for this package should look something like this:
// func LoadPointer func(addr *unsafe.Pointer) (val unsafe.Pointer)
// type Pointer struct{v unsafe.Pointer}
// method (*Pointer[T any]) Load() *T
// func init func()
// var init$guard bool
for _, mode := range []ir.BuilderMode{
ir.SanityCheckFunctions,
ir.SanityCheckFunctions | ir.InstantiateGenerics,
} {
p, _ := buildPackage(t, input, mode)
prog := p.Prog
ptr := p.Type("Pointer").Type().(*types.Named)
if ptr.NumMethods() != 1 {
t.Fatalf("Expected Pointer to have 1 method. got %d", ptr.NumMethods())
}
obj := ptr.Method(0)
if obj.Name() != "Load" {
t.Errorf("Expected Pointer to have method named 'Load'. got %q", obj.Name())
}
meth := prog.FuncValue(obj)
// instantiateLoadMethod returns the first method (Load) of the instantiation *Pointer[T].
instantiateLoadMethod := func(T types.Type) *ir.Function {
ptrT, err := types.Instantiate(nil, ptr, []types.Type{T}, false)
if err != nil {
t.Fatalf("Failed to Instantiate %q by %q", ptr, T)
}
methods := types.NewMethodSet(types.NewPointer(ptrT))
if methods.Len() != 1 {
t.Fatalf("Expected 1 method for %q. got %d", ptrT, methods.Len())
}
return prog.MethodValue(methods.At(0))
}
intSliceTyp := types.NewSlice(types.Typ[types.Int])
inst1 := instantiateLoadMethod(intSliceTyp) // (*p.Pointer[[]int]).Load
if inst1.Origin() != meth {
t.Errorf("Expected Origin of %s to be %s. got %s", inst1, meth, inst1.Origin())
}
if len(inst1.TypeArgs()) != 1 || !types.Identical(inst1.TypeArgs()[0], intSliceTyp) {
t.Errorf("Expected TypeArgs of %s to be %v. got %v", inst1, []types.Type{intSliceTyp}, inst1.TypeArgs())
}
// A second request with an identical type returns the same Function.
second := instantiateLoadMethod(types.NewSlice(types.Typ[types.Int]))
if second != inst1 {
t.Error("Expected second identical instantiation to be the same function")
}
// (*p.Pointer[[]uint]).Load
inst2 := instantiateLoadMethod(types.NewSlice(types.Typ[types.Uint]))
if inst1.Name() != "Load" {
t.Errorf("Unexpected name of instance %s; got %s, want Load", inst1.String(), inst1.Name())
}
if inst2.Name() != "Load" {
t.Errorf("Unexpected name of instance %s; got %s, want Load", inst1.String(), inst2.Name())
}
if inst1.String() != "(*p.Pointer[[]int]).Load" {
t.Errorf("Unexpected string of first instance; got %s, want (*p.Pointer[[]int]).Load", inst1.String())
}
if inst2.String() != "(*p.Pointer[[]uint]).Load" {
t.Errorf("Unexpected string of second instance; got %s, want (*p.Pointer[[]uint]).Load", inst2.String())
}
}
}
func TestNestedFunctionsInMethodWithInstantiatedReceiver(t *testing.T) {
for _, test := range []struct {
name, input string
}{
{"func-literal", `
package p
type T[P any] struct{}
func (T[P]) f() {
func() {
func() { var _ P }()
}()
}
var _ = T[int].f
`},
{"range-over-func", `
package p
type T[P any] struct{}
func (T[P]) f(seq func(func() bool)) {
for range seq {
func() { var _ P }()
}
}
var _ = T[int].f
`},
} {
t.Run(test.name, func(t *testing.T) {
buildPackage(t, test.input, ir.SanityCheckFunctions|ir.InstantiateGenerics)
})
}
}
// TestCallsToInstances checks that calles of calls to generic functions,
// without monomorphization, are wrappers around the origin generic function.
func TestCallsToInstances(t *testing.T) {
const input = `
package p
type I interface {
Foo()
}
type A int
func (a A) Foo() {}
type J[T any] interface{ Bar() T }
type K[T any] struct{ J[T] }
func Id[T any] (t T) T {
return t
}
func Lambda[T I]() func() func(T) {
return func() func(T) {
return T.Foo
}
}
func NoOp[T any]() {}
func Bar[T interface { Foo(); ~int | ~string }, U any] (t T, u U) {
Id[U](u)
Id[T](t)
}
func Make[T any]() interface{} {
NoOp[K[T]]()
return nil
}
func entry(i int, a A) int {
Lambda[A]()()(a)
x := Make[int]()
if j, ok := x.(interface{ Bar() int }); ok {
print(j)
}
Bar[A, int](a, i)
return Id[int](i)
}
`
p, _ := buildPackage(t, input, ir.SanityCheckFunctions)
all := irutil.AllFunctions(p.Prog)
for _, ti := range []struct {
orig string
instance string
tparams string
targs string
chTypeInstrs int // number of ChangeType instructions in f's body
}{
{"Id", "Id[int]", "[T]", "[int]", 2},
{"Lambda", "Lambda[p.A]", "[T]", "[p.A]", 1},
{"Make", "Make[int]", "[T]", "[int]", 0},
{"NoOp", "NoOp[p.K[T]]", "[T]", "[p.K[T]]", 0},
} {
test := ti
t.Run(test.instance, func(t *testing.T) {
f := p.Members[test.orig].(*ir.Function)
if f == nil {
t.Fatalf("origin function not found")
}
var i *ir.Function
for _, fn := range instancesOf(all, f) {
if fn.Name() == test.instance {
i = fn
break
}
}
if i == nil {
t.Fatalf("instance not found")
}
// for logging on failures
var body strings.Builder
i.WriteTo(&body)
t.Log(body.String())
if len(i.Blocks) != 1 {
t.Fatalf("body has more than 1 block")
}
if instrs := changeTypeInstrs(i.Blocks[0]); instrs != test.chTypeInstrs {
t.Errorf("want %v instructions; got %v", test.chTypeInstrs, instrs)
}
if test.tparams != tparams(i) {
t.Errorf("want %v type params; got %v", test.tparams, tparams(i))
}
if test.targs != targs(i) {
t.Errorf("want %v type arguments; got %v", test.targs, targs(i))
}
})
}
}
func tparams(f *ir.Function) string {
tplist := f.TypeParams()
var tps []string
for tparam := range tplist.TypeParams() {
tps = append(tps, tparam.String())
}
return fmt.Sprint(tps)
}
func targs(f *ir.Function) string {
var tas []string
for _, ta := range f.TypeArgs() {
tas = append(tas, ta.String())
}
return fmt.Sprint(tas)
}
func changeTypeInstrs(b *ir.BasicBlock) int {
cnt := 0
for _, i := range b.Instrs {
if _, ok := i.(*ir.ChangeType); ok {
cnt++
}
}
return cnt
}
func TestInstanceUniqueness(t *testing.T) {
const input = `
package p
func H[T any](t T) {
print(t)
}
func F[T any](t T) {
H[T](t)
H[T](t)
H[T](t)
}
func G[T any](t T) {
H[T](t)
H[T](t)
}
func Foo[T any, S any](t T, s S) {
Foo[S, T](s, t)
Foo[T, S](t, s)
}
`
p, _ := buildPackage(t, input, ir.SanityCheckFunctions)
all := irutil.AllFunctions(p.Prog)
for _, test := range []struct {
orig string
instances string
}{
{"H", "[p.H[T] p.H[T]]"},
{"Foo", "[p.Foo[S, T] p.Foo[T, S]]"},
} {
t.Run(test.orig, func(t *testing.T) {
f := p.Members[test.orig].(*ir.Function)
if f == nil {
t.Fatalf("origin function not found")
}
instances := instancesOf(all, f)
sort.Slice(instances, func(i, j int) bool { return instances[i].Name() < instances[j].Name() })
if got := fmt.Sprintf("%v", instances); !reflect.DeepEqual(got, test.instances) {
t.Errorf("got %v instances, want %v", got, test.instances)
}
})
}
}
// instancesOf returns a new unordered slice of all instances of the
// specified function g in fns.
func instancesOf(fns map[*ir.Function]bool, g *ir.Function) []*ir.Function {
var instances []*ir.Function
for fn := range fns {
if fn != g && fn.Origin() == g {
instances = append(instances, fn)
}
}
return instances
}