github.com/AndrienkoAleksandr/go@v0.0.19/src/go/types/unify.go (about)

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