@@ -6709,7 +6709,10 @@ static bool isCastToExpressibleByNilLiteral(ConstraintSystem &cs, Type fromType,
6709
6709
static ConstraintFix *maybeWarnAboutExtraneousCast (
6710
6710
ConstraintSystem &cs, Type origFromType, Type origToType, Type fromType,
6711
6711
Type toType, SmallVector<Type, 4 > fromOptionals,
6712
- SmallVector<Type, 4 > toOptionals, ConstraintSystem::TypeMatchOptions flags,
6712
+ SmallVector<Type, 4 > toOptionals,
6713
+ const std::vector<std::tuple<Type, Type, ConversionRestrictionKind>>
6714
+ &constraintRestrictions,
6715
+ ConstraintSystem::TypeMatchOptions flags,
6713
6716
ConstraintLocatorBuilder locator) {
6714
6717
6715
6718
auto last = locator.last ();
@@ -6731,6 +6734,22 @@ static ConstraintFix *maybeWarnAboutExtraneousCast(
6731
6734
// "from" could be less optional than "to" e.g. `0 as Any?`, so
6732
6735
// we need to store the difference as a signed integer.
6733
6736
int extraOptionals = fromOptionals.size () - toOptionals.size ();
6737
+
6738
+ // From expression could be a type variable with a value to optional
6739
+ // restrictions that we have to account for optionality mismatch.
6740
+ const auto subExprType = cs.getType (castExpr->getSubExpr ());
6741
+ if (llvm::any_of (constraintRestrictions, [&](auto &entry) {
6742
+ Type type1, type2;
6743
+ ConversionRestrictionKind kind;
6744
+ std::tie (type1, type2, kind) = entry;
6745
+ if (kind != ConversionRestrictionKind::ValueToOptional)
6746
+ return false ;
6747
+ return fromType->isEqual (type1) && subExprType->isEqual (type2);
6748
+ })) {
6749
+ extraOptionals++;
6750
+ origFromType = OptionalType::get (origFromType);
6751
+ }
6752
+
6734
6753
// Removing the optionality from to type when the force cast expr is an IUO.
6735
6754
const auto *const TR = castExpr->getCastTypeRepr ();
6736
6755
if (isExpr<ForcedCheckedCastExpr>(anchor) && TR &&
@@ -6886,7 +6905,7 @@ ConstraintSystem::simplifyCheckedCastConstraint(
6886
6905
6887
6906
if (auto *fix = maybeWarnAboutExtraneousCast (
6888
6907
*this , origFromType, origToType, fromType, toType, fromOptionals,
6889
- toOptionals, flags, locator)) {
6908
+ toOptionals, ConstraintRestrictions, flags, locator)) {
6890
6909
(void )recordFix (fix);
6891
6910
}
6892
6911
};
@@ -6954,7 +6973,7 @@ ConstraintSystem::simplifyCheckedCastConstraint(
6954
6973
// succeed or fail.
6955
6974
if (auto *fix = maybeWarnAboutExtraneousCast (
6956
6975
*this , origFromType, origToType, fromType, toType, fromOptionals,
6957
- toOptionals, flags, locator)) {
6976
+ toOptionals, ConstraintRestrictions, flags, locator)) {
6958
6977
(void )recordFix (fix);
6959
6978
}
6960
6979
0 commit comments