...

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

Documentation: cmd/compile/internal/types2

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

View as plain text