Skip to content
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
6 changes: 4 additions & 2 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4114,8 +4114,10 @@ performMemberLookup(ConstraintKind constraintKind, DeclName memberName,
if (auto *storage = dyn_cast<AbstractStorageDecl>(decl)) {
// If this is an attempt to access read-only member via
// writable key path, let's fail this choice early.
auto &ctx = getASTContext();
if (isReadOnlyKeyPathComponent(storage) &&
keyPath == getASTContext().getWritableKeyPathDecl()) {
(keyPath == ctx.getWritableKeyPathDecl() ||
keyPath == ctx.getReferenceWritableKeyPathDecl())) {
result.addUnviable(
candidate,
MemberLookupResult::UR_WritableKeyPathOnReadOnlyMember);
Expand All @@ -4126,7 +4128,7 @@ performMemberLookup(ConstraintKind constraintKind, DeclName memberName,
// on the other hand if setter is mutating there is no point
// of attempting `ReferenceWritableKeyPath` overload.
if (storage->isSetterMutating() &&
keyPath == getASTContext().getReferenceWritableKeyPathDecl()) {
keyPath == ctx.getReferenceWritableKeyPathDecl()) {
result.addUnviable(
candidate,
MemberLookupResult::UR_ReferenceWritableKeyPathOnMutatingMember);
Expand Down
35 changes: 35 additions & 0 deletions test/Constraints/keypath_dynamic_member_lookup.swift
Original file line number Diff line number Diff line change
Expand Up @@ -250,3 +250,38 @@ func test_recursive_dynamic_lookup(_ lens: Lens<Lens<Point>>) {
// CHECK-NEXT: keypath $KeyPath<Lens<Lens<Rectangle>>, Lens<Lens<Int>>>, (root $Lens<Lens<Rectangle>>; settable_property $Lens<Lens<Point>>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig : {{.*}})
_ = \Lens<Lens<Rectangle>>.topLeft.x
}

@dynamicMemberLookup
struct RefWritableBox<T> {
var obj: T

init(_ obj: T) {
self.obj = obj
}

subscript<U>(dynamicMember member: KeyPath<T, U>) -> U {
get { return obj[keyPath: member] }
}

subscript<U>(dynamicMember member: ReferenceWritableKeyPath<T, U>) -> U {
get { return obj[keyPath: member] }
set { obj[keyPath: member] = newValue }
}
}

func prefer_readonly_keypath_over_reference_writable() {
class C {
let foo: Int

init(_ foo: Int) {
self.foo = foo
}
}

var box = RefWritableBox(C(42))
// expected-warning@-1 {{variable 'box' was never mutated; consider changing to 'let' constant}}

// CHECK: function_ref RefWritableBox.subscript.getter
// CHECK-NEXT: function_ref @$s29keypath_dynamic_member_lookup14RefWritableBoxV0B6Memberqd__s7KeyPathCyxqd__G_tcluig
_ = box.foo
}