Debian Codegraph @

go/ir/instantiate_test.go

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