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