Skip to content

Commit 8195cce

Browse files
[SR-12309] Cannot force unwrap 'nil'
1 parent a7470db commit 8195cce

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

include/swift/AST/DiagnosticsSema.def

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3197,6 +3197,8 @@ ERROR(cannot_infer_base_of_unresolved_member,none,
31973197
"cannot infer contextual base in reference to member %0", (DeclNameRef))
31983198
ERROR(unresolved_nil_literal,none,
31993199
"'nil' requires a contextual type", ())
3200+
ERROR(cannot_force_unwrap_nil_literal,none,
3201+
"'nil' literal cannot be force unwrapped", ())
32003202

32013203
ERROR(type_of_expression_is_ambiguous,none,
32023204
"type of expression is ambiguous without more context", ())

lib/Sema/CSGen.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3207,6 +3207,15 @@ namespace {
32073207
}
32083208

32093209
Type visitForceValueExpr(ForceValueExpr *expr) {
3210+
// Diagnose force-unwrapping a 'nil' literal
3211+
auto &DE = CS.getASTContext().Diags;
3212+
auto subExpr = expr->getSubExpr();
3213+
if (isa<NilLiteralExpr>(subExpr)) {
3214+
DE.diagnose(subExpr->getLoc(), diag::cannot_force_unwrap_nil_literal);
3215+
return Type();
3216+
}
3217+
3218+
32103219
// Force-unwrap an optional of type T? to produce a T.
32113220
auto locator = CS.getConstraintLocator(expr);
32123221

test/Constraints/sr12309.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// RUN: %target-typecheck-verify-swift
2+
3+
struct Foo {
4+
var bar: Int
5+
}
6+
7+
let f = Foo(bar: nil!) // expected-error {{'nil' literal cannot be force unwrapped}}

0 commit comments

Comments
 (0)