...

Source file src/go/types/infer.go

Documentation: go/types

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

View as plain text