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

     1  // Copyright 2018 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 parameter inference.
     6  
     7  package types2
     8  
     9  import (
    10  	"cmd/compile/internal/syntax"
    11  	"fmt"
    12  	. "internal/types/errors"
    13  	"strings"
    14  )
    15  
    16  // If enableReverseTypeInference is set, uninstantiated and
    17  // partially instantiated generic functions may be assigned
    18  // (incl. returned) to variables of function type and type
    19  // inference will attempt to infer the missing type arguments.
    20  // Available with go1.21.
    21  const enableReverseTypeInference = true // disable for debugging
    22  
    23  // infer attempts to infer the complete set of type arguments for generic function instantiation/call
    24  // based on the given type parameters tparams, type arguments targs, function parameters params, and
    25  // function arguments args, if any. There must be at least one type parameter, no more type arguments
    26  // than type parameters, and params and args must match in number (incl. zero).
    27  // If reverse is set, an error message's contents are reversed for a better error message for some
    28  // errors related to reverse type inference (where the function call is synthetic).
    29  // If successful, infer returns the complete list of given and inferred type arguments, one for each
    30  // type parameter. Otherwise the result is nil and appropriate errors will be reported.
    31  func (check *Checker) infer(pos syntax.Pos, tparams []*TypeParam, targs []Type, params *Tuple, args []*operand, reverse bool) (inferred []Type) {
    32  	// Don't verify result conditions if there's no error handler installed:
    33  	// in that case, an error leads to an exit panic and the result value may
    34  	// be incorrect. But in that case it doesn't matter because callers won't
    35  	// be able to use it either.
    36  	if check.conf.Error != nil {
    37  		defer func() {
    38  			assert(inferred == nil || len(inferred) == len(tparams) && !containsNil(inferred))
    39  		}()
    40  	}
    41  
    42  	if traceInference {
    43  		check.dump("== infer : %s%s ➞ %s", tparams, params, targs) // aligned with rename print below
    44  		defer func() {
    45  			check.dump("=> %s ➞ %s\n", tparams, inferred)
    46  		}()
    47  	}
    48  
    49  	// There must be at least one type parameter, and no more type arguments than type parameters.
    50  	n := len(tparams)
    51  	assert(n > 0 && len(targs) <= n)
    52  
    53  	// Parameters and arguments must match in number.
    54  	assert(params.Len() == len(args))
    55  
    56  	// If we already have all type arguments, we're done.
    57  	if len(targs) == n && !containsNil(targs) {
    58  		return targs
    59  	}
    60  
    61  	// If we have invalid (ordinary) arguments, an error was reported before.
    62  	// Avoid additional inference errors and exit early (go.dev/issue/60434).
    63  	for _, arg := range args {
    64  		if arg.mode == invalid {
    65  			return nil
    66  		}
    67  	}
    68  
    69  	// Make sure we have a "full" list of type arguments, some of which may
    70  	// be nil (unknown). Make a copy so as to not clobber the incoming slice.
    71  	if len(targs) < n {
    72  		targs2 := make([]Type, n)
    73  		copy(targs2, targs)
    74  		targs = targs2
    75  	}
    76  	// len(targs) == n
    77  
    78  	// Continue with the type arguments we have. Avoid matching generic
    79  	// parameters that already have type arguments against function arguments:
    80  	// It may fail because matching uses type identity while parameter passing
    81  	// uses assignment rules. Instantiate the parameter list with the type
    82  	// arguments we have, and continue with that parameter list.
    83  
    84  	// Substitute type arguments for their respective type parameters in params,
    85  	// if any. Note that nil targs entries are ignored by check.subst.
    86  	// We do this for better error messages; it's not needed for correctness.
    87  	// For instance, given:
    88  	//
    89  	//   func f[P, Q any](P, Q) {}
    90  	//
    91  	//   func _(s string) {
    92  	//           f[int](s, s) // ERROR
    93  	//   }
    94  	//
    95  	// With substitution, we get the error:
    96  	//   "cannot use s (variable of type string) as int value in argument to f[int]"
    97  	//
    98  	// Without substitution we get the (worse) error:
    99  	//   "type string of s does not match inferred type int for P"
   100  	// even though the type int was provided (not inferred) for P.
   101  	//
   102  	// TODO(gri) We might be able to finesse this in the error message reporting
   103  	//           (which only happens in case of an error) and then avoid doing
   104  	//           the substitution (which always happens).
   105  	if params.Len() > 0 {
   106  		smap := makeSubstMap(tparams, targs)
   107  		params = check.subst(nopos, params, smap, nil, check.context()).(*Tuple)
   108  	}
   109  
   110  	// Unify parameter and argument types for generic parameters with typed arguments
   111  	// and collect the indices of generic parameters with untyped arguments.
   112  	// Terminology: generic parameter = function parameter with a type-parameterized type
   113  	u := newUnifier(tparams, targs, check.allowVersion(check.pkg, pos, go1_21))
   114  
   115  	errorf := func(tpar, targ Type, arg *operand) {
   116  		// provide a better error message if we can
   117  		targs := u.inferred(tparams)
   118  		if targs[0] == nil {
   119  			// The first type parameter couldn't be inferred.
   120  			// If none of them could be inferred, don't try
   121  			// to provide the inferred type in the error msg.
   122  			allFailed := true
   123  			for _, targ := range targs {
   124  				if targ != nil {
   125  					allFailed = false
   126  					break
   127  				}
   128  			}
   129  			if allFailed {
   130  				check.errorf(arg, CannotInferTypeArgs, "type %s of %s does not match %s (cannot infer %s)", targ, arg.expr, tpar, typeParamsString(tparams))
   131  				return
   132  			}
   133  		}
   134  		smap := makeSubstMap(tparams, targs)
   135  		// TODO(gri): pass a poser here, rather than arg.Pos().
   136  		inferred := check.subst(arg.Pos(), tpar, smap, nil, check.context())
   137  		// CannotInferTypeArgs indicates a failure of inference, though the actual
   138  		// error may be better attributed to a user-provided type argument (hence
   139  		// InvalidTypeArg). We can't differentiate these cases, so fall back on
   140  		// the more general CannotInferTypeArgs.
   141  		if inferred != tpar {
   142  			if reverse {
   143  				check.errorf(arg, CannotInferTypeArgs, "inferred type %s for %s does not match type %s of %s", inferred, tpar, targ, arg.expr)
   144  			} else {
   145  				check.errorf(arg, CannotInferTypeArgs, "type %s of %s does not match inferred type %s for %s", targ, arg.expr, inferred, tpar)
   146  			}
   147  		} else {
   148  			check.errorf(arg, CannotInferTypeArgs, "type %s of %s does not match %s", targ, arg.expr, tpar)
   149  		}
   150  	}
   151  
   152  	// indices of generic parameters with untyped arguments, for later use
   153  	var untyped []int
   154  
   155  	// --- 1 ---
   156  	// use information from function arguments
   157  
   158  	if traceInference {
   159  		u.tracef("== function parameters: %s", params)
   160  		u.tracef("-- function arguments : %s", args)
   161  	}
   162  
   163  	for i, arg := range args {
   164  		if arg.mode == invalid {
   165  			// An error was reported earlier. Ignore this arg
   166  			// and continue, we may still be able to infer all
   167  			// targs resulting in fewer follow-on errors.
   168  			// TODO(gri) determine if we still need this check
   169  			continue
   170  		}
   171  		par := params.At(i)
   172  		if isParameterized(tparams, par.typ) || isParameterized(tparams, arg.typ) {
   173  			// Function parameters are always typed. Arguments may be untyped.
   174  			// Collect the indices of untyped arguments and handle them later.
   175  			if isTyped(arg.typ) {
   176  				if !u.unify(par.typ, arg.typ, assign) {
   177  					errorf(par.typ, arg.typ, arg)
   178  					return nil
   179  				}
   180  			} else if _, ok := par.typ.(*TypeParam); ok && !arg.isNil() {
   181  				// Since default types are all basic (i.e., non-composite) types, an
   182  				// untyped argument will never match a composite parameter type; the
   183  				// only parameter type it can possibly match against is a *TypeParam.
   184  				// Thus, for untyped arguments we only need to look at parameter types
   185  				// that are single type parameters.
   186  				// Also, untyped nils don't have a default type and can be ignored.
   187  				untyped = append(untyped, i)
   188  			}
   189  		}
   190  	}
   191  
   192  	if traceInference {
   193  		inferred := u.inferred(tparams)
   194  		u.tracef("=> %s ➞ %s\n", tparams, inferred)
   195  	}
   196  
   197  	// --- 2 ---
   198  	// use information from type parameter constraints
   199  
   200  	if traceInference {
   201  		u.tracef("== type parameters: %s", tparams)
   202  	}
   203  
   204  	// Unify type parameters with their constraints as long
   205  	// as progress is being made.
   206  	//
   207  	// This is an O(n^2) algorithm where n is the number of
   208  	// type parameters: if there is progress, at least one
   209  	// type argument is inferred per iteration, and we have
   210  	// a doubly nested loop.
   211  	//
   212  	// In practice this is not a problem because the number
   213  	// of type parameters tends to be very small (< 5 or so).
   214  	// (It should be possible for unification to efficiently
   215  	// signal newly inferred type arguments; then the loops
   216  	// here could handle the respective type parameters only,
   217  	// but that will come at a cost of extra complexity which
   218  	// may not be worth it.)
   219  	for i := 0; ; i++ {
   220  		nn := u.unknowns()
   221  		if traceInference {
   222  			if i > 0 {
   223  				fmt.Println()
   224  			}
   225  			u.tracef("-- iteration %d", i)
   226  		}
   227  
   228  		for _, tpar := range tparams {
   229  			tx := u.at(tpar)
   230  			core, single := coreTerm(tpar)
   231  			if traceInference {
   232  				u.tracef("-- type parameter %s = %s: core(%s) = %s, single = %v", tpar, tx, tpar, core, single)
   233  			}
   234  
   235  			// If there is a core term (i.e., a core type with tilde information)
   236  			// unify the type parameter with the core type.
   237  			if core != nil {
   238  				// A type parameter can be unified with its core type in two cases.
   239  				switch {
   240  				case tx != nil:
   241  					// The corresponding type argument tx is known. There are 2 cases:
   242  					// 1) If the core type has a tilde, per spec requirement for tilde
   243  					//    elements, the core type is an underlying (literal) type.
   244  					//    And because of the tilde, the underlying type of tx must match
   245  					//    against the core type.
   246  					//    But because unify automatically matches a defined type against
   247  					//    an underlying literal type, we can simply unify tx with the
   248  					//    core type.
   249  					// 2) If the core type doesn't have a tilde, we also must unify tx
   250  					//    with the core type.
   251  					if !u.unify(tx, core.typ, 0) {
   252  						// TODO(gri) Type parameters that appear in the constraint and
   253  						//           for which we have type arguments inferred should
   254  						//           use those type arguments for a better error message.
   255  						check.errorf(pos, CannotInferTypeArgs, "%s (type %s) does not satisfy %s", tpar, tx, tpar.Constraint())
   256  						return nil
   257  					}
   258  				case single && !core.tilde:
   259  					// The corresponding type argument tx is unknown and there's a single
   260  					// specific type and no tilde.
   261  					// In this case the type argument must be that single type; set it.
   262  					u.set(tpar, core.typ)
   263  				}
   264  			} else {
   265  				if tx != nil {
   266  					// We don't have a core type, but the type argument tx is known.
   267  					// It must have (at least) all the methods of the type constraint,
   268  					// and the method signatures must unify; otherwise tx cannot satisfy
   269  					// the constraint.
   270  					// TODO(gri) Now that unification handles interfaces, this code can
   271  					//           be reduced to calling u.unify(tx, tpar.iface(), assign)
   272  					//           (which will compare signatures exactly as we do below).
   273  					//           We leave it as is for now because missingMethod provides
   274  					//           a failure cause which allows for a better error message.
   275  					//           Eventually, unify should return an error with cause.
   276  					var cause string
   277  					constraint := tpar.iface()
   278  					if m, _ := check.missingMethod(tx, constraint, true, func(x, y Type) bool { return u.unify(x, y, exact) }, &cause); m != nil {
   279  						// TODO(gri) better error message (see TODO above)
   280  						check.errorf(pos, CannotInferTypeArgs, "%s (type %s) does not satisfy %s %s", tpar, tx, tpar.Constraint(), cause)
   281  						return nil
   282  					}
   283  				}
   284  			}
   285  		}
   286  
   287  		if u.unknowns() == nn {
   288  			break // no progress
   289  		}
   290  	}
   291  
   292  	if traceInference {
   293  		inferred := u.inferred(tparams)
   294  		u.tracef("=> %s ➞ %s\n", tparams, inferred)
   295  	}
   296  
   297  	// --- 3 ---
   298  	// use information from untyped constants
   299  
   300  	if traceInference {
   301  		u.tracef("== untyped arguments: %v", untyped)
   302  	}
   303  
   304  	// Some generic parameters with untyped arguments may have been given a type by now.
   305  	// Collect all remaining parameters that don't have a type yet and determine the
   306  	// maximum untyped type for each of those parameters, if possible.
   307  	var maxUntyped map[*TypeParam]Type // lazily allocated (we may not need it)
   308  	for _, index := range untyped {
   309  		tpar := params.At(index).typ.(*TypeParam) // is type parameter by construction of untyped
   310  		if u.at(tpar) == nil {
   311  			arg := args[index] // arg corresponding to tpar
   312  			if maxUntyped == nil {
   313  				maxUntyped = make(map[*TypeParam]Type)
   314  			}
   315  			max := maxUntyped[tpar]
   316  			if max == nil {
   317  				max = arg.typ
   318  			} else {
   319  				m := maxType(max, arg.typ)
   320  				if m == nil {
   321  					check.errorf(arg, CannotInferTypeArgs, "mismatched types %s and %s (cannot infer %s)", max, arg.typ, tpar)
   322  					return nil
   323  				}
   324  				max = m
   325  			}
   326  			maxUntyped[tpar] = max
   327  		}
   328  	}
   329  	// maxUntyped contains the maximum untyped type for each type parameter
   330  	// which doesn't have a type yet. Set the respective default types.
   331  	for tpar, typ := range maxUntyped {
   332  		d := Default(typ)
   333  		assert(isTyped(d))
   334  		u.set(tpar, d)
   335  	}
   336  
   337  	// --- simplify ---
   338  
   339  	// u.inferred(tparams) now contains the incoming type arguments plus any additional type
   340  	// arguments which were inferred. The inferred non-nil entries may still contain
   341  	// references to other type parameters found in constraints.
   342  	// For instance, for [A any, B interface{ []C }, C interface{ *A }], if A == int
   343  	// was given, unification produced the type list [int, []C, *A]. We eliminate the
   344  	// remaining type parameters by substituting the type parameters in this type list
   345  	// until nothing changes anymore.
   346  	inferred = u.inferred(tparams)
   347  	if debug {
   348  		for i, targ := range targs {
   349  			assert(targ == nil || inferred[i] == targ)
   350  		}
   351  	}
   352  
   353  	// The data structure of each (provided or inferred) type represents a graph, where
   354  	// each node corresponds to a type and each (directed) vertex points to a component
   355  	// type. The substitution process described above repeatedly replaces type parameter
   356  	// nodes in these graphs with the graphs of the types the type parameters stand for,
   357  	// which creates a new (possibly bigger) graph for each type.
   358  	// The substitution process will not stop if the replacement graph for a type parameter
   359  	// also contains that type parameter.
   360  	// For instance, for [A interface{ *A }], without any type argument provided for A,
   361  	// unification produces the type list [*A]. Substituting A in *A with the value for
   362  	// A will lead to infinite expansion by producing [**A], [****A], [********A], etc.,
   363  	// because the graph A -> *A has a cycle through A.
   364  	// Generally, cycles may occur across multiple type parameters and inferred types
   365  	// (for instance, consider [P interface{ *Q }, Q interface{ func(P) }]).
   366  	// We eliminate cycles by walking the graphs for all type parameters. If a cycle
   367  	// through a type parameter is detected, killCycles nils out the respective type
   368  	// (in the inferred list) which kills the cycle, and marks the corresponding type
   369  	// parameter as not inferred.
   370  	//
   371  	// TODO(gri) If useful, we could report the respective cycle as an error. We don't
   372  	//           do this now because type inference will fail anyway, and furthermore,
   373  	//           constraints with cycles of this kind cannot currently be satisfied by
   374  	//           any user-supplied type. But should that change, reporting an error
   375  	//           would be wrong.
   376  	killCycles(tparams, inferred)
   377  
   378  	// dirty tracks the indices of all types that may still contain type parameters.
   379  	// We know that nil type entries and entries corresponding to provided (non-nil)
   380  	// type arguments are clean, so exclude them from the start.
   381  	var dirty []int
   382  	for i, typ := range inferred {
   383  		if typ != nil && (i >= len(targs) || targs[i] == nil) {
   384  			dirty = append(dirty, i)
   385  		}
   386  	}
   387  
   388  	for len(dirty) > 0 {
   389  		if traceInference {
   390  			u.tracef("-- simplify %s ➞ %s", tparams, inferred)
   391  		}
   392  		// TODO(gri) Instead of creating a new substMap for each iteration,
   393  		// provide an update operation for substMaps and only change when
   394  		// needed. Optimization.
   395  		smap := makeSubstMap(tparams, inferred)
   396  		n := 0
   397  		for _, index := range dirty {
   398  			t0 := inferred[index]
   399  			if t1 := check.subst(nopos, t0, smap, nil, check.context()); t1 != t0 {
   400  				// t0 was simplified to t1.
   401  				// If t0 was a generic function, but the simplified signature t1 does
   402  				// not contain any type parameters anymore, the function is not generic
   403  				// anymore. Remove it's type parameters. (go.dev/issue/59953)
   404  				// Note that if t0 was a signature, t1 must be a signature, and t1
   405  				// can only be a generic signature if it originated from a generic
   406  				// function argument. Those signatures are never defined types and
   407  				// thus there is no need to call under below.
   408  				// TODO(gri) Consider doing this in Checker.subst.
   409  				//           Then this would fall out automatically here and also
   410  				//           in instantiation (where we also explicitly nil out
   411  				//           type parameters). See the *Signature TODO in subst.
   412  				if sig, _ := t1.(*Signature); sig != nil && sig.TypeParams().Len() > 0 && !isParameterized(tparams, sig) {
   413  					sig.tparams = nil
   414  				}
   415  				inferred[index] = t1
   416  				dirty[n] = index
   417  				n++
   418  			}
   419  		}
   420  		dirty = dirty[:n]
   421  	}
   422  
   423  	// Once nothing changes anymore, we may still have type parameters left;
   424  	// e.g., a constraint with core type *P may match a type parameter Q but
   425  	// we don't have any type arguments to fill in for *P or Q (go.dev/issue/45548).
   426  	// Don't let such inferences escape; instead treat them as unresolved.
   427  	for i, typ := range inferred {
   428  		if typ == nil || isParameterized(tparams, typ) {
   429  			obj := tparams[i].obj
   430  			check.errorf(pos, CannotInferTypeArgs, "cannot infer %s (%s)", obj.name, obj.pos)
   431  			return nil
   432  		}
   433  	}
   434  
   435  	return
   436  }
   437  
   438  // containsNil reports whether list contains a nil entry.
   439  func containsNil(list []Type) bool {
   440  	for _, t := range list {
   441  		if t == nil {
   442  			return true
   443  		}
   444  	}
   445  	return false
   446  }
   447  
   448  // renameTParams renames the type parameters in the given type such that each type
   449  // parameter is given a new identity. renameTParams returns the new type parameters
   450  // and updated type. If the result type is unchanged from the argument type, none
   451  // of the type parameters in tparams occurred in the type.
   452  // If typ is a generic function, type parameters held with typ are not changed and
   453  // must be updated separately if desired.
   454  // The positions is only used for debug traces.
   455  func (check *Checker) renameTParams(pos syntax.Pos, tparams []*TypeParam, typ Type) ([]*TypeParam, Type) {
   456  	// For the purpose of type inference we must differentiate type parameters
   457  	// occurring in explicit type or value function arguments from the type
   458  	// parameters we are solving for via unification because they may be the
   459  	// same in self-recursive calls:
   460  	//
   461  	//   func f[P constraint](x P) {
   462  	//           f(x)
   463  	//   }
   464  	//
   465  	// In this example, without type parameter renaming, the P used in the
   466  	// instantiation f[P] has the same pointer identity as the P we are trying
   467  	// to solve for through type inference. This causes problems for type
   468  	// unification. Because any such self-recursive call is equivalent to
   469  	// a mutually recursive call, type parameter renaming can be used to
   470  	// create separate, disentangled type parameters. The above example
   471  	// can be rewritten into the following equivalent code:
   472  	//
   473  	//   func f[P constraint](x P) {
   474  	//           f2(x)
   475  	//   }
   476  	//
   477  	//   func f2[P2 constraint](x P2) {
   478  	//           f(x)
   479  	//   }
   480  	//
   481  	// Type parameter renaming turns the first example into the second
   482  	// example by renaming the type parameter P into P2.
   483  	if len(tparams) == 0 {
   484  		return nil, typ // nothing to do
   485  	}
   486  
   487  	tparams2 := make([]*TypeParam, len(tparams))
   488  	for i, tparam := range tparams {
   489  		tname := NewTypeName(tparam.Obj().Pos(), tparam.Obj().Pkg(), tparam.Obj().Name(), nil)
   490  		tparams2[i] = NewTypeParam(tname, nil)
   491  		tparams2[i].index = tparam.index // == i
   492  	}
   493  
   494  	renameMap := makeRenameMap(tparams, tparams2)
   495  	for i, tparam := range tparams {
   496  		tparams2[i].bound = check.subst(pos, tparam.bound, renameMap, nil, check.context())
   497  	}
   498  
   499  	return tparams2, check.subst(pos, typ, renameMap, nil, check.context())
   500  }
   501  
   502  // typeParamsString produces a string containing all the type parameter names
   503  // in list suitable for human consumption.
   504  func typeParamsString(list []*TypeParam) string {
   505  	// common cases
   506  	n := len(list)
   507  	switch n {
   508  	case 0:
   509  		return ""
   510  	case 1:
   511  		return list[0].obj.name
   512  	case 2:
   513  		return list[0].obj.name + " and " + list[1].obj.name
   514  	}
   515  
   516  	// general case (n > 2)
   517  	var buf strings.Builder
   518  	for i, tname := range list[:n-1] {
   519  		if i > 0 {
   520  			buf.WriteString(", ")
   521  		}
   522  		buf.WriteString(tname.obj.name)
   523  	}
   524  	buf.WriteString(", and ")
   525  	buf.WriteString(list[n-1].obj.name)
   526  	return buf.String()
   527  }
   528  
   529  // isParameterized reports whether typ contains any of the type parameters of tparams.
   530  // If typ is a generic function, isParameterized ignores the type parameter declarations;
   531  // it only considers the signature proper (incoming and result parameters).
   532  func isParameterized(tparams []*TypeParam, typ Type) bool {
   533  	w := tpWalker{
   534  		tparams: tparams,
   535  		seen:    make(map[Type]bool),
   536  	}
   537  	return w.isParameterized(typ)
   538  }
   539  
   540  type tpWalker struct {
   541  	tparams []*TypeParam
   542  	seen    map[Type]bool
   543  }
   544  
   545  func (w *tpWalker) isParameterized(typ Type) (res bool) {
   546  	// detect cycles
   547  	if x, ok := w.seen[typ]; ok {
   548  		return x
   549  	}
   550  	w.seen[typ] = false
   551  	defer func() {
   552  		w.seen[typ] = res
   553  	}()
   554  
   555  	switch t := typ.(type) {
   556  	case *Basic:
   557  		// nothing to do
   558  
   559  	case *Alias:
   560  		return w.isParameterized(Unalias(t))
   561  
   562  	case *Array:
   563  		return w.isParameterized(t.elem)
   564  
   565  	case *Slice:
   566  		return w.isParameterized(t.elem)
   567  
   568  	case *Struct:
   569  		return w.varList(t.fields)
   570  
   571  	case *Pointer:
   572  		return w.isParameterized(t.base)
   573  
   574  	case *Tuple:
   575  		// This case does not occur from within isParameterized
   576  		// because tuples only appear in signatures where they
   577  		// are handled explicitly. But isParameterized is also
   578  		// called by Checker.callExpr with a function result tuple
   579  		// if instantiation failed (go.dev/issue/59890).
   580  		return t != nil && w.varList(t.vars)
   581  
   582  	case *Signature:
   583  		// t.tparams may not be nil if we are looking at a signature
   584  		// of a generic function type (or an interface method) that is
   585  		// part of the type we're testing. We don't care about these type
   586  		// parameters.
   587  		// Similarly, the receiver of a method may declare (rather than
   588  		// use) type parameters, we don't care about those either.
   589  		// Thus, we only need to look at the input and result parameters.
   590  		return t.params != nil && w.varList(t.params.vars) || t.results != nil && w.varList(t.results.vars)
   591  
   592  	case *Interface:
   593  		tset := t.typeSet()
   594  		for _, m := range tset.methods {
   595  			if w.isParameterized(m.typ) {
   596  				return true
   597  			}
   598  		}
   599  		return tset.is(func(t *term) bool {
   600  			return t != nil && w.isParameterized(t.typ)
   601  		})
   602  
   603  	case *Map:
   604  		return w.isParameterized(t.key) || w.isParameterized(t.elem)
   605  
   606  	case *Chan:
   607  		return w.isParameterized(t.elem)
   608  
   609  	case *Named:
   610  		for _, t := range t.TypeArgs().list() {
   611  			if w.isParameterized(t) {
   612  				return true
   613  			}
   614  		}
   615  
   616  	case *TypeParam:
   617  		return tparamIndex(w.tparams, t) >= 0
   618  
   619  	default:
   620  		panic(fmt.Sprintf("unexpected %T", typ))
   621  	}
   622  
   623  	return false
   624  }
   625  
   626  func (w *tpWalker) varList(list []*Var) bool {
   627  	for _, v := range list {
   628  		if w.isParameterized(v.typ) {
   629  			return true
   630  		}
   631  	}
   632  	return false
   633  }
   634  
   635  // If the type parameter has a single specific type S, coreTerm returns (S, true).
   636  // Otherwise, if tpar has a core type T, it returns a term corresponding to that
   637  // core type and false. In that case, if any term of tpar has a tilde, the core
   638  // term has a tilde. In all other cases coreTerm returns (nil, false).
   639  func coreTerm(tpar *TypeParam) (*term, bool) {
   640  	n := 0
   641  	var single *term // valid if n == 1
   642  	var tilde bool
   643  	tpar.is(func(t *term) bool {
   644  		if t == nil {
   645  			assert(n == 0)
   646  			return false // no terms
   647  		}
   648  		n++
   649  		single = t
   650  		if t.tilde {
   651  			tilde = true
   652  		}
   653  		return true
   654  	})
   655  	if n == 1 {
   656  		if debug {
   657  			assert(debug && under(single.typ) == coreType(tpar))
   658  		}
   659  		return single, true
   660  	}
   661  	if typ := coreType(tpar); typ != nil {
   662  		// A core type is always an underlying type.
   663  		// If any term of tpar has a tilde, we don't
   664  		// have a precise core type and we must return
   665  		// a tilde as well.
   666  		return &term{tilde, typ}, false
   667  	}
   668  	return nil, false
   669  }
   670  
   671  // killCycles walks through the given type parameters and looks for cycles
   672  // created by type parameters whose inferred types refer back to that type
   673  // parameter, either directly or indirectly. If such a cycle is detected,
   674  // it is killed by setting the corresponding inferred type to nil.
   675  //
   676  // TODO(gri) Determine if we can simply abort inference as soon as we have
   677  // found a single cycle.
   678  func killCycles(tparams []*TypeParam, inferred []Type) {
   679  	w := cycleFinder{tparams, inferred, make(map[Type]bool)}
   680  	for _, t := range tparams {
   681  		w.typ(t) // t != nil
   682  	}
   683  }
   684  
   685  type cycleFinder struct {
   686  	tparams  []*TypeParam
   687  	inferred []Type
   688  	seen     map[Type]bool
   689  }
   690  
   691  func (w *cycleFinder) typ(typ Type) {
   692  	if w.seen[typ] {
   693  		// We have seen typ before. If it is one of the type parameters
   694  		// in w.tparams, iterative substitution will lead to infinite expansion.
   695  		// Nil out the corresponding type which effectively kills the cycle.
   696  		if tpar, _ := typ.(*TypeParam); tpar != nil {
   697  			if i := tparamIndex(w.tparams, tpar); i >= 0 {
   698  				// cycle through tpar
   699  				w.inferred[i] = nil
   700  			}
   701  		}
   702  		// If we don't have one of our type parameters, the cycle is due
   703  		// to an ordinary recursive type and we can just stop walking it.
   704  		return
   705  	}
   706  	w.seen[typ] = true
   707  	defer delete(w.seen, typ)
   708  
   709  	switch t := typ.(type) {
   710  	case *Basic:
   711  		// nothing to do
   712  
   713  	case *Alias:
   714  		w.typ(Unalias(t))
   715  
   716  	case *Array:
   717  		w.typ(t.elem)
   718  
   719  	case *Slice:
   720  		w.typ(t.elem)
   721  
   722  	case *Struct:
   723  		w.varList(t.fields)
   724  
   725  	case *Pointer:
   726  		w.typ(t.base)
   727  
   728  	// case *Tuple:
   729  	//      This case should not occur because tuples only appear
   730  	//      in signatures where they are handled explicitly.
   731  
   732  	case *Signature:
   733  		if t.params != nil {
   734  			w.varList(t.params.vars)
   735  		}
   736  		if t.results != nil {
   737  			w.varList(t.results.vars)
   738  		}
   739  
   740  	case *Union:
   741  		for _, t := range t.terms {
   742  			w.typ(t.typ)
   743  		}
   744  
   745  	case *Interface:
   746  		for _, m := range t.methods {
   747  			w.typ(m.typ)
   748  		}
   749  		for _, t := range t.embeddeds {
   750  			w.typ(t)
   751  		}
   752  
   753  	case *Map:
   754  		w.typ(t.key)
   755  		w.typ(t.elem)
   756  
   757  	case *Chan:
   758  		w.typ(t.elem)
   759  
   760  	case *Named:
   761  		for _, tpar := range t.TypeArgs().list() {
   762  			w.typ(tpar)
   763  		}
   764  
   765  	case *TypeParam:
   766  		if i := tparamIndex(w.tparams, t); i >= 0 && w.inferred[i] != nil {
   767  			w.typ(w.inferred[i])
   768  		}
   769  
   770  	default:
   771  		panic(fmt.Sprintf("unexpected %T", typ))
   772  	}
   773  }
   774  
   775  func (w *cycleFinder) varList(list []*Var) {
   776  	for _, v := range list {
   777  		w.typ(v.typ)
   778  	}
   779  }
   780  
   781  // If tpar is a type parameter in list, tparamIndex returns the index
   782  // of the type parameter in list. Otherwise the result is < 0.
   783  func tparamIndex(list []*TypeParam, tpar *TypeParam) int {
   784  	for i, p := range list {
   785  		if p == tpar {
   786  			return i
   787  		}
   788  	}
   789  	return -1
   790  }
   791  

View as plain text