Skip to content

Commit f4f44d2

Browse files
[CSDiagnostics] MissingOptionalUnwrapKeyPathFailure to diagnose missing unwrap on base of keypath application
1 parent ecb70d2 commit f4f44d2

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

lib/Sema/CSDiagnostics.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6493,3 +6493,19 @@ void MissingRawValueFailure::fixIt(InFlightDiagnostic &diagnostic) const {
64936493

64946494
diagnostic.fixItInsertAfter(range.End, fix);
64956495
}
6496+
6497+
bool MissingOptionalUnwrapKeyPathFailure::diagnoseAsError() {
6498+
emitDiagnostic(diag::optional_not_unwrapped, getFromType(),
6499+
getFromType()->lookThroughSingleOptionalType());
6500+
6501+
emitDiagnostic(diag::optional_keypath_application_base)
6502+
.fixItInsertAfter(getLoc(), "?");
6503+
emitDiagnostic(diag::unwrap_with_force_value)
6504+
.fixItInsertAfter(getLoc(), "!");
6505+
return true;
6506+
}
6507+
6508+
SourceLoc MissingOptionalUnwrapKeyPathFailure::getLoc() const {
6509+
auto *SE = castToExpr<SubscriptExpr>(getAnchor());
6510+
return SE->getBase()->getEndLoc();
6511+
}

lib/Sema/CSDiagnostics.h

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2191,6 +2191,24 @@ class MissingRawValueFailure final : public AbstractRawRepresentableFailure {
21912191
void fixIt(InFlightDiagnostic &diagnostic) const override;
21922192
};
21932193

2194+
/// Diagnose a key path optional base that should be unwraped in order to
2195+
/// apply key path subscript.
2196+
///
2197+
/// \code
2198+
/// func f(_ bar: Bar? , keyPath: KeyPath<Bar, Int>) {
2199+
/// bar[keyPath: keyPath]
2200+
/// }
2201+
/// \endcode
2202+
class MissingOptionalUnwrapKeyPathFailure final : public ContextualFailure {
2203+
public:
2204+
MissingOptionalUnwrapKeyPathFailure(const Solution &solution, Type lhs,
2205+
Type rhs, ConstraintLocator *locator)
2206+
: ContextualFailure(solution, lhs, rhs, locator) {}
2207+
2208+
bool diagnoseAsError() override;
2209+
SourceLoc getLoc() const override;
2210+
};
2211+
21942212
} // end namespace constraints
21952213
} // end namespace swift
21962214

0 commit comments

Comments
 (0)