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.
5 // This file implements type unification.
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.
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.
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.
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
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
52 // If enableCoreTypeUnification is set, unification will consider
53 // the core types, if any, of non-local (unbound) type parameters.
54 enableCoreTypeUnification = true
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
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.
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
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 {
101 return &unifier{handles, 0}
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)
110 func (u *unifier) tracef(format string, args ...interface{}) {
111 fmt.Println(strings.Repeat(". ", u.depth) + sprintf(nil, true, format, args...))
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))
120 for tpar := range u.handles {
127 w := newTypeWriter(&buf, nil)
129 for i, x := range tparams {
141 type typeParamsById []*TypeParam
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] }
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 {
152 u.tracef("%s ⇄ %s", x, y)
154 switch hx, hy := u.handles[x], u.handles[y]; {
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.
161 // Only type parameter x has an inferred type. Use handle of x.
163 // This case is treated like the default case.
165 // // Only type parameter y has an inferred type. Use handle of y.
166 // u.setHandle(x, hy)
168 // Neither type parameter has an inferred type. Use handle of y.
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 {
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) {
190 for y, hy := range u.handles {
197 // at returns the (possibly nil) type for type parameter x.
198 func (u *unifier) at(x *TypeParam) Type {
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) {
207 u.tracef("%s ➞ %s", x, t)
212 // unknowns returns the number of type parameters for which no type has been set yet.
213 func (u *unifier) unknowns() int {
215 for _, h := range u.handles {
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 {
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) {
242 u.tracef("%s ≡ %s", x, y)
245 if traceInference && !result {
246 u.tracef("%s ≢ %s", x, y)
251 // nothing to do if x == y
256 // Stop gap for cases where unification fails.
257 if u.depth > unificationDepthLimit {
259 u.tracef("depth %d >= %d", u.depth, unificationDepthLimit)
261 if panicAtUnificationDepthLimit {
262 panic("unification reached recursion depth limit")
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 {
273 u.tracef("%s ≡ %s (swap)", y, x)
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.
294 // If we have at least one defined type, there is one in y.
295 if ny, _ := y.(*Named); ny != nil && isTypeLit(x) {
297 u.tracef("%s ≡ under %s", x, ny)
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
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
321 // both x and y have an inferred type - they must match
322 return u.nify(u.at(px), u.at(py), p)
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
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 {
340 // otherwise, infer type from y
345 // x != y if we get here
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).
354 u.tracef("%s ≡ %s (swap)", y, x)
359 switch x := x.(type) {
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
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)
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)
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 {
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) {
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)
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() {
415 for i, v := range x.vars {
417 if !u.nify(v.typ, w.typ, p) {
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)
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 {
446 if xset.comparable != yset.comparable {
449 if !xset.terms.equal(yset.terms) {
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:
461 // type T interface {
465 // If two such (differently named) interfaces are compared,
466 // endless recursion occurs if the cycle is not detected.
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.
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}
480 return true // same pair was compared before
485 assertSortedMethods(a)
486 assertSortedMethods(b)
488 for i, f := range a {
490 if f.Id() != g.Id() || !u.nify(f.typ, g.typ, q) {
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)
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)
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) {
523 for i, xarg := range xargs {
524 if !u.nify(xarg, yargs[i], p) {
528 return indenticalOrigin(x, y)
532 // x must be an unbound type parameter (see comment above).
534 assert(u.asTypeParam(x) == nil)
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 {
557 u.tracef("core %s ≡ %s", x, y)
559 return u.nify(cx, y, p)
562 // x != y and there's nothing to do
565 // avoid a crash in case of nil type
568 panic(sprintf(nil, true, "u.nify(%s, %s)", x, y))