Skip to content

Commit c1bac12

Browse files
committed
[CSSimplify] Fix warning check to account that "from" might be less optional than "to" type
While checking whether compiler needs to produce a checked cast warning, account for the fact that "from" could be less optional than "to" e.g. `0 as Any?`, so the difference has to be stored as a signed integer otherwise it's going to underflow and result in a crash or infinite recursion in the diagnostics. Resolves: rdar://79523605
1 parent fc982ae commit c1bac12

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

lib/Sema/CSSimplify.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6549,7 +6549,9 @@ static ConstraintFix *maybeWarnAboutExtraneousCast(
65496549
if (!castExpr)
65506550
return nullptr;
65516551

6552-
unsigned extraOptionals = fromOptionals.size() - toOptionals.size();
6552+
// "from" could be less optional than "to" e.g. `0 as Any?`, so
6553+
// we need to store the difference as a signed integer.
6554+
int extraOptionals = fromOptionals.size() - toOptionals.size();
65536555
// Removing the optionality from to type when the force cast expr is an IUO.
65546556
const auto *const TR = castExpr->getCastTypeRepr();
65556557
if (isExpr<ForcedCheckedCastExpr>(anchor) && TR &&
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// RUN: %target-swift-frontend %s -typecheck -verify
2+
3+
func test() -> Any? {
4+
0 as! Any? // expected-warning {{forced cast from 'Int' to 'Any?' always succeeds; did you mean to use 'as'?}}
5+
}

0 commit comments

Comments
 (0)