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

View as plain text