Skip to content

[CSBindings] Infer key path types from superclass constrained existen… #68940

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions lib/Sema/CSBindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
//===----------------------------------------------------------------------===//
#include "swift/Sema/CSBindings.h"
#include "TypeChecker.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/Sema/ConstraintGraph.h"
#include "swift/Sema/ConstraintSystem.h"
Expand Down Expand Up @@ -1249,6 +1250,21 @@ PotentialBindings::inferFromRelational(Constraint *constraint) {

if (TypeVar->getImpl().isKeyPathType()) {
auto objectTy = type->lookThroughAllOptionalTypes();

// If contextual type is an existential with a superclass
// constraint, let's try to infer a key path type from it.
if (kind == AllowedBindingKind::Subtypes) {
if (type->isExistentialType()) {
auto layout = type->getExistentialLayout();
if (auto superclass = layout.explicitSuperclass) {
if (isKnownKeyPathType(superclass)) {
type = superclass;
objectTy = superclass;
}
}
}
}

if (!(isKnownKeyPathType(objectTy) || objectTy->is<AnyFunctionType>()))
return llvm::None;
}
Expand Down
21 changes: 21 additions & 0 deletions test/expr/unary/keypath/keypath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1181,3 +1181,24 @@ func f_56854() {
// expected-note@-1 2 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}
}
}

// rdar://93103421 - Key path type inference doesn't work when the context is an existential type with a key-path superclass
extension KeyPath : P {
var member: String { "" }
}

func test_keypath_inference_from_existentials() {
struct A<T> : P {
var member: String { "a" }
var other: T { fatalError() }
}

func test<T, U>(_: any P & KeyPath<A<T>, U>, _: T) {
}

let _: any P & KeyPath<A<Int>, String> = \.member // Ok
let _: (any P & KeyPath<A<Int>, String>) = \.member // Ok

test(\.other, 42) // Ok
test(\.member, "") // Ok
}