github.com/AndrienkoAleksandr/go@v0.0.19/src/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, assign) { 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, 0) { 236 // TODO(gri) Type parameters that appear in the constraint and 237 // for which we have type arguments inferred should 238 // use those type arguments for a better error message. 239 check.errorf(posn, CannotInferTypeArgs, "%s (type %s) does not satisfy %s", tpar, tx, tpar.Constraint()) 240 return nil 241 } 242 case single && !core.tilde: 243 // The corresponding type argument tx is unknown and there's a single 244 // specific type and no tilde. 245 // In this case the type argument must be that single type; set it. 246 u.set(tpar, core.typ) 247 } 248 } else { 249 if tx != nil { 250 // We don't have a core type, but the type argument tx is known. 251 // It must have (at least) all the methods of the type constraint, 252 // and the method signatures must unify; otherwise tx cannot satisfy 253 // the constraint. 254 // TODO(gri) Now that unification handles interfaces, this code can 255 // be reduced to calling u.unify(tx, tpar.iface(), assign) 256 // (which will compare signatures exactly as we do below). 257 // We leave it as is for now because missingMethod provides 258 // a failure cause which allows for a better error message. 259 // Eventually, unify should return an error with cause. 260 var cause string 261 constraint := tpar.iface() 262 if m, _ := check.missingMethod(tx, constraint, true, func(x, y Type) bool { return u.unify(x, y, exact) }, &cause); m != nil { 263 // TODO(gri) better error message (see TODO above) 264 check.errorf(posn, CannotInferTypeArgs, "%s (type %s) does not satisfy %s %s", tpar, tx, tpar.Constraint(), cause) 265 return nil 266 } 267 } 268 } 269 } 270 271 if u.unknowns() == nn { 272 break // no progress 273 } 274 } 275 276 if traceInference { 277 inferred := u.inferred(tparams) 278 u.tracef("=> %s ➞ %s\n", tparams, inferred) 279 } 280 281 // --- 3 --- 282 // use information from untyped constants 283 284 if traceInference { 285 u.tracef("== untyped arguments: %v", untyped) 286 } 287 288 // Some generic parameters with untyped arguments may have been given a type by now. 289 // Collect all remaining parameters that don't have a type yet and determine the 290 // maximum untyped type for each of those parameters, if possible. 291 var maxUntyped map[*TypeParam]Type // lazily allocated (we may not need it) 292 for _, index := range untyped { 293 tpar := params.At(index).typ.(*TypeParam) // is type parameter by construction of untyped 294 if u.at(tpar) == nil { 295 arg := args[index] // arg corresponding to tpar 296 if maxUntyped == nil { 297 maxUntyped = make(map[*TypeParam]Type) 298 } 299 max := maxUntyped[tpar] 300 if max == nil { 301 max = arg.typ 302 } else { 303 m := maxType(max, arg.typ) 304 if m == nil { 305 check.errorf(arg, CannotInferTypeArgs, "mismatched types %s and %s (cannot infer %s)", max, arg.typ, tpar) 306 return nil 307 } 308 max = m 309 } 310 maxUntyped[tpar] = max 311 } 312 } 313 // maxUntyped contains the maximum untyped type for each type parameter 314 // which doesn't have a type yet. Set the respective default types. 315 for tpar, typ := range maxUntyped { 316 d := Default(typ) 317 assert(isTyped(d)) 318 u.set(tpar, d) 319 } 320 321 // --- simplify --- 322 323 // u.inferred(tparams) now contains the incoming type arguments plus any additional type 324 // arguments which were inferred. The inferred non-nil entries may still contain 325 // references to other type parameters found in constraints. 326 // For instance, for [A any, B interface{ []C }, C interface{ *A }], if A == int 327 // was given, unification produced the type list [int, []C, *A]. We eliminate the 328 // remaining type parameters by substituting the type parameters in this type list 329 // until nothing changes anymore. 330 inferred = u.inferred(tparams) 331 if debug { 332 for i, targ := range targs { 333 assert(targ == nil || inferred[i] == targ) 334 } 335 } 336 337 // The data structure of each (provided or inferred) type represents a graph, where 338 // each node corresponds to a type and each (directed) vertex points to a component 339 // type. The substitution process described above repeatedly replaces type parameter 340 // nodes in these graphs with the graphs of the types the type parameters stand for, 341 // which creates a new (possibly bigger) graph for each type. 342 // The substitution process will not stop if the replacement graph for a type parameter 343 // also contains that type parameter. 344 // For instance, for [A interface{ *A }], without any type argument provided for A, 345 // unification produces the type list [*A]. Substituting A in *A with the value for 346 // A will lead to infinite expansion by producing [**A], [****A], [********A], etc., 347 // because the graph A -> *A has a cycle through A. 348 // Generally, cycles may occur across multiple type parameters and inferred types 349 // (for instance, consider [P interface{ *Q }, Q interface{ func(P) }]). 350 // We eliminate cycles by walking the graphs for all type parameters. If a cycle 351 // through a type parameter is detected, killCycles nils out the respective type 352 // (in the inferred list) which kills the cycle, and marks the corresponding type 353 // parameter as not inferred. 354 // 355 // TODO(gri) If useful, we could report the respective cycle as an error. We don't 356 // do this now because type inference will fail anyway, and furthermore, 357 // constraints with cycles of this kind cannot currently be satisfied by 358 // any user-supplied type. But should that change, reporting an error 359 // would be wrong. 360 killCycles(tparams, inferred) 361 362 // dirty tracks the indices of all types that may still contain type parameters. 363 // We know that nil type entries and entries corresponding to provided (non-nil) 364 // type arguments are clean, so exclude them from the start. 365 var dirty []int 366 for i, typ := range inferred { 367 if typ != nil && (i >= len(targs) || targs[i] == nil) { 368 dirty = append(dirty, i) 369 } 370 } 371 372 for len(dirty) > 0 { 373 if traceInference { 374 u.tracef("-- simplify %s ➞ %s", tparams, inferred) 375 } 376 // TODO(gri) Instead of creating a new substMap for each iteration, 377 // provide an update operation for substMaps and only change when 378 // needed. Optimization. 379 smap := makeSubstMap(tparams, inferred) 380 n := 0 381 for _, index := range dirty { 382 t0 := inferred[index] 383 if t1 := check.subst(nopos, t0, smap, nil, check.context()); t1 != t0 { 384 // t0 was simplified to t1. 385 // If t0 was a generic function, but the simplified signature t1 does 386 // not contain any type parameters anymore, the function is not generic 387 // anymore. Remove it's type parameters. (go.dev/issue/59953) 388 // Note that if t0 was a signature, t1 must be a signature, and t1 389 // can only be a generic signature if it originated from a generic 390 // function argument. Those signatures are never defined types and 391 // thus there is no need to call under below. 392 // TODO(gri) Consider doing this in Checker.subst. 393 // Then this would fall out automatically here and also 394 // in instantiation (where we also explicitly nil out 395 // type parameters). See the *Signature TODO in subst. 396 if sig, _ := t1.(*Signature); sig != nil && sig.TypeParams().Len() > 0 && !isParameterized(tparams, sig) { 397 sig.tparams = nil 398 } 399 inferred[index] = t1 400 dirty[n] = index 401 n++ 402 } 403 } 404 dirty = dirty[:n] 405 } 406 407 // Once nothing changes anymore, we may still have type parameters left; 408 // e.g., a constraint with core type *P may match a type parameter Q but 409 // we don't have any type arguments to fill in for *P or Q (go.dev/issue/45548). 410 // Don't let such inferences escape; instead treat them as unresolved. 411 for i, typ := range inferred { 412 if typ == nil || isParameterized(tparams, typ) { 413 obj := tparams[i].obj 414 check.errorf(posn, CannotInferTypeArgs, "cannot infer %s (%s)", obj.name, obj.pos) 415 return nil 416 } 417 } 418 419 return 420 } 421 422 // containsNil reports whether list contains a nil entry. 423 func containsNil(list []Type) bool { 424 for _, t := range list { 425 if t == nil { 426 return true 427 } 428 } 429 return false 430 } 431 432 // renameTParams renames the type parameters in the given type such that each type 433 // parameter is given a new identity. renameTParams returns the new type parameters 434 // and updated type. If the result type is unchanged from the argument type, none 435 // of the type parameters in tparams occurred in the type. 436 // If typ is a generic function, type parameters held with typ are not changed and 437 // must be updated separately if desired. 438 // The positions is only used for debug traces. 439 func (check *Checker) renameTParams(pos token.Pos, tparams []*TypeParam, typ Type) ([]*TypeParam, Type) { 440 // For the purpose of type inference we must differentiate type parameters 441 // occurring in explicit type or value function arguments from the type 442 // parameters we are solving for via unification because they may be the 443 // same in self-recursive calls: 444 // 445 // func f[P constraint](x P) { 446 // f(x) 447 // } 448 // 449 // In this example, without type parameter renaming, the P used in the 450 // instantiation f[P] has the same pointer identity as the P we are trying 451 // to solve for through type inference. This causes problems for type 452 // unification. Because any such self-recursive call is equivalent to 453 // a mutually recursive call, type parameter renaming can be used to 454 // create separate, disentangled type parameters. The above example 455 // can be rewritten into the following equivalent code: 456 // 457 // func f[P constraint](x P) { 458 // f2(x) 459 // } 460 // 461 // func f2[P2 constraint](x P2) { 462 // f(x) 463 // } 464 // 465 // Type parameter renaming turns the first example into the second 466 // example by renaming the type parameter P into P2. 467 if len(tparams) == 0 { 468 return nil, typ // nothing to do 469 } 470 471 tparams2 := make([]*TypeParam, len(tparams)) 472 for i, tparam := range tparams { 473 tname := NewTypeName(tparam.Obj().Pos(), tparam.Obj().Pkg(), tparam.Obj().Name(), nil) 474 tparams2[i] = NewTypeParam(tname, nil) 475 tparams2[i].index = tparam.index // == i 476 } 477 478 renameMap := makeRenameMap(tparams, tparams2) 479 for i, tparam := range tparams { 480 tparams2[i].bound = check.subst(pos, tparam.bound, renameMap, nil, check.context()) 481 } 482 483 return tparams2, check.subst(pos, typ, renameMap, nil, check.context()) 484 } 485 486 // typeParamsString produces a string containing all the type parameter names 487 // in list suitable for human consumption. 488 func typeParamsString(list []*TypeParam) string { 489 // common cases 490 n := len(list) 491 switch n { 492 case 0: 493 return "" 494 case 1: 495 return list[0].obj.name 496 case 2: 497 return list[0].obj.name + " and " + list[1].obj.name 498 } 499 500 // general case (n > 2) 501 var buf strings.Builder 502 for i, tname := range list[:n-1] { 503 if i > 0 { 504 buf.WriteString(", ") 505 } 506 buf.WriteString(tname.obj.name) 507 } 508 buf.WriteString(", and ") 509 buf.WriteString(list[n-1].obj.name) 510 return buf.String() 511 } 512 513 // isParameterized reports whether typ contains any of the type parameters of tparams. 514 // If typ is a generic function, isParameterized ignores the type parameter declarations; 515 // it only considers the signature proper (incoming and result parameters). 516 func isParameterized(tparams []*TypeParam, typ Type) bool { 517 w := tpWalker{ 518 tparams: tparams, 519 seen: make(map[Type]bool), 520 } 521 return w.isParameterized(typ) 522 } 523 524 type tpWalker struct { 525 tparams []*TypeParam 526 seen map[Type]bool 527 } 528 529 func (w *tpWalker) isParameterized(typ Type) (res bool) { 530 // detect cycles 531 if x, ok := w.seen[typ]; ok { 532 return x 533 } 534 w.seen[typ] = false 535 defer func() { 536 w.seen[typ] = res 537 }() 538 539 switch t := typ.(type) { 540 case *Basic: 541 // nothing to do 542 543 case *Array: 544 return w.isParameterized(t.elem) 545 546 case *Slice: 547 return w.isParameterized(t.elem) 548 549 case *Struct: 550 return w.varList(t.fields) 551 552 case *Pointer: 553 return w.isParameterized(t.base) 554 555 case *Tuple: 556 // This case does not occur from within isParameterized 557 // because tuples only appear in signatures where they 558 // are handled explicitly. But isParameterized is also 559 // called by Checker.callExpr with a function result tuple 560 // if instantiation failed (go.dev/issue/59890). 561 return t != nil && w.varList(t.vars) 562 563 case *Signature: 564 // t.tparams may not be nil if we are looking at a signature 565 // of a generic function type (or an interface method) that is 566 // part of the type we're testing. We don't care about these type 567 // parameters. 568 // Similarly, the receiver of a method may declare (rather than 569 // use) type parameters, we don't care about those either. 570 // Thus, we only need to look at the input and result parameters. 571 return t.params != nil && w.varList(t.params.vars) || t.results != nil && w.varList(t.results.vars) 572 573 case *Interface: 574 tset := t.typeSet() 575 for _, m := range tset.methods { 576 if w.isParameterized(m.typ) { 577 return true 578 } 579 } 580 return tset.is(func(t *term) bool { 581 return t != nil && w.isParameterized(t.typ) 582 }) 583 584 case *Map: 585 return w.isParameterized(t.key) || w.isParameterized(t.elem) 586 587 case *Chan: 588 return w.isParameterized(t.elem) 589 590 case *Named: 591 for _, t := range t.TypeArgs().list() { 592 if w.isParameterized(t) { 593 return true 594 } 595 } 596 597 case *TypeParam: 598 return tparamIndex(w.tparams, t) >= 0 599 600 default: 601 panic(fmt.Sprintf("unexpected %T", typ)) 602 } 603 604 return false 605 } 606 607 func (w *tpWalker) varList(list []*Var) bool { 608 for _, v := range list { 609 if w.isParameterized(v.typ) { 610 return true 611 } 612 } 613 return false 614 } 615 616 // If the type parameter has a single specific type S, coreTerm returns (S, true). 617 // Otherwise, if tpar has a core type T, it returns a term corresponding to that 618 // core type and false. In that case, if any term of tpar has a tilde, the core 619 // term has a tilde. In all other cases coreTerm returns (nil, false). 620 func coreTerm(tpar *TypeParam) (*term, bool) { 621 n := 0 622 var single *term // valid if n == 1 623 var tilde bool 624 tpar.is(func(t *term) bool { 625 if t == nil { 626 assert(n == 0) 627 return false // no terms 628 } 629 n++ 630 single = t 631 if t.tilde { 632 tilde = true 633 } 634 return true 635 }) 636 if n == 1 { 637 if debug { 638 assert(debug && under(single.typ) == coreType(tpar)) 639 } 640 return single, true 641 } 642 if typ := coreType(tpar); typ != nil { 643 // A core type is always an underlying type. 644 // If any term of tpar has a tilde, we don't 645 // have a precise core type and we must return 646 // a tilde as well. 647 return &term{tilde, typ}, false 648 } 649 return nil, false 650 } 651 652 // killCycles walks through the given type parameters and looks for cycles 653 // created by type parameters whose inferred types refer back to that type 654 // parameter, either directly or indirectly. If such a cycle is detected, 655 // it is killed by setting the corresponding inferred type to nil. 656 // 657 // TODO(gri) Determine if we can simply abort inference as soon as we have 658 // found a single cycle. 659 func killCycles(tparams []*TypeParam, inferred []Type) { 660 w := cycleFinder{tparams, inferred, make(map[Type]bool)} 661 for _, t := range tparams { 662 w.typ(t) // t != nil 663 } 664 } 665 666 type cycleFinder struct { 667 tparams []*TypeParam 668 inferred []Type 669 seen map[Type]bool 670 } 671 672 func (w *cycleFinder) typ(typ Type) { 673 if w.seen[typ] { 674 // We have seen typ before. If it is one of the type parameters 675 // in w.tparams, iterative substitution will lead to infinite expansion. 676 // Nil out the corresponding type which effectively kills the cycle. 677 if tpar, _ := typ.(*TypeParam); tpar != nil { 678 if i := tparamIndex(w.tparams, tpar); i >= 0 { 679 // cycle through tpar 680 w.inferred[i] = nil 681 } 682 } 683 // If we don't have one of our type parameters, the cycle is due 684 // to an ordinary recursive type and we can just stop walking it. 685 return 686 } 687 w.seen[typ] = true 688 defer delete(w.seen, typ) 689 690 switch t := typ.(type) { 691 case *Basic: 692 // nothing to do 693 694 case *Array: 695 w.typ(t.elem) 696 697 case *Slice: 698 w.typ(t.elem) 699 700 case *Struct: 701 w.varList(t.fields) 702 703 case *Pointer: 704 w.typ(t.base) 705 706 // case *Tuple: 707 // This case should not occur because tuples only appear 708 // in signatures where they are handled explicitly. 709 710 case *Signature: 711 if t.params != nil { 712 w.varList(t.params.vars) 713 } 714 if t.results != nil { 715 w.varList(t.results.vars) 716 } 717 718 case *Union: 719 for _, t := range t.terms { 720 w.typ(t.typ) 721 } 722 723 case *Interface: 724 for _, m := range t.methods { 725 w.typ(m.typ) 726 } 727 for _, t := range t.embeddeds { 728 w.typ(t) 729 } 730 731 case *Map: 732 w.typ(t.key) 733 w.typ(t.elem) 734 735 case *Chan: 736 w.typ(t.elem) 737 738 case *Named: 739 for _, tpar := range t.TypeArgs().list() { 740 w.typ(tpar) 741 } 742 743 case *TypeParam: 744 if i := tparamIndex(w.tparams, t); i >= 0 && w.inferred[i] != nil { 745 w.typ(w.inferred[i]) 746 } 747 748 default: 749 panic(fmt.Sprintf("unexpected %T", typ)) 750 } 751 } 752 753 func (w *cycleFinder) varList(list []*Var) { 754 for _, v := range list { 755 w.typ(v.typ) 756 } 757 } 758 759 // If tpar is a type parameter in list, tparamIndex returns the index 760 // of the type parameter in list. Otherwise the result is < 0. 761 func tparamIndex(list []*TypeParam, tpar *TypeParam) int { 762 for i, p := range list { 763 if p == tpar { 764 return i 765 } 766 } 767 return -1 768 }