Skip to content

Commit 03ede74

Browse files
committed
[Diagnostics] Diagnose use of one or more return statements in a result builder body
1 parent da8159c commit 03ede74

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

lib/Sema/CSDiagnostics.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7052,3 +7052,22 @@ bool ReferenceToInvalidDeclaration::diagnoseAsError() {
70527052
emitDiagnosticAt(decl, diag::decl_declared_here, decl->getName());
70537053
return true;
70547054
}
7055+
7056+
bool InvalidReturnInResultBuilderBody::diagnoseAsError() {
7057+
auto *closure = castToExpr<ClosureExpr>(getAnchor());
7058+
7059+
auto returnStmts = TypeChecker::findReturnStatements(closure);
7060+
assert(!returnStmts.empty());
7061+
7062+
auto loc = returnStmts.front()->getReturnLoc();
7063+
emitDiagnosticAt(loc, diag::result_builder_disabled_by_return, BuilderType);
7064+
7065+
// Note that one can remove all of the return statements.
7066+
{
7067+
auto diag = emitDiagnosticAt(loc, diag::result_builder_remove_returns);
7068+
for (auto returnStmt : returnStmts)
7069+
diag.fixItRemove(returnStmt->getReturnLoc());
7070+
}
7071+
7072+
return true;
7073+
}

lib/Sema/CSDiagnostics.h

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2308,6 +2308,26 @@ class ReferenceToInvalidDeclaration final : public FailureDiagnostic {
23082308
bool diagnoseAsError() override;
23092309
};
23102310

2311+
/// Diagnose use of `return` statements in a body of a result builder.
2312+
///
2313+
/// \code
2314+
/// struct S : Builder {
2315+
/// var foo: some Builder {
2316+
/// return EmptyBuilder()
2317+
/// }
2318+
/// }
2319+
/// \endcode
2320+
class InvalidReturnInResultBuilderBody final : public FailureDiagnostic {
2321+
Type BuilderType;
2322+
2323+
public:
2324+
InvalidReturnInResultBuilderBody(const Solution &solution, Type builderTy,
2325+
ConstraintLocator *locator)
2326+
: FailureDiagnostic(solution, locator), BuilderType(builderTy) {}
2327+
2328+
bool diagnoseAsError() override;
2329+
};
2330+
23112331
} // end namespace constraints
23122332
} // end namespace swift
23132333

lib/Sema/CSFix.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1647,7 +1647,8 @@ AllowRefToInvalidDecl::create(ConstraintSystem &cs,
16471647

16481648
bool IgnoreResultBuilderWithReturnStmts::diagnose(const Solution &solution,
16491649
bool asNote) const {
1650-
return false;
1650+
InvalidReturnInResultBuilderBody failure(solution, BuilderType, getLocator());
1651+
return failure.diagnose(asNote);
16511652
}
16521653

16531654
IgnoreResultBuilderWithReturnStmts *

0 commit comments

Comments
 (0)