Skip to content

Commit 948f11b

Browse files
griesemergopherbot
authored andcommitted
go/types, types2: consider shared methods when unifying against interfaces
When unifying two types A and B where one or both of them are interfaces, consider the shared method signatures in unification. 1) If a defined interface (an interface with a type name) is unified with another (defined) interface, currently they must originate in the same type declaration (same origin) for unification to succeed. This is more restrictive than necessary for assignments: when interfaces are assigned to each other, corresponding methods must match, but the interfaces don't have to be identical. In unification, we don't know which direction the assignment is happening (or if we have an assignment in the first place), but in any case one interface must implement the other. Thus, we check that one interface has a subset of the methods of the other and that corresponding method signatures unify. The assignment or instantiation may still not be possible but that will be checked when instantiation and parameter passing is checked. If two interfaces are compared as part of another type during unification, the types must be equal. If they are not, unifying a method subset may still succeed (and possibly produce more type arguments), but that is ok: again, subsequent instantiation and assignment will fail if the types are indeed not identical. 2) In a non-interface type is unified with an interface, currently unification fails. If this unification is a consequence of an assignment (parameter passing), this is again too restrictive: the non-interface type must only implement the interface (possibly among other type set requirements). In any case, all methods of the interface type must be present in the non-interface type and unify with the corresponding interface methods. If they don't, unification will fail either way. If they do, we may infer additional type arguments. Again, the resulting types may still not be correct but that will be determined by the instantiation and parameter passing or assignment checks. If the non-interface type and the interface type appear as component of another type, unification may now produce additional type arguments. But that is again ok because the respective types won't pass instantiation or assignment checks since they are different types. This CL introduces a new unifier flag, enableInterfaceInference, to enable this new behavior. It is currently disabled. For #60353. For #41176. For #57192. Change-Id: I983d0ad5f043c7fe9d377dbb95f6b9342f36f45f Reviewed-on: https://go-review.googlesource.com/c/go/+/497656 TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Robert Griesemer <[email protected]> Reviewed-by: Robert Findley <[email protected]> Run-TryBot: Robert Griesemer <[email protected]> Auto-Submit: Robert Griesemer <[email protected]>
1 parent 26f2569 commit 948f11b

File tree

4 files changed

+335
-4
lines changed

4 files changed

+335
-4
lines changed

src/cmd/compile/internal/types2/unify.go

+146-2
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@ const (
5353
// the core types, if any, of non-local (unbound) type parameters.
5454
enableCoreTypeUnification = true
5555

56+
// If enableInterfaceInference is set, type inference uses
57+
// shared methods for improved type inference involving
58+
// interfaces.
59+
enableInterfaceInference = false
60+
5661
// If traceInference is set, unification will print a trace of its operation.
5762
// Interpretation of trace:
5863
// x ≡ y attempt to unify types x and y
@@ -292,7 +297,7 @@ func (u *unifier) nify(x, y Type, p *ifacePair) (result bool) {
292297
// we will fail at function instantiation or argument assignment time.
293298
//
294299
// If we have at least one defined type, there is one in y.
295-
if ny, _ := y.(*Named); ny != nil && isTypeLit(x) {
300+
if ny, _ := y.(*Named); ny != nil && isTypeLit(x) && !(enableInterfaceInference && IsInterface(x)) {
296301
if traceInference {
297302
u.tracef("%s ≡ under %s", x, ny)
298303
}
@@ -356,6 +361,104 @@ func (u *unifier) nify(x, y Type, p *ifacePair) (result bool) {
356361
x, y = y, x
357362
}
358363

364+
// If EnableInterfaceInference is set and both types are interfaces, one
365+
// interface must have a subset of the methods of the other and corresponding
366+
// method signatures must unify.
367+
// If only one type is an interface, all its methods must be present in the
368+
// other type and corresponding method signatures must unify.
369+
if enableInterfaceInference {
370+
xi, _ := x.(*Interface)
371+
yi, _ := y.(*Interface)
372+
// If we have two interfaces, check the type terms for equivalence,
373+
// and unify common methods if possible.
374+
if xi != nil && yi != nil {
375+
xset := xi.typeSet()
376+
yset := yi.typeSet()
377+
if xset.comparable != yset.comparable {
378+
return false
379+
}
380+
// For now we require terms to be equal.
381+
// We should be able to relax this as well, eventually.
382+
if !xset.terms.equal(yset.terms) {
383+
return false
384+
}
385+
// Interface types are the only types where cycles can occur
386+
// that are not "terminated" via named types; and such cycles
387+
// can only be created via method parameter types that are
388+
// anonymous interfaces (directly or indirectly) embedding
389+
// the current interface. Example:
390+
//
391+
// type T interface {
392+
// m() interface{T}
393+
// }
394+
//
395+
// If two such (differently named) interfaces are compared,
396+
// endless recursion occurs if the cycle is not detected.
397+
//
398+
// If x and y were compared before, they must be equal
399+
// (if they were not, the recursion would have stopped);
400+
// search the ifacePair stack for the same pair.
401+
//
402+
// This is a quadratic algorithm, but in practice these stacks
403+
// are extremely short (bounded by the nesting depth of interface
404+
// type declarations that recur via parameter types, an extremely
405+
// rare occurrence). An alternative implementation might use a
406+
// "visited" map, but that is probably less efficient overall.
407+
q := &ifacePair{xi, yi, p}
408+
for p != nil {
409+
if p.identical(q) {
410+
return true // same pair was compared before
411+
}
412+
p = p.prev
413+
}
414+
// The method set of x must be a subset of the method set
415+
// of y or vice versa, and the common methods must unify.
416+
xmethods := xset.methods
417+
ymethods := yset.methods
418+
// The smaller method set must be the subset, if it exists.
419+
if len(xmethods) > len(ymethods) {
420+
xmethods, ymethods = ymethods, xmethods
421+
}
422+
// len(xmethods) <= len(ymethods)
423+
// Collect the ymethods in a map for quick lookup.
424+
ymap := make(map[string]*Func, len(ymethods))
425+
for _, ym := range ymethods {
426+
ymap[ym.Id()] = ym
427+
}
428+
// All xmethods must exist in ymethods and corresponding signatures must unify.
429+
for _, xm := range xmethods {
430+
if ym := ymap[xm.Id()]; ym == nil || !u.nify(xm.typ, ym.typ, p) {
431+
return false
432+
}
433+
}
434+
return true
435+
}
436+
437+
// We don't have two interfaces. If we have one, make sure it's in xi.
438+
if yi != nil {
439+
xi = yi
440+
y = x
441+
}
442+
443+
// If we have one interface, at a minimum each of the interface methods
444+
// must be implemented and thus unify with a corresponding method from
445+
// the non-interface type, otherwise unification fails.
446+
if xi != nil {
447+
// All xi methods must exist in y and corresponding signatures must unify.
448+
xmethods := xi.typeSet().methods
449+
for _, xm := range xmethods {
450+
obj, _, _ := LookupFieldOrMethod(y, false, xm.pkg, xm.name)
451+
if ym, _ := obj.(*Func); ym == nil || !u.nify(xm.typ, ym.typ, p) {
452+
return false
453+
}
454+
}
455+
return true
456+
}
457+
458+
// Neither x nor y are interface types.
459+
// They must be structurally equivalent to unify.
460+
}
461+
359462
switch x := x.(type) {
360463
case *Basic:
361464
// Basic types are singletons except for the rune and byte
@@ -436,6 +539,8 @@ func (u *unifier) nify(x, y Type, p *ifacePair) (result bool) {
436539
}
437540

438541
case *Interface:
542+
assert(!enableInterfaceInference) // handled before this switch
543+
439544
// Two interface types unify if they have the same set of methods with
440545
// the same names, and corresponding function types unify.
441546
// Lower-case method names from different packages are always different.
@@ -512,6 +617,45 @@ func (u *unifier) nify(x, y Type, p *ifacePair) (result bool) {
512617
// in the same type declaration. If they are instantiated,
513618
// their type argument lists must unify.
514619
if y, ok := y.(*Named); ok {
620+
sameOrig := indenticalOrigin(x, y)
621+
if enableInterfaceInference {
622+
xu := x.under()
623+
yu := y.under()
624+
xi, _ := xu.(*Interface)
625+
yi, _ := yu.(*Interface)
626+
// If one or both defined types are interfaces, use interface unification,
627+
// unless they originated in the same type declaration.
628+
if xi != nil && yi != nil {
629+
// If both interfaces originate in the same declaration,
630+
// their methods unify if the type parameters unify.
631+
// Unify the type parameters rather than the methods in
632+
// case the type parameters are not used in the methods
633+
// (and to preserve existing behavior in this case).
634+
if sameOrig {
635+
xargs := x.TypeArgs().list()
636+
yargs := y.TypeArgs().list()
637+
assert(len(xargs) == len(yargs))
638+
for i, xarg := range xargs {
639+
if !u.nify(xarg, yargs[i], p) {
640+
return false
641+
}
642+
}
643+
return true
644+
}
645+
return u.nify(xu, yu, p)
646+
}
647+
// We don't have two interfaces. If we have one, make sure it's in xi.
648+
if yi != nil {
649+
xi = yi
650+
y = x
651+
}
652+
// If xi is an interface, use interface unification.
653+
if xi != nil {
654+
return u.nify(xi, y, p)
655+
}
656+
// In all other cases, the type arguments and origins must match.
657+
}
658+
515659
// Check type arguments before origins so they unify
516660
// even if the origins don't match; for better error
517661
// messages (see go.dev/issue/53692).
@@ -525,7 +669,7 @@ func (u *unifier) nify(x, y Type, p *ifacePair) (result bool) {
525669
return false
526670
}
527671
}
528-
return indenticalOrigin(x, y)
672+
return sameOrig
529673
}
530674

531675
case *TypeParam:

src/go/types/unify.go

+146-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)