]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/infer.go
go/types, types2: implement Alias proposal (export API)
[gostls13.git] / src / go / types / infer.go
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 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 {
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         // 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.
63         if len(targs) < n {
64                 targs2 := make([]Type, n)
65                 copy(targs2, targs)
66                 targs = targs2
67         }
68         // len(targs) == n
69
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.
75
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:
80         //
81         //   func f[P, Q any](P, Q) {}
82         //
83         //   func _(s string) {
84         //           f[int](s, s) // ERROR
85         //   }
86         //
87         // With substitution, we get the error:
88         //   "cannot use s (variable of type string) as int value in argument to f[int]"
89         //
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.
93         //
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).
97         if params.Len() > 0 {
98                 smap := makeSubstMap(tparams, targs)
99                 params = check.subst(nopos, params, smap, nil, check.context()).(*Tuple)
100         }
101
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))
106
107         errorf := func(kind string, tpar, targ Type, arg *operand) {
108                 // provide a better error message if we can
109                 targs := u.inferred(tparams)
110                 if targs[0] == nil {
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.
114                         allFailed := true
115                         for _, targ := range targs {
116                                 if targ != nil {
117                                         allFailed = false
118                                         break
119                                 }
120                         }
121                         if allFailed {
122                                 check.errorf(arg, CannotInferTypeArgs, "%s %s of %s does not match %s (cannot infer %s)", kind, targ, arg.expr, tpar, typeParamsString(tparams))
123                                 return
124                         }
125                 }
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)
135                 } else {
136                         check.errorf(arg, CannotInferTypeArgs, "%s %s of %s does not match %s", kind, targ, arg.expr, tpar)
137                 }
138         }
139
140         // indices of generic parameters with untyped arguments, for later use
141         var untyped []int
142
143         // --- 1 ---
144         // use information from function arguments
145
146         if traceInference {
147                 u.tracef("== function parameters: %s", params)
148                 u.tracef("-- function arguments : %s", args)
149         }
150
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
157                         continue
158                 }
159                 par := params.At(i)
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)
166                                         return nil
167                                 }
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)
176                         }
177                 }
178         }
179
180         if traceInference {
181                 inferred := u.inferred(tparams)
182                 u.tracef("=> %s ➞ %s\n", tparams, inferred)
183         }
184
185         // --- 2 ---
186         // use information from type parameter constraints
187
188         if traceInference {
189                 u.tracef("== type parameters: %s", tparams)
190         }
191
192         // Unify type parameters with their constraints as long
193         // as progress is being made.
194         //
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.
199         //
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.)
207         for i := 0; ; i++ {
208                 nn := u.unknowns()
209                 if traceInference {
210                         if i > 0 {
211                                 fmt.Println()
212                         }
213                         u.tracef("-- iteration %d", i)
214                 }
215
216                 for _, tpar := range tparams {
217                         tx := u.at(tpar)
218                         core, single := coreTerm(tpar)
219                         if traceInference {
220                                 u.tracef("-- type parameter %s = %s: core(%s) = %s, single = %v", tpar, tx, tpar, core, single)
221                         }
222
223                         // If there is a core term (i.e., a core type with tilde information)
224                         // unify the type parameter with the core type.
225                         if core != nil {
226                                 // A type parameter can be unified with its core type in two cases.
227                                 switch {
228                                 case tx != nil:
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
236                                         //    core type.
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())
244                                                 return nil
245                                         }
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)
251                                 }
252                         } else {
253                                 if tx != nil {
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
257                                         // the constraint.
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.
264                                         var cause string
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)
269                                                 return nil
270                                         }
271                                 }
272                         }
273                 }
274
275                 if u.unknowns() == nn {
276                         break // no progress
277                 }
278         }
279
280         if traceInference {
281                 inferred := u.inferred(tparams)
282                 u.tracef("=> %s ➞ %s\n", tparams, inferred)
283         }
284
285         // --- 3 ---
286         // use information from untyped constants
287
288         if traceInference {
289                 u.tracef("== untyped arguments: %v", untyped)
290         }
291
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)
302                         }
303                         max := maxUntyped[tpar]
304                         if max == nil {
305                                 max = arg.typ
306                         } else {
307                                 m := maxType(max, arg.typ)
308                                 if m == nil {
309                                         check.errorf(arg, CannotInferTypeArgs, "mismatched types %s and %s (cannot infer %s)", max, arg.typ, tpar)
310                                         return nil
311                                 }
312                                 max = m
313                         }
314                         maxUntyped[tpar] = max
315                 }
316         }
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 {
320                 d := Default(typ)
321                 assert(isTyped(d))
322                 u.set(tpar, d)
323         }
324
325         // --- simplify ---
326
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)
335         if debug {
336                 for i, targ := range targs {
337                         assert(targ == nil || inferred[i] == targ)
338                 }
339         }
340
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.
358         //
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
363         //           would be wrong.
364         killCycles(tparams, inferred)
365
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.
369         var dirty []int
370         for i, typ := range inferred {
371                 if typ != nil && (i >= len(targs) || targs[i] == nil) {
372                         dirty = append(dirty, i)
373                 }
374         }
375
376         for len(dirty) > 0 {
377                 if traceInference {
378                         u.tracef("-- simplify %s ➞ %s", tparams, inferred)
379                 }
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)
384                 n := 0
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) {
401                                         sig.tparams = nil
402                                 }
403                                 inferred[index] = t1
404                                 dirty[n] = index
405                                 n++
406                         }
407                 }
408                 dirty = dirty[:n]
409         }
410
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)
419                         return nil
420                 }
421         }
422
423         return
424 }
425
426 // containsNil reports whether list contains a nil entry.
427 func containsNil(list []Type) bool {
428         for _, t := range list {
429                 if t == nil {
430                         return true
431                 }
432         }
433         return false
434 }
435
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:
448         //
449         //   func f[P constraint](x P) {
450         //           f(x)
451         //   }
452         //
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:
460         //
461         //   func f[P constraint](x P) {
462         //           f2(x)
463         //   }
464         //
465         //   func f2[P2 constraint](x P2) {
466         //           f(x)
467         //   }
468         //
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
473         }
474
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
480         }
481
482         renameMap := makeRenameMap(tparams, tparams2)
483         for i, tparam := range tparams {
484                 tparams2[i].bound = check.subst(pos, tparam.bound, renameMap, nil, check.context())
485         }
486
487         return tparams2, check.subst(pos, typ, renameMap, nil, check.context())
488 }
489
490 // typeParamsString produces a string containing all the type parameter names
491 // in list suitable for human consumption.
492 func typeParamsString(list []*TypeParam) string {
493         // common cases
494         n := len(list)
495         switch n {
496         case 0:
497                 return ""
498         case 1:
499                 return list[0].obj.name
500         case 2:
501                 return list[0].obj.name + " and " + list[1].obj.name
502         }
503
504         // general case (n > 2)
505         var buf strings.Builder
506         for i, tname := range list[:n-1] {
507                 if i > 0 {
508                         buf.WriteString(", ")
509                 }
510                 buf.WriteString(tname.obj.name)
511         }
512         buf.WriteString(", and ")
513         buf.WriteString(list[n-1].obj.name)
514         return buf.String()
515 }
516
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 {
521         w := tpWalker{
522                 tparams: tparams,
523                 seen:    make(map[Type]bool),
524         }
525         return w.isParameterized(typ)
526 }
527
528 type tpWalker struct {
529         tparams []*TypeParam
530         seen    map[Type]bool
531 }
532
533 func (w *tpWalker) isParameterized(typ Type) (res bool) {
534         // detect cycles
535         if x, ok := w.seen[typ]; ok {
536                 return x
537         }
538         w.seen[typ] = false
539         defer func() {
540                 w.seen[typ] = res
541         }()
542
543         switch t := typ.(type) {
544         case *Basic:
545                 // nothing to do
546
547         case *Alias:
548                 return w.isParameterized(Unalias(t))
549
550         case *Array:
551                 return w.isParameterized(t.elem)
552
553         case *Slice:
554                 return w.isParameterized(t.elem)
555
556         case *Struct:
557                 return w.varList(t.fields)
558
559         case *Pointer:
560                 return w.isParameterized(t.base)
561
562         case *Tuple:
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)
569
570         case *Signature:
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
574                 // parameters.
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)
579
580         case *Interface:
581                 tset := t.typeSet()
582                 for _, m := range tset.methods {
583                         if w.isParameterized(m.typ) {
584                                 return true
585                         }
586                 }
587                 return tset.is(func(t *term) bool {
588                         return t != nil && w.isParameterized(t.typ)
589                 })
590
591         case *Map:
592                 return w.isParameterized(t.key) || w.isParameterized(t.elem)
593
594         case *Chan:
595                 return w.isParameterized(t.elem)
596
597         case *Named:
598                 for _, t := range t.TypeArgs().list() {
599                         if w.isParameterized(t) {
600                                 return true
601                         }
602                 }
603
604         case *TypeParam:
605                 return tparamIndex(w.tparams, t) >= 0
606
607         default:
608                 panic(fmt.Sprintf("unexpected %T", typ))
609         }
610
611         return false
612 }
613
614 func (w *tpWalker) varList(list []*Var) bool {
615         for _, v := range list {
616                 if w.isParameterized(v.typ) {
617                         return true
618                 }
619         }
620         return false
621 }
622
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) {
628         n := 0
629         var single *term // valid if n == 1
630         var tilde bool
631         tpar.is(func(t *term) bool {
632                 if t == nil {
633                         assert(n == 0)
634                         return false // no terms
635                 }
636                 n++
637                 single = t
638                 if t.tilde {
639                         tilde = true
640                 }
641                 return true
642         })
643         if n == 1 {
644                 if debug {
645                         assert(debug && under(single.typ) == coreType(tpar))
646                 }
647                 return single, true
648         }
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
653                 // a tilde as well.
654                 return &term{tilde, typ}, false
655         }
656         return nil, false
657 }
658
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.
663 //
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 {
669                 w.typ(t) // t != nil
670         }
671 }
672
673 type cycleFinder struct {
674         tparams  []*TypeParam
675         inferred []Type
676         seen     map[Type]bool
677 }
678
679 func (w *cycleFinder) typ(typ Type) {
680         if w.seen[typ] {
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
687                                 w.inferred[i] = nil
688                         }
689                 }
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.
692                 return
693         }
694         w.seen[typ] = true
695         defer delete(w.seen, typ)
696
697         switch t := typ.(type) {
698         case *Basic:
699                 // nothing to do
700
701         case *Alias:
702                 w.typ(Unalias(t))
703
704         case *Array:
705                 w.typ(t.elem)
706
707         case *Slice:
708                 w.typ(t.elem)
709
710         case *Struct:
711                 w.varList(t.fields)
712
713         case *Pointer:
714                 w.typ(t.base)
715
716         // case *Tuple:
717         //      This case should not occur because tuples only appear
718         //      in signatures where they are handled explicitly.
719
720         case *Signature:
721                 if t.params != nil {
722                         w.varList(t.params.vars)
723                 }
724                 if t.results != nil {
725                         w.varList(t.results.vars)
726                 }
727
728         case *Union:
729                 for _, t := range t.terms {
730                         w.typ(t.typ)
731                 }
732
733         case *Interface:
734                 for _, m := range t.methods {
735                         w.typ(m.typ)
736                 }
737                 for _, t := range t.embeddeds {
738                         w.typ(t)
739                 }
740
741         case *Map:
742                 w.typ(t.key)
743                 w.typ(t.elem)
744
745         case *Chan:
746                 w.typ(t.elem)
747
748         case *Named:
749                 for _, tpar := range t.TypeArgs().list() {
750                         w.typ(tpar)
751                 }
752
753         case *TypeParam:
754                 if i := tparamIndex(w.tparams, t); i >= 0 && w.inferred[i] != nil {
755                         w.typ(w.inferred[i])
756                 }
757
758         default:
759                 panic(fmt.Sprintf("unexpected %T", typ))
760         }
761 }
762
763 func (w *cycleFinder) varList(list []*Var) {
764         for _, v := range list {
765                 w.typ(v.typ)
766         }
767 }
768
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 {
773                 if p == tpar {
774                         return i
775                 }
776         }
777         return -1
778 }