Debian Codegraph @

gopls/internal/golang/completion/unify.go

raw symbols SCIP
1 // Below was copied from go/types/unify.go on September 24, 2024,
2 // and combined with snippets from other files as well.
3 // It is copied to implement unification for code completion inferences,
4 // in lieu of an official type unification API.
5 //
6 // TODO: When such an API is available, the code below should deleted.
7 //
8 // Due to complexity of extracting private types from the go/types package,
9 // the unifier does not fully implement interface unification.
10 //
11 // The code has been modified to compile without introducing any key functionality changes.
12 //
13
14 // Copyright 2020 The Go Authors. All rights reserved.
15 // Use of this source code is governed by a BSD-style
16 // license that can be found in the LICENSE file.
17
18 // This file implements type unification.
19 //
20 // Type unification attempts to make two types x and y structurally
21 // equivalent by determining the types for a given list of (bound)
22 // type parameters which may occur within x and y. If x and y are
23 // structurally different (say []T vs chan T), or conflicting
24 // types are determined for type parameters, unification fails.
25 // If unification succeeds, as a side-effect, the types of the
26 // bound type parameters may be determined.
27 //
28 // Unification typically requires multiple calls u.unify(x, y) to
29 // a given unifier u, with various combinations of types x and y.
30 // In each call, additional type parameter types may be determined
31 // as a side effect and recorded in u.
32 // If a call fails (returns false), unification fails.
33 //
34 // In the unification context, structural equivalence of two types
35 // ignores the difference between a defined type and its underlying
36 // type if one type is a defined type and the other one is not.
37 // It also ignores the difference between an (external, unbound)
38 // type parameter and its core type.
39 // If two types are not structurally equivalent, they cannot be Go
40 // identical types. On the other hand, if they are structurally
41 // equivalent, they may be Go identical or at least assignable, or
42 // they may be in the type set of a constraint.
43 // Whether they indeed are identical or assignable is determined
44 // upon instantiation and function argument passing.
45
46 package completion
47
48 import (
49 "fmt"
50 "go/types"
51 "strings"
52 )
53
54 const (
55 // Upper limit for recursion depth. Used to catch infinite recursions
56 // due to implementation issues (e.g., see issues go.dev/issue/48619, go.dev/issue/48656).
57 unificationDepthLimit = 50
58
59 // Whether to panic when unificationDepthLimit is reached.
60 // If disabled, a recursion depth overflow results in a (quiet)
61 // unification failure.
62 panicAtUnificationDepthLimit = true
63
64 // If enableCoreTypeUnification is set, unification will consider
65 // the core types, if any, of non-local (unbound) type parameters.
66 enableCoreTypeUnification = true
67 )
68
69 // A unifier maintains a list of type parameters and
70 // corresponding types inferred for each type parameter.
71 // A unifier is created by calling newUnifier.
72 type unifier struct {
73 // handles maps each type parameter to its inferred type through
74 // an indirection *Type called (inferred type) "handle".
75 // Initially, each type parameter has its own, separate handle,
76 // with a nil (i.e., not yet inferred) type.
77 // After a type parameter P is unified with a type parameter Q,
78 // P and Q share the same handle (and thus type). This ensures
79 // that inferring the type for a given type parameter P will
80 // automatically infer the same type for all other parameters
81 // unified (joined) with P.
82 handles map[*types.TypeParam]*types.Type
83 depth int // recursion depth during unification
84 }
85
86 // newUnifier returns a new unifier initialized with the given type parameter
87 // and corresponding type argument lists. The type argument list may be shorter
88 // than the type parameter list, and it may contain nil types. Matching type
89 // parameters and arguments must have the same index.
90 func newUnifier(tparams []*types.TypeParam, targs []types.Type) *unifier {
91 handles := make(map[*types.TypeParam]*types.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 types.Type
98 if i < len(targs) {
99 t = targs[i]
100 }
101 handles[x] = &t
102 }
103 return &unifier{handles, 0}
104 }
105
106 // unifyMode controls the behavior of the unifier.
107 type unifyMode uint
108
109 const (
110 // If unifyModeAssign is set, we are unifying types involved in an assignment:
111 // they may match inexactly at the top, but element types must match
112 // exactly.
113 unifyModeAssign unifyMode = 1 << iota
114
115 // If unifyModeExact is set, types unify if they are identical (or can be
116 // made identical with suitable arguments for type parameters).
117 // Otherwise, a named type and a type literal unify if their
118 // underlying types unify, channel directions are ignored, and
119 // if there is an interface, the other type must implement the
120 // interface.
121 unifyModeExact
122 )
123
124 // This function was copied from go/types/unify.go
125 //
126 // unify attempts to unify x and y and reports whether it succeeded.
127 // As a side-effect, types may be inferred for type parameters.
128 // The mode parameter controls how types are compared.
129 func (u *unifier) unify(x, y types.Type, mode unifyMode) bool {
130 return u.nify(x, y, mode)
131 }
132
133 // join unifies the given type parameters x and y.
134 // If both type parameters already have a type associated with them
135 // and they are not joined, join fails and returns false.
136 func (u *unifier) join(x, y *types.TypeParam) bool {
137 switch hx, hy := u.handles[x], u.handles[y]; {
138 case hx == hy:
139 // Both type parameters already share the same handle. Nothing to do.
140 case *hx != nil && *hy != nil:
141 // Both type parameters have (possibly different) inferred types. Cannot join.
142 return false
143 case *hx != nil:
144 // Only type parameter x has an inferred type. Use handle of x.
145 u.setHandle(y, hx)
146 // This case is treated like the default case.
147 // case *hy != nil:
148 // // Only type parameter y has an inferred type. Use handle of y.
149 // u.setHandle(x, hy)
150 default:
151 // Neither type parameter has an inferred type. Use handle of y.
152 u.setHandle(x, hy)
153 }
154 return true
155 }
156
157 // asBoundTypeParam returns x.(*types.TypeParam) if x is a type parameter recorded with u.
158 // Otherwise, the result is nil.
159 func (u *unifier) asBoundTypeParam(x types.Type) *types.TypeParam {
160 if x, _ := types.Unalias(x).(*types.TypeParam); x != nil {
161 if _, found := u.handles[x]; found {
162 return x
163 }
164 }
165 return nil
166 }
167
168 // setHandle sets the handle for type parameter x
169 // (and all its joined type parameters) to h.
170 func (u *unifier) setHandle(x *types.TypeParam, h *types.Type) {
171 hx := u.handles[x]
172 for y, hy := range u.handles {
173 if hy == hx {
174 u.handles[y] = h
175 }
176 }
177 }
178
179 // at returns the (possibly nil) type for type parameter x.
180 func (u *unifier) at(x *types.TypeParam) types.Type {
181 return *u.handles[x]
182 }
183
184 // set sets the type t for type parameter x;
185 // t must not be nil.
186 func (u *unifier) set(x *types.TypeParam, t types.Type) {
187 *u.handles[x] = t
188 }
189
190 // asInterface returns the underlying type of x as an interface if
191 // it is a non-type parameter interface. Otherwise it returns nil.
192 func asInterface(x types.Type) (i *types.Interface) {
193 if _, ok := types.Unalias(x).(*types.TypeParam); !ok {
194 i, _ = x.Underlying().(*types.Interface)
195 }
196 return i
197 }
198
199 func isTypeParam(t types.Type) bool {
200 _, ok := types.Unalias(t).(*types.TypeParam)
201 return ok
202 }
203
204 func asNamed(t types.Type) *types.Named {
205 n, _ := types.Unalias(t).(*types.Named)
206 return n
207 }
208
209 func isTypeLit(t types.Type) bool {
210 switch types.Unalias(t).(type) {
211 case *types.Named, *types.TypeParam:
212 return false
213 }
214 return true
215 }
216
217 // identicalOrigin reports whether x and y originated in the same declaration.
218 func identicalOrigin(x, y *types.Named) bool {
219 // TODO(gri) is this correct?
220 return x.Origin().Obj() == y.Origin().Obj()
221 }
222
223 func coreType(t types.Type) types.Type {
224 t = types.Unalias(t)
225 tpar, _ := t.(*types.TypeParam)
226 if tpar == nil {
227 return t.Underlying()
228 }
229
230 return nil
231 }
232
233 func sameId(obj *types.Var, pkg *types.Package, name string, foldCase bool) bool {
234 // If we don't care about capitalization, we also ignore packages.
235 if foldCase && strings.EqualFold(obj.Name(), name) {
236 return true
237 }
238 // spec:
239 // "Two identifiers are different if they are spelled differently,
240 // or if they appear in different packages and are not exported.
241 // Otherwise, they are the same."
242 if obj.Name() != name {
243 return false
244 }
245 // obj.Name == name
246 if obj.Exported() {
247 return true
248 }
249 // not exported, so packages must be the same
250 if obj.Pkg() != nil && pkg != nil {
251 return obj.Pkg() == pkg
252 }
253 return obj.Pkg().Path() == pkg.Path()
254 }
255
256 // nify implements the core unification algorithm which is an
257 // adapted version of Checker.identical. For changes to that
258 // code the corresponding changes should be made here.
259 // Must not be called directly from outside the unifier.
260 func (u *unifier) nify(x, y types.Type, mode unifyMode) (result bool) {
261 u.depth++
262 defer func() {
263 u.depth--
264 }()
265
266 // nothing to do if x == y
267 if x == y || types.Unalias(x) == types.Unalias(y) {
268 return true
269 }
270
271 // Stop gap for cases where unification fails.
272 if u.depth > unificationDepthLimit {
273 if panicAtUnificationDepthLimit {
274 panic("unification reached recursion depth limit")
275 }
276 return false
277 }
278
279 // Unification is symmetric, so we can swap the operands.
280 // Ensure that if we have at least one
281 // - defined type, make sure one is in y
282 // - type parameter recorded with u, make sure one is in x
283 if asNamed(x) != nil || u.asBoundTypeParam(y) != nil {
284 x, y = y, x
285 }
286
287 // Unification will fail if we match a defined type against a type literal.
288 // If we are matching types in an assignment, at the top-level, types with
289 // the same type structure are permitted as long as at least one of them
290 // is not a defined type. To accommodate for that possibility, we continue
291 // unification with the underlying type of a defined type if the other type
292 // is a type literal. This is controlled by the exact unification mode.
293 // We also continue if the other type is a basic type because basic types
294 // are valid underlying types and may appear as core types of type constraints.
295 // If we exclude them, inferred defined types for type parameters may not
296 // match against the core types of their constraints (even though they might
297 // correctly match against some of the types in the constraint's type set).
298 // Finally, if unification (incorrectly) succeeds by matching the underlying
299 // type of a defined type against a basic type (because we include basic types
300 // as type literals here), and if that leads to an incorrectly inferred type,
301 // we will fail at function instantiation or argument assignment time.
302 //
303 // If we have at least one defined type, there is one in y.
304 if ny := asNamed(y); mode&unifyModeExact == 0 && ny != nil && isTypeLit(x) {
305 y = ny.Underlying()
306 // Per the spec, a defined type cannot have an underlying type
307 // that is a type parameter.
308 // x and y may be identical now
309 if x == y || types.Unalias(x) == types.Unalias(y) {
310 return true
311 }
312 }
313
314 // Cases where at least one of x or y is a type parameter recorded with u.
315 // If we have at least one type parameter, there is one in x.
316 // If we have exactly one type parameter, because it is in x,
317 // isTypeLit(x) is false and y was not changed above. In other
318 // words, if y was a defined type, it is still a defined type
319 // (relevant for the logic below).
320 switch px, py := u.asBoundTypeParam(x), u.asBoundTypeParam(y); {
321 case px != nil && py != nil:
322 // both x and y are type parameters
323 if u.join(px, py) {
324 return true
325 }
326 // both x and y have an inferred type - they must match
327 return u.nify(u.at(px), u.at(py), mode)
328
329 case px != nil:
330 // x is a type parameter, y is not
331 if x := u.at(px); x != nil {
332 // x has an inferred type which must match y
333 if u.nify(x, y, mode) {
334 // We have a match, possibly through underlying types.
335 xi := asInterface(x)
336 yi := asInterface(y)
337 xn := asNamed(x) != nil
338 yn := asNamed(y) != nil
339 // If we have two interfaces, what to do depends on
340 // whether they are named and their method sets.
341 if xi != nil && yi != nil {
342 // Both types are interfaces.
343 // If both types are defined types, they must be identical
344 // because unification doesn't know which type has the "right" name.
345 if xn && yn {
346 return types.Identical(x, y)
347 }
348 return false
349 // Below is the original code for reference
350
351 // In all other cases, the method sets must match.
352 // The types unified so we know that corresponding methods
353 // match and we can simply compare the number of methods.
354 // TODO(gri) We may be able to relax this rule and select
355 // the more general interface. But if one of them is a defined
356 // type, it's not clear how to choose and whether we introduce
357 // an order dependency or not. Requiring the same method set
358 // is conservative.
359 // if len(xi.typeSet().methods) != len(yi.typeSet().methods) {
360 // return false
361 // }
362 } else if xi != nil || yi != nil {
363 // One but not both of them are interfaces.
364 // In this case, either x or y could be viable matches for the corresponding
365 // type parameter, which means choosing either introduces an order dependence.
366 // Therefore, we must fail unification (go.dev/issue/60933).
367 return false
368 }
369 // If we have inexact unification and one of x or y is a defined type, select the
370 // defined type. This ensures that in a series of types, all matching against the
371 // same type parameter, we infer a defined type if there is one, independent of
372 // order. Type inference or assignment may fail, which is ok.
373 // Selecting a defined type, if any, ensures that we don't lose the type name;
374 // and since we have inexact unification, a value of equally named or matching
375 // undefined type remains assignable (go.dev/issue/43056).
376 //
377 // Similarly, if we have inexact unification and there are no defined types but
378 // channel types, select a directed channel, if any. This ensures that in a series
379 // of unnamed types, all matching against the same type parameter, we infer the
380 // directed channel if there is one, independent of order.
381 // Selecting a directional channel, if any, ensures that a value of another
382 // inexactly unifying channel type remains assignable (go.dev/issue/62157).
383 //
384 // If we have multiple defined channel types, they are either identical or we
385 // have assignment conflicts, so we can ignore directionality in this case.
386 //
387 // If we have defined and literal channel types, a defined type wins to avoid
388 // order dependencies.
389 if mode&unifyModeExact == 0 {
390 switch {
391 case xn:
392 // x is a defined type: nothing to do.
393 case yn:
394 // x is not a defined type and y is a defined type: select y.
395 u.set(px, y)
396 default:
397 // Neither x nor y are defined types.
398 if yc, _ := y.Underlying().(*types.Chan); yc != nil && yc.Dir() != types.SendRecv {
399 // y is a directed channel type: select y.
400 u.set(px, y)
401 }
402 }
403 }
404 return true
405 }
406 return false
407 }
408 // otherwise, infer type from y
409 u.set(px, y)
410 return true
411 }
412
413 // If u.EnableInterfaceInference is set and we don't require exact unification,
414 // if both types are interfaces, one interface must have a subset of the
415 // methods of the other and corresponding method signatures must unify.
416 // If only one type is an interface, all its methods must be present in the
417 // other type and corresponding method signatures must unify.
418
419 // Unless we have exact unification, neither x nor y are interfaces now.
420 // Except for unbound type parameters (see below), x and y must be structurally
421 // equivalent to unify.
422
423 // If we get here and x or y is a type parameter, they are unbound
424 // (not recorded with the unifier).
425 // Ensure that if we have at least one type parameter, it is in x
426 // (the earlier swap checks for _recorded_ type parameters only).
427 // This ensures that the switch switches on the type parameter.
428 //
429 // TODO(gri) Factor out type parameter handling from the switch.
430 if isTypeParam(y) {
431 x, y = y, x
432 }
433
434 // Type elements (array, slice, etc. elements) use emode for unification.
435 // Element types must match exactly if the types are used in an assignment.
436 emode := mode
437 if mode&unifyModeAssign != 0 {
438 emode |= unifyModeExact
439 }
440
441 // Continue with unaliased types but don't lose original alias names, if any (go.dev/issue/67628).
442 xorig, x := x, types.Unalias(x)
443 yorig, y := y, types.Unalias(y)
444
445 switch x := x.(type) {
446 case *types.Basic:
447 // Basic types are singletons except for the rune and byte
448 // aliases, thus we cannot solely rely on the x == y check
449 // above. See also comment in TypeName.IsAlias.
450 if y, ok := y.(*types.Basic); ok {
451 return x.Kind() == y.Kind()
452 }
453
454 case *types.Array:
455 // Two array types unify if they have the same array length
456 // and their element types unify.
457 if y, ok := y.(*types.Array); ok {
458 // If one or both array lengths are unknown (< 0) due to some error,
459 // assume they are the same to avoid spurious follow-on errors.
460 return (x.Len() < 0 || y.Len() < 0 || x.Len() == y.Len()) && u.nify(x.Elem(), y.Elem(), emode)
461 }
462
463 case *types.Slice:
464 // Two slice types unify if their element types unify.
465 if y, ok := y.(*types.Slice); ok {
466 return u.nify(x.Elem(), y.Elem(), emode)
467 }
468
469 case *types.Struct:
470 // Two struct types unify if they have the same sequence of fields,
471 // and if corresponding fields have the same names, their (field) types unify,
472 // and they have identical tags. Two embedded fields are considered to have the same
473 // name. Lower-case field names from different packages are always different.
474 if y, ok := y.(*types.Struct); ok {
475 if x.NumFields() == y.NumFields() {
476 for i := range x.NumFields() {
477 f := x.Field(i)
478 g := y.Field(i)
479 if f.Embedded() != g.Embedded() ||
480 x.Tag(i) != y.Tag(i) ||
481 !sameId(f, g.Pkg(), g.Name(), false) ||
482 !u.nify(f.Type(), g.Type(), emode) {
483 return false
484 }
485 }
486 return true
487 }
488 }
489
490 case *types.Pointer:
491 // Two pointer types unify if their base types unify.
492 if y, ok := y.(*types.Pointer); ok {
493 return u.nify(x.Elem(), y.Elem(), emode)
494 }
495
496 case *types.Tuple:
497 // Two tuples types unify if they have the same number of elements
498 // and the types of corresponding elements unify.
499 if y, ok := y.(*types.Tuple); ok {
500 if x.Len() == y.Len() {
501 if x != nil {
502 for i := range x.Len() {
503 v := x.At(i)
504 w := y.At(i)
505 if !u.nify(v.Type(), w.Type(), mode) {
506 return false
507 }
508 }
509 }
510 return true
511 }
512 }
513
514 case *types.Signature:
515 // Two function types unify if they have the same number of parameters
516 // and result values, corresponding parameter and result types unify,
517 // and either both functions are variadic or neither is.
518 // Parameter and result names are not required to match.
519 // TODO(gri) handle type parameters or document why we can ignore them.
520 if y, ok := y.(*types.Signature); ok {
521 return x.Variadic() == y.Variadic() &&
522 u.nify(x.Params(), y.Params(), emode) &&
523 u.nify(x.Results(), y.Results(), emode)
524 }
525
526 case *types.Interface:
527 return false
528 // Below is the original code
529
530 // Two interface types unify if they have the same set of methods with
531 // the same names, and corresponding function types unify.
532 // Lower-case method names from different packages are always different.
533 // The order of the methods is irrelevant.
534 // xset := x.typeSet()
535 // yset := y.typeSet()
536 // if xset.comparable != yset.comparable {
537 // return false
538 // }
539 // if !xset.terms.equal(yset.terms) {
540 // return false
541 // }
542 // a := xset.methods
543 // b := yset.methods
544 // if len(a) == len(b) {
545 // // Interface types are the only types where cycles can occur
546 // // that are not "terminated" via named types; and such cycles
547 // // can only be created via method parameter types that are
548 // // anonymous interfaces (directly or indirectly) embedding
549 // // the current interface. Example:
550 // //
551 // // type T interface {
552 // // m() interface{T}
553 // // }
554 // //
555 // // If two such (differently named) interfaces are compared,
556 // // endless recursion occurs if the cycle is not detected.
557 // //
558 // // If x and y were compared before, they must be equal
559 // // (if they were not, the recursion would have stopped);
560 // // search the ifacePair stack for the same pair.
561 // //
562 // // This is a quadratic algorithm, but in practice these stacks
563 // // are extremely short (bounded by the nesting depth of interface
564 // // type declarations that recur via parameter types, an extremely
565 // // rare occurrence). An alternative implementation might use a
566 // // "visited" map, but that is probably less efficient overall.
567 // q := &ifacePair{x, y, p}
568 // for p != nil {
569 // if p.identical(q) {
570 // return true // same pair was compared before
571 // }
572 // p = p.prev
573 // }
574 // if debug {
575 // assertSortedMethods(a)
576 // assertSortedMethods(b)
577 // }
578 // for i, f := range a {
579 // g := b[i]
580 // if f.Id() != g.Id() || !u.nify(f.typ, g.typ, exact, q) {
581 // return false
582 // }
583 // }
584 // return true
585 // }
586
587 case *types.Map:
588 // Two map types unify if their key and value types unify.
589 if y, ok := y.(*types.Map); ok {
590 return u.nify(x.Key(), y.Key(), emode) && u.nify(x.Elem(), y.Elem(), emode)
591 }
592
593 case *types.Chan:
594 // Two channel types unify if their value types unify
595 // and if they have the same direction.
596 // The channel direction is ignored for inexact unification.
597 if y, ok := y.(*types.Chan); ok {
598 return (mode&unifyModeExact == 0 || x.Dir() == y.Dir()) && u.nify(x.Elem(), y.Elem(), emode)
599 }
600
601 case *types.Named:
602 // Two named types unify if their type names originate in the same type declaration.
603 // If they are instantiated, their type argument lists must unify.
604 if y := asNamed(y); y != nil {
605 // Check type arguments before origins so they unify
606 // even if the origins don't match; for better error
607 // messages (see go.dev/issue/53692).
608 xargs := x.TypeArgs()
609 yargs := y.TypeArgs()
610 if xargs.Len() != yargs.Len() {
611 return false
612 }
613 for i := range xargs.Len() {
614 xarg := xargs.At(i)
615 yarg := yargs.At(i)
616 if !u.nify(xarg, yarg, mode) {
617 return false
618 }
619 }
620 return identicalOrigin(x, y)
621 }
622
623 case *types.TypeParam:
624 // By definition, a valid type argument must be in the type set of
625 // the respective type constraint. Therefore, the type argument's
626 // underlying type must be in the set of underlying types of that
627 // constraint. If there is a single such underlying type, it's the
628 // constraint's core type. It must match the type argument's under-
629 // lying type, irrespective of whether the actual type argument,
630 // which may be a defined type, is actually in the type set (that
631 // will be determined at instantiation time).
632 // Thus, if we have the core type of an unbound type parameter,
633 // we know the structure of the possible types satisfying such
634 // parameters. Use that core type for further unification
635 // (see go.dev/issue/50755 for a test case).
636 if enableCoreTypeUnification {
637 // Because the core type is always an underlying type,
638 // unification will take care of matching against a
639 // defined or literal type automatically.
640 // If y is also an unbound type parameter, we will end
641 // up here again with x and y swapped, so we don't
642 // need to take care of that case separately.
643 if cx := coreType(x); cx != nil {
644 // If y is a defined type, it may not match against cx which
645 // is an underlying type (incl. int, string, etc.). Use assign
646 // mode here so that the unifier automatically takes under(y)
647 // if necessary.
648 return u.nify(cx, yorig, unifyModeAssign)
649 }
650 }
651 // x != y and there's nothing to do
652
653 case nil:
654 // avoid a crash in case of nil type
655
656 default:
657 panic(fmt.Sprintf("u.nify(%s, %s, %d)", xorig, yorig, mode))
658 }
659
660 return false
661 }