Skip to content

Commit 7d3785a

Browse files
committed
[Sema] Enable Optional-to-Any diagnostics for IUOs
For example, the implicit coercion from `Int!` to `Any` now produces a warning. Previously a warning wasn't emitted despite the optional being implicitly erased to `Any` (but warnings were emitted in some other cases, such as `Int?!` to `Any?`; this commit fixes that inconsistency).
1 parent 1158362 commit 7d3785a

File tree

2 files changed

+10
-9
lines changed

2 files changed

+10
-9
lines changed

lib/Sema/MiscDiagnostics.cpp

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3545,12 +3545,6 @@ static void diagnoseUnintendedOptionalBehavior(TypeChecker &TC, const Expr *E,
35453545

35463546
auto subExpr = E->getSubExpr();
35473547

3548-
// Currently we don't produce Optional-as-Any warnings for implicit IUO
3549-
// to Any coercions (this doesn't take into consideration implicit
3550-
// coercions such as Any?! to Any?, however; we warn on those).
3551-
if (subExpr->getType()->getImplicitlyUnwrappedOptionalObjectType())
3552-
return;
3553-
35543548
// Look through any BindOptionalExprs, as the coercion may have started
35553549
// from a higher level of optionality.
35563550
while (auto *bindExpr = dyn_cast<BindOptionalExpr>(subExpr))

test/Sema/diag_unintended_optional_behavior.swift

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,16 @@ func warnNestedOptionalToOptionalAnyCoercion(_ a: Int?, _ b: Any??, _ c: Int???,
8282
takesOptionalAny(c as Any?, d as Any?)
8383
}
8484

85-
func dontWarnIUOToAnyCoercion(_ a: Int!, _ b: Any?!, _ c: Int??!, _ d: Any???!) {
86-
_ = takeAny(a, b)
87-
_ = takeAny(c, d)
85+
func warnIUOToAnyCoercion(_ a: Int!, _ b: Any?!) {
86+
_ = takeAny(a, b) // expected-warning {{expression implicitly coerced from 'Int!' to 'Any'}}
87+
// expected-note@-1 {{provide a default value to avoid this warning}}{{16-16= ?? <#default value#>}}
88+
// expected-note@-2 {{force-unwrap the value to avoid this warning}}{{16-16=!}}
89+
// expected-note@-3 {{explicitly cast to 'Any' with 'as Any' to silence this warning}}{{16-16= as Any}}
90+
// expected-warning@-4 {{expression implicitly coerced from 'Any?!' to 'Any'}}
91+
// expected-note@-5 {{force-unwrap the value to avoid this warning}}{{19-19=!!}}
92+
// expected-note@-6 {{explicitly cast to 'Any' with 'as Any' to silence this warning}}{{19-19= as Any}}
93+
94+
_ = takeAny(a as Any, b as Any)
8895
}
8996

9097
func warnIUOToOptionalAnyCoercion(_ a: Int!, _ b: Any?!, _ c: Int??!, _ d: Any???!) {

0 commit comments

Comments
 (0)