@@ -6792,7 +6792,12 @@ Expr *ExprRewriter::coerceToType(Expr *expr, Type toType,
6792
6792
case ConversionRestrictionKind::DoubleToCGFloat: {
6793
6793
auto conversionKind = knownRestriction->second ;
6794
6794
6795
- auto *argExpr = locator.trySimplifyToExpr ();
6795
+ // If conversion wraps the whole body of a single-expression closure,
6796
+ // let's use the passed-in expression since the closure itself doesn't
6797
+ // get updated until coercion is done.
6798
+ auto *argExpr = locator.endsWith <LocatorPathElt::ClosureBody>()
6799
+ ? expr
6800
+ : locator.trySimplifyToExpr ();
6796
6801
assert (argExpr);
6797
6802
6798
6803
// Source requires implicit conversion to match destination
@@ -9081,11 +9086,28 @@ ExprWalker::rewriteTarget(SolutionApplicationTarget target) {
9081
9086
// If we're supposed to convert the expression to some particular type,
9082
9087
// do so now.
9083
9088
if (shouldCoerceToContextualType ()) {
9089
+ ConstraintLocator *locator = nullptr ;
9090
+ // Bodies of single-expression closures use a special locator
9091
+ // for contextual type conversion to make sure that result is
9092
+ // convertible to `Void` when `return` is not used explicitly.
9093
+ if (target.getExprContextualTypePurpose () == CTP_ClosureResult) {
9094
+ auto *closure = cast<ClosureExpr>(target.getDeclContext ());
9095
+ auto *returnStmt =
9096
+ castToStmt<ReturnStmt>(closure->getBody ()->getLastElement ());
9097
+
9098
+ locator = cs.getConstraintLocator (
9099
+ closure, LocatorPathElt::ClosureBody (
9100
+ /* hasReturn=*/ !returnStmt->isImplicit ()));
9101
+ } else {
9102
+ locator = cs.getConstraintLocator (
9103
+ resultExpr, LocatorPathElt::ContextualType (
9104
+ target.getExprContextualTypePurpose ()));
9105
+ }
9106
+
9107
+ assert (locator);
9108
+
9084
9109
resultExpr = Rewriter.coerceToType (
9085
- resultExpr, solution.simplifyType (convertType),
9086
- cs.getConstraintLocator (resultExpr,
9087
- LocatorPathElt::ContextualType (
9088
- target.getExprContextualTypePurpose ())));
9110
+ resultExpr, solution.simplifyType (convertType), locator);
9089
9111
} else if (cs.getType (resultExpr)->hasLValueType () &&
9090
9112
!target.isDiscardedExpr ()) {
9091
9113
// We referenced an lvalue. Load it.
0 commit comments