Skip to content

[MiscDiagnostics] Diagnose passing a non-@objc dynamic KeyPath property to KVO observe #28135

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
Nov 8, 2019
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
3 changes: 3 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -4540,6 +4540,9 @@ WARNING(variable_never_mutated, none,
WARNING(variable_never_read, none,
"variable %0 was written to, but never read",
(Identifier))
WARNING(observe_keypath_property_not_objc_dynamic, none,
"passing reference to non-'@objc dynamic' property %0 to KVO method %1 "
"may lead to unexpected behavior or runtime trap", (DeclName, DeclName))

//------------------------------------------------------------------------------
// MARK: Debug diagnostics
Expand Down
54 changes: 54 additions & 0 deletions lib/Sema/MiscDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3990,6 +3990,59 @@ static void diagnoseDeprecatedWritableKeyPath(const Expr *E,
const_cast<Expr *>(E)->walk(Walker);
}

static void maybeDiagnoseCallToKeyValueObserveMethod(const Expr *E,
const DeclContext *DC) {
class KVOObserveCallWalker : public ASTWalker {
const ASTContext &C;

public:
KVOObserveCallWalker(ASTContext &ctx) : C(ctx) {}

void maybeDiagnoseCallExpr(CallExpr *expr) {
auto fn = expr->getCalledValue();
if (!fn)
return;
if (fn->getModuleContext()->getName() != C.Id_Foundation)
return;
if (!fn->getFullName().isCompoundName("observe",
{"", "options", "changeHandler"}))
return;
auto args = cast<TupleExpr>(expr->getArg());
auto firstArg = dyn_cast<KeyPathExpr>(args->getElement(0));
if (!firstArg)
return;
auto lastComponent = firstArg->getComponents().back();
if (lastComponent.getKind() != KeyPathExpr::Component::Kind::Property)
return;
auto property = lastComponent.getDeclRef().getDecl();
if (!property)
return;
if (property->isObjCDynamic())
return;
C.Diags
.diagnose(expr->getLoc(),
diag::observe_keypath_property_not_objc_dynamic,
property->getFullName(), fn->getFullName())
.highlight(lastComponent.getLoc());
}

std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
if (!E || isa<ErrorExpr>(E) || !E->getType())
return {false, E};

if (auto *CE = dyn_cast<CallExpr>(E)) {
maybeDiagnoseCallExpr(CE);
return {false, E};
}

return {true, E};
}
};

KVOObserveCallWalker Walker(DC->getASTContext());
const_cast<Expr *>(E)->walk(Walker);
}

//===----------------------------------------------------------------------===//
// High-level entry points.
//===----------------------------------------------------------------------===//
Expand All @@ -4004,6 +4057,7 @@ void swift::performSyntacticExprDiagnostics(const Expr *E,
diagRecursivePropertyAccess(E, DC);
diagnoseImplicitSelfUseInClosure(E, DC);
diagnoseUnintendedOptionalBehavior(E, DC);
maybeDiagnoseCallToKeyValueObserveMethod(E, DC);
if (!ctx.isSwiftVersionAtLeast(5))
diagnoseDeprecatedWritableKeyPath(E, DC);
if (!ctx.LangOpts.DisableAvailabilityChecking)
Expand Down
39 changes: 39 additions & 0 deletions test/expr/primary/keypath/keypath-observe-objc.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop

import Foundation

class Foo: NSObject {
var number1 = 1
dynamic var number2 = 2
@objc var number3 = 3
@objc dynamic var number4 = 4
}

class Bar: NSObject {
@objc dynamic let foo: Foo

init(foo: Foo) {
self.foo = foo
super.init()

_ = observe(\.foo.number1, options: [.new]) { _, change in
// expected-warning@-1 {{passing reference to non-'@objc dynamic' property 'number1' to KVO method 'observe(_:options:changeHandler:)' may lead to unexpected behavior or runtime trap}}
print("observer1")
}

_ = observe(\.foo.number2, options: [.new]) { _, change in
// expected-warning@-1 {{passing reference to non-'@objc dynamic' property 'number2' to KVO method 'observe(_:options:changeHandler:)' may lead to unexpected behavior or runtime trap}}
print("observer2")
}

_ = observe(\.foo.number3, options: [.new]) { _, change in
// expected-warning@-1 {{passing reference to non-'@objc dynamic' property 'number3' to KVO method 'observe(_:options:changeHandler:)' may lead to unexpected behavior or runtime trap}}
print("observer3")
}

_ = observe(\.foo.number4, options: [.new]) { _, change in // Okay
print("observer4")
}
}
}