...

Source file src/cmd/compile/internal/types2/unify.go

Documentation: cmd/compile/internal/types2

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

View as plain text