Skip to content

[SR-12626] Fix crash when non WritableKeyPath to a set subscript assign #31140

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
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
7 changes: 7 additions & 0 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7802,6 +7802,13 @@ ConstraintSystem::simplifyKeyPathApplicationConstraint(
return SolutionKind::Unsolved;
};

// When locator points to a KeyPathDynamicMemberLookup, reject the
// key path application.
auto last = locator.last();
if (last && last->isKeyPathDynamicMember()) {
return SolutionKind::Error;
}

if (auto clas = keyPathTy->getAs<NominalType>()) {
if (clas->getDecl() == getASTContext().getAnyKeyPathDecl()) {
// Read-only keypath, whose projected value is upcast to `Any?`.
Expand Down
28 changes: 28 additions & 0 deletions test/attr/attr_dynamic_member_lookup.swift
Original file line number Diff line number Diff line change
Expand Up @@ -789,3 +789,31 @@ func test_combination_of_keypath_and_string_lookups() {
_ = outer.hello.world // Ok
}
}

// SR-12626
@dynamicMemberLookup
struct SR12626 {
var i: Int

subscript(dynamicMember member: KeyPath<SR12626, Int>) -> Int {
get { self[keyPath: member] }
set { self[keyPath: member] = newValue } // expected-error {{cannot assign through subscript: 'member' is a read-only key path}}
}
}

// SR-12245
public struct SR12425_S {}

@dynamicMemberLookup
public struct SR12425_R {}

internal var rightStructInstance: SR12425_R = SR12425_R()

public extension SR12425_R {
subscript<T>(dynamicMember member: WritableKeyPath<SR12425_S, T>) -> T {
// TODO(Diagnostics): bad diagnostic for member assign.
// A better diagnostic would be: key path of type WritableKeyPath<SR12425_S, T> cannot be applied to a base of type SR12425_R
get { rightStructInstance[keyPath: member] } // expected-error {{cannot convert return expression of type 'Any?' to return type 'T'}}
set { rightStructInstance[keyPath: member] = newValue } // expected-error {{type of expression is ambiguous without more context}}
}
}