Skip to content

Commit 9348907

Browse files
authored
Merge pull request #34060 from xedin/rdar-69454410-5.3
[5.3][CSGen] Check whether parent has a contextual type before diagnosing `nil` use
2 parents 1b2565a + 1421959 commit 9348907

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

lib/Sema/CSGen.cpp

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1207,8 +1207,35 @@ namespace {
12071207
// `_ = nil`, let's diagnose it here because solver can't
12081208
// attempt any types for it.
12091209
auto *parentExpr = CS.getParentExpr(expr);
1210-
while (parentExpr && isa<ParenExpr>(parentExpr))
1211-
parentExpr = CS.getParentExpr(parentExpr);
1210+
bool hasContextualType = bool(CS.getContextualType(expr));
1211+
1212+
while (parentExpr) {
1213+
if (!isa<IdentityExpr>(parentExpr))
1214+
break;
1215+
1216+
// If there is a parent, use it, otherwise we need
1217+
// to check whether the last parent node in the chain
1218+
// had a contextual type associated with it because
1219+
// in situations like:
1220+
//
1221+
// \code
1222+
// func foo() -> Int? {
1223+
// return (nil)
1224+
// }
1225+
// \endcode
1226+
//
1227+
// parentheses around `nil` are significant.
1228+
if (auto *nextParent = CS.getParentExpr(parentExpr)) {
1229+
parentExpr = nextParent;
1230+
} else {
1231+
hasContextualType |= bool(CS.getContextualType(parentExpr));
1232+
// Since current expression is an identity expr
1233+
// and there are no more parents, let's pretend
1234+
// that `nil` don't have a parent since parens
1235+
// are not semantically significant for further checks.
1236+
parentExpr = nullptr;
1237+
}
1238+
}
12121239

12131240
// In cases like `_ = nil?` AST would have `nil`
12141241
// wrapped in `BindOptionalExpr`.
@@ -1243,7 +1270,7 @@ namespace {
12431270
}
12441271
}
12451272

1246-
if (!parentExpr && !CS.getContextualType(expr)) {
1273+
if (!parentExpr && !hasContextualType) {
12471274
DE.diagnose(expr->getLoc(), diag::unresolved_nil_literal);
12481275
return Type();
12491276
}

test/Constraints/optional.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -449,4 +449,12 @@ func sr_12309() {
449449
_ = (((nil))) // expected-error {{'nil' requires a contextual type}}
450450
_ = ((((((nil)))))) // expected-error {{'nil' requires a contextual type}}
451451
_ = (((((((((nil))))))))) // expected-error {{'nil' requires a contextual type}}
452+
453+
func test_with_contextual_type_one() -> Int? {
454+
return (nil) // Ok
455+
}
456+
457+
func test_with_contextual_type_many() -> Int? {
458+
return (((nil))) // Ok
459+
}
452460
}

0 commit comments

Comments
 (0)