Skip to content

Commit 7a46f2f

Browse files
committed
Introduce do expressions
Allow `do` and `do catch` statements to be treated as expressions if they either have single expression branches, or have terminating `then` statements, following the same rules as `if`/`switch` expressions. This is currently gated behind an experimental feature flag pending evolution discussion.
1 parent d9ec4a8 commit 7a46f2f

23 files changed

+700
-48
lines changed

include/swift/AST/DiagnosticsSema.def

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1234,6 +1234,9 @@ ERROR(single_value_stmt_must_be_unlabeled,none,
12341234
ERROR(if_expr_must_be_syntactically_exhaustive,none,
12351235
"'if' must have an unconditional 'else' to be used as expression",
12361236
())
1237+
ERROR(do_catch_expr_must_be_syntactically_exhaustive,none,
1238+
"'do catch' must have an unconditional 'catch' to be used as expression",
1239+
())
12371240
ERROR(single_value_stmt_branch_empty,none,
12381241
"expected expression in branch of '%0' expression",
12391242
(StmtKind))
@@ -1247,8 +1250,8 @@ ERROR(cannot_jump_in_single_value_stmt,none,
12471250
ERROR(effect_marker_on_single_value_stmt,none,
12481251
"'%0' may not be used on '%1' expression", (StringRef, StmtKind))
12491252
ERROR(out_of_place_then_stmt,none,
1250-
"'then' may only appear as the last statement in an 'if' or 'switch' "
1251-
"expression", ())
1253+
"'then' may only appear as the last statement in an 'if', 'switch', or "
1254+
"'do' expression", ())
12521255

12531256
ERROR(did_not_call_function_value,none,
12541257
"function value was used as a property; add () to call it",

include/swift/AST/Expr.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6036,7 +6036,7 @@ class KeyPathDotExpr : public Expr {
60366036
class SingleValueStmtExpr : public Expr {
60376037
public:
60386038
enum class Kind {
6039-
If, Switch
6039+
If, Switch, Do, DoCatch
60406040
};
60416041

60426042
private:

include/swift/AST/Stmt.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1417,6 +1417,9 @@ class DoCatchStmt final
14171417
return {getTrailingObjects<CaseStmt *>(), Bits.DoCatchStmt.NumCatches};
14181418
}
14191419

1420+
/// Retrieve the complete set of branches for this do-catch statement.
1421+
ArrayRef<Stmt *> getBranches(SmallVectorImpl<Stmt *> &scratch) const;
1422+
14201423
/// Does this statement contain a syntactically exhaustive catch
14211424
/// clause?
14221425
///

include/swift/AST/TypeCheckRequests.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3905,6 +3905,10 @@ class IsSingleValueStmtResult {
39053905
/// The statement is an 'if' statement without an unconditional 'else'.
39063906
NonExhaustiveIf,
39073907

3908+
/// The statement is a 'do catch' statement without an unconditional
3909+
/// 'catch'.
3910+
NonExhaustiveDoCatch,
3911+
39083912
/// There is no branch that produces a resulting value.
39093913
NoResult,
39103914

@@ -3961,6 +3965,9 @@ class IsSingleValueStmtResult {
39613965
static IsSingleValueStmtResult nonExhaustiveIf() {
39623966
return IsSingleValueStmtResult(Kind::NonExhaustiveIf);
39633967
}
3968+
static IsSingleValueStmtResult nonExhaustiveDoCatch() {
3969+
return IsSingleValueStmtResult(Kind::NonExhaustiveDoCatch);
3970+
}
39643971
static IsSingleValueStmtResult noResult() {
39653972
return IsSingleValueStmtResult(Kind::NoResult);
39663973
}

include/swift/Basic/Features.def

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,9 @@ EXPERIMENTAL_FEATURE(PlaygroundExtendedCallbacks, true)
229229
/// Enable 'then' statements.
230230
EXPERIMENTAL_FEATURE(ThenStatements, false)
231231

232+
/// Enable 'do' expressions.
233+
EXPERIMENTAL_FEATURE(DoExpressions, false)
234+
232235
/// Enable the `@_rawLayout` attribute.
233236
EXPERIMENTAL_FEATURE(RawLayout, true)
234237

lib/AST/ASTPrinter.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3534,6 +3534,10 @@ static bool usesFeatureThenStatements(Decl *decl) {
35343534
return false;
35353535
}
35363536

3537+
static bool usesFeatureDoExpressions(Decl *decl) {
3538+
return false;
3539+
}
3540+
35373541
static bool usesFeatureNewCxxMethodSafetyHeuristics(Decl *decl) {
35383542
return decl->hasClangNode();
35393543
}

lib/AST/ASTVerifier.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1222,6 +1222,7 @@ class Verifier : public ASTWalker {
12221222
break;
12231223
case Kind::UnterminatedBranches:
12241224
case Kind::NonExhaustiveIf:
1225+
case Kind::NonExhaustiveDoCatch:
12251226
case Kind::UnhandledStmt:
12261227
case Kind::CircularReference:
12271228
case Kind::HasLabel:

lib/AST/Expr.cpp

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2460,6 +2460,8 @@ SingleValueStmtExpr *SingleValueStmtExpr::create(ASTContext &ctx, Stmt *S,
24602460

24612461
SingleValueStmtExpr *SingleValueStmtExpr::createWithWrappedBranches(
24622462
ASTContext &ctx, Stmt *S, DeclContext *DC, bool mustBeExpr) {
2463+
assert(!(isa<DoStmt>(S) || isa<DoCatchStmt>(S)) ||
2464+
ctx.LangOpts.hasFeature(Feature::DoExpressions));
24632465
auto *SVE = create(ctx, S, DC);
24642466

24652467
// Attempt to wrap any branches that can be wrapped.
@@ -2471,12 +2473,15 @@ SingleValueStmtExpr *SingleValueStmtExpr::createWithWrappedBranches(
24712473

24722474
if (auto *S = BS->getSingleActiveStatement()) {
24732475
if (mustBeExpr) {
2474-
// If this must be an expression, we can eagerly wrap any exhaustive if
2475-
// and switch branch.
2476+
// If this must be an expression, we can eagerly wrap any exhaustive if,
2477+
// switch, and do statement.
24762478
if (auto *IS = dyn_cast<IfStmt>(S)) {
24772479
if (!IS->isSyntacticallyExhaustive())
24782480
continue;
2479-
} else if (!isa<SwitchStmt>(S)) {
2481+
} else if (auto *DCS = dyn_cast<DoCatchStmt>(S)) {
2482+
if (!DCS->isSyntacticallyExhaustive())
2483+
continue;
2484+
} else if (!isa<SwitchStmt>(S) && !isa<DoStmt>(S)) {
24802485
continue;
24812486
}
24822487
} else {
@@ -2559,18 +2564,28 @@ SingleValueStmtExpr::Kind SingleValueStmtExpr::getStmtKind() const {
25592564
return Kind::If;
25602565
case StmtKind::Switch:
25612566
return Kind::Switch;
2567+
case StmtKind::Do:
2568+
return Kind::Do;
2569+
case StmtKind::DoCatch:
2570+
return Kind::DoCatch;
25622571
default:
25632572
llvm_unreachable("Unhandled kind!");
25642573
}
25652574
}
25662575

25672576
ArrayRef<Stmt *>
25682577
SingleValueStmtExpr::getBranches(SmallVectorImpl<Stmt *> &scratch) const {
2578+
assert(scratch.empty());
25692579
switch (getStmtKind()) {
25702580
case Kind::If:
25712581
return cast<IfStmt>(getStmt())->getBranches(scratch);
25722582
case Kind::Switch:
25732583
return cast<SwitchStmt>(getStmt())->getBranches(scratch);
2584+
case Kind::Do:
2585+
scratch.push_back(cast<DoStmt>(getStmt())->getBody());
2586+
return scratch;
2587+
case Kind::DoCatch:
2588+
return cast<DoCatchStmt>(getStmt())->getBranches(scratch);
25742589
}
25752590
llvm_unreachable("Unhandled case in switch!");
25762591
}

lib/AST/Stmt.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -850,6 +850,15 @@ SwitchStmt::getBranches(SmallVectorImpl<Stmt *> &scratch) const {
850850
return scratch;
851851
}
852852

853+
ArrayRef<Stmt *>
854+
DoCatchStmt::getBranches(SmallVectorImpl<Stmt *> &scratch) const {
855+
assert(scratch.empty());
856+
scratch.push_back(getBody());
857+
for (auto *CS : getCatches())
858+
scratch.push_back(CS->getBody());
859+
return scratch;
860+
}
861+
853862
// See swift/Basic/Statistic.h for declaration: this enables tracing Stmts, is
854863
// defined here to avoid too much layering violation / circular linkage
855864
// dependency.

lib/ASTGen/Sources/ASTGen/SourceFile.swift

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@ extension Parser.ExperimentalFeatures {
3535
insert(feature)
3636
}
3737
}
38+
mapFeature(.ReferenceBindings, to: .referenceBindings)
3839
mapFeature(.ThenStatements, to: .thenStatements)
40+
mapFeature(.DoExpressions, to: .doExpressions)
3941
}
4042
}
4143

lib/Parse/ParseExpr.cpp

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -584,11 +584,13 @@ ParserResult<Expr> Parser::parseExprUnary(Diag<> Message, bool isExprBasic) {
584584
// First check to see if we have the start of a regex literal `/.../`.
585585
tryLexRegexLiteral(/*forUnappliedOperator*/ false);
586586

587-
// Try parse an 'if' or 'switch' as an expression. Note we do this here in
588-
// parseExprUnary as we don't allow postfix syntax to hang off such
587+
// Try parse 'if', 'switch', and 'do' as expressions. Note we do this here
588+
// in parseExprUnary as we don't allow postfix syntax to hang off such
589589
// expressions to avoid ambiguities such as postfix '.member', which can
590590
// currently be parsed as a static dot member for a result builder.
591-
if (Tok.isAny(tok::kw_if, tok::kw_switch)) {
591+
if (Tok.isAny(tok::kw_if, tok::kw_switch) ||
592+
(Tok.is(tok::kw_do) &&
593+
Context.LangOpts.hasFeature(Feature::DoExpressions))) {
592594
auto Result = parseStmt();
593595
Expr *E = nullptr;
594596
if (Result.isNonNull()) {

lib/Parse/ParseStmt.cpp

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,10 @@ bool Parser::isStartOfStmt(bool preferExpr) {
7878
// "try" cannot actually start any statements, but we parse it there for
7979
// better recovery in cases like 'try return'.
8080

81-
// For 'if' and 'switch' we can parse as an expression.
82-
if (peekToken().isAny(tok::kw_if, tok::kw_switch)) {
81+
// For 'if', 'switch', and 'do' we can parse as an expression.
82+
if (peekToken().isAny(tok::kw_if, tok::kw_switch) ||
83+
(peekToken().is(tok::kw_do) &&
84+
Context.LangOpts.hasFeature(Feature::DoExpressions))) {
8385
return false;
8486
}
8587
Parser::BacktrackingScope backtrack(*this);
@@ -157,7 +159,10 @@ ParserStatus Parser::parseExprOrStmt(ASTNode &Result) {
157159
// We could also achieve this by more eagerly attempting to parse an 'if'
158160
// or 'switch' as an expression when in statement position, but that
159161
// could result in less useful recovery behavior.
160-
if ((isa<IfStmt>(S) || isa<SwitchStmt>(S)) && Tok.is(tok::kw_as)) {
162+
if ((isa<IfStmt>(S) || isa<SwitchStmt>(S) ||
163+
((isa<DoStmt>(S) || isa<DoCatchStmt>(S)) &&
164+
Context.LangOpts.hasFeature(Feature::DoExpressions))) &&
165+
Tok.is(tok::kw_as)) {
161166
auto *SVE = SingleValueStmtExpr::createWithWrappedBranches(
162167
Context, S, CurDeclContext, /*mustBeExpr*/ true);
163168
auto As = parseExprAs();
@@ -778,8 +783,10 @@ ParserResult<Stmt> Parser::parseStmtReturn(SourceLoc tryLoc) {
778783
tok::pound_else, tok::pound_elseif)) {
779784
return false;
780785
}
781-
// Allowed for if/switch expressions.
782-
if (Tok.isAny(tok::kw_if, tok::kw_switch)) {
786+
// Allowed for if/switch/do expressions.
787+
if (Tok.isAny(tok::kw_if, tok::kw_switch) ||
788+
(Tok.is(tok::kw_do) &&
789+
Context.LangOpts.hasFeature(Feature::DoExpressions))) {
783790
return true;
784791
}
785792
if (isStartOfStmt(/*preferExpr*/ true) || isStartOfSwiftDecl())

lib/Sema/CSSyntacticElement.cpp

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -999,14 +999,23 @@ class SyntacticElementConstraintGenerator
999999

10001000
SmallVector<ElementInfo, 4> elements;
10011001

1002-
// First, let's record a body of `do` statement.
1003-
elements.push_back(makeElement(doStmt->getBody(), doLoc));
1002+
// First, let's record a body of `do` statement. Note we need to add a
1003+
// SyntaticElement locator path element here to avoid treating the inner
1004+
// brace conjunction as being isolated if 'doLoc' is for an isolated
1005+
// conjunction (as is the case with 'do' expressions).
1006+
auto *doBodyLoc = cs.getConstraintLocator(
1007+
doLoc, LocatorPathElt::SyntacticElement(doStmt->getBody()));
1008+
elements.push_back(makeElement(doStmt->getBody(), doBodyLoc));
10041009

10051010
// After that has been type-checked, let's switch to
10061011
// individual `catch` statements.
10071012
for (auto *catchStmt : doStmt->getCatches())
10081013
elements.push_back(makeElement(catchStmt, doLoc));
10091014

1015+
// Inject a join if we have one.
1016+
if (auto *join = context.ElementJoin.getPtrOrNull())
1017+
elements.push_back(makeJoinElement(cs, join, locator));
1018+
10101019
createConjunction(elements, doLoc);
10111020
}
10121021

@@ -1195,6 +1204,10 @@ class SyntacticElementConstraintGenerator
11951204
contextInfo.value_or(ContextualTypeInfo()), isDiscarded));
11961205
}
11971206

1207+
// Inject a join if we have one.
1208+
if (auto *join = context.ElementJoin.getPtrOrNull())
1209+
elements.push_back(makeJoinElement(cs, join, locator));
1210+
11981211
createConjunction(elements, locator);
11991212
}
12001213

lib/Sema/ConstraintLocator.cpp

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -661,7 +661,8 @@ bool ConstraintLocator::isForSingleValueStmtConjunction() const {
661661
}
662662

663663
bool ConstraintLocator::isForSingleValueStmtConjunctionOrBrace() const {
664-
if (!isExpr<SingleValueStmtExpr>(getAnchor()))
664+
auto *SVE = getAsExpr<SingleValueStmtExpr>(getAnchor());
665+
if (!SVE)
665666
return false;
666667

667668
auto path = getPath();
@@ -672,11 +673,17 @@ bool ConstraintLocator::isForSingleValueStmtConjunctionOrBrace() const {
672673
continue;
673674
}
674675

675-
// Ignore a SyntaticElement path element for a case statement of a switch.
676+
// Ignore a SyntaticElement path element for a case statement of a switch,
677+
// or the catch of a do-catch, or the brace of a do-statement.
676678
if (auto elt = path.back().getAs<LocatorPathElt::SyntacticElement>()) {
677679
if (elt->getElement().isStmt(StmtKind::Case)) {
678680
path = path.drop_back();
679-
continue;
681+
break;
682+
}
683+
if (elt->getElement().isStmt(StmtKind::Brace) &&
684+
isa<DoCatchStmt>(SVE->getStmt())) {
685+
path = path.drop_back();
686+
break;
680687
}
681688
}
682689
break;

lib/Sema/MiscDiagnostics.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3947,6 +3947,11 @@ class SingleValueStmtUsageChecker final : public ASTWalker {
39473947
diag::if_expr_must_be_syntactically_exhaustive);
39483948
break;
39493949
}
3950+
case IsSingleValueStmtResult::Kind::NonExhaustiveDoCatch: {
3951+
Diags.diagnose(S->getStartLoc(),
3952+
diag::do_catch_expr_must_be_syntactically_exhaustive);
3953+
break;
3954+
}
39503955
case IsSingleValueStmtResult::Kind::HasLabel: {
39513956
// FIXME: We should offer a fix-it to remove (currently we don't track
39523957
// the colon SourceLoc).

lib/Sema/TypeCheckStmt.cpp

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2981,14 +2981,11 @@ IsSingleValueStmtRequest::evaluate(Evaluator &eval, const Stmt *S,
29812981
assert(_ctx);
29822982
auto &ctx = *_ctx;
29832983

2984-
if (!isa<IfStmt>(S) && !isa<SwitchStmt>(S))
2985-
return IsSingleValueStmtResult::unhandledStmt();
2986-
29872984
// Statements must be unlabeled.
2988-
auto *LS = cast<LabeledStmt>(S);
2989-
if (LS->getLabelInfo())
2990-
return IsSingleValueStmtResult::hasLabel();
2991-
2985+
if (auto *LS = dyn_cast<LabeledStmt>(S)) {
2986+
if (LS->getLabelInfo())
2987+
return IsSingleValueStmtResult::hasLabel();
2988+
}
29922989
if (auto *IS = dyn_cast<IfStmt>(S)) {
29932990
// Must be exhaustive.
29942991
if (!IS->isSyntacticallyExhaustive())
@@ -3001,7 +2998,23 @@ IsSingleValueStmtRequest::evaluate(Evaluator &eval, const Stmt *S,
30012998
SmallVector<Stmt *, 4> scratch;
30022999
return areBranchesValidForSingleValueStmt(ctx, SS->getBranches(scratch));
30033000
}
3004-
llvm_unreachable("Unhandled case");
3001+
if (auto *DS = dyn_cast<DoStmt>(S)) {
3002+
if (!ctx.LangOpts.hasFeature(Feature::DoExpressions))
3003+
return IsSingleValueStmtResult::unhandledStmt();
3004+
3005+
return areBranchesValidForSingleValueStmt(ctx, DS->getBody());
3006+
}
3007+
if (auto *DCS = dyn_cast<DoCatchStmt>(S)) {
3008+
if (!ctx.LangOpts.hasFeature(Feature::DoExpressions))
3009+
return IsSingleValueStmtResult::unhandledStmt();
3010+
3011+
if (!DCS->isSyntacticallyExhaustive())
3012+
return IsSingleValueStmtResult::nonExhaustiveDoCatch();
3013+
3014+
SmallVector<Stmt *, 4> scratch;
3015+
return areBranchesValidForSingleValueStmt(ctx, DCS->getBranches(scratch));
3016+
}
3017+
return IsSingleValueStmtResult::unhandledStmt();
30053018
}
30063019

30073020
void swift::checkUnknownAttrRestrictions(

0 commit comments

Comments
 (0)