github.com/lovishpuri/go-40569/src@v0.0.0-20230519171745-f8623e7c56cf/go/types/unify.go (about) 1 // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT. 2 3 // Copyright 2020 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 unification. 8 // 9 // Type unification attempts to make two types x and y structurally 10 // equivalent by determining the types for a given list of (bound) 11 // type parameters which may occur within x and y. If x and y are 12 // structurally different (say []T vs chan T), or conflicting 13 // types are determined for type parameters, unification fails. 14 // If unification succeeds, as a side-effect, the types of the 15 // bound type parameters may be determined. 16 // 17 // Unification typically requires multiple calls u.unify(x, y) to 18 // a given unifier u, with various combinations of types x and y. 19 // In each call, additional type parameter types may be determined 20 // as a side effect and recorded in u. 21 // If a call fails (returns false), unification fails. 22 // 23 // In the unification context, structural equivalence of two types 24 // ignores the difference between a defined type and its underlying 25 // type if one type is a defined type and the other one is not. 26 // It also ignores the difference between an (external, unbound) 27 // type parameter and its core type. 28 // If two types are not structurally equivalent, they cannot be Go 29 // identical types. On the other hand, if they are structurally 30 // equivalent, they may be Go identical or at least assignable, or 31 // they may be in the type set of a constraint. 32 // Whether they indeed are identical or assignable is determined 33 // upon instantiation and function argument passing. 34 35 package types 36 37 import ( 38 "bytes" 39 "fmt" 40 "sort" 41 "strings" 42 ) 43 44 const ( 45 // Upper limit for recursion depth. Used to catch infinite recursions 46 // due to implementation issues (e.g., see issues go.dev/issue/48619, go.dev/issue/48656). 47 unificationDepthLimit = 50 48 49 // Whether to panic when unificationDepthLimit is reached. 50 // If disabled, a recursion depth overflow results in a (quiet) 51 // unification failure. 52 panicAtUnificationDepthLimit = false // go.dev/issue/59740 53 54 // If enableCoreTypeUnification is set, unification will consider 55 // the core types, if any, of non-local (unbound) type parameters. 56 enableCoreTypeUnification = true 57 58 // If traceInference is set, unification will print a trace of its operation. 59 // Interpretation of trace: 60 // x ≡ y attempt to unify types x and y 61 // p ➞ y type parameter p is set to type y (p is inferred to be y) 62 // p ⇄ q type parameters p and q match (p is inferred to be q and vice versa) 63 // x ≢ y types x and y cannot be unified 64 // [p, q, ...] ➞ [x, y, ...] mapping from type parameters to types 65 traceInference = false 66 ) 67 68 // A unifier maintains a list of type parameters and 69 // corresponding types inferred for each type parameter. 70 // A unifier is created by calling newUnifier. 71 type unifier struct { 72 // handles maps each type parameter to its inferred type through 73 // an indirection *Type called (inferred type) "handle". 74 // Initially, each type parameter has its own, separate handle, 75 // with a nil (i.e., not yet inferred) type. 76 // After a type parameter P is unified with a type parameter Q, 77 // P and Q share the same handle (and thus type). This ensures 78 // that inferring the type for a given type parameter P will 79 // automatically infer the same type for all other parameters 80 // unified (joined) with P. 81 handles map[*TypeParam]*Type 82 depth int // recursion depth during unification 83 } 84 85 // newUnifier returns a new unifier initialized with the given type parameter 86 // and corresponding type argument lists. The type argument list may be shorter 87 // than the type parameter list, and it may contain nil types. Matching type 88 // parameters and arguments must have the same index. 89 func newUnifier(tparams []*TypeParam, targs []Type) *unifier { 90 assert(len(tparams) >= len(targs)) 91 handles := make(map[*TypeParam]*Type, len(tparams)) 92 // Allocate all handles up-front: in a correct program, all type parameters 93 // must be resolved and thus eventually will get a handle. 94 // Also, sharing of handles caused by unified type parameters is rare and 95 // so it's ok to not optimize for that case (and delay handle allocation). 96 for i, x := range tparams { 97 var t Type 98 if i < len(targs) { 99 t = targs[i] 100 } 101 handles[x] = &t 102 } 103 return &unifier{handles, 0} 104 } 105 106 // unify attempts to unify x and y and reports whether it succeeded. 107 // As a side-effect, types may be inferred for type parameters. 108 func (u *unifier) unify(x, y Type) bool { 109 return u.nify(x, y, nil) 110 } 111 112 func (u *unifier) tracef(format string, args ...interface{}) { 113 fmt.Println(strings.Repeat(". ", u.depth) + sprintf(nil, nil, true, format, args...)) 114 } 115 116 // String returns a string representation of the current mapping 117 // from type parameters to types. 118 func (u *unifier) String() string { 119 // sort type parameters for reproducible strings 120 tparams := make(typeParamsById, len(u.handles)) 121 i := 0 122 for tpar := range u.handles { 123 tparams[i] = tpar 124 i++ 125 } 126 sort.Sort(tparams) 127 128 var buf bytes.Buffer 129 w := newTypeWriter(&buf, nil) 130 w.byte('[') 131 for i, x := range tparams { 132 if i > 0 { 133 w.string(", ") 134 } 135 w.typ(x) 136 w.string(": ") 137 w.typ(u.at(x)) 138 } 139 w.byte(']') 140 return buf.String() 141 } 142 143 type typeParamsById []*TypeParam 144 145 func (s typeParamsById) Len() int { return len(s) } 146 func (s typeParamsById) Less(i, j int) bool { return s[i].id < s[j].id } 147 func (s typeParamsById) Swap(i, j int) { s[i], s[j] = s[j], s[i] } 148 149 // join unifies the given type parameters x and y. 150 // If both type parameters already have a type associated with them 151 // and they are not joined, join fails and returns false. 152 func (u *unifier) join(x, y *TypeParam) bool { 153 if traceInference { 154 u.tracef("%s ⇄ %s", x, y) 155 } 156 switch hx, hy := u.handles[x], u.handles[y]; { 157 case hx == hy: 158 // Both type parameters already share the same handle. Nothing to do. 159 case *hx != nil && *hy != nil: 160 // Both type parameters have (possibly different) inferred types. Cannot join. 161 return false 162 case *hx != nil: 163 // Only type parameter x has an inferred type. Use handle of x. 164 u.setHandle(y, hx) 165 // This case is treated like the default case. 166 // case *hy != nil: 167 // // Only type parameter y has an inferred type. Use handle of y. 168 // u.setHandle(x, hy) 169 default: 170 // Neither type parameter has an inferred type. Use handle of y. 171 u.setHandle(x, hy) 172 } 173 return true 174 } 175 176 // asTypeParam returns x.(*TypeParam) if x is a type parameter recorded with u. 177 // Otherwise, the result is nil. 178 func (u *unifier) asTypeParam(x Type) *TypeParam { 179 if x, _ := x.(*TypeParam); x != nil { 180 if _, found := u.handles[x]; found { 181 return x 182 } 183 } 184 return nil 185 } 186 187 // setHandle sets the handle for type parameter x 188 // (and all its joined type parameters) to h. 189 func (u *unifier) setHandle(x *TypeParam, h *Type) { 190 hx := u.handles[x] 191 assert(hx != nil) 192 for y, hy := range u.handles { 193 if hy == hx { 194 u.handles[y] = h 195 } 196 } 197 } 198 199 // at returns the (possibly nil) type for type parameter x. 200 func (u *unifier) at(x *TypeParam) Type { 201 return *u.handles[x] 202 } 203 204 // set sets the type t for type parameter x; 205 // t must not be nil. 206 func (u *unifier) set(x *TypeParam, t Type) { 207 assert(t != nil) 208 if traceInference { 209 u.tracef("%s ➞ %s", x, t) 210 } 211 *u.handles[x] = t 212 } 213 214 // unknowns returns the number of type parameters for which no type has been set yet. 215 func (u *unifier) unknowns() int { 216 n := 0 217 for _, h := range u.handles { 218 if *h == nil { 219 n++ 220 } 221 } 222 return n 223 } 224 225 // inferred returns the list of inferred types for the given type parameter list. 226 // The result is never nil and has the same length as tparams; result types that 227 // could not be inferred are nil. Corresponding type parameters and result types 228 // have identical indices. 229 func (u *unifier) inferred(tparams []*TypeParam) []Type { 230 list := make([]Type, len(tparams)) 231 for i, x := range tparams { 232 list[i] = u.at(x) 233 } 234 return list 235 } 236 237 // nify implements the core unification algorithm which is an 238 // adapted version of Checker.identical. For changes to that 239 // code the corresponding changes should be made here. 240 // Must not be called directly from outside the unifier. 241 func (u *unifier) nify(x, y Type, p *ifacePair) (result bool) { 242 u.depth++ 243 if traceInference { 244 u.tracef("%s ≡ %s", x, y) 245 } 246 defer func() { 247 if traceInference && !result { 248 u.tracef("%s ≢ %s", x, y) 249 } 250 u.depth-- 251 }() 252 253 // nothing to do if x == y 254 if x == y { 255 return true 256 } 257 258 // Stop gap for cases where unification fails. 259 if u.depth > unificationDepthLimit { 260 if traceInference { 261 u.tracef("depth %d >= %d", u.depth, unificationDepthLimit) 262 } 263 if panicAtUnificationDepthLimit { 264 panic("unification reached recursion depth limit") 265 } 266 return false 267 } 268 269 // Unification is symmetric, so we can swap the operands. 270 // Ensure that if we have at least one 271 // - defined type, make sure one is in y 272 // - type parameter recorded with u, make sure one is in x 273 if _, ok := x.(*Named); ok || u.asTypeParam(y) != nil { 274 if traceInference { 275 u.tracef("%s ≡ %s (swap)", y, x) 276 } 277 x, y = y, x 278 } 279 280 // Unification will fail if we match a defined type against a type literal. 281 // Per the (spec) assignment rules, assignments of values to variables with 282 // the same type structure are permitted as long as at least one of them 283 // is not a defined type. To accommodate for that possibility, we continue 284 // unification with the underlying type of a defined type if the other type 285 // is a type literal. 286 // We also continue if the other type is a basic type because basic types 287 // are valid underlying types and may appear as core types of type constraints. 288 // If we exclude them, inferred defined types for type parameters may not 289 // match against the core types of their constraints (even though they might 290 // correctly match against some of the types in the constraint's type set). 291 // Finally, if unification (incorrectly) succeeds by matching the underlying 292 // type of a defined type against a basic type (because we include basic types 293 // as type literals here), and if that leads to an incorrectly inferred type, 294 // we will fail at function instantiation or argument assignment time. 295 // 296 // If we have at least one defined type, there is one in y. 297 if ny, _ := y.(*Named); ny != nil && isTypeLit(x) { 298 if traceInference { 299 u.tracef("%s ≡ under %s", x, ny) 300 } 301 y = ny.under() 302 // Per the spec, a defined type cannot have an underlying type 303 // that is a type parameter. 304 assert(!isTypeParam(y)) 305 // x and y may be identical now 306 if x == y { 307 return true 308 } 309 } 310 311 // Cases where at least one of x or y is a type parameter recorded with u. 312 // If we have at least one type parameter, there is one in x. 313 // If we have exactly one type parameter, because it is in x, 314 // isTypeLit(x) is false and y was not changed above. In other 315 // words, if y was a defined type, it is still a defined type 316 // (relevant for the logic below). 317 switch px, py := u.asTypeParam(x), u.asTypeParam(y); { 318 case px != nil && py != nil: 319 // both x and y are type parameters 320 if u.join(px, py) { 321 return true 322 } 323 // both x and y have an inferred type - they must match 324 return u.nify(u.at(px), u.at(py), p) 325 326 case px != nil: 327 // x is a type parameter, y is not 328 if x := u.at(px); x != nil { 329 // x has an inferred type which must match y 330 if u.nify(x, y, p) { 331 // If we have a match, possibly through underlying types, 332 // and y is a defined type, make sure we record that type 333 // for type parameter x, which may have until now only 334 // recorded an underlying type (go.dev/issue/43056). 335 if _, ok := y.(*Named); ok { 336 u.set(px, y) 337 } 338 return true 339 } 340 return false 341 } 342 // otherwise, infer type from y 343 u.set(px, y) 344 return true 345 } 346 347 // x != y if we get here 348 assert(x != y) 349 350 // If we get here and x or y is a type parameter, they are unbound 351 // (not recorded with the unifier). 352 // Ensure that if we have at least one type parameter, it is in x 353 // (the earlier swap checks for _recorded_ type parameters only). 354 if isTypeParam(y) { 355 if traceInference { 356 u.tracef("%s ≡ %s (swap)", y, x) 357 } 358 x, y = y, x 359 } 360 361 switch x := x.(type) { 362 case *Basic: 363 // Basic types are singletons except for the rune and byte 364 // aliases, thus we cannot solely rely on the x == y check 365 // above. See also comment in TypeName.IsAlias. 366 if y, ok := y.(*Basic); ok { 367 return x.kind == y.kind 368 } 369 370 case *Array: 371 // Two array types unify if they have the same array length 372 // and their element types unify. 373 if y, ok := y.(*Array); ok { 374 // If one or both array lengths are unknown (< 0) due to some error, 375 // assume they are the same to avoid spurious follow-on errors. 376 return (x.len < 0 || y.len < 0 || x.len == y.len) && u.nify(x.elem, y.elem, p) 377 } 378 379 case *Slice: 380 // Two slice types unify if their element types unify. 381 if y, ok := y.(*Slice); ok { 382 return u.nify(x.elem, y.elem, p) 383 } 384 385 case *Struct: 386 // Two struct types unify if they have the same sequence of fields, 387 // and if corresponding fields have the same names, their (field) types unify, 388 // and they have identical tags. Two embedded fields are considered to have the same 389 // name. Lower-case field names from different packages are always different. 390 if y, ok := y.(*Struct); ok { 391 if x.NumFields() == y.NumFields() { 392 for i, f := range x.fields { 393 g := y.fields[i] 394 if f.embedded != g.embedded || 395 x.Tag(i) != y.Tag(i) || 396 !f.sameId(g.pkg, g.name) || 397 !u.nify(f.typ, g.typ, p) { 398 return false 399 } 400 } 401 return true 402 } 403 } 404 405 case *Pointer: 406 // Two pointer types unify if their base types unify. 407 if y, ok := y.(*Pointer); ok { 408 return u.nify(x.base, y.base, p) 409 } 410 411 case *Tuple: 412 // Two tuples types unify if they have the same number of elements 413 // and the types of corresponding elements unify. 414 if y, ok := y.(*Tuple); ok { 415 if x.Len() == y.Len() { 416 if x != nil { 417 for i, v := range x.vars { 418 w := y.vars[i] 419 if !u.nify(v.typ, w.typ, p) { 420 return false 421 } 422 } 423 } 424 return true 425 } 426 } 427 428 case *Signature: 429 // Two function types unify if they have the same number of parameters 430 // and result values, corresponding parameter and result types unify, 431 // and either both functions are variadic or neither is. 432 // Parameter and result names are not required to match. 433 // TODO(gri) handle type parameters or document why we can ignore them. 434 if y, ok := y.(*Signature); ok { 435 return x.variadic == y.variadic && 436 u.nify(x.params, y.params, p) && 437 u.nify(x.results, y.results, p) 438 } 439 440 case *Interface: 441 // Two interface types unify if they have the same set of methods with 442 // the same names, and corresponding function types unify. 443 // Lower-case method names from different packages are always different. 444 // The order of the methods is irrelevant. 445 if y, ok := y.(*Interface); ok { 446 xset := x.typeSet() 447 yset := y.typeSet() 448 if xset.comparable != yset.comparable { 449 return false 450 } 451 if !xset.terms.equal(yset.terms) { 452 return false 453 } 454 a := xset.methods 455 b := yset.methods 456 if len(a) == len(b) { 457 // Interface types are the only types where cycles can occur 458 // that are not "terminated" via named types; and such cycles 459 // can only be created via method parameter types that are 460 // anonymous interfaces (directly or indirectly) embedding 461 // the current interface. Example: 462 // 463 // type T interface { 464 // m() interface{T} 465 // } 466 // 467 // If two such (differently named) interfaces are compared, 468 // endless recursion occurs if the cycle is not detected. 469 // 470 // If x and y were compared before, they must be equal 471 // (if they were not, the recursion would have stopped); 472 // search the ifacePair stack for the same pair. 473 // 474 // This is a quadratic algorithm, but in practice these stacks 475 // are extremely short (bounded by the nesting depth of interface 476 // type declarations that recur via parameter types, an extremely 477 // rare occurrence). An alternative implementation might use a 478 // "visited" map, but that is probably less efficient overall. 479 q := &ifacePair{x, y, p} 480 for p != nil { 481 if p.identical(q) { 482 return true // same pair was compared before 483 } 484 p = p.prev 485 } 486 if debug { 487 assertSortedMethods(a) 488 assertSortedMethods(b) 489 } 490 for i, f := range a { 491 g := b[i] 492 if f.Id() != g.Id() || !u.nify(f.typ, g.typ, q) { 493 return false 494 } 495 } 496 return true 497 } 498 } 499 500 case *Map: 501 // Two map types unify if their key and value types unify. 502 if y, ok := y.(*Map); ok { 503 return u.nify(x.key, y.key, p) && u.nify(x.elem, y.elem, p) 504 } 505 506 case *Chan: 507 // Two channel types unify if their value types unify. 508 if y, ok := y.(*Chan); ok { 509 return u.nify(x.elem, y.elem, p) 510 } 511 512 case *Named: 513 // Two named types unify if their type names originate 514 // in the same type declaration. If they are instantiated, 515 // their type argument lists must unify. 516 if y, ok := y.(*Named); ok { 517 // Check type arguments before origins so they unify 518 // even if the origins don't match; for better error 519 // messages (see go.dev/issue/53692). 520 xargs := x.TypeArgs().list() 521 yargs := y.TypeArgs().list() 522 if len(xargs) != len(yargs) { 523 return false 524 } 525 for i, xarg := range xargs { 526 if !u.nify(xarg, yargs[i], p) { 527 return false 528 } 529 } 530 return indenticalOrigin(x, y) 531 } 532 533 case *TypeParam: 534 // x must be an unbound type parameter (see comment above). 535 if debug { 536 assert(u.asTypeParam(x) == nil) 537 } 538 // By definition, a valid type argument must be in the type set of 539 // the respective type constraint. Therefore, the type argument's 540 // underlying type must be in the set of underlying types of that 541 // constraint. If there is a single such underlying type, it's the 542 // constraint's core type. It must match the type argument's under- 543 // lying type, irrespective of whether the actual type argument, 544 // which may be a defined type, is actually in the type set (that 545 // will be determined at instantiation time). 546 // Thus, if we have the core type of an unbound type parameter, 547 // we know the structure of the possible types satisfying such 548 // parameters. Use that core type for further unification 549 // (see go.dev/issue/50755 for a test case). 550 if enableCoreTypeUnification { 551 // Because the core type is always an underlying type, 552 // unification will take care of matching against a 553 // defined or literal type automatically. 554 // If y is also an unbound type parameter, we will end 555 // up here again with x and y swapped, so we don't 556 // need to take care of that case separately. 557 if cx := coreType(x); cx != nil { 558 if traceInference { 559 u.tracef("core %s ≡ %s", x, y) 560 } 561 return u.nify(cx, y, p) 562 } 563 } 564 // x != y and there's nothing to do 565 566 case nil: 567 // avoid a crash in case of nil type 568 569 default: 570 panic(sprintf(nil, nil, true, "u.nify(%s, %s)", x, y)) 571 } 572 573 return false 574 }