Merge pull request #85183 from slavapestov/fix-issue-85034

Sema: Don't coerce subexpression of 'try' to rvalue
This commit is contained in:
Slava Pestov
2025-10-29 07:20:27 -04:00
committed by GitHub
6 changed files with 34 additions and 10 deletions

View File

@@ -3752,7 +3752,11 @@ namespace {
return expr;
}
Expr *visitAnyTryExpr(AnyTryExpr *expr) {
Expr *visitTryExpr(TryExpr *expr) {
return simplifyExprType(expr);
}
Expr *visitForceTryExpr(ForceTryExpr *expr) {
auto *subExpr = expr->getSubExpr();
auto type = simplifyType(cs.getType(subExpr));

View File

@@ -2060,10 +2060,20 @@ namespace {
return valueTy;
}
Type visitAnyTryExpr(AnyTryExpr *expr) {
Type visitTryExpr(AnyTryExpr *expr) {
return CS.getType(expr->getSubExpr());
}
Type visitForceTryExpr(AnyTryExpr *expr) {
auto valueTy = CS.createTypeVariable(CS.getConstraintLocator(expr),
TVO_PrefersSubtypeBinding |
TVO_CanBindToNoEscape);
CS.addConstraint(ConstraintKind::Equal, valueTy,
CS.getType(expr->getSubExpr()),
CS.getConstraintLocator(expr));
return valueTy;
}
Type visitOptionalTryExpr(OptionalTryExpr *expr) {
auto valueTy = CS.createTypeVariable(CS.getConstraintLocator(expr),
TVO_PrefersSubtypeBinding |

View File

@@ -1192,10 +1192,7 @@ TypeChecker::coerceToRValue(ASTContext &Context, Expr *expr,
llvm::function_ref<Type(Expr *)> getType,
llvm::function_ref<void(Expr *, Type)> setType) {
Type exprTy = getType(expr);
// If expr has no type, just assume it's the right expr.
if (!exprTy)
return expr;
ASSERT(exprTy);
// If the type is already materializable, then we're already done.
if (!exprTy->hasLValueType())

View File

@@ -1702,10 +1702,11 @@ public:
// Type-check the subject expression.
Expr *subjectExpr = switchStmt->getSubjectExpr();
auto resultTy = TypeChecker::typeCheckExpression(subjectExpr, DC);
auto limitExhaustivityChecks = !resultTy;
if (Expr *newSubjectExpr =
TypeChecker::coerceToRValue(getASTContext(), subjectExpr))
subjectExpr = newSubjectExpr;
if (resultTy)
subjectExpr = TypeChecker::coerceToRValue(getASTContext(), subjectExpr);
switchStmt->setSubjectExpr(subjectExpr);
Type subjectType = switchStmt->getSubjectExpr()->getType();

View File

@@ -1,4 +1,4 @@
// RUN: %target-swift-frontend %s -typecheck
// RUN: %target-swift-emit-silgen %s
struct Info {
}

View File

@@ -0,0 +1,12 @@
// RUN: %target-typecheck-verify-swift
// RUN: %target-swift-emit-silgen %s
class C {
var x = 0
}
do {
let x = C()
let _ = (0, try x.x) // expected-warning {{no calls to throwing functions occur within 'try' expression}}
let _ = (0, try! x.x) // expected-warning {{no calls to throwing functions occur within 'try' expression}}
}