Debian Codegraph @

go/ir/subst.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
6
7 import (
8 "fmt"
9 "go/types"
10
11 "honnef.co/go/tools/go/types/typeutil"
12 "honnef.co/go/tools/internal/xtools-internal/aliases"
13 )
14
15 // subster defines a type substitution operation of a set of type parameters
16 // to type parameter free replacement types. Substitution is done within
17 // the context of a package-level function instantiation. *Named types
18 // declared in the function are unique to the instantiation.
19 //
20 // For example, given a parameterized function F
21 //
22 // func F[S, T any]() any {
23 // type X struct{ s S; next *X }
24 // var p *X
25 // return p
26 // }
27 //
28 // calling the instantiation F[string, int]() returns an interface
29 // value (*X[string,int], nil) where the underlying value of
30 // X[string,int] is a struct{s string; next *X[string,int]}.
31 //
32 // A nil *subster is a valid, empty substitution map. It always acts as
33 // the identity function. This allows for treating parameterized and
34 // non-parameterized functions identically while compiling to ssa.
35 //
36 // Not concurrency-safe.
37 //
38 // Note: Some may find it helpful to think through some of the most
39 // complex substitution cases using lambda calculus inspired notation.
40 // subst.typ() solves evaluating a type expression E
41 // within the body of a function Fn[m] with the type parameters m
42 // once we have applied the type arguments N.
43 // We can succinctly write this as a function application:
44 //
45 // ((λm. E) N)
46 //
47 // go/types does not provide this interface directly.
48 // So what subster provides is a type substitution operation
49 //
50 // E[m:=N]
51 type subster struct {
52 replacements map[*types.TypeParam]types.Type // values should contain no type params
53 cache map[types.Type]types.Type // cache of subst results
54 origin *types.Func // types.Objects declared within this origin function are unique within this context
55 ctxt *types.Context // speeds up repeated instantiations
56 uniqueness typeutil.Map[types.Type] // determines the uniqueness of the instantiations within the function
57 // TODO(taking): consider adding Pos
58 }
59
60 // Returns a subster that replaces rtparams[i] with rtargs[i] and tparams[i] with targs[i].
61 // Uses ctxt as a cache. rtargs and targs should not contain any types in rtparams or tparams.
62 // fn is the generic function for which we are substituting.
63 func makeSubster(ctxt *types.Context, fn *types.Func, rtparams *types.TypeParamList, rtargs []types.Type, tparams *types.TypeParamList, targs []types.Type) *subster {
64 got := len(rtargs) + len(targs)
65 want := rtparams.Len() + tparams.Len()
66 if got != want {
67 panic(fmt.Sprintf("makeSubster argument count must match: got %d; want %d", got, want))
68 }
69
70 subst := &subster{
71 replacements: make(map[*types.TypeParam]types.Type, want),
72 cache: make(map[types.Type]types.Type),
73 origin: fn.Origin(),
74 ctxt: ctxt,
75 }
76 for i := 0; i < rtparams.Len(); i++ {
77 subst.replacements[rtparams.At(i)] = rtargs[i]
78 }
79 for i := 0; i < tparams.Len(); i++ {
80 subst.replacements[tparams.At(i)] = targs[i]
81 }
82 return subst
83 }
84
85 // typ returns the type of t with the type parameter tparams[i] substituted
86 // for the type targs[i] where subst was created using tparams and targs.
87 func (subst *subster) typ(t types.Type) (res types.Type) {
88 if subst == nil {
89 return t // A nil subst is type preserving.
90 }
91 if r, ok := subst.cache[t]; ok {
92 return r
93 }
94 defer func() {
95 subst.cache[t] = res
96 }()
97
98 switch t := t.(type) {
99 case *types.TypeParam:
100 if r := subst.replacements[t]; r != nil {
101 return r
102 }
103 return t
104
105 case *types.Basic:
106 return t
107
108 case *types.Array:
109 if r := subst.typ(t.Elem()); r != t.Elem() {
110 return types.NewArray(r, t.Len())
111 }
112 return t
113
114 case *types.Slice:
115 if r := subst.typ(t.Elem()); r != t.Elem() {
116 return types.NewSlice(r)
117 }
118 return t
119
120 case *types.Pointer:
121 if r := subst.typ(t.Elem()); r != t.Elem() {
122 return types.NewPointer(r)
123 }
124 return t
125
126 case *types.Tuple:
127 return subst.tuple(t)
128
129 case *types.Struct:
130 return subst.struct_(t)
131
132 case *types.Map:
133 key := subst.typ(t.Key())
134 elem := subst.typ(t.Elem())
135 if key != t.Key() || elem != t.Elem() {
136 return types.NewMap(key, elem)
137 }
138 return t
139
140 case *types.Chan:
141 if elem := subst.typ(t.Elem()); elem != t.Elem() {
142 return types.NewChan(t.Dir(), elem)
143 }
144 return t
145
146 case *types.Signature:
147 return subst.signature(t)
148
149 case *types.Union:
150 return subst.union(t)
151
152 case *types.Interface:
153 return subst.interface_(t)
154
155 case *types.Alias:
156 return subst.alias(t)
157
158 case *types.Named:
159 return subst.named(t)
160
161 case *typeutil.Iterator:
162 elem := subst.typ(t.Elem())
163 if elem != t.Elem() {
164 return typeutil.NewIterator(elem)
165 }
166 return t
167
168 case *typeutil.DeferStack:
169 return t
170
171 default:
172 panic(fmt.Sprintf("internal error: unhandled type %T", t))
173 }
174 }
175
176 // types returns the result of {subst.typ(ts[i])}.
177 func (subst *subster) types(ts []types.Type) []types.Type {
178 res := make([]types.Type, len(ts))
179 for i := range ts {
180 res[i] = subst.typ(ts[i])
181 }
182 return res
183 }
184
185 func (subst *subster) tuple(t *types.Tuple) *types.Tuple {
186 if t != nil {
187 if vars := subst.varlist(t); vars != nil {
188 return types.NewTuple(vars...)
189 }
190 }
191 return t
192 }
193
194 type varlist interface {
195 At(i int) *types.Var
196 Len() int
197 }
198
199 // fieldlist is an adapter for structs for the varlist interface.
200 type fieldlist struct {
201 str *types.Struct
202 }
203
204 func (fl fieldlist) At(i int) *types.Var { return fl.str.Field(i) }
205 func (fl fieldlist) Len() int { return fl.str.NumFields() }
206
207 func (subst *subster) struct_(t *types.Struct) *types.Struct {
208 if t != nil {
209 if fields := subst.varlist(fieldlist{t}); fields != nil {
210 tags := make([]string, t.NumFields())
211 for i, n := 0, t.NumFields(); i < n; i++ {
212 tags[i] = t.Tag(i)
213 }
214 return types.NewStruct(fields, tags)
215 }
216 }
217 return t
218 }
219
220 // varlist returns subst(in[i]) or return nils if subst(v[i]) == v[i] for all i.
221 func (subst *subster) varlist(in varlist) []*types.Var {
222 var out []*types.Var // nil => no updates
223 for i, n := 0, in.Len(); i < n; i++ {
224 v := in.At(i)
225 w := subst.var_(v)
226 if v != w && out == nil {
227 out = make([]*types.Var, n)
228 for j := 0; j < i; j++ {
229 out[j] = in.At(j)
230 }
231 }
232 if out != nil {
233 out[i] = w
234 }
235 }
236 return out
237 }
238
239 func (subst *subster) var_(v *types.Var) *types.Var {
240 if v != nil {
241 if typ := subst.typ(v.Type()); typ != v.Type() {
242 if v.IsField() {
243 return types.NewField(v.Pos(), v.Pkg(), v.Name(), typ, v.Embedded())
244 }
245 return types.NewParam(v.Pos(), v.Pkg(), v.Name(), typ)
246 }
247 }
248 return v
249 }
250
251 func (subst *subster) union(u *types.Union) *types.Union {
252 var out []*types.Term // nil => no updates
253
254 for i, n := 0, u.Len(); i < n; i++ {
255 t := u.Term(i)
256 r := subst.typ(t.Type())
257 if r != t.Type() && out == nil {
258 out = make([]*types.Term, n)
259 for j := 0; j < i; j++ {
260 out[j] = u.Term(j)
261 }
262 }
263 if out != nil {
264 out[i] = types.NewTerm(t.Tilde(), r)
265 }
266 }
267
268 if out != nil {
269 return types.NewUnion(out)
270 }
271 return u
272 }
273
274 func (subst *subster) interface_(iface *types.Interface) *types.Interface {
275 if iface == nil {
276 return nil
277 }
278
279 // methods for the interface. Initially nil if there is no known change needed.
280 // Signatures for the method where recv is nil. NewInterfaceType fills in the receivers.
281 var methods []*types.Func
282 initMethods := func(n int) { // copy first n explicit methods
283 methods = make([]*types.Func, iface.NumExplicitMethods())
284 for i := range n {
285 f := iface.ExplicitMethod(i)
286 norecv := changeRecv(f.Type().(*types.Signature), nil)
287 methods[i] = types.NewFunc(f.Pos(), f.Pkg(), f.Name(), norecv)
288 }
289 }
290 for i := 0; i < iface.NumExplicitMethods(); i++ {
291 f := iface.ExplicitMethod(i)
292 // On interfaces, we need to cycle break on anonymous interface types
293 // being in a cycle with their signatures being in cycles with their receivers
294 // that do not go through a Named.
295 norecv := changeRecv(f.Type().(*types.Signature), nil)
296 sig := subst.typ(norecv)
297 if sig != norecv && methods == nil {
298 initMethods(i)
299 }
300 if methods != nil {
301 methods[i] = types.NewFunc(f.Pos(), f.Pkg(), f.Name(), sig.(*types.Signature))
302 }
303 }
304
305 var embeds []types.Type
306 initEmbeds := func(n int) { // copy first n embedded types
307 embeds = make([]types.Type, iface.NumEmbeddeds())
308 for i := range n {
309 embeds[i] = iface.EmbeddedType(i)
310 }
311 }
312 for i := 0; i < iface.NumEmbeddeds(); i++ {
313 e := iface.EmbeddedType(i)
314 r := subst.typ(e)
315 if e != r && embeds == nil {
316 initEmbeds(i)
317 }
318 if embeds != nil {
319 embeds[i] = r
320 }
321 }
322
323 if methods == nil && embeds == nil {
324 return iface
325 }
326 if methods == nil {
327 initMethods(iface.NumExplicitMethods())
328 }
329 if embeds == nil {
330 initEmbeds(iface.NumEmbeddeds())
331 }
332 return types.NewInterfaceType(methods, embeds).Complete()
333 }
334
335 func (subst *subster) alias(t *types.Alias) types.Type {
336 // See subster.named. This follows the same strategy.
337 tparams := t.TypeParams()
338 targs := t.TypeArgs()
339 tname := t.Obj()
340 torigin := t.Origin()
341
342 if !declaredWithin(tname, subst.origin) {
343 // t is declared outside of the function origin. So t is a package level type alias.
344 if targs.Len() == 0 {
345 // No type arguments so no instantiation needed.
346 return t
347 }
348
349 // Instantiate with the substituted type arguments.
350 newTArgs := subst.typelist(targs)
351 return subst.instantiate(torigin, newTArgs)
352 }
353
354 if targs.Len() == 0 {
355 // t is declared within the function origin and has no type arguments.
356 //
357 // Example: This corresponds to A or B in F, but not A[int]:
358 //
359 // func F[T any]() {
360 // type A[S any] = struct{t T, s S}
361 // type B = T
362 // var x A[int]
363 // ...
364 // }
365 //
366 // This is somewhat different than *Named as *Alias cannot be created recursively.
367
368 // Copy and substitute type params.
369 var newTParams []*types.TypeParam
370 for cur := range tparams.TypeParams() {
371 cobj := cur.Obj()
372 cname := types.NewTypeName(cobj.Pos(), cobj.Pkg(), cobj.Name(), nil)
373 ntp := types.NewTypeParam(cname, nil)
374 subst.cache[cur] = ntp // See the comment "Note: Subtle" in subster.named.
375 newTParams = append(newTParams, ntp)
376 }
377
378 // Substitute rhs.
379 rhs := subst.typ(t.Rhs())
380
381 // Create the fresh alias.
382 obj := aliases.New(tname.Pos(), tname.Pkg(), tname.Name(), rhs, newTParams)
383
384 // Substitute into all of the constraints after they are created.
385 for i, ntp := range newTParams {
386 bound := tparams.At(i).Constraint()
387 ntp.SetConstraint(subst.typ(bound))
388 }
389 return obj.Type()
390 }
391
392 // t is declared within the function origin and has type arguments.
393 //
394 // Example: This corresponds to A[int] in F. Cases A and B are handled above.
395 // func F[T any]() {
396 // type A[S any] = struct{t T, s S}
397 // type B = T
398 // var x A[int]
399 // ...
400 // }
401 subOrigin := subst.typ(torigin)
402 subTArgs := subst.typelist(targs)
403 return subst.instantiate(subOrigin, subTArgs)
404 }
405
406 func (subst *subster) named(t *types.Named) types.Type {
407 // A Named type is a user defined type.
408 // Ignoring generics, Named types are canonical: they are identical if
409 // and only if they have the same defining symbol.
410 // Generics complicate things, both if the type definition itself is
411 // parameterized, and if the type is defined within the scope of a
412 // parameterized function. In this case, two named types are identical if
413 // and only if their identifying symbols are identical, and all type
414 // arguments bindings in scope of the named type definition (including the
415 // type parameters of the definition itself) are equivalent.
416 //
417 // Notably:
418 // 1. For type definition type T[P1 any] struct{}, T[A] and T[B] are identical
419 // only if A and B are identical.
420 // 2. Inside the generic func Fn[m any]() any { type T struct{}; return T{} },
421 // the result of Fn[A] and Fn[B] have identical type if and only if A and
422 // B are identical.
423 // 3. Both 1 and 2 could apply, such as in
424 // func F[m any]() any { type T[x any] struct{}; return T{} }
425 //
426 // A subster replaces type parameters within a function scope, and therefore must
427 // also replace free type parameters in the definitions of local types.
428 //
429 // Note: There are some detailed notes sprinkled throughout that borrow from
430 // lambda calculus notation. These contain some over simplifying math.
431 //
432 // LC: One way to think about subster is that it is a way of evaluating
433 // ((λm. E) N) as E[m:=N].
434 // Each Named type t has an object *TypeName within a scope S that binds an
435 // underlying type expression U. U can refer to symbols within S (+ S's ancestors).
436 // Let x = t.TypeParams() and A = t.TypeArgs().
437 // Each Named type t is then either:
438 // U where len(x) == 0 && len(A) == 0
439 // λx. U where len(x) != 0 && len(A) == 0
440 // ((λx. U) A) where len(x) == len(A)
441 // In each case, we will evaluate t[m:=N].
442 tparams := t.TypeParams() // x
443 targs := t.TypeArgs() // A
444
445 if !declaredWithin(t.Obj(), subst.origin) {
446 // t is declared outside of Fn[m].
447 //
448 // In this case, we can skip substituting t.Underlying().
449 // The underlying type cannot refer to the type parameters.
450 //
451 // LC: Let free(E) be the set of free type parameters in an expression E.
452 // Then whenever m ∉ free(E), then E = E[m:=N].
453 // t ∉ Scope(fn) so therefore m ∉ free(U) and m ∩ x = ∅.
454 if targs.Len() == 0 {
455 // t has no type arguments. So it does not need to be instantiated.
456 //
457 // This is the normal case in real Go code, where t is not parameterized,
458 // declared at some package scope, and m is a TypeParam from a parameterized
459 // function F[m] or method.
460 //
461 // LC: m ∉ free(A) lets us conclude m ∉ free(t). So t=t[m:=N].
462 return t
463 }
464
465 // t is declared outside of Fn[m] and has type arguments.
466 // The type arguments may contain type parameters m so
467 // substitute the type arguments, and instantiate the substituted
468 // type arguments.
469 //
470 // LC: Evaluate this as ((λx. U) A') where A' = A[m := N].
471 newTArgs := subst.typelist(targs)
472 return subst.instantiate(t.Origin(), newTArgs)
473 }
474
475 // t is declared within Fn[m].
476
477 if targs.Len() == 0 { // no type arguments?
478 assert(t == t.Origin(), "local parameterized type abstraction must be an origin type")
479
480 // t has no type arguments.
481 // The underlying type of t may contain the function's type parameters,
482 // replace these, and create a new type.
483 //
484 // Subtle: We short circuit substitution and use a newly created type in
485 // subst, i.e. cache[t]=fresh, to preemptively replace t with fresh
486 // in recursive types during traversal. This both breaks infinite cycles
487 // and allows for constructing types with the replacement applied in
488 // subst.typ(U).
489 //
490 // A new copy of the Named and Typename (and constraints) per function
491 // instantiation matches the semantics of Go, which treats all function
492 // instantiations F[N] as having distinct local types.
493 //
494 // LC: x.Len()=0 can be thought of as a special case of λx. U.
495 // LC: Evaluate (λx. U)[m:=N] as (λx'. U') where U'=U[x:=x',m:=N].
496 tname := t.Obj()
497 obj := types.NewTypeName(tname.Pos(), tname.Pkg(), tname.Name(), nil)
498 fresh := types.NewNamed(obj, nil, nil)
499 var newTParams []*types.TypeParam
500 for cur := range tparams.TypeParams() {
501 cobj := cur.Obj()
502 cname := types.NewTypeName(cobj.Pos(), cobj.Pkg(), cobj.Name(), nil)
503 ntp := types.NewTypeParam(cname, nil)
504 subst.cache[cur] = ntp
505 newTParams = append(newTParams, ntp)
506 }
507 fresh.SetTypeParams(newTParams)
508 subst.cache[t] = fresh
509 subst.cache[fresh] = fresh
510 fresh.SetUnderlying(subst.typ(t.Underlying()))
511 // Substitute into all of the constraints after they are created.
512 for i, ntp := range newTParams {
513 bound := tparams.At(i).Constraint()
514 ntp.SetConstraint(subst.typ(bound))
515 }
516 return fresh
517 }
518
519 // t is defined within Fn[m] and t has type arguments (an instantiation).
520 // We reduce this to the two cases above:
521 // (1) substitute the function's type parameters into t.Origin().
522 // (2) substitute t's type arguments A and instantiate the updated t.Origin() with these.
523 //
524 // LC: Evaluate ((λx. U) A)[m:=N] as (t' A') where t' = (λx. U)[m:=N] and A'=A [m:=N]
525 subOrigin := subst.typ(t.Origin())
526 subTArgs := subst.typelist(targs)
527 return subst.instantiate(subOrigin, subTArgs)
528 }
529
530 func (subst *subster) instantiate(orig types.Type, targs []types.Type) types.Type {
531 i, err := types.Instantiate(subst.ctxt, orig, targs, false)
532 assert(err == nil, "failed to Instantiate named (Named or Alias) type")
533 if c, _ := subst.uniqueness.At(i); c != nil {
534 return c
535 }
536 subst.uniqueness.Set(i, i)
537 return i
538 }
539
540 func (subst *subster) typelist(l *types.TypeList) []types.Type {
541 res := make([]types.Type, l.Len())
542 for i := 0; i < l.Len(); i++ {
543 res[i] = subst.typ(l.At(i))
544 }
545 return res
546 }
547
548 func (subst *subster) signature(t *types.Signature) types.Type {
549 tparams := t.TypeParams()
550
551 // We are choosing not to support tparams.Len() > 0 until a need has been observed in practice.
552 //
553 // There are some known usages for types.Types coming from types.{Eval,CheckExpr}.
554 // To support tparams.Len() > 0, we just need to do the following [pseudocode]:
555 // targs := {subst.replacements[tparams[i]]]}; Instantiate(ctxt, t, targs, false)
556
557 assert(tparams.Len() == 0, "Substituting types.Signatures with generic functions are currently unsupported.")
558
559 // Either:
560 // (1)non-generic function.
561 // no type params to substitute
562 // (2)generic method and recv needs to be substituted.
563
564 // Receivers can be either:
565 // named
566 // pointer to named
567 // interface
568 // nil
569 // interface is the problematic case. We need to cycle break there!
570 recv := subst.var_(t.Recv())
571 params := subst.tuple(t.Params())
572 results := subst.tuple(t.Results())
573 if recv != t.Recv() || params != t.Params() || results != t.Results() {
574 return types.NewSignatureType(recv, nil, nil, params, results, t.Variadic())
575 }
576 return t
577 }