Skip to content

Commit c8ec2c0

Browse files
committed
[Diag] Fixit when trying to pattern match Optional and non-Optional
If the variable to be matched is an optional and the match partner is non-optional, provide a fixit that inserts a '?' after the match partner
1 parent fc4216e commit c8ec2c0

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

lib/Sema/CSDiag.cpp

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4558,10 +4558,16 @@ bool FailureDiagnosis::visitApplyExpr(ApplyExpr *callExpr) {
45584558

45594559
if (callExpr->isImplicit() && overloadName == "~=") {
45604560
// This binop was synthesized when typechecking an expression pattern.
4561-
diagnose(lhsExpr->getLoc(),
4562-
diag::cannot_match_expr_pattern_with_value, lhsType, rhsType)
4563-
.highlight(lhsExpr->getSourceRange())
4564-
.highlight(rhsExpr->getSourceRange());
4561+
auto diag = diagnose(lhsExpr->getLoc(),
4562+
diag::cannot_match_expr_pattern_with_value,
4563+
lhsType, rhsType);
4564+
diag.highlight(lhsExpr->getSourceRange());
4565+
diag.highlight(rhsExpr->getSourceRange());
4566+
if (auto optUnwrappedType = rhsType->getOptionalObjectType()) {
4567+
if (lhsType->isEqual(optUnwrappedType)) {
4568+
diag.fixItInsert(lhsExpr->getEndLoc(), "?");
4569+
}
4570+
}
45654571
return true;
45664572
}
45674573

test/expr/unary/selector/selector.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ case #selector(C1.method1)?:
126126
}
127127

128128
switch optionalSel {
129-
case #selector(SR1827.bar): // expected-error{{expression pattern of type 'Selector' cannot match values of type 'Selector?'}}
129+
case #selector(SR1827.bar): // expected-error{{expression pattern of type 'Selector' cannot match values of type 'Selector?'}} {{26-26=?}}
130130
break
131131
case #selector(SR1827.bar)!: // expected-error{{cannot force unwrap value of non-optional type 'Selector'}}
132132
break

0 commit comments

Comments
 (0)