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