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