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