Skip to content

Emit a warning when optionals are coerced to Any. #4900

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 2 commits into from
Sep 22, 2016
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
9 changes: 8 additions & 1 deletion include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -2328,7 +2328,14 @@ WARNING(optional_check_promotion,none,
WARNING(optional_pattern_match_promotion,none,
"pattern match introduces an implicit promotion from %0 to %1",
(Type, Type))

WARNING(optional_to_any_coercion,none,
"expression implicitly coerced from %0 to Any", (Type))
NOTE(default_optional_to_any,none,
"provide a default value to avoid this warning", ())
NOTE(force_optional_to_any,none,
"force-unwrap the value to avoid this warning", ())
NOTE(silence_optional_to_any,none,
"explicitly cast to Any with 'as Any' to silence this warning", ())

ERROR(invalid_noescape_use,none,
"non-escaping %select{value|parameter}1 %0 may only be called",
Expand Down
51 changes: 50 additions & 1 deletion lib/Sema/MiscDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3593,7 +3593,55 @@ checkImplicitPromotionsInCondition(const StmtConditionElement &cond,
.highlight(subExpr->getSourceRange());
}
}


static void diagnoseOptionalToAnyCoercion(TypeChecker &TC, const Expr *E,
const DeclContext *DC) {
if (!E || isa<ErrorExpr>(E) || !E->getType())
return;

class OptionalToAnyCoercionWalker : public ASTWalker {
TypeChecker &TC;
SmallPtrSet<Expr *, 4> ErasureCoercedToAny;

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

if (auto *coercion = dyn_cast<CoerceExpr>(E)) {
if (E->getType()->isAny() && isa<ErasureExpr>(coercion->getSubExpr()))
ErasureCoercedToAny.insert(coercion->getSubExpr());
} else if (isa<ErasureExpr>(E) && !ErasureCoercedToAny.count(E) &&
E->getType()->isAny()) {
auto subExpr = cast<ErasureExpr>(E)->getSubExpr();
auto erasedTy = subExpr->getType();
if (erasedTy->getOptionalObjectType()) {
TC.diagnose(subExpr->getStartLoc(), diag::optional_to_any_coercion,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we should be eagerly desugaring here; it makes the diagnostic worse. getOptionalObjectType should look through sugar already.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(as should isAny and any other such query)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah yes, that's the type we're displaying.

I'll commit a follow-up to master and then cherry-pick and add that to this PR.

erasedTy)
.highlight(subExpr->getSourceRange());

TC.diagnose(subExpr->getLoc(), diag::default_optional_to_any)
.highlight(subExpr->getSourceRange())
.fixItInsertAfter(subExpr->getEndLoc(), " ?? <#default value#>");
TC.diagnose(subExpr->getLoc(), diag::force_optional_to_any)
.highlight(subExpr->getSourceRange())
.fixItInsertAfter(subExpr->getEndLoc(), "!");
TC.diagnose(subExpr->getLoc(), diag::silence_optional_to_any)
.highlight(subExpr->getSourceRange())
.fixItInsertAfter(subExpr->getEndLoc(), " as Any");
}
}

return { true, E };
}

public:
OptionalToAnyCoercionWalker(TypeChecker &tc) : TC(tc) { }
};

OptionalToAnyCoercionWalker Walker(TC);
const_cast<Expr *>(E)->walk(Walker);
}

//===----------------------------------------------------------------------===//
// High-level entry points.
//===----------------------------------------------------------------------===//
Expand All @@ -3606,6 +3654,7 @@ void swift::performSyntacticExprDiagnostics(TypeChecker &TC, const Expr *E,
diagSyntacticUseRestrictions(TC, E, DC, isExprStmt);
diagRecursivePropertyAccess(TC, E, DC);
diagnoseImplicitSelfUseInClosure(TC, E, DC);
diagnoseOptionalToAnyCoercion(TC, E, DC);
if (!TC.getLangOpts().DisableAvailabilityChecking)
diagAvailability(TC, E, const_cast<DeclContext*>(DC));
if (TC.Context.LangOpts.EnableObjCInterop)
Expand Down
2 changes: 1 addition & 1 deletion test/ClangModules/accessibility_framework.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ class AA: NSView {
}

let a = A()
print(a.accessibilityLabel(), terminator: "")
print(a.accessibilityLabel() as Any, terminator: "")
2 changes: 1 addition & 1 deletion test/Constraints/bridging.swift
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ func dictionaryToNSDictionary() {

// <rdar://problem/17134986>
var bcOpt: BridgedClass?
nsd = [BridgedStruct() : bcOpt]
nsd = [BridgedStruct() : bcOpt as Any]
bcOpt = nil
_ = nsd
}
Expand Down
4 changes: 2 additions & 2 deletions test/Constraints/patterns.swift
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,8 @@ func SR2066(x: Int?) {
// Test x???? patterns.
switch (nil as Int???) {
case let x???: print(x, terminator: "")
case let x??: print(x, terminator: "")
case let x?: print(x, terminator: "")
case let x??: print(x as Any, terminator: "")
case let x?: print(x as Any, terminator: "")
case 4???: break
case nil??: break
case nil?: break
Expand Down
2 changes: 1 addition & 1 deletion test/SILOptimizer/definite_init_diagnostics.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1121,7 +1121,7 @@ func test22436880() {

// sr-184
let x: String? // expected-note 2 {{constant defined here}}
print(x?.characters.count) // expected-error {{constant 'x' used before being initialized}}
print(x?.characters.count as Any) // expected-error {{constant 'x' used before being initialized}}
print(x!) // expected-error {{constant 'x' used before being initialized}}


Expand Down
60 changes: 60 additions & 0 deletions test/Sema/diag_optional_to_any.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// RUN: %target-parse-verify-swift

func takeAny(_ left: Any, _ right: Any) -> Int? {
return left as? Int
}

func throwing() throws -> Int? {}

func warnOptionalToAnyCoercion(value x: Int?) -> Any {
let a: Any = x // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}

let b: Any = x as Any

let c: Any = takeAny(a, b) // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}

let _: Any = takeAny(c, c) as Any

let _: Any = (x) // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}

let f: Any = (x as Any)
let g: Any = (x) as (Any)

_ = takeAny(f as? Int, g) // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like at least one of these note-cascades to test the Fix-Its themselves using the -verify syntax, e.g.,

// expected-note@-1 {{provide a default value to avoid this warning}}{{23-23= ?? <#default value#>}}

to make sure the locations are reasonable and don't break in the future.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, you're right! I'll add one on master.

// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}

let _: Any = takeAny(f as? Int, g) as Any // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}

let _: Any = takeAny(f as? Int as Any, g) as Any

let _: Any = x! == x! ? 1 : x // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}

do {
let _: Any = try throwing() // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}
} catch {}

return x // expected-warning {{expression implicitly coerced from 'Int?' to Any}}
// expected-note@-1 {{provide a default value to avoid this warning}}
// expected-note@-2 {{force-unwrap the value to avoid this warning}}
// expected-note@-3 {{explicitly cast to Any with 'as Any' to silence this warning}}
}