1 // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
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.
7 // This file implements type parameter inference.
14 . "internal/types/errors"
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
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 successful, infer returns the complete list of given and inferred type arguments, one for each
30 // type parameter. Otherwise the result is nil and appropriate errors will be reported.
31 func (check *Checker) infer(posn positioner, tparams []*TypeParam, targs []Type, params *Tuple, args []*operand) (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 {
38 assert(inferred == nil || len(inferred) == len(tparams) && !containsNil(inferred))
43 check.dump("== infer : %s%s ➞ %s", tparams, params, targs) // aligned with rename print below
45 check.dump("=> %s ➞ %s\n", tparams, inferred)
49 // There must be at least one type parameter, and no more type arguments than type parameters.
51 assert(n > 0 && len(targs) <= n)
53 // Parameters and arguments must match in number.
54 assert(params.Len() == len(args))
56 // If we already have all type arguments, we're done.
57 if len(targs) == n && !containsNil(targs) {
61 // Make sure we have a "full" list of type arguments, some of which may
62 // be nil (unknown). Make a copy so as to not clobber the incoming slice.
64 targs2 := make([]Type, n)
70 // Continue with the type arguments we have. Avoid matching generic
71 // parameters that already have type arguments against function arguments:
72 // It may fail because matching uses type identity while parameter passing
73 // uses assignment rules. Instantiate the parameter list with the type
74 // arguments we have, and continue with that parameter list.
76 // Substitute type arguments for their respective type parameters in params,
77 // if any. Note that nil targs entries are ignored by check.subst.
78 // We do this for better error messages; it's not needed for correctness.
79 // For instance, given:
81 // func f[P, Q any](P, Q) {}
84 // f[int](s, s) // ERROR
87 // With substitution, we get the error:
88 // "cannot use s (variable of type string) as int value in argument to f[int]"
90 // Without substitution we get the (worse) error:
91 // "type string of s does not match inferred type int for P"
92 // even though the type int was provided (not inferred) for P.
94 // TODO(gri) We might be able to finesse this in the error message reporting
95 // (which only happens in case of an error) and then avoid doing
96 // the substitution (which always happens).
98 smap := makeSubstMap(tparams, targs)
99 params = check.subst(nopos, params, smap, nil, check.context()).(*Tuple)
102 // Unify parameter and argument types for generic parameters with typed arguments
103 // and collect the indices of generic parameters with untyped arguments.
104 // Terminology: generic parameter = function parameter with a type-parameterized type
105 u := newUnifier(tparams, targs, check.allowVersion(check.pkg, posn, go1_21))
107 errorf := func(kind string, tpar, targ Type, arg *operand) {
108 // provide a better error message if we can
109 targs := u.inferred(tparams)
111 // The first type parameter couldn't be inferred.
112 // If none of them could be inferred, don't try
113 // to provide the inferred type in the error msg.
115 for _, targ := range targs {
122 check.errorf(arg, CannotInferTypeArgs, "%s %s of %s does not match %s (cannot infer %s)", kind, targ, arg.expr, tpar, typeParamsString(tparams))
126 smap := makeSubstMap(tparams, targs)
127 // TODO(gri): pass a poser here, rather than arg.Pos().
128 inferred := check.subst(arg.Pos(), tpar, smap, nil, check.context())
129 // CannotInferTypeArgs indicates a failure of inference, though the actual
130 // error may be better attributed to a user-provided type argument (hence
131 // InvalidTypeArg). We can't differentiate these cases, so fall back on
132 // the more general CannotInferTypeArgs.
133 if inferred != tpar {
134 check.errorf(arg, CannotInferTypeArgs, "%s %s of %s does not match inferred type %s for %s", kind, targ, arg.expr, inferred, tpar)
136 check.errorf(arg, CannotInferTypeArgs, "%s %s of %s does not match %s", kind, targ, arg.expr, tpar)
140 // indices of generic parameters with untyped arguments, for later use
144 // use information from function arguments
147 u.tracef("== function parameters: %s", params)
148 u.tracef("-- function arguments : %s", args)
151 for i, arg := range args {
152 if arg.mode == invalid {
153 // An error was reported earlier. Ignore this arg
154 // and continue, we may still be able to infer all
155 // targs resulting in fewer follow-on errors.
156 // TODO(gri) determine if we still need this check
160 if isParameterized(tparams, par.typ) || isParameterized(tparams, arg.typ) {
161 // Function parameters are always typed. Arguments may be untyped.
162 // Collect the indices of untyped arguments and handle them later.
163 if isTyped(arg.typ) {
164 if !u.unify(par.typ, arg.typ, assign) {
165 errorf("type", par.typ, arg.typ, arg)
168 } else if _, ok := par.typ.(*TypeParam); ok && !arg.isNil() {
169 // Since default types are all basic (i.e., non-composite) types, an
170 // untyped argument will never match a composite parameter type; the
171 // only parameter type it can possibly match against is a *TypeParam.
172 // Thus, for untyped arguments we only need to look at parameter types
173 // that are single type parameters.
174 // Also, untyped nils don't have a default type and can be ignored.
175 untyped = append(untyped, i)
181 inferred := u.inferred(tparams)
182 u.tracef("=> %s ➞ %s\n", tparams, inferred)
186 // use information from type parameter constraints
189 u.tracef("== type parameters: %s", tparams)
192 // Unify type parameters with their constraints as long
193 // as progress is being made.
195 // This is an O(n^2) algorithm where n is the number of
196 // type parameters: if there is progress, at least one
197 // type argument is inferred per iteration, and we have
198 // a doubly nested loop.
200 // In practice this is not a problem because the number
201 // of type parameters tends to be very small (< 5 or so).
202 // (It should be possible for unification to efficiently
203 // signal newly inferred type arguments; then the loops
204 // here could handle the respective type parameters only,
205 // but that will come at a cost of extra complexity which
206 // may not be worth it.)
213 u.tracef("-- iteration %d", i)
216 for _, tpar := range tparams {
218 core, single := coreTerm(tpar)
220 u.tracef("-- type parameter %s = %s: core(%s) = %s, single = %v", tpar, tx, tpar, core, single)
223 // If there is a core term (i.e., a core type with tilde information)
224 // unify the type parameter with the core type.
226 // A type parameter can be unified with its core type in two cases.
229 // The corresponding type argument tx is known. There are 2 cases:
230 // 1) If the core type has a tilde, per spec requirement for tilde
231 // elements, the core type is an underlying (literal) type.
232 // And because of the tilde, the underlying type of tx must match
233 // against the core type.
234 // But because unify automatically matches a defined type against
235 // an underlying literal type, we can simply unify tx with the
237 // 2) If the core type doesn't have a tilde, we also must unify tx
238 // with the core type.
239 if !u.unify(tx, core.typ, 0) {
240 // TODO(gri) Type parameters that appear in the constraint and
241 // for which we have type arguments inferred should
242 // use those type arguments for a better error message.
243 check.errorf(posn, CannotInferTypeArgs, "%s (type %s) does not satisfy %s", tpar, tx, tpar.Constraint())
246 case single && !core.tilde:
247 // The corresponding type argument tx is unknown and there's a single
248 // specific type and no tilde.
249 // In this case the type argument must be that single type; set it.
250 u.set(tpar, core.typ)
254 // We don't have a core type, but the type argument tx is known.
255 // It must have (at least) all the methods of the type constraint,
256 // and the method signatures must unify; otherwise tx cannot satisfy
258 // TODO(gri) Now that unification handles interfaces, this code can
259 // be reduced to calling u.unify(tx, tpar.iface(), assign)
260 // (which will compare signatures exactly as we do below).
261 // We leave it as is for now because missingMethod provides
262 // a failure cause which allows for a better error message.
263 // Eventually, unify should return an error with cause.
265 constraint := tpar.iface()
266 if m, _ := check.missingMethod(tx, constraint, true, func(x, y Type) bool { return u.unify(x, y, exact) }, &cause); m != nil {
267 // TODO(gri) better error message (see TODO above)
268 check.errorf(posn, CannotInferTypeArgs, "%s (type %s) does not satisfy %s %s", tpar, tx, tpar.Constraint(), cause)
275 if u.unknowns() == nn {
281 inferred := u.inferred(tparams)
282 u.tracef("=> %s ➞ %s\n", tparams, inferred)
286 // use information from untyped constants
289 u.tracef("== untyped arguments: %v", untyped)
292 // Some generic parameters with untyped arguments may have been given a type by now.
293 // Collect all remaining parameters that don't have a type yet and determine the
294 // maximum untyped type for each of those parameters, if possible.
295 var maxUntyped map[*TypeParam]Type // lazily allocated (we may not need it)
296 for _, index := range untyped {
297 tpar := params.At(index).typ.(*TypeParam) // is type parameter by construction of untyped
298 if u.at(tpar) == nil {
299 arg := args[index] // arg corresponding to tpar
300 if maxUntyped == nil {
301 maxUntyped = make(map[*TypeParam]Type)
303 max := maxUntyped[tpar]
307 m := maxType(max, arg.typ)
309 check.errorf(arg, CannotInferTypeArgs, "mismatched types %s and %s (cannot infer %s)", max, arg.typ, tpar)
314 maxUntyped[tpar] = max
317 // maxUntyped contains the maximum untyped type for each type parameter
318 // which doesn't have a type yet. Set the respective default types.
319 for tpar, typ := range maxUntyped {
327 // u.inferred(tparams) now contains the incoming type arguments plus any additional type
328 // arguments which were inferred. The inferred non-nil entries may still contain
329 // references to other type parameters found in constraints.
330 // For instance, for [A any, B interface{ []C }, C interface{ *A }], if A == int
331 // was given, unification produced the type list [int, []C, *A]. We eliminate the
332 // remaining type parameters by substituting the type parameters in this type list
333 // until nothing changes anymore.
334 inferred = u.inferred(tparams)
336 for i, targ := range targs {
337 assert(targ == nil || inferred[i] == targ)
341 // The data structure of each (provided or inferred) type represents a graph, where
342 // each node corresponds to a type and each (directed) vertex points to a component
343 // type. The substitution process described above repeatedly replaces type parameter
344 // nodes in these graphs with the graphs of the types the type parameters stand for,
345 // which creates a new (possibly bigger) graph for each type.
346 // The substitution process will not stop if the replacement graph for a type parameter
347 // also contains that type parameter.
348 // For instance, for [A interface{ *A }], without any type argument provided for A,
349 // unification produces the type list [*A]. Substituting A in *A with the value for
350 // A will lead to infinite expansion by producing [**A], [****A], [********A], etc.,
351 // because the graph A -> *A has a cycle through A.
352 // Generally, cycles may occur across multiple type parameters and inferred types
353 // (for instance, consider [P interface{ *Q }, Q interface{ func(P) }]).
354 // We eliminate cycles by walking the graphs for all type parameters. If a cycle
355 // through a type parameter is detected, killCycles nils out the respective type
356 // (in the inferred list) which kills the cycle, and marks the corresponding type
357 // parameter as not inferred.
359 // TODO(gri) If useful, we could report the respective cycle as an error. We don't
360 // do this now because type inference will fail anyway, and furthermore,
361 // constraints with cycles of this kind cannot currently be satisfied by
362 // any user-supplied type. But should that change, reporting an error
364 killCycles(tparams, inferred)
366 // dirty tracks the indices of all types that may still contain type parameters.
367 // We know that nil type entries and entries corresponding to provided (non-nil)
368 // type arguments are clean, so exclude them from the start.
370 for i, typ := range inferred {
371 if typ != nil && (i >= len(targs) || targs[i] == nil) {
372 dirty = append(dirty, i)
378 u.tracef("-- simplify %s ➞ %s", tparams, inferred)
380 // TODO(gri) Instead of creating a new substMap for each iteration,
381 // provide an update operation for substMaps and only change when
382 // needed. Optimization.
383 smap := makeSubstMap(tparams, inferred)
385 for _, index := range dirty {
386 t0 := inferred[index]
387 if t1 := check.subst(nopos, t0, smap, nil, check.context()); t1 != t0 {
388 // t0 was simplified to t1.
389 // If t0 was a generic function, but the simplified signature t1 does
390 // not contain any type parameters anymore, the function is not generic
391 // anymore. Remove it's type parameters. (go.dev/issue/59953)
392 // Note that if t0 was a signature, t1 must be a signature, and t1
393 // can only be a generic signature if it originated from a generic
394 // function argument. Those signatures are never defined types and
395 // thus there is no need to call under below.
396 // TODO(gri) Consider doing this in Checker.subst.
397 // Then this would fall out automatically here and also
398 // in instantiation (where we also explicitly nil out
399 // type parameters). See the *Signature TODO in subst.
400 if sig, _ := t1.(*Signature); sig != nil && sig.TypeParams().Len() > 0 && !isParameterized(tparams, sig) {
411 // Once nothing changes anymore, we may still have type parameters left;
412 // e.g., a constraint with core type *P may match a type parameter Q but
413 // we don't have any type arguments to fill in for *P or Q (go.dev/issue/45548).
414 // Don't let such inferences escape; instead treat them as unresolved.
415 for i, typ := range inferred {
416 if typ == nil || isParameterized(tparams, typ) {
417 obj := tparams[i].obj
418 check.errorf(posn, CannotInferTypeArgs, "cannot infer %s (%s)", obj.name, obj.pos)
426 // containsNil reports whether list contains a nil entry.
427 func containsNil(list []Type) bool {
428 for _, t := range list {
436 // renameTParams renames the type parameters in the given type such that each type
437 // parameter is given a new identity. renameTParams returns the new type parameters
438 // and updated type. If the result type is unchanged from the argument type, none
439 // of the type parameters in tparams occurred in the type.
440 // If typ is a generic function, type parameters held with typ are not changed and
441 // must be updated separately if desired.
442 // The positions is only used for debug traces.
443 func (check *Checker) renameTParams(pos token.Pos, tparams []*TypeParam, typ Type) ([]*TypeParam, Type) {
444 // For the purpose of type inference we must differentiate type parameters
445 // occurring in explicit type or value function arguments from the type
446 // parameters we are solving for via unification because they may be the
447 // same in self-recursive calls:
449 // func f[P constraint](x P) {
453 // In this example, without type parameter renaming, the P used in the
454 // instantiation f[P] has the same pointer identity as the P we are trying
455 // to solve for through type inference. This causes problems for type
456 // unification. Because any such self-recursive call is equivalent to
457 // a mutually recursive call, type parameter renaming can be used to
458 // create separate, disentangled type parameters. The above example
459 // can be rewritten into the following equivalent code:
461 // func f[P constraint](x P) {
465 // func f2[P2 constraint](x P2) {
469 // Type parameter renaming turns the first example into the second
470 // example by renaming the type parameter P into P2.
471 if len(tparams) == 0 {
472 return nil, typ // nothing to do
475 tparams2 := make([]*TypeParam, len(tparams))
476 for i, tparam := range tparams {
477 tname := NewTypeName(tparam.Obj().Pos(), tparam.Obj().Pkg(), tparam.Obj().Name(), nil)
478 tparams2[i] = NewTypeParam(tname, nil)
479 tparams2[i].index = tparam.index // == i
482 renameMap := makeRenameMap(tparams, tparams2)
483 for i, tparam := range tparams {
484 tparams2[i].bound = check.subst(pos, tparam.bound, renameMap, nil, check.context())
487 return tparams2, check.subst(pos, typ, renameMap, nil, check.context())
490 // typeParamsString produces a string containing all the type parameter names
491 // in list suitable for human consumption.
492 func typeParamsString(list []*TypeParam) string {
499 return list[0].obj.name
501 return list[0].obj.name + " and " + list[1].obj.name
504 // general case (n > 2)
505 var buf strings.Builder
506 for i, tname := range list[:n-1] {
508 buf.WriteString(", ")
510 buf.WriteString(tname.obj.name)
512 buf.WriteString(", and ")
513 buf.WriteString(list[n-1].obj.name)
517 // isParameterized reports whether typ contains any of the type parameters of tparams.
518 // If typ is a generic function, isParameterized ignores the type parameter declarations;
519 // it only considers the signature proper (incoming and result parameters).
520 func isParameterized(tparams []*TypeParam, typ Type) bool {
523 seen: make(map[Type]bool),
525 return w.isParameterized(typ)
528 type tpWalker struct {
533 func (w *tpWalker) isParameterized(typ Type) (res bool) {
535 if x, ok := w.seen[typ]; ok {
543 switch t := typ.(type) {
548 return w.isParameterized(Unalias(t))
551 return w.isParameterized(t.elem)
554 return w.isParameterized(t.elem)
557 return w.varList(t.fields)
560 return w.isParameterized(t.base)
563 // This case does not occur from within isParameterized
564 // because tuples only appear in signatures where they
565 // are handled explicitly. But isParameterized is also
566 // called by Checker.callExpr with a function result tuple
567 // if instantiation failed (go.dev/issue/59890).
568 return t != nil && w.varList(t.vars)
571 // t.tparams may not be nil if we are looking at a signature
572 // of a generic function type (or an interface method) that is
573 // part of the type we're testing. We don't care about these type
575 // Similarly, the receiver of a method may declare (rather than
576 // use) type parameters, we don't care about those either.
577 // Thus, we only need to look at the input and result parameters.
578 return t.params != nil && w.varList(t.params.vars) || t.results != nil && w.varList(t.results.vars)
582 for _, m := range tset.methods {
583 if w.isParameterized(m.typ) {
587 return tset.is(func(t *term) bool {
588 return t != nil && w.isParameterized(t.typ)
592 return w.isParameterized(t.key) || w.isParameterized(t.elem)
595 return w.isParameterized(t.elem)
598 for _, t := range t.TypeArgs().list() {
599 if w.isParameterized(t) {
605 return tparamIndex(w.tparams, t) >= 0
608 panic(fmt.Sprintf("unexpected %T", typ))
614 func (w *tpWalker) varList(list []*Var) bool {
615 for _, v := range list {
616 if w.isParameterized(v.typ) {
623 // If the type parameter has a single specific type S, coreTerm returns (S, true).
624 // Otherwise, if tpar has a core type T, it returns a term corresponding to that
625 // core type and false. In that case, if any term of tpar has a tilde, the core
626 // term has a tilde. In all other cases coreTerm returns (nil, false).
627 func coreTerm(tpar *TypeParam) (*term, bool) {
629 var single *term // valid if n == 1
631 tpar.is(func(t *term) bool {
634 return false // no terms
645 assert(debug && under(single.typ) == coreType(tpar))
649 if typ := coreType(tpar); typ != nil {
650 // A core type is always an underlying type.
651 // If any term of tpar has a tilde, we don't
652 // have a precise core type and we must return
654 return &term{tilde, typ}, false
659 // killCycles walks through the given type parameters and looks for cycles
660 // created by type parameters whose inferred types refer back to that type
661 // parameter, either directly or indirectly. If such a cycle is detected,
662 // it is killed by setting the corresponding inferred type to nil.
664 // TODO(gri) Determine if we can simply abort inference as soon as we have
665 // found a single cycle.
666 func killCycles(tparams []*TypeParam, inferred []Type) {
667 w := cycleFinder{tparams, inferred, make(map[Type]bool)}
668 for _, t := range tparams {
673 type cycleFinder struct {
679 func (w *cycleFinder) typ(typ Type) {
681 // We have seen typ before. If it is one of the type parameters
682 // in w.tparams, iterative substitution will lead to infinite expansion.
683 // Nil out the corresponding type which effectively kills the cycle.
684 if tpar, _ := typ.(*TypeParam); tpar != nil {
685 if i := tparamIndex(w.tparams, tpar); i >= 0 {
686 // cycle through tpar
690 // If we don't have one of our type parameters, the cycle is due
691 // to an ordinary recursive type and we can just stop walking it.
695 defer delete(w.seen, typ)
697 switch t := typ.(type) {
717 // This case should not occur because tuples only appear
718 // in signatures where they are handled explicitly.
722 w.varList(t.params.vars)
724 if t.results != nil {
725 w.varList(t.results.vars)
729 for _, t := range t.terms {
734 for _, m := range t.methods {
737 for _, t := range t.embeddeds {
749 for _, tpar := range t.TypeArgs().list() {
754 if i := tparamIndex(w.tparams, t); i >= 0 && w.inferred[i] != nil {
759 panic(fmt.Sprintf("unexpected %T", typ))
763 func (w *cycleFinder) varList(list []*Var) {
764 for _, v := range list {
769 // If tpar is a type parameter in list, tparamIndex returns the index
770 // of the type parameter in list. Otherwise the result is < 0.
771 func tparamIndex(list []*TypeParam, tpar *TypeParam) int {
772 for i, p := range list {