]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/unify.go
go/types, types2: handle unbound type parameters in switch (cleanup)
[gostls13.git] / src / cmd / compile / internal / types2 / unify.go
1 // Copyright 2020 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 // This file implements type unification.
6 //
7 // Type unification attempts to make two types x and y structurally
8 // identical by determining the types for a given list of (bound)
9 // type parameters which may occur within x and y. If x and y are
10 // are structurally different (say []T vs chan T), or conflicting
11 // types are determined for type parameters, unification fails.
12 // If unification succeeds, as a side-effect, the types of the
13 // bound type parameters may be determined.
14 //
15 // Unification typically requires multiple calls u.unify(x, y) to
16 // a given unifier u, with various combinations of types x and y.
17 // In each call, additional type parameter types may be determined
18 // as a side effect. If a call fails (returns false), unification
19 // fails.
20 //
21 // In the unification context, structural identity ignores the
22 // difference between a defined type and its underlying type.
23 // It also ignores the difference between an (external, unbound)
24 // type parameter and its core type.
25 // If two types are not structurally identical, they cannot be Go
26 // identical types. On the other hand, if they are structurally
27 // identical, they may be Go identical or at least assignable, or
28 // they may be in the type set of a constraint.
29 // Whether they indeed are identical or assignable is determined
30 // upon instantiation and function argument passing.
31
32 package types2
33
34 import (
35         "bytes"
36         "fmt"
37         "sort"
38         "strings"
39 )
40
41 const (
42         // Upper limit for recursion depth. Used to catch infinite recursions
43         // due to implementation issues (e.g., see issues go.dev/issue/48619, go.dev/issue/48656).
44         unificationDepthLimit = 50
45
46         // Whether to panic when unificationDepthLimit is reached.
47         // If disabled, a recursion depth overflow results in a (quiet)
48         // unification failure.
49         panicAtUnificationDepthLimit = true
50
51         // If enableCoreTypeUnification is set, unification will consider
52         // the core types, if any, of non-local (unbound) type parameters.
53         enableCoreTypeUnification = true
54
55         // If traceInference is set, unification will print a trace of its operation.
56         // Interpretation of trace:
57         //   x ≡ y    attempt to unify types x and y
58         //   p ➞ y    type parameter p is set to type y (p is inferred to be y)
59         //   p ⇄ q    type parameters p and q match (p is inferred to be q and vice versa)
60         //   x ≢ y    types x and y cannot be unified
61         //   [p, q, ...] ➞ [x, y, ...]    mapping from type parameters to types
62         traceInference = false
63 )
64
65 // A unifier maintains a list of type parameters and
66 // corresponding types inferred for each type parameter.
67 // A unifier is created by calling newUnifier.
68 type unifier struct {
69         // handles maps each type parameter to its inferred type through
70         // an indirection *Type called (inferred type) "handle".
71         // Initially, each type parameter has its own, separate handle,
72         // with a nil (i.e., not yet inferred) type.
73         // After a type parameter P is unified with a type parameter Q,
74         // P and Q share the same handle (and thus type). This ensures
75         // that inferring the type for a given type parameter P will
76         // automatically infer the same type for all other parameters
77         // unified (joined) with P.
78         handles map[*TypeParam]*Type
79         depth   int // recursion depth during unification
80 }
81
82 // newUnifier returns a new unifier initialized with the given type parameter
83 // and corresponding type argument lists. The type argument list may be shorter
84 // than the type parameter list, and it may contain nil types. Matching type
85 // parameters and arguments must have the same index.
86 func newUnifier(tparams []*TypeParam, targs []Type) *unifier {
87         assert(len(tparams) >= len(targs))
88         handles := make(map[*TypeParam]*Type, len(tparams))
89         // Allocate all handles up-front: in a correct program, all type parameters
90         // must be resolved and thus eventually will get a handle.
91         // Also, sharing of handles caused by unified type parameters is rare and
92         // so it's ok to not optimize for that case (and delay handle allocation).
93         for i, x := range tparams {
94                 var t Type
95                 if i < len(targs) {
96                         t = targs[i]
97                 }
98                 handles[x] = &t
99         }
100         return &unifier{handles, 0}
101 }
102
103 // unify attempts to unify x and y and reports whether it succeeded.
104 // As a side-effect, types may be inferred for type parameters.
105 func (u *unifier) unify(x, y Type) bool {
106         return u.nify(x, y, nil)
107 }
108
109 func (u *unifier) tracef(format string, args ...interface{}) {
110         fmt.Println(strings.Repeat(".  ", u.depth) + sprintf(nil, true, format, args...))
111 }
112
113 // String returns a string representation of the current mapping
114 // from type parameters to types.
115 func (u *unifier) String() string {
116         // sort type parameters for reproducible strings
117         tparams := make(typeParamsById, len(u.handles))
118         i := 0
119         for tpar := range u.handles {
120                 tparams[i] = tpar
121                 i++
122         }
123         sort.Sort(tparams)
124
125         var buf bytes.Buffer
126         w := newTypeWriter(&buf, nil)
127         w.byte('[')
128         for i, x := range tparams {
129                 if i > 0 {
130                         w.string(", ")
131                 }
132                 w.typ(x)
133                 w.string(": ")
134                 w.typ(u.at(x))
135         }
136         w.byte(']')
137         return buf.String()
138 }
139
140 type typeParamsById []*TypeParam
141
142 func (s typeParamsById) Len() int           { return len(s) }
143 func (s typeParamsById) Less(i, j int) bool { return s[i].id < s[j].id }
144 func (s typeParamsById) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
145
146 // join unifies the given type parameters x and y.
147 // If both type parameters already have a type associated with them
148 // and they are not joined, join fails and returns false.
149 func (u *unifier) join(x, y *TypeParam) bool {
150         if traceInference {
151                 u.tracef("%s ⇄ %s", x, y)
152         }
153         switch hx, hy := u.handles[x], u.handles[y]; {
154         case hx == hy:
155                 // Both type parameters already share the same handle. Nothing to do.
156         case *hx != nil && *hy != nil:
157                 // Both type parameters have (possibly different) inferred types. Cannot join.
158                 return false
159         case *hx != nil:
160                 // Only type parameter x has an inferred type. Use handle of x.
161                 u.setHandle(y, hx)
162         // This case is treated like the default case.
163         // case *hy != nil:
164         //      // Only type parameter y has an inferred type. Use handle of y.
165         //      u.setHandle(x, hy)
166         default:
167                 // Neither type parameter has an inferred type. Use handle of y.
168                 u.setHandle(x, hy)
169         }
170         return true
171 }
172
173 // asTypeParam returns x.(*TypeParam) if x is a type parameter recorded with u.
174 // Otherwise, the result is nil.
175 func (u *unifier) asTypeParam(x Type) *TypeParam {
176         if x, _ := x.(*TypeParam); x != nil {
177                 if _, found := u.handles[x]; found {
178                         return x
179                 }
180         }
181         return nil
182 }
183
184 // setHandle sets the handle for type parameter x
185 // (and all its joined type parameters) to h.
186 func (u *unifier) setHandle(x *TypeParam, h *Type) {
187         hx := u.handles[x]
188         assert(hx != nil)
189         for y, hy := range u.handles {
190                 if hy == hx {
191                         u.handles[y] = h
192                 }
193         }
194 }
195
196 // at returns the (possibly nil) type for type parameter x.
197 func (u *unifier) at(x *TypeParam) Type {
198         return *u.handles[x]
199 }
200
201 // set sets the type t for type parameter x;
202 // t must not be nil.
203 func (u *unifier) set(x *TypeParam, t Type) {
204         assert(t != nil)
205         if traceInference {
206                 u.tracef("%s ➞ %s", x, t)
207         }
208         *u.handles[x] = t
209 }
210
211 // unknowns returns the number of type parameters for which no type has been set yet.
212 func (u *unifier) unknowns() int {
213         n := 0
214         for _, h := range u.handles {
215                 if *h == nil {
216                         n++
217                 }
218         }
219         return n
220 }
221
222 // inferred returns the list of inferred types for the given type parameter list.
223 // The result is never nil and has the same length as tparams; result types that
224 // could not be inferred are nil. Corresponding type parameters and result types
225 // have identical indices.
226 func (u *unifier) inferred(tparams []*TypeParam) []Type {
227         list := make([]Type, len(tparams))
228         for i, x := range tparams {
229                 list[i] = u.at(x)
230         }
231         return list
232 }
233
234 // nify implements the core unification algorithm which is an
235 // adapted version of Checker.identical. For changes to that
236 // code the corresponding changes should be made here.
237 // Must not be called directly from outside the unifier.
238 func (u *unifier) nify(x, y Type, p *ifacePair) (result bool) {
239         u.depth++
240         if traceInference {
241                 u.tracef("%s ≡ %s", x, y)
242         }
243         defer func() {
244                 if traceInference && !result {
245                         u.tracef("%s ≢ %s", x, y)
246                 }
247                 u.depth--
248         }()
249
250         // nothing to do if x == y
251         if x == y {
252                 return true
253         }
254
255         // Stop gap for cases where unification fails.
256         if u.depth > unificationDepthLimit {
257                 if traceInference {
258                         u.tracef("depth %d >= %d", u.depth, unificationDepthLimit)
259                 }
260                 if panicAtUnificationDepthLimit {
261                         panic("unification reached recursion depth limit")
262                 }
263                 return false
264         }
265
266         // Unification is symmetric, so we can swap the operands.
267         // Ensure that if we have at least one
268         // - defined type, make sure one is in y
269         // - type parameter recorded with u, make sure one is in x
270         if _, ok := x.(*Named); ok || u.asTypeParam(y) != nil {
271                 if traceInference {
272                         u.tracef("%s ≡ %s (swap)", y, x)
273                 }
274                 x, y = y, x
275         }
276
277         // Unification will fail if we match a defined type against a type literal.
278         // Per the (spec) assignment rules, assignments of values to variables with
279         // the same type structure are permitted as long as at least one of them
280         // is not a defined type. To accomodate for that possibility, we continue
281         // unification with the underlying type of a defined type if the other type
282         // is a type literal.
283         // We also continue if the other type is a basic type because basic types
284         // are valid underlying types and may appear as core types of type constraints.
285         // If we exclude them, inferred defined types for type parameters may not
286         // match against the core types of their constraints (even though they might
287         // correctly match against some of the types in the constraint's type set).
288         // Finally, if unification (incorrectly) succeeds by matching the underlying
289         // type of a defined type against a basic type (because we include basic types
290         // as type literals here), and if that leads to an incorrectly inferred type,
291         // we will fail at function instantiation or argument assignment time.
292         //
293         // If we have at least one defined type, there is one in y.
294         if ny, _ := y.(*Named); ny != nil && isTypeLit(x) {
295                 if traceInference {
296                         u.tracef("%s ≡ under %s", x, ny)
297                 }
298                 y = ny.under()
299                 // Per the spec, a defined type cannot have an underlying type
300                 // that is a type parameter.
301                 assert(!isTypeParam(y))
302                 // x and y may be identical now
303                 if x == y {
304                         return true
305                 }
306         }
307
308         // Cases where at least one of x or y is a type parameter recorded with u.
309         // If we have at least one type parameter, there is one in x.
310         // If we have exactly one type parameter, because it is in x,
311         // isTypeLit(x) is false and y was not changed above. In other
312         // words, if y was a defined type, it is still a defined type
313         // (relevant for the logic below).
314         switch px, py := u.asTypeParam(x), u.asTypeParam(y); {
315         case px != nil && py != nil:
316                 // both x and y are type parameters
317                 if u.join(px, py) {
318                         return true
319                 }
320                 // both x and y have an inferred type - they must match
321                 return u.nify(u.at(px), u.at(py), p)
322
323         case px != nil:
324                 // x is a type parameter, y is not
325                 if x := u.at(px); x != nil {
326                         // x has an inferred type which must match y
327                         if u.nify(x, y, p) {
328                                 // If we have a match, possibly through underlying types,
329                                 // and y is a defined type, make sure we record that type
330                                 // for type parameter x, which may have until now only
331                                 // recorded an underlying type (go.dev/issue/43056).
332                                 if _, ok := y.(*Named); ok {
333                                         u.set(px, y)
334                                 }
335                                 return true
336                         }
337                         return false
338                 }
339                 // otherwise, infer type from y
340                 u.set(px, y)
341                 return true
342         }
343
344         // x != y if we get here
345         assert(x != y)
346
347         // If we get here and x or y is a type parameter, they are unbound
348         // (not recorded with the unifier).
349         // Ensure that if we have at least one type parameter, it is in x
350         // (the earlier swap checks for _recorded_ type parameters only).
351         if isTypeParam(y) {
352                 if traceInference {
353                         u.tracef("%s ≡ %s (swap)", y, x)
354                 }
355                 x, y = y, x
356         }
357
358         switch x := x.(type) {
359         case *Basic:
360                 // Basic types are singletons except for the rune and byte
361                 // aliases, thus we cannot solely rely on the x == y check
362                 // above. See also comment in TypeName.IsAlias.
363                 if y, ok := y.(*Basic); ok {
364                         return x.kind == y.kind
365                 }
366
367         case *Array:
368                 // Two array types are identical if they have identical element types
369                 // and the same array length.
370                 if y, ok := y.(*Array); ok {
371                         // If one or both array lengths are unknown (< 0) due to some error,
372                         // assume they are the same to avoid spurious follow-on errors.
373                         return (x.len < 0 || y.len < 0 || x.len == y.len) && u.nify(x.elem, y.elem, p)
374                 }
375
376         case *Slice:
377                 // Two slice types are identical if they have identical element types.
378                 if y, ok := y.(*Slice); ok {
379                         return u.nify(x.elem, y.elem, p)
380                 }
381
382         case *Struct:
383                 // Two struct types are identical if they have the same sequence of fields,
384                 // and if corresponding fields have the same names, and identical types,
385                 // and identical tags. Two embedded fields are considered to have the same
386                 // name. Lower-case field names from different packages are always different.
387                 if y, ok := y.(*Struct); ok {
388                         if x.NumFields() == y.NumFields() {
389                                 for i, f := range x.fields {
390                                         g := y.fields[i]
391                                         if f.embedded != g.embedded ||
392                                                 x.Tag(i) != y.Tag(i) ||
393                                                 !f.sameId(g.pkg, g.name) ||
394                                                 !u.nify(f.typ, g.typ, p) {
395                                                 return false
396                                         }
397                                 }
398                                 return true
399                         }
400                 }
401
402         case *Pointer:
403                 // Two pointer types are identical if they have identical base types.
404                 if y, ok := y.(*Pointer); ok {
405                         return u.nify(x.base, y.base, p)
406                 }
407
408         case *Tuple:
409                 // Two tuples types are identical if they have the same number of elements
410                 // and corresponding elements have identical types.
411                 if y, ok := y.(*Tuple); ok {
412                         if x.Len() == y.Len() {
413                                 if x != nil {
414                                         for i, v := range x.vars {
415                                                 w := y.vars[i]
416                                                 if !u.nify(v.typ, w.typ, p) {
417                                                         return false
418                                                 }
419                                         }
420                                 }
421                                 return true
422                         }
423                 }
424
425         case *Signature:
426                 // Two function types are identical if they have the same number of parameters
427                 // and result values, corresponding parameter and result types are identical,
428                 // and either both functions are variadic or neither is. Parameter and result
429                 // names are not required to match.
430                 // TODO(gri) handle type parameters or document why we can ignore them.
431                 if y, ok := y.(*Signature); ok {
432                         return x.variadic == y.variadic &&
433                                 u.nify(x.params, y.params, p) &&
434                                 u.nify(x.results, y.results, p)
435                 }
436
437         case *Interface:
438                 // Two interface types are identical if they have the same set of methods with
439                 // the same names and identical function types. Lower-case method names from
440                 // different packages are always different. The order of the methods is irrelevant.
441                 if y, ok := y.(*Interface); ok {
442                         xset := x.typeSet()
443                         yset := y.typeSet()
444                         if xset.comparable != yset.comparable {
445                                 return false
446                         }
447                         if !xset.terms.equal(yset.terms) {
448                                 return false
449                         }
450                         a := xset.methods
451                         b := yset.methods
452                         if len(a) == len(b) {
453                                 // Interface types are the only types where cycles can occur
454                                 // that are not "terminated" via named types; and such cycles
455                                 // can only be created via method parameter types that are
456                                 // anonymous interfaces (directly or indirectly) embedding
457                                 // the current interface. Example:
458                                 //
459                                 //    type T interface {
460                                 //        m() interface{T}
461                                 //    }
462                                 //
463                                 // If two such (differently named) interfaces are compared,
464                                 // endless recursion occurs if the cycle is not detected.
465                                 //
466                                 // If x and y were compared before, they must be equal
467                                 // (if they were not, the recursion would have stopped);
468                                 // search the ifacePair stack for the same pair.
469                                 //
470                                 // This is a quadratic algorithm, but in practice these stacks
471                                 // are extremely short (bounded by the nesting depth of interface
472                                 // type declarations that recur via parameter types, an extremely
473                                 // rare occurrence). An alternative implementation might use a
474                                 // "visited" map, but that is probably less efficient overall.
475                                 q := &ifacePair{x, y, p}
476                                 for p != nil {
477                                         if p.identical(q) {
478                                                 return true // same pair was compared before
479                                         }
480                                         p = p.prev
481                                 }
482                                 if debug {
483                                         assertSortedMethods(a)
484                                         assertSortedMethods(b)
485                                 }
486                                 for i, f := range a {
487                                         g := b[i]
488                                         if f.Id() != g.Id() || !u.nify(f.typ, g.typ, q) {
489                                                 return false
490                                         }
491                                 }
492                                 return true
493                         }
494                 }
495
496         case *Map:
497                 // Two map types are identical if they have identical key and value types.
498                 if y, ok := y.(*Map); ok {
499                         return u.nify(x.key, y.key, p) && u.nify(x.elem, y.elem, p)
500                 }
501
502         case *Chan:
503                 // Two channel types are identical if they have identical value types.
504                 if y, ok := y.(*Chan); ok {
505                         return u.nify(x.elem, y.elem, p)
506                 }
507
508         case *Named:
509                 // TODO(gri) This code differs now from the parallel code in Checker.identical. Investigate.
510                 if y, ok := y.(*Named); ok {
511                         xargs := x.TypeArgs().list()
512                         yargs := y.TypeArgs().list()
513
514                         if len(xargs) != len(yargs) {
515                                 return false
516                         }
517
518                         // TODO(gri) This is not always correct: two types may have the same names
519                         //           in the same package if one of them is nested in a function.
520                         //           Extremely unlikely but we need an always correct solution.
521                         if x.obj.pkg == y.obj.pkg && x.obj.name == y.obj.name {
522                                 for i, x := range xargs {
523                                         if !u.nify(x, yargs[i], p) {
524                                                 return false
525                                         }
526                                 }
527                                 return true
528                         }
529                 }
530
531         case *TypeParam:
532                 // x must be an unbound type parameter (see comment above).
533                 if debug {
534                         assert(u.asTypeParam(x) == nil)
535                 }
536                 // By definition, a valid type argument must be in the type set of
537                 // the respective type constraint. Therefore, the type argument's
538                 // underlying type must be in the set of underlying types of that
539                 // constraint. If there is a single such underlying type, it's the
540                 // constraint's core type. It must match the type argument's under-
541                 // lying type, irrespective of whether the actual type argument,
542                 // which may be a defined type, is actually in the type set (that
543                 // will be determined at instantiation time).
544                 // Thus, if we have the core type of an unbound type parameter,
545                 // we know the structure of the possible types satisfying such
546                 // parameters. Use that core type for further unification
547                 // (see go.dev/issue/50755 for a test case).
548                 if enableCoreTypeUnification {
549                         // Because the core type is always an underlying type,
550                         // unification will take care of matching against a
551                         // defined or literal type automatically.
552                         // If y is also an unbound type parameter, we will end
553                         // up here again with x and y swapped, so we don't
554                         // need to take care of that case separately.
555                         if cx := coreType(x); cx != nil {
556                                 if traceInference {
557                                         u.tracef("core %s ≡ %s", x, y)
558                                 }
559                                 return u.nify(cx, y, p)
560                         }
561                 }
562                 // x != y and there's nothing to do
563
564         case nil:
565                 // avoid a crash in case of nil type
566
567         default:
568                 panic(sprintf(nil, true, "u.nify(%s, %s)", x, y))
569         }
570
571         return false
572 }