]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/unify.go
bef851f4238e8ee4ad6e23fe53cde00975f774fe
[gostls13.git] / src / go / types / unify.go
1 // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
2
3 // Copyright 2020 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 // This file implements type unification.
8 //
9 // Type unification attempts to make two types x and y structurally
10 // equivalent by determining the types for a given list of (bound)
11 // type parameters which may occur within x and y. If x and y are
12 // structurally different (say []T vs chan T), or conflicting
13 // types are determined for type parameters, unification fails.
14 // If unification succeeds, as a side-effect, the types of the
15 // bound type parameters may be determined.
16 //
17 // Unification typically requires multiple calls u.unify(x, y) to
18 // a given unifier u, with various combinations of types x and y.
19 // In each call, additional type parameter types may be determined
20 // as a side effect and recorded in u.
21 // If a call fails (returns false), unification fails.
22 //
23 // In the unification context, structural equivalence of two types
24 // ignores the difference between a defined type and its underlying
25 // type if one type is a defined type and the other one is not.
26 // It also ignores the difference between an (external, unbound)
27 // type parameter and its core type.
28 // If two types are not structurally equivalent, they cannot be Go
29 // identical types. On the other hand, if they are structurally
30 // equivalent, they may be Go identical or at least assignable, or
31 // they may be in the type set of a constraint.
32 // Whether they indeed are identical or assignable is determined
33 // upon instantiation and function argument passing.
34
35 package types
36
37 import (
38         "bytes"
39         "fmt"
40         "sort"
41         "strings"
42 )
43
44 const (
45         // Upper limit for recursion depth. Used to catch infinite recursions
46         // due to implementation issues (e.g., see issues go.dev/issue/48619, go.dev/issue/48656).
47         unificationDepthLimit = 50
48
49         // Whether to panic when unificationDepthLimit is reached.
50         // If disabled, a recursion depth overflow results in a (quiet)
51         // unification failure.
52         panicAtUnificationDepthLimit = true
53
54         // If enableCoreTypeUnification is set, unification will consider
55         // the core types, if any, of non-local (unbound) type parameters.
56         enableCoreTypeUnification = true
57
58         // If enableInterfaceInference is set, type inference uses
59         // shared methods for improved type inference involving
60         // interfaces.
61         enableInterfaceInference = true
62
63         // If traceInference is set, unification will print a trace of its operation.
64         // Interpretation of trace:
65         //   x ≡ y    attempt to unify types x and y
66         //   p ➞ y    type parameter p is set to type y (p is inferred to be y)
67         //   p ⇄ q    type parameters p and q match (p is inferred to be q and vice versa)
68         //   x ≢ y    types x and y cannot be unified
69         //   [p, q, ...] ➞ [x, y, ...]    mapping from type parameters to types
70         traceInference = false
71 )
72
73 // A unifier maintains a list of type parameters and
74 // corresponding types inferred for each type parameter.
75 // A unifier is created by calling newUnifier.
76 type unifier struct {
77         // handles maps each type parameter to its inferred type through
78         // an indirection *Type called (inferred type) "handle".
79         // Initially, each type parameter has its own, separate handle,
80         // with a nil (i.e., not yet inferred) type.
81         // After a type parameter P is unified with a type parameter Q,
82         // P and Q share the same handle (and thus type). This ensures
83         // that inferring the type for a given type parameter P will
84         // automatically infer the same type for all other parameters
85         // unified (joined) with P.
86         handles map[*TypeParam]*Type
87         depth   int // recursion depth during unification
88 }
89
90 // newUnifier returns a new unifier initialized with the given type parameter
91 // and corresponding type argument lists. The type argument list may be shorter
92 // than the type parameter list, and it may contain nil types. Matching type
93 // parameters and arguments must have the same index.
94 func newUnifier(tparams []*TypeParam, targs []Type) *unifier {
95         assert(len(tparams) >= len(targs))
96         handles := make(map[*TypeParam]*Type, len(tparams))
97         // Allocate all handles up-front: in a correct program, all type parameters
98         // must be resolved and thus eventually will get a handle.
99         // Also, sharing of handles caused by unified type parameters is rare and
100         // so it's ok to not optimize for that case (and delay handle allocation).
101         for i, x := range tparams {
102                 var t Type
103                 if i < len(targs) {
104                         t = targs[i]
105                 }
106                 handles[x] = &t
107         }
108         return &unifier{handles, 0}
109 }
110
111 // unifyMode controls the behavior of the unifier.
112 type unifyMode uint
113
114 const (
115         // If assign is set, we are unifying types involved in an assignment:
116         // they may match inexactly at the top, but element types must match
117         // exactly.
118         assign unifyMode = 1 << iota
119
120         // If exact is set, types unify if they are identical (or can be
121         // made identical with suitable arguments for type parameters).
122         // Otherwise, a named type and a type literal unify if their
123         // underlying types unify, channel directions are ignored, and
124         // if there is an interface, the other type must implement the
125         // interface.
126         exact
127 )
128
129 func (m unifyMode) String() string {
130         switch m {
131         case 0:
132                 return "inexact"
133         case assign:
134                 return "assign"
135         case exact:
136                 return "exact"
137         case assign | exact:
138                 return "assign, exact"
139         }
140         return fmt.Sprintf("mode %d", m)
141 }
142
143 // unify attempts to unify x and y and reports whether it succeeded.
144 // As a side-effect, types may be inferred for type parameters.
145 // The mode parameter controls how types are compared.
146 func (u *unifier) unify(x, y Type, mode unifyMode) bool {
147         return u.nify(x, y, mode, nil)
148 }
149
150 func (u *unifier) tracef(format string, args ...interface{}) {
151         fmt.Println(strings.Repeat(".  ", u.depth) + sprintf(nil, nil, true, format, args...))
152 }
153
154 // String returns a string representation of the current mapping
155 // from type parameters to types.
156 func (u *unifier) String() string {
157         // sort type parameters for reproducible strings
158         tparams := make(typeParamsById, len(u.handles))
159         i := 0
160         for tpar := range u.handles {
161                 tparams[i] = tpar
162                 i++
163         }
164         sort.Sort(tparams)
165
166         var buf bytes.Buffer
167         w := newTypeWriter(&buf, nil)
168         w.byte('[')
169         for i, x := range tparams {
170                 if i > 0 {
171                         w.string(", ")
172                 }
173                 w.typ(x)
174                 w.string(": ")
175                 w.typ(u.at(x))
176         }
177         w.byte(']')
178         return buf.String()
179 }
180
181 type typeParamsById []*TypeParam
182
183 func (s typeParamsById) Len() int           { return len(s) }
184 func (s typeParamsById) Less(i, j int) bool { return s[i].id < s[j].id }
185 func (s typeParamsById) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
186
187 // join unifies the given type parameters x and y.
188 // If both type parameters already have a type associated with them
189 // and they are not joined, join fails and returns false.
190 func (u *unifier) join(x, y *TypeParam) bool {
191         if traceInference {
192                 u.tracef("%s ⇄ %s", x, y)
193         }
194         switch hx, hy := u.handles[x], u.handles[y]; {
195         case hx == hy:
196                 // Both type parameters already share the same handle. Nothing to do.
197         case *hx != nil && *hy != nil:
198                 // Both type parameters have (possibly different) inferred types. Cannot join.
199                 return false
200         case *hx != nil:
201                 // Only type parameter x has an inferred type. Use handle of x.
202                 u.setHandle(y, hx)
203         // This case is treated like the default case.
204         // case *hy != nil:
205         //      // Only type parameter y has an inferred type. Use handle of y.
206         //      u.setHandle(x, hy)
207         default:
208                 // Neither type parameter has an inferred type. Use handle of y.
209                 u.setHandle(x, hy)
210         }
211         return true
212 }
213
214 // asTypeParam returns x.(*TypeParam) if x is a type parameter recorded with u.
215 // Otherwise, the result is nil.
216 func (u *unifier) asTypeParam(x Type) *TypeParam {
217         if x, _ := x.(*TypeParam); x != nil {
218                 if _, found := u.handles[x]; found {
219                         return x
220                 }
221         }
222         return nil
223 }
224
225 // setHandle sets the handle for type parameter x
226 // (and all its joined type parameters) to h.
227 func (u *unifier) setHandle(x *TypeParam, h *Type) {
228         hx := u.handles[x]
229         assert(hx != nil)
230         for y, hy := range u.handles {
231                 if hy == hx {
232                         u.handles[y] = h
233                 }
234         }
235 }
236
237 // at returns the (possibly nil) type for type parameter x.
238 func (u *unifier) at(x *TypeParam) Type {
239         return *u.handles[x]
240 }
241
242 // set sets the type t for type parameter x;
243 // t must not be nil.
244 func (u *unifier) set(x *TypeParam, t Type) {
245         assert(t != nil)
246         if traceInference {
247                 u.tracef("%s ➞ %s", x, t)
248         }
249         *u.handles[x] = t
250 }
251
252 // unknowns returns the number of type parameters for which no type has been set yet.
253 func (u *unifier) unknowns() int {
254         n := 0
255         for _, h := range u.handles {
256                 if *h == nil {
257                         n++
258                 }
259         }
260         return n
261 }
262
263 // inferred returns the list of inferred types for the given type parameter list.
264 // The result is never nil and has the same length as tparams; result types that
265 // could not be inferred are nil. Corresponding type parameters and result types
266 // have identical indices.
267 func (u *unifier) inferred(tparams []*TypeParam) []Type {
268         list := make([]Type, len(tparams))
269         for i, x := range tparams {
270                 list[i] = u.at(x)
271         }
272         return list
273 }
274
275 // asInterface returns the underlying type of x as an interface if
276 // it is a non-type parameter interface. Otherwise it returns nil.
277 func asInterface(x Type) (i *Interface) {
278         if _, ok := x.(*TypeParam); !ok {
279                 i, _ = under(x).(*Interface)
280         }
281         return i
282 }
283
284 // nify implements the core unification algorithm which is an
285 // adapted version of Checker.identical. For changes to that
286 // code the corresponding changes should be made here.
287 // Must not be called directly from outside the unifier.
288 func (u *unifier) nify(x, y Type, mode unifyMode, p *ifacePair) (result bool) {
289         u.depth++
290         if traceInference {
291                 u.tracef("%s ≡ %s\t// %s", x, y, mode)
292         }
293         defer func() {
294                 if traceInference && !result {
295                         u.tracef("%s ≢ %s", x, y)
296                 }
297                 u.depth--
298         }()
299
300         // nothing to do if x == y
301         if x == y {
302                 return true
303         }
304
305         // Stop gap for cases where unification fails.
306         if u.depth > unificationDepthLimit {
307                 if traceInference {
308                         u.tracef("depth %d >= %d", u.depth, unificationDepthLimit)
309                 }
310                 if panicAtUnificationDepthLimit {
311                         panic("unification reached recursion depth limit")
312                 }
313                 return false
314         }
315
316         // Unification is symmetric, so we can swap the operands.
317         // Ensure that if we have at least one
318         // - defined type, make sure one is in y
319         // - type parameter recorded with u, make sure one is in x
320         if _, ok := x.(*Named); ok || u.asTypeParam(y) != nil {
321                 if traceInference {
322                         u.tracef("%s ≡ %s\t// swap", y, x)
323                 }
324                 x, y = y, x
325         }
326
327         // Unification will fail if we match a defined type against a type literal.
328         // If we are matching types in an assignment, at the top-level, types with
329         // the same type structure are permitted as long as at least one of them
330         // is not a defined type. To accommodate for that possibility, we continue
331         // unification with the underlying type of a defined type if the other type
332         // is a type literal. This is controlled by the exact unification mode.
333         // We also continue if the other type is a basic type because basic types
334         // are valid underlying types and may appear as core types of type constraints.
335         // If we exclude them, inferred defined types for type parameters may not
336         // match against the core types of their constraints (even though they might
337         // correctly match against some of the types in the constraint's type set).
338         // Finally, if unification (incorrectly) succeeds by matching the underlying
339         // type of a defined type against a basic type (because we include basic types
340         // as type literals here), and if that leads to an incorrectly inferred type,
341         // we will fail at function instantiation or argument assignment time.
342         //
343         // If we have at least one defined type, there is one in y.
344         if ny, _ := y.(*Named); mode&exact == 0 && ny != nil && isTypeLit(x) && !(enableInterfaceInference && IsInterface(x)) {
345                 if traceInference {
346                         u.tracef("%s ≡ under %s", x, ny)
347                 }
348                 y = ny.under()
349                 // Per the spec, a defined type cannot have an underlying type
350                 // that is a type parameter.
351                 assert(!isTypeParam(y))
352                 // x and y may be identical now
353                 if x == y {
354                         return true
355                 }
356         }
357
358         // Cases where at least one of x or y is a type parameter recorded with u.
359         // If we have at least one type parameter, there is one in x.
360         // If we have exactly one type parameter, because it is in x,
361         // isTypeLit(x) is false and y was not changed above. In other
362         // words, if y was a defined type, it is still a defined type
363         // (relevant for the logic below).
364         switch px, py := u.asTypeParam(x), u.asTypeParam(y); {
365         case px != nil && py != nil:
366                 // both x and y are type parameters
367                 if u.join(px, py) {
368                         return true
369                 }
370                 // both x and y have an inferred type - they must match
371                 return u.nify(u.at(px), u.at(py), mode, p)
372
373         case px != nil:
374                 // x is a type parameter, y is not
375                 if x := u.at(px); x != nil {
376                         // x has an inferred type which must match y
377                         if u.nify(x, y, mode, p) {
378                                 // We have a match, possibly through underlying types.
379                                 xi := asInterface(x)
380                                 yi := asInterface(y)
381                                 _, xn := x.(*Named)
382                                 _, yn := y.(*Named)
383                                 // If we have two interfaces, what to do depends on
384                                 // whether they are named and their method sets.
385                                 if xi != nil && yi != nil {
386                                         // Both types are interfaces.
387                                         // If both types are defined types, they must be identical
388                                         // because unification doesn't know which type has the "right" name.
389                                         if xn && yn {
390                                                 return Identical(x, y)
391                                         }
392                                         // In all other cases, the method sets must match.
393                                         // The types unified so we know that corresponding methods
394                                         // match and we can simply compare the number of methods.
395                                         // TODO(gri) We may be able to relax this rule and select
396                                         // the more general interface. But if one of them is a defined
397                                         // type, it's not clear how to choose and whether we introduce
398                                         // an order dependency or not. Requiring the same method set
399                                         // is conservative.
400                                         if len(xi.typeSet().methods) != len(yi.typeSet().methods) {
401                                                 return false
402                                         }
403                                 } else if xi != nil || yi != nil {
404                                         // One but not both of them are interfaces.
405                                         // In this case, either x or y could be viable matches for the corresponding
406                                         // type parameter, which means choosing either introduces an order dependence.
407                                         // Therefore, we must fail unification (go.dev/issue/60933).
408                                         return false
409                                 }
410                                 // If y is a defined type, make sure we record that type
411                                 // for type parameter x, which may have until now only
412                                 // recorded an underlying type (go.dev/issue/43056).
413                                 // Either both types are interfaces, or neither type is.
414                                 // If both are interfaces, they have the same methods.
415                                 //
416                                 // Note: Changing the recorded type for a type parameter to
417                                 // a defined type is only ok when unification is inexact.
418                                 // But in exact unification, if we have a match, x and y must
419                                 // be identical, so changing the recorded type for x is a no-op.
420                                 if yn {
421                                         u.set(px, y)
422                                 }
423                                 return true
424                         }
425                         return false
426                 }
427                 // otherwise, infer type from y
428                 u.set(px, y)
429                 return true
430         }
431
432         // x != y if we get here
433         assert(x != y)
434
435         // Type elements (array, slice, etc. elements) use emode for unification.
436         // Element types must match exactly if the types are used in an assignment.
437         emode := mode
438         if mode&assign != 0 {
439                 emode |= exact
440         }
441
442         // If EnableInterfaceInference is set and we don't require exact unification,
443         // if both types are interfaces, one interface must have a subset of the
444         // methods of the other and corresponding method signatures must unify.
445         // If only one type is an interface, all its methods must be present in the
446         // other type and corresponding method signatures must unify.
447         if enableInterfaceInference && mode&exact == 0 {
448                 // One or both interfaces may be defined types.
449                 // Look under the name, but not under type parameters (go.dev/issue/60564).
450                 xi := asInterface(x)
451                 yi := asInterface(y)
452                 // If we have two interfaces, check the type terms for equivalence,
453                 // and unify common methods if possible.
454                 if xi != nil && yi != nil {
455                         xset := xi.typeSet()
456                         yset := yi.typeSet()
457                         if xset.comparable != yset.comparable {
458                                 return false
459                         }
460                         // For now we require terms to be equal.
461                         // We should be able to relax this as well, eventually.
462                         if !xset.terms.equal(yset.terms) {
463                                 return false
464                         }
465                         // Interface types are the only types where cycles can occur
466                         // that are not "terminated" via named types; and such cycles
467                         // can only be created via method parameter types that are
468                         // anonymous interfaces (directly or indirectly) embedding
469                         // the current interface. Example:
470                         //
471                         //    type T interface {
472                         //        m() interface{T}
473                         //    }
474                         //
475                         // If two such (differently named) interfaces are compared,
476                         // endless recursion occurs if the cycle is not detected.
477                         //
478                         // If x and y were compared before, they must be equal
479                         // (if they were not, the recursion would have stopped);
480                         // search the ifacePair stack for the same pair.
481                         //
482                         // This is a quadratic algorithm, but in practice these stacks
483                         // are extremely short (bounded by the nesting depth of interface
484                         // type declarations that recur via parameter types, an extremely
485                         // rare occurrence). An alternative implementation might use a
486                         // "visited" map, but that is probably less efficient overall.
487                         q := &ifacePair{xi, yi, p}
488                         for p != nil {
489                                 if p.identical(q) {
490                                         return true // same pair was compared before
491                                 }
492                                 p = p.prev
493                         }
494                         // The method set of x must be a subset of the method set
495                         // of y or vice versa, and the common methods must unify.
496                         xmethods := xset.methods
497                         ymethods := yset.methods
498                         // The smaller method set must be the subset, if it exists.
499                         if len(xmethods) > len(ymethods) {
500                                 xmethods, ymethods = ymethods, xmethods
501                         }
502                         // len(xmethods) <= len(ymethods)
503                         // Collect the ymethods in a map for quick lookup.
504                         ymap := make(map[string]*Func, len(ymethods))
505                         for _, ym := range ymethods {
506                                 ymap[ym.Id()] = ym
507                         }
508                         // All xmethods must exist in ymethods and corresponding signatures must unify.
509                         for _, xm := range xmethods {
510                                 if ym := ymap[xm.Id()]; ym == nil || !u.nify(xm.typ, ym.typ, emode, p) {
511                                         return false
512                                 }
513                         }
514                         return true
515                 }
516
517                 // We don't have two interfaces. If we have one, make sure it's in xi.
518                 if yi != nil {
519                         xi = yi
520                         y = x
521                 }
522
523                 // If we have one interface, at a minimum each of the interface methods
524                 // must be implemented and thus unify with a corresponding method from
525                 // the non-interface type, otherwise unification fails.
526                 if xi != nil {
527                         // All xi methods must exist in y and corresponding signatures must unify.
528                         xmethods := xi.typeSet().methods
529                         for _, xm := range xmethods {
530                                 obj, _, _ := LookupFieldOrMethod(y, false, xm.pkg, xm.name)
531                                 if ym, _ := obj.(*Func); ym == nil || !u.nify(xm.typ, ym.typ, emode, p) {
532                                         return false
533                                 }
534                         }
535                         return true
536                 }
537         }
538
539         // Unless we have exact unification, neither x nor y are interfaces now.
540         // Except for unbound type parameters (see below), x and y must be structurally
541         // equivalent to unify.
542
543         // If we get here and x or y is a type parameter, they are unbound
544         // (not recorded with the unifier).
545         // Ensure that if we have at least one type parameter, it is in x
546         // (the earlier swap checks for _recorded_ type parameters only).
547         // This ensures that the switch switches on the type parameter.
548         //
549         // TODO(gri) Factor out type parameter handling from the switch.
550         if isTypeParam(y) {
551                 if traceInference {
552                         u.tracef("%s ≡ %s\t// swap", y, x)
553                 }
554                 x, y = y, x
555         }
556
557         switch x := x.(type) {
558         case *Basic:
559                 // Basic types are singletons except for the rune and byte
560                 // aliases, thus we cannot solely rely on the x == y check
561                 // above. See also comment in TypeName.IsAlias.
562                 if y, ok := y.(*Basic); ok {
563                         return x.kind == y.kind
564                 }
565
566         case *Array:
567                 // Two array types unify if they have the same array length
568                 // and their element types unify.
569                 if y, ok := y.(*Array); ok {
570                         // If one or both array lengths are unknown (< 0) due to some error,
571                         // assume they are the same to avoid spurious follow-on errors.
572                         return (x.len < 0 || y.len < 0 || x.len == y.len) && u.nify(x.elem, y.elem, emode, p)
573                 }
574
575         case *Slice:
576                 // Two slice types unify if their element types unify.
577                 if y, ok := y.(*Slice); ok {
578                         return u.nify(x.elem, y.elem, emode, p)
579                 }
580
581         case *Struct:
582                 // Two struct types unify if they have the same sequence of fields,
583                 // and if corresponding fields have the same names, their (field) types unify,
584                 // and they have identical tags. Two embedded fields are considered to have the same
585                 // name. Lower-case field names from different packages are always different.
586                 if y, ok := y.(*Struct); ok {
587                         if x.NumFields() == y.NumFields() {
588                                 for i, f := range x.fields {
589                                         g := y.fields[i]
590                                         if f.embedded != g.embedded ||
591                                                 x.Tag(i) != y.Tag(i) ||
592                                                 !f.sameId(g.pkg, g.name) ||
593                                                 !u.nify(f.typ, g.typ, emode, p) {
594                                                 return false
595                                         }
596                                 }
597                                 return true
598                         }
599                 }
600
601         case *Pointer:
602                 // Two pointer types unify if their base types unify.
603                 if y, ok := y.(*Pointer); ok {
604                         return u.nify(x.base, y.base, emode, p)
605                 }
606
607         case *Tuple:
608                 // Two tuples types unify if they have the same number of elements
609                 // and the types of corresponding elements unify.
610                 if y, ok := y.(*Tuple); ok {
611                         if x.Len() == y.Len() {
612                                 if x != nil {
613                                         for i, v := range x.vars {
614                                                 w := y.vars[i]
615                                                 if !u.nify(v.typ, w.typ, mode, p) {
616                                                         return false
617                                                 }
618                                         }
619                                 }
620                                 return true
621                         }
622                 }
623
624         case *Signature:
625                 // Two function types unify if they have the same number of parameters
626                 // and result values, corresponding parameter and result types unify,
627                 // and either both functions are variadic or neither is.
628                 // Parameter and result names are not required to match.
629                 // TODO(gri) handle type parameters or document why we can ignore them.
630                 if y, ok := y.(*Signature); ok {
631                         return x.variadic == y.variadic &&
632                                 u.nify(x.params, y.params, emode, p) &&
633                                 u.nify(x.results, y.results, emode, p)
634                 }
635
636         case *Interface:
637                 assert(!enableInterfaceInference || mode&exact != 0) // handled before this switch
638
639                 // Two interface types unify if they have the same set of methods with
640                 // the same names, and corresponding function types unify.
641                 // Lower-case method names from different packages are always different.
642                 // The order of the methods is irrelevant.
643                 if y, ok := y.(*Interface); ok {
644                         xset := x.typeSet()
645                         yset := y.typeSet()
646                         if xset.comparable != yset.comparable {
647                                 return false
648                         }
649                         if !xset.terms.equal(yset.terms) {
650                                 return false
651                         }
652                         a := xset.methods
653                         b := yset.methods
654                         if len(a) == len(b) {
655                                 // Interface types are the only types where cycles can occur
656                                 // that are not "terminated" via named types; and such cycles
657                                 // can only be created via method parameter types that are
658                                 // anonymous interfaces (directly or indirectly) embedding
659                                 // the current interface. Example:
660                                 //
661                                 //    type T interface {
662                                 //        m() interface{T}
663                                 //    }
664                                 //
665                                 // If two such (differently named) interfaces are compared,
666                                 // endless recursion occurs if the cycle is not detected.
667                                 //
668                                 // If x and y were compared before, they must be equal
669                                 // (if they were not, the recursion would have stopped);
670                                 // search the ifacePair stack for the same pair.
671                                 //
672                                 // This is a quadratic algorithm, but in practice these stacks
673                                 // are extremely short (bounded by the nesting depth of interface
674                                 // type declarations that recur via parameter types, an extremely
675                                 // rare occurrence). An alternative implementation might use a
676                                 // "visited" map, but that is probably less efficient overall.
677                                 q := &ifacePair{x, y, p}
678                                 for p != nil {
679                                         if p.identical(q) {
680                                                 return true // same pair was compared before
681                                         }
682                                         p = p.prev
683                                 }
684                                 if debug {
685                                         assertSortedMethods(a)
686                                         assertSortedMethods(b)
687                                 }
688                                 for i, f := range a {
689                                         g := b[i]
690                                         if f.Id() != g.Id() || !u.nify(f.typ, g.typ, emode, q) {
691                                                 return false
692                                         }
693                                 }
694                                 return true
695                         }
696                 }
697
698         case *Map:
699                 // Two map types unify if their key and value types unify.
700                 if y, ok := y.(*Map); ok {
701                         return u.nify(x.key, y.key, emode, p) && u.nify(x.elem, y.elem, emode, p)
702                 }
703
704         case *Chan:
705                 // Two channel types unify if their value types unify
706                 // and if they have the same direction.
707                 // The channel direction is ignored for inexact unification.
708                 if y, ok := y.(*Chan); ok {
709                         return (mode&exact == 0 || x.dir == y.dir) && u.nify(x.elem, y.elem, emode, p)
710                 }
711
712         case *Named:
713                 // Two named types unify if their type names originate in the same type declaration.
714                 // If they are instantiated, their type argument lists must unify.
715                 if y, ok := y.(*Named); ok {
716                         // Check type arguments before origins so they unify
717                         // even if the origins don't match; for better error
718                         // messages (see go.dev/issue/53692).
719                         xargs := x.TypeArgs().list()
720                         yargs := y.TypeArgs().list()
721                         if len(xargs) != len(yargs) {
722                                 return false
723                         }
724                         for i, xarg := range xargs {
725                                 if !u.nify(xarg, yargs[i], mode, p) {
726                                         return false
727                                 }
728                         }
729                         return indenticalOrigin(x, y)
730                 }
731
732         case *TypeParam:
733                 // x must be an unbound type parameter (see comment above).
734                 if debug {
735                         assert(u.asTypeParam(x) == nil)
736                 }
737                 // By definition, a valid type argument must be in the type set of
738                 // the respective type constraint. Therefore, the type argument's
739                 // underlying type must be in the set of underlying types of that
740                 // constraint. If there is a single such underlying type, it's the
741                 // constraint's core type. It must match the type argument's under-
742                 // lying type, irrespective of whether the actual type argument,
743                 // which may be a defined type, is actually in the type set (that
744                 // will be determined at instantiation time).
745                 // Thus, if we have the core type of an unbound type parameter,
746                 // we know the structure of the possible types satisfying such
747                 // parameters. Use that core type for further unification
748                 // (see go.dev/issue/50755 for a test case).
749                 if enableCoreTypeUnification {
750                         // Because the core type is always an underlying type,
751                         // unification will take care of matching against a
752                         // defined or literal type automatically.
753                         // If y is also an unbound type parameter, we will end
754                         // up here again with x and y swapped, so we don't
755                         // need to take care of that case separately.
756                         if cx := coreType(x); cx != nil {
757                                 if traceInference {
758                                         u.tracef("core %s ≡ %s", x, y)
759                                 }
760                                 // If y is a defined type, it may not match against cx which
761                                 // is an underlying type (incl. int, string, etc.). Use assign
762                                 // mode here so that the unifier automatically takes under(y)
763                                 // if necessary.
764                                 return u.nify(cx, y, assign, p)
765                         }
766                 }
767                 // x != y and there's nothing to do
768
769         case nil:
770                 // avoid a crash in case of nil type
771
772         default:
773                 panic(sprintf(nil, nil, true, "u.nify(%s, %s, %d)", x, y, mode))
774         }
775
776         return false
777 }