Skip to content

Commit b694698

Browse files
committed
[Diagnostics] Don't record unwrap fix if ? was used incorrectly
In situations like `""?` or `42?`, let's not record an unwrap fix since it was incorrect to use `?` in the first place.
1 parent 2a9903d commit b694698

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

lib/Sema/CSSimplify.cpp

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3243,7 +3243,14 @@ repairViaOptionalUnwrap(ConstraintSystem &cs, Type fromType, Type toType,
32433243
// behind itself which we can use to better understand
32443244
// how many levels of optionality have to be unwrapped.
32453245
if (auto *OEE = dyn_cast<OptionalEvaluationExpr>(anchor)) {
3246-
auto type = cs.getType(OEE->getSubExpr());
3246+
auto *subExpr = OEE->getSubExpr();
3247+
3248+
// First, let's check whether it has been determined that
3249+
// it was incorrect to use `?` in this position.
3250+
if (cs.hasFixFor(cs.getConstraintLocator(subExpr), FixKind::RemoveUnwrap))
3251+
return true;
3252+
3253+
auto type = cs.getType(subExpr);
32473254
// If the type of sub-expression is optional, type of the
32483255
// `OptionalEvaluationExpr` could be safely ignored because
32493256
// it doesn't add any type information.

test/Constraints/optional.swift

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -425,8 +425,9 @@ func test_force_unwrap_not_being_too_eager() {
425425

426426
// rdar://problem/57097401
427427
func invalidOptionalChaining(a: Any) {
428-
a == "="? // expected-error {{binary operator '==' cannot be applied to operands of type 'Any' and 'String?'}}
429-
// expected-note@-1 {{overloads for '==' exist with these partially matching parameter lists: (CodingUserInfoKey, CodingUserInfoKey), (FloatingPointSign, FloatingPointSign), (String, String), (Unicode.CanonicalCombiningClass, Unicode.CanonicalCombiningClass)}}
428+
a == "="? // expected-error {{cannot use optional chaining on non-optional value of type 'String'}}
429+
// expected-error@-1 {{protocol 'Any' as a type cannot conform to 'Equatable'}}
430+
// expected-note@-2 {{requirement from conditional conformance of 'Any?' to 'Equatable'}} expected-note@-2 {{only concrete types such as structs, enums and classes can conform to protocols}}
430431
}
431432

432433
// SR-12309 - Force unwrapping 'nil' compiles without warning

0 commit comments

Comments
 (0)