Skip to content

Commit 8a0d61f

Browse files
committed
[CSDiagnostics] Add a diagnostic for an invalid key path subscript index argument
1 parent 1a011c3 commit 8a0d61f

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

include/swift/AST/DiagnosticsSema.def

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,10 @@ ERROR(expr_swift_keypath_anyobject_root,none,
704704
"the root type of a Swift key path cannot be 'AnyObject'", ())
705705
ERROR(expr_keypath_multiparam_func_conversion, none,
706706
"cannot convert key path into a multi-argument function type %0", (Type))
707+
ERROR(cannot_convert_type_to_keypath_subscript_index,none,
708+
"cannot use value of type %0 as a key path subscript index; argument must be"
709+
" a key path",
710+
(Type))
707711
WARNING(expr_deprecated_writable_keypath,Deprecation,
708712
"forming a writable keypath to property %0 that is read-only in this context "
709713
"is deprecated and will be removed in a future release",

lib/Sema/CSDiagnostics.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9357,3 +9357,8 @@ bool InvalidTypeSpecializationArity::diagnoseAsError() {
93579357
/*generic=*/nullptr);
93589358
return true;
93599359
}
9360+
9361+
bool InvalidTypeAsKeyPathSubscriptIndex::diagnoseAsError() {
9362+
emitDiagnostic(diag::cannot_convert_type_to_keypath_subscript_index, ArgType);
9363+
return true;
9364+
}

lib/Sema/CSDiagnostics.h

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3128,6 +3128,24 @@ class InvalidTypeSpecializationArity final : public FailureDiagnostic {
31283128
bool diagnoseAsError() override;
31293129
};
31303130

3131+
/// Diagnose attempts to pass non-keypath as an argument to key path subscript:
3132+
///
3133+
/// \code
3134+
/// func test(data: Int) {
3135+
/// data[keyPath: 42] // error `42` is not a key path
3136+
/// }
3137+
/// \endcode
3138+
class InvalidTypeAsKeyPathSubscriptIndex final : public FailureDiagnostic {
3139+
Type ArgType;
3140+
3141+
public:
3142+
InvalidTypeAsKeyPathSubscriptIndex(const Solution &solution, Type argType,
3143+
ConstraintLocator *locator)
3144+
: FailureDiagnostic(solution, locator), ArgType(resolveType(argType)) {}
3145+
3146+
bool diagnoseAsError() override;
3147+
};
3148+
31313149
} // end namespace constraints
31323150
} // end namespace swift
31333151

0 commit comments

Comments
 (0)