Source file src/go/types/infer.go

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

View as plain text