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.
15 // The unifier maintains two separate sets of type parameters x and y
16 // which are used to resolve type parameters in the x and y arguments
17 // provided to the unify call. For unidirectional unification, only
18 // one of these sets (say x) is provided, and then type parameters are
19 // only resolved for the x argument passed to unify, not the y argument
20 // (even if that also contains possibly the same type parameters).
22 // For bidirectional unification, both sets are provided. This enables
23 // unification to go from argument to parameter type and vice versa.
24 // For constraint type inference, we use bidirectional unification
25 // where both the x and y type parameters are identical. This is done
26 // by setting up one of them (using init) and then assigning its value
30 // Upper limit for recursion depth. Used to catch infinite recursions
31 // due to implementation issues (e.g., see issues #48619, #48656).
32 unificationDepthLimit = 50
34 // Whether to panic when unificationDepthLimit is reached.
35 // If disabled, a recursion depth overflow results in a (quiet)
36 // unification failure.
37 panicAtUnificationDepthLimit = true
39 // If enableCoreTypeUnification is set, unification will consider
40 // the core types, if any, of non-local (unbound) type parameters.
41 enableCoreTypeUnification = true
43 // If traceInference is set, unification will print a trace of its operation.
44 // Interpretation of trace:
45 // x ≡ y attempt to unify types x and y
46 // p ➞ y type parameter p is set to type y (p is inferred to be y)
47 // p ⇄ q type parameters p and q match (p is inferred to be q and vice versa)
48 // x ≢ y types x and y cannot be unified
49 // [p, q, ...] ➞ [x, y, ...] mapping from type parameters to types
50 traceInference = false
53 // A unifier maintains the current type parameters for x and y
54 // and the respective types inferred for each type parameter.
55 // A unifier is created by calling newUnifier.
58 x, y tparamsList // x and y must initialized via tparamsList.init
59 types []Type // inferred types, shared by x and y
60 depth int // recursion depth during unification
63 // newUnifier returns a new unifier.
64 // If exact is set, unification requires unified types to match
65 // exactly. If exact is not set, a named type's underlying type
66 // is considered if unification would fail otherwise, and the
67 // direction of channels is ignored.
68 // TODO(gri) exact is not set anymore by a caller. Consider removing it.
69 func newUnifier(exact bool) *unifier {
70 u := &unifier{exact: exact}
76 // unify attempts to unify x and y and reports whether it succeeded.
77 func (u *unifier) unify(x, y Type) bool {
78 return u.nify(x, y, nil)
81 func (u *unifier) tracef(format string, args ...interface{}) {
82 fmt.Println(strings.Repeat(". ", u.depth) + sprintf(nil, true, format, args...))
85 // A tparamsList describes a list of type parameters and the types inferred for them.
86 type tparamsList struct {
89 // For each tparams element, there is a corresponding type slot index in indices.
90 // index < 0: unifier.types[-index-1] == nil
91 // index == 0: no type slot allocated yet
92 // index > 0: unifier.types[index-1] == typ
93 // Joined tparams elements share the same type slot and thus have the same index.
94 // By using a negative index for nil types we don't need to check unifier.types
95 // to see if we have a type or not.
96 indices []int // len(d.indices) == len(d.tparams)
99 // String returns a string representation for a tparamsList. For debugging.
100 func (d *tparamsList) String() string {
102 w := newTypeWriter(&buf, nil)
104 for i, tpar := range d.tparams {
116 // init initializes d with the given type parameters.
117 // The type parameters must be in the order in which they appear in their declaration
118 // (this ensures that the tparams indices match the respective type parameter index).
119 func (d *tparamsList) init(tparams []*TypeParam) {
120 if len(tparams) == 0 {
124 for i, tpar := range tparams {
125 assert(i == tpar.index)
129 d.indices = make([]int, len(tparams))
132 // join unifies the i'th type parameter of x with the j'th type parameter of y.
133 // If both type parameters already have a type associated with them and they are
134 // not joined, join fails and returns false.
135 func (u *unifier) join(i, j int) bool {
137 u.tracef("%s ⇄ %s", u.x.tparams[i], u.y.tparams[j])
142 case ti == 0 && tj == 0:
143 // Neither type parameter has a type slot associated with them.
144 // Allocate a new joined nil type slot (negative index).
145 u.types = append(u.types, nil)
146 u.x.indices[i] = -len(u.types)
147 u.y.indices[j] = -len(u.types)
149 // The type parameter for x has no type slot yet. Use slot of y.
152 // The type parameter for y has no type slot yet. Use slot of x.
155 // Both type parameters have a slot: ti != 0 && tj != 0.
157 // Both type parameters already share the same slot. Nothing to do.
159 case ti > 0 && tj > 0:
160 // Both type parameters have (possibly different) inferred types. Cannot join.
161 // TODO(gri) Should we check if types are identical? Investigate.
164 // Only the type parameter for x has an inferred type. Use x slot for y.
166 // This case is handled like the default case.
168 // // Only the type parameter for y has an inferred type. Use y slot for x.
169 // u.x.setIndex(i, tj)
171 // Neither type parameter has an inferred type. Use y slot for x
172 // (or x slot for y, it doesn't matter).
178 // If typ is a type parameter of d, index returns the type parameter index.
179 // Otherwise, the result is < 0.
180 func (d *tparamsList) index(typ Type) int {
181 if tpar, ok := typ.(*TypeParam); ok {
182 return tparamIndex(d.tparams, tpar)
187 // If tpar is a type parameter in list, tparamIndex returns the type parameter index.
188 // Otherwise, the result is < 0. tpar must not be nil.
189 func tparamIndex(list []*TypeParam, tpar *TypeParam) int {
190 // Once a type parameter is bound its index is >= 0. However, there are some
191 // code paths (namely tracing and type hashing) by which it is possible to
192 // arrive here with a type parameter that has not been bound, hence the check
194 // TODO(rfindley): investigate a better approach for guarding against using
195 // unbound type parameters.
196 if i := tpar.index; 0 <= i && i < len(list) && list[i] == tpar {
202 // setIndex sets the type slot index for the i'th type parameter
203 // (and all its joined parameters) to tj. The type parameter
204 // must have a (possibly nil) type slot associated with it.
205 func (d *tparamsList) setIndex(i, tj int) {
207 assert(ti != 0 && tj != 0)
208 for k, tk := range d.indices {
215 // at returns the type set for the i'th type parameter; or nil.
216 func (d *tparamsList) at(i int) Type {
217 if ti := d.indices[i]; ti > 0 {
218 return d.unifier.types[ti-1]
223 // set sets the type typ for the i'th type parameter;
224 // typ must not be nil and it must not have been set before.
225 func (d *tparamsList) set(i int, typ Type) {
229 u.tracef("%s ➞ %s", d.tparams[i], typ)
231 switch ti := d.indices[i]; {
236 u.types = append(u.types, typ)
237 d.indices[i] = len(u.types)
239 panic("type already set")
243 // unknowns returns the number of type parameters for which no type has been set yet.
244 func (d *tparamsList) unknowns() int {
246 for _, ti := range d.indices {
254 // types returns the list of inferred types (via unification) for the type parameters
255 // described by d, and an index. If all types were inferred, the returned index is < 0.
256 // Otherwise, it is the index of the first type parameter which couldn't be inferred;
257 // i.e., for which list[index] is nil.
258 func (d *tparamsList) types() (list []Type, index int) {
259 list = make([]Type, len(d.tparams))
261 for i := range d.tparams {
264 if index < 0 && t == nil {
271 func (u *unifier) nifyEq(x, y Type, p *ifacePair) bool {
272 return x == y || u.nify(x, y, p)
275 // nify implements the core unification algorithm which is an
276 // adapted version of Checker.identical. For changes to that
277 // code the corresponding changes should be made here.
278 // Must not be called directly from outside the unifier.
279 func (u *unifier) nify(x, y Type, p *ifacePair) (result bool) {
281 u.tracef("%s ≡ %s", x, y)
284 // Stop gap for cases where unification fails.
285 if u.depth >= unificationDepthLimit {
287 u.tracef("depth %d >= %d", u.depth, unificationDepthLimit)
289 if panicAtUnificationDepthLimit {
290 panic("unification reached recursion depth limit")
297 if traceInference && !result {
298 u.tracef("%s ≢ %s", x, y)
303 // If exact unification is known to fail because we attempt to
304 // match a type name against an unnamed type literal, consider
305 // the underlying type of the named type.
306 // (We use !hasName to exclude any type with a name, including
307 // basic types and type parameters; the rest are unamed types.)
308 if nx, _ := x.(*Named); nx != nil && !hasName(y) {
310 u.tracef("under %s ≡ %s", nx, y)
312 return u.nify(nx.under(), y, p)
313 } else if ny, _ := y.(*Named); ny != nil && !hasName(x) {
315 u.tracef("%s ≡ under %s", x, ny)
317 return u.nify(x, ny.under(), p)
321 // Cases where at least one of x or y is a type parameter.
322 switch i, j := u.x.index(x), u.y.index(y); {
323 case i >= 0 && j >= 0:
324 // both x and y are type parameters
328 // both x and y have an inferred type - they must match
329 return u.nifyEq(u.x.at(i), u.y.at(j), p)
332 // x is a type parameter, y is not
333 if tx := u.x.at(i); tx != nil {
334 return u.nifyEq(tx, y, p)
336 // otherwise, infer type from y
341 // y is a type parameter, x is not
342 if ty := u.y.at(j); ty != nil {
343 return u.nifyEq(x, ty, p)
345 // otherwise, infer type from x
350 // If we get here and x or y is a type parameter, they are type parameters
351 // from outside our declaration list. Try to unify their core types, if any
352 // (see go.dev/issue/50755 for a test case).
353 if enableCoreTypeUnification && !u.exact {
354 if isTypeParam(x) && !hasName(y) {
355 // When considering the type parameter for unification
356 // we look at the adjusted core term (adjusted core type
357 // with tilde information).
358 // If the adjusted core type is a named type N; the
359 // corresponding core type is under(N). Since !u.exact
360 // and y doesn't have a name, unification will end up
361 // comparing under(N) to y, so we can just use the core
362 // type instead. And we can ignore the tilde because we
363 // already look at the underlying types on both sides
364 // and we have known types on both sides.
366 if cx := coreType(x); cx != nil {
368 u.tracef("core %s ≡ %s", x, y)
370 return u.nify(cx, y, p)
372 } else if isTypeParam(y) && !hasName(x) {
374 if cy := coreType(y); cy != nil {
376 u.tracef("%s ≡ core %s", x, y)
378 return u.nify(x, cy, p)
383 // For type unification, do not shortcut (x == y) for identical
384 // types. Instead keep comparing them element-wise to unify the
385 // matching (and equal type parameter types). A simple test case
386 // where this matters is: func f[P any](a P) { f(a) } .
388 switch x := x.(type) {
390 // Basic types are singletons except for the rune and byte
391 // aliases, thus we cannot solely rely on the x == y check
392 // above. See also comment in TypeName.IsAlias.
393 if y, ok := y.(*Basic); ok {
394 return x.kind == y.kind
398 // Two array types are identical if they have identical element types
399 // and the same array length.
400 if y, ok := y.(*Array); ok {
401 // If one or both array lengths are unknown (< 0) due to some error,
402 // assume they are the same to avoid spurious follow-on errors.
403 return (x.len < 0 || y.len < 0 || x.len == y.len) && u.nify(x.elem, y.elem, p)
407 // Two slice types are identical if they have identical element types.
408 if y, ok := y.(*Slice); ok {
409 return u.nify(x.elem, y.elem, p)
413 // Two struct types are identical if they have the same sequence of fields,
414 // and if corresponding fields have the same names, and identical types,
415 // and identical tags. Two embedded fields are considered to have the same
416 // name. Lower-case field names from different packages are always different.
417 if y, ok := y.(*Struct); ok {
418 if x.NumFields() == y.NumFields() {
419 for i, f := range x.fields {
421 if f.embedded != g.embedded ||
422 x.Tag(i) != y.Tag(i) ||
423 !f.sameId(g.pkg, g.name) ||
424 !u.nify(f.typ, g.typ, p) {
433 // Two pointer types are identical if they have identical base types.
434 if y, ok := y.(*Pointer); ok {
435 return u.nify(x.base, y.base, p)
439 // Two tuples types are identical if they have the same number of elements
440 // and corresponding elements have identical types.
441 if y, ok := y.(*Tuple); ok {
442 if x.Len() == y.Len() {
444 for i, v := range x.vars {
446 if !u.nify(v.typ, w.typ, p) {
456 // Two function types are identical if they have the same number of parameters
457 // and result values, corresponding parameter and result types are identical,
458 // and either both functions are variadic or neither is. Parameter and result
459 // names are not required to match.
460 // TODO(gri) handle type parameters or document why we can ignore them.
461 if y, ok := y.(*Signature); ok {
462 return x.variadic == y.variadic &&
463 u.nify(x.params, y.params, p) &&
464 u.nify(x.results, y.results, p)
468 // Two interface types are identical if they have the same set of methods with
469 // the same names and identical function types. Lower-case method names from
470 // different packages are always different. The order of the methods is irrelevant.
471 if y, ok := y.(*Interface); ok {
474 if xset.comparable != yset.comparable {
477 if !xset.terms.equal(yset.terms) {
482 if len(a) == len(b) {
483 // Interface types are the only types where cycles can occur
484 // that are not "terminated" via named types; and such cycles
485 // can only be created via method parameter types that are
486 // anonymous interfaces (directly or indirectly) embedding
487 // the current interface. Example:
489 // type T interface {
493 // If two such (differently named) interfaces are compared,
494 // endless recursion occurs if the cycle is not detected.
496 // If x and y were compared before, they must be equal
497 // (if they were not, the recursion would have stopped);
498 // search the ifacePair stack for the same pair.
500 // This is a quadratic algorithm, but in practice these stacks
501 // are extremely short (bounded by the nesting depth of interface
502 // type declarations that recur via parameter types, an extremely
503 // rare occurrence). An alternative implementation might use a
504 // "visited" map, but that is probably less efficient overall.
505 q := &ifacePair{x, y, p}
508 return true // same pair was compared before
513 assertSortedMethods(a)
514 assertSortedMethods(b)
516 for i, f := range a {
518 if f.Id() != g.Id() || !u.nify(f.typ, g.typ, q) {
527 // Two map types are identical if they have identical key and value types.
528 if y, ok := y.(*Map); ok {
529 return u.nify(x.key, y.key, p) && u.nify(x.elem, y.elem, p)
533 // Two channel types are identical if they have identical value types.
534 if y, ok := y.(*Chan); ok {
535 return (!u.exact || x.dir == y.dir) && u.nify(x.elem, y.elem, p)
539 // TODO(gri) This code differs now from the parallel code in Checker.identical. Investigate.
540 if y, ok := y.(*Named); ok {
541 xargs := x.TypeArgs().list()
542 yargs := y.TypeArgs().list()
544 if len(xargs) != len(yargs) {
548 // TODO(gri) This is not always correct: two types may have the same names
549 // in the same package if one of them is nested in a function.
550 // Extremely unlikely but we need an always correct solution.
551 if x.obj.pkg == y.obj.pkg && x.obj.name == y.obj.name {
552 for i, x := range xargs {
553 if !u.nify(x, yargs[i], p) {
562 // Two type parameters (which are not part of the type parameters of the
563 // enclosing type as those are handled in the beginning of this function)
564 // are identical if they originate in the same declaration.
568 // avoid a crash in case of nil type
571 panic(sprintf(nil, true, "u.nify(%s, %s), u.x.tparams = %s", x, y, u.x.tparams))