Skip to content

Commit 7471125

Browse files
committed
xxx
1 parent 8624e9a commit 7471125

File tree

18 files changed

+169
-25
lines changed

18 files changed

+169
-25
lines changed

include/swift/AST/DiagnosticsSema.def

Lines changed: 3 additions & 0 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))

include/swift/AST/Expr.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6119,7 +6119,7 @@ class KeyPathDotExpr : public Expr {
61196119
class SingleValueStmtExpr : public Expr {
61206120
public:
61216121
enum class Kind {
6122-
If, Switch
6122+
If, Switch, Do, DoCatch
61236123
};
61246124

61256125
private:

include/swift/AST/Stmt.h

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

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

include/swift/AST/TypeCheckRequests.h

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

3906+
/// The statement is a 'do catch' statement without an unconditional
3907+
/// 'catch'.
3908+
NonExhaustiveDoCatch,
3909+
39063910
/// There is no branch that produces a resulting value.
39073911
NoResult,
39083912

@@ -3959,6 +3963,9 @@ class IsSingleValueStmtResult {
39593963
static IsSingleValueStmtResult nonExhaustiveIf() {
39603964
return IsSingleValueStmtResult(Kind::NonExhaustiveIf);
39613965
}
3966+
static IsSingleValueStmtResult nonExhaustiveDoCatch() {
3967+
return IsSingleValueStmtResult(Kind::NonExhaustiveDoCatch);
3968+
}
39623969
static IsSingleValueStmtResult noResult() {
39633970
return IsSingleValueStmtResult(Kind::NoResult);
39643971
}

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
@@ -3529,6 +3529,10 @@ static bool usesFeatureThenStatements(Decl *decl) {
35293529
return false;
35303530
}
35313531

3532+
static bool usesFeatureDoExpressions(Decl *decl) {
3533+
return false;
3534+
}
3535+
35323536
static bool usesFeatureNewCxxMethodSafetyHeuristics(Decl *decl) {
35333537
return decl->hasClangNode();
35343538
}

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
@@ -2488,6 +2488,8 @@ SingleValueStmtExpr *SingleValueStmtExpr::create(ASTContext &ctx, Stmt *S,
24882488

24892489
SingleValueStmtExpr *SingleValueStmtExpr::createWithWrappedBranches(
24902490
ASTContext &ctx, Stmt *S, DeclContext *DC, bool mustBeExpr) {
2491+
assert(!isa<DoStmt>(S) || !isa<DoCatchStmt>(S) ||
2492+
ctx.LangOpts.hasFeature(Feature::DoExpressions));
24912493
auto *SVE = create(ctx, S, DC);
24922494

24932495
// Attempt to wrap any branches that can be wrapped.
@@ -2499,12 +2501,15 @@ SingleValueStmtExpr *SingleValueStmtExpr::createWithWrappedBranches(
24992501

25002502
if (auto *S = BS->getSingleActiveStatement()) {
25012503
if (mustBeExpr) {
2502-
// If this must be an expression, we can eagerly wrap any exhaustive if
2503-
// and switch branch.
2504+
// If this must be an expression, we can eagerly wrap any exhaustive if,
2505+
// switch, and do statement.
25042506
if (auto *IS = dyn_cast<IfStmt>(S)) {
25052507
if (!IS->isSyntacticallyExhaustive())
25062508
continue;
2507-
} else if (!isa<SwitchStmt>(S)) {
2509+
} else if (auto *DCS = dyn_cast<DoCatchStmt>(S)) {
2510+
if (!DCS->isSyntacticallyExhaustive())
2511+
continue;
2512+
} else if (!isa<SwitchStmt>(S) && !isa<DoStmt>(S)) {
25082513
continue;
25092514
}
25102515
} else {
@@ -2587,18 +2592,28 @@ SingleValueStmtExpr::Kind SingleValueStmtExpr::getStmtKind() const {
25872592
return Kind::If;
25882593
case StmtKind::Switch:
25892594
return Kind::Switch;
2595+
case StmtKind::Do:
2596+
return Kind::Do;
2597+
case StmtKind::DoCatch:
2598+
return Kind::DoCatch;
25902599
default:
25912600
llvm_unreachable("Unhandled kind!");
25922601
}
25932602
}
25942603

25952604
ArrayRef<Stmt *>
25962605
SingleValueStmtExpr::getBranches(SmallVectorImpl<Stmt *> &scratch) const {
2606+
assert(scratch.empty());
25972607
switch (getStmtKind()) {
25982608
case Kind::If:
25992609
return cast<IfStmt>(getStmt())->getBranches(scratch);
26002610
case Kind::Switch:
26012611
return cast<SwitchStmt>(getStmt())->getBranches(scratch);
2612+
case Kind::Do:
2613+
scratch.push_back(cast<DoStmt>(getStmt())->getBody());
2614+
return scratch;
2615+
case Kind::DoCatch:
2616+
return cast<DoCatchStmt>(getStmt())->getBranches(scratch);
26022617
}
26032618
llvm_unreachable("Unhandled case in switch!");
26042619
}

lib/AST/Stmt.cpp

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

857+
ArrayRef<Stmt *>
858+
DoCatchStmt::getBranches(SmallVectorImpl<Stmt *> &scratch) const {
859+
assert(scratch.empty());
860+
scratch.push_back(getBody());
861+
for (auto *CS : getCatches())
862+
scratch.push_back(CS->getBody());
863+
return scratch;
864+
}
865+
857866
// See swift/Basic/Statistic.h for declaration: this enables tracing Stmts, is
858867
// defined here to avoid too much layering violation / circular linkage
859868
// 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: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2997,14 +2997,11 @@ areBranchesValidForSingleValueStmt(Evaluator &eval, ArrayRef<Stmt *> branches) {
29972997

29982998
IsSingleValueStmtResult
29992999
IsSingleValueStmtRequest::evaluate(Evaluator &eval, const Stmt *S) const {
3000-
if (!isa<IfStmt>(S) && !isa<SwitchStmt>(S))
3001-
return IsSingleValueStmtResult::unhandledStmt();
3002-
30033000
// Statements must be unlabeled.
3004-
auto *LS = cast<LabeledStmt>(S);
3005-
if (LS->getLabelInfo())
3006-
return IsSingleValueStmtResult::hasLabel();
3007-
3001+
if (auto *LS = dyn_cast<LabeledStmt>(S)) {
3002+
if (LS->getLabelInfo())
3003+
return IsSingleValueStmtResult::hasLabel();
3004+
}
30083005
if (auto *IS = dyn_cast<IfStmt>(S)) {
30093006
// Must be exhaustive.
30103007
if (!IS->isSyntacticallyExhaustive())
@@ -3017,7 +3014,17 @@ IsSingleValueStmtRequest::evaluate(Evaluator &eval, const Stmt *S) const {
30173014
SmallVector<Stmt *, 4> scratch;
30183015
return areBranchesValidForSingleValueStmt(eval, SS->getBranches(scratch));
30193016
}
3020-
llvm_unreachable("Unhandled case");
3017+
if (auto *DS = dyn_cast<DoStmt>(S))
3018+
return areBranchesValidForSingleValueStmt(eval, DS->getBody());
3019+
3020+
if (auto *DCS = dyn_cast<DoCatchStmt>(S)) {
3021+
if (!DCS->isSyntacticallyExhaustive())
3022+
return IsSingleValueStmtResult::nonExhaustiveDoCatch();
3023+
3024+
SmallVector<Stmt *, 4> scratch;
3025+
return areBranchesValidForSingleValueStmt(eval, DCS->getBranches(scratch));
3026+
}
3027+
return IsSingleValueStmtResult::unhandledStmt();
30213028
}
30223029

30233030
void swift::checkUnknownAttrRestrictions(

test/SILGen/do_expr.swift

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// RUN: %target-swift-emit-silgen -enable-experimental-feature ThenStatements -enable-experimental-feature DoExpressions %s | %FileCheck %s
2+
// RUN: %target-swift-emit-ir -enable-experimental-feature ThenStatements -enable-experimental-feature DoExpressions %s
3+
4+
// Required for experimental features
5+
// REQUIRES: asserts
6+
7+
@discardableResult
8+
func throwsError(_ x: Int = 0) throws -> Int { 0 }
9+
10+
func test1() -> Int {
11+
do { 5 }
12+
}
13+
14+
func test2() -> Int {
15+
return do { 5 }
16+
}
17+
18+
func test3() -> Int {
19+
let x = do { 5 }
20+
return x
21+
}
22+
23+
func test4() -> Int {
24+
do { then 5 }
25+
}
26+
27+
func test5() -> Int {
28+
let x = do { (); then 5 }
29+
return x
30+
}
31+
32+
func test6(_ x: Bool) -> Int {
33+
let x = do {
34+
let y = 0
35+
try throwsError()
36+
then y
37+
} catch {
38+
7
39+
}
40+
return x
41+
}
42+
43+
func test7() throws -> Int {
44+
let x = do {
45+
let y = 0
46+
then try throwsError(y)
47+
} catch _ where .random() {
48+
then try throwsError()
49+
} catch {
50+
8
51+
}
52+
return x
53+
}
54+
55+
// CHECK: test1

test/expr/unary/if_expr.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -933,6 +933,7 @@ func continue1() -> Int {
933933
func return1() -> Int {
934934
// Make sure we always reject a return.
935935
let i = if .random() {
936+
()
936937
do {
937938
for _ in [0] {
938939
while true {

0 commit comments

Comments
 (0)