Skip to content

Commit 6e5be5b

Browse files
[CSDiagnostics] Create KeyPathRootTypeMismatchFailure to diagnose key path root fail on key path application
1 parent 49ca2d0 commit 6e5be5b

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

lib/Sema/CSDiagnostics.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6224,3 +6224,23 @@ bool CoercionAsForceCastFailure::diagnoseAsError() {
62246224
.highlight(getSourceRange());
62256225
return true;
62266226
}
6227+
6228+
bool KeyPathRootTypeMismatchFailure::diagnoseAsError() {
6229+
auto &cs = getConstraintSystem();
6230+
auto locator = getLocator();
6231+
auto anchor = locator->getAnchor();
6232+
6233+
assert(locator->isKeyPathRoot() && "Expect a key path root");
6234+
6235+
if (auto *subscriptExpr = dyn_cast_or_null<SubscriptExpr>(anchor)) {
6236+
auto *tupleExpr = cast<TupleExpr>(subscriptExpr->getIndex());
6237+
auto keyPathType = cs.getType(tupleExpr->getElement(0));
6238+
auto baseType = cs.getType(subscriptExpr->getBase());
6239+
6240+
emitDiagnosticAt(anchor->getLoc(),
6241+
diag::expr_smart_keypath_application_type_mismatch,
6242+
keyPathType, baseType->getRValueType());
6243+
return true;
6244+
}
6245+
return false;
6246+
}

lib/Sema/CSDiagnostics.h

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2022,6 +2022,24 @@ class CoercionAsForceCastFailure final : public ContextualFailure {
20222022

20232023
bool diagnoseAsError() override;
20242024
};
2025+
2026+
/// Diagnose an key path root type that cannot be applied to an instance
2027+
/// base that has another type.
2028+
///
2029+
/// \code
2030+
/// func f (_ bar: Bar , keyPath: KeyPath<Foo, Int> ) {
2031+
/// bar[keyPath: keyPath]
2032+
/// }
2033+
/// \endcode
2034+
class KeyPathRootTypeMismatchFailure final : public ContextualFailure {
2035+
public:
2036+
KeyPathRootTypeMismatchFailure(const Solution &solution, Type lhs, Type rhs,
2037+
ConstraintLocator *locator)
2038+
: ContextualFailure(solution, lhs, rhs, locator) {}
2039+
2040+
bool diagnoseAsError() override;
2041+
};
2042+
20252043
} // end namespace constraints
20262044
} // end namespace swift
20272045

0 commit comments

Comments
 (0)