Skip to content

Commit a40f1ab

Browse files
committed
Introduce if/switch expressions
Introduce SingleValueStmtExpr, which allows the embedding of a statement in an expression context. This then allows us to parse and type-check `if` and `switch` statements as expressions, gated behind the `IfSwitchExpression` experimental feature for now. In the future, SingleValueStmtExpr could also be used for e.g `do` expressions. For now, only single expression branches are supported for producing a value from an `if`/`switch` expression, and each branch is type-checked independently. A multi-statement branch may only appear if it ends with a `throw`, and it may not `break`, `continue`, or `return`. The placement of `if`/`switch` expressions is also currently limited by a syntactic use diagnostic. Currently they're only allowed in bindings, assignments, throws, and returns. But this could be lifted in the future if desired.
1 parent df2b3b2 commit a40f1ab

File tree

70 files changed

+5521
-189
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

70 files changed

+5521
-189
lines changed

include/swift/AST/ASTScope.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -955,6 +955,7 @@ class PatternEntryInitializerScope final : public AbstractPatternEntryScope {
955955

956956
protected:
957957
bool lookupLocalsOrMembers(DeclConsumer) const override;
958+
bool isLabeledStmtLookupTerminator() const override;
958959
};
959960

960961
/// The scope introduced by a conditional clause initializer in an

include/swift/AST/ASTTypeIDZone.def

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ SWIFT_TYPEID(Fingerprint)
2626
SWIFT_TYPEID(GenericSignature)
2727
SWIFT_TYPEID(ImplicitImportList)
2828
SWIFT_TYPEID(ImplicitMemberAction)
29+
SWIFT_TYPEID(IsSingleValueStmtResult)
2930
SWIFT_TYPEID(ParamSpecifier)
3031
SWIFT_TYPEID(PropertyWrapperAuxiliaryVariables)
3132
SWIFT_TYPEID(PropertyWrapperInitializerInfo)

include/swift/AST/ASTTypeIDs.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ class GenericParamList;
4141
class GenericSignature;
4242
class GenericTypeParamType;
4343
class InfixOperatorDecl;
44+
class IsSingleValueStmtResult;
4445
class IterableDeclContext;
4546
class ModuleDecl;
4647
struct ImplicitImportList;

include/swift/AST/CASTBridging.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,9 @@ void *SwiftVarDecl_create(void *ctx, BridgedIdentifier _Nullable name,
169169
void *initExpr, void *loc, _Bool isStatic,
170170
_Bool isLet, void *dc);
171171

172+
void *SingleValueStmtExpr_createWithWrappedBranches(void *ctx, void *S,
173+
void *DC, _Bool mustBeExpr);
174+
172175
void *IfStmt_create(void *ctx, void *ifLoc, void *cond, void *_Nullable then,
173176
void *_Nullable elseLoc, void *_Nullable elseStmt);
174177

include/swift/AST/DiagnosticsSema.def

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1108,6 +1108,27 @@ ERROR(ternary_expr_cases_mismatch,none,
11081108
"result values in '? :' expression have mismatching types %0 and %1",
11091109
(Type, Type))
11101110

1111+
// Statements as expressions
1112+
ERROR(single_value_stmt_branches_mismatch,none,
1113+
"branches have mismatching types %0 and %1",
1114+
(Type, Type))
1115+
ERROR(single_value_stmt_out_of_place,none,
1116+
"'%0' may only be used as expression in return, throw, or as the source "
1117+
"of an assignment",
1118+
(StmtKind))
1119+
ERROR(single_value_stmt_must_be_unlabeled,none,
1120+
"'%0' cannot have a jump label when used as expression",
1121+
(StmtKind))
1122+
ERROR(if_expr_must_be_syntactically_exhaustive,none,
1123+
"'if' must have an unconditional 'else' to be used as expression",
1124+
())
1125+
ERROR(single_value_stmt_branch_must_end_in_throw,none,
1126+
"non-expression branch of '%0' expression may only end with a 'throw'",
1127+
(StmtKind))
1128+
ERROR(cannot_jump_in_single_value_stmt,none,
1129+
"cannot '%0' in '%1' when used as expression",
1130+
(StmtKind, StmtKind))
1131+
11111132
ERROR(did_not_call_function_value,none,
11121133
"function value was used as a property; add () to call it",
11131134
())

include/swift/AST/Expr.h

Lines changed: 74 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5979,6 +5979,63 @@ class KeyPathDotExpr : public Expr {
59795979
}
59805980
};
59815981

5982+
/// An expression that may wrap a statement which produces a single value.
5983+
class SingleValueStmtExpr : public Expr {
5984+
public:
5985+
enum class Kind {
5986+
If, Switch
5987+
};
5988+
5989+
private:
5990+
Stmt *S;
5991+
DeclContext *DC;
5992+
5993+
SingleValueStmtExpr(Stmt *S, DeclContext *DC)
5994+
: Expr(ExprKind::SingleValueStmt, /*isImplicit*/ true), S(S), DC(DC) {}
5995+
5996+
public:
5997+
/// Creates a new SingleValueStmtExpr wrapping a statement.
5998+
static SingleValueStmtExpr *create(ASTContext &ctx, Stmt *S, DeclContext *DC);
5999+
6000+
/// Creates a new SingleValueStmtExpr wrapping a statement, and recursively
6001+
/// attempts to wrap any branches of that statement that can become single
6002+
/// value statement expressions.
6003+
///
6004+
/// If \p mustBeExpr is true, branches will be eagerly wrapped even if they
6005+
/// may not be valid SingleValueStmtExprs (which Sema will later diagnose).
6006+
static SingleValueStmtExpr *createWithWrappedBranches(ASTContext &ctx,
6007+
Stmt *S,
6008+
DeclContext *DC,
6009+
bool mustBeExpr);
6010+
6011+
/// Attempt to look through valid parent expressions to a child
6012+
/// SingleValueStmtExpr.
6013+
static SingleValueStmtExpr *tryDigOutSingleValueStmtExpr(Expr *E);
6014+
6015+
/// Retrieve the wrapped statement.
6016+
Stmt *getStmt() const { return S; }
6017+
void setStmt(Stmt *newS) { S = newS; }
6018+
6019+
/// Retrieve the kind of statement being wrapped.
6020+
Kind getStmtKind() const;
6021+
6022+
/// Retrieve the complete set of branches for the underlying statement.
6023+
ArrayRef<Stmt *> getBranches(SmallVectorImpl<Stmt *> &scratch) const;
6024+
6025+
/// Retrieve the single expression branches of the statement, excluding
6026+
/// branches that either have multiple expressions, or have statements.
6027+
ArrayRef<Expr *>
6028+
getSingleExprBranches(SmallVectorImpl<Expr *> &scratch) const;
6029+
6030+
DeclContext *getDeclContext() const { return DC; }
6031+
6032+
SourceRange getSourceRange() const;
6033+
6034+
static bool classof(const Expr *E) {
6035+
return E->getKind() == ExprKind::SingleValueStmt;
6036+
}
6037+
};
6038+
59826039
/// Expression node that effects a "one-way" constraint in
59836040
/// the constraint system, allowing type information to flow from the
59846041
/// subexpression outward but not the other way.
@@ -6012,6 +6069,10 @@ class TypeJoinExpr final : public Expr,
60126069

60136070
DeclRefExpr *Var;
60146071

6072+
/// If this is joining the expression branches for a SingleValueStmtExpr,
6073+
/// this holds the expr node. Otherwise, it is \c nullptr.
6074+
SingleValueStmtExpr *SVE;
6075+
60156076
size_t numTrailingObjects() const {
60166077
return getNumElements();
60176078
}
@@ -6021,13 +6082,14 @@ class TypeJoinExpr final : public Expr,
60216082
}
60226083

60236084
TypeJoinExpr(llvm::PointerUnion<DeclRefExpr *, TypeBase *> result,
6024-
ArrayRef<Expr *> elements);
6085+
ArrayRef<Expr *> elements, SingleValueStmtExpr *SVE);
60256086

60266087
static TypeJoinExpr *
60276088
createImpl(ASTContext &ctx,
60286089
llvm::PointerUnion<DeclRefExpr *, TypeBase *> varOrType,
60296090
ArrayRef<Expr *> elements,
6030-
AllocationArena arena = AllocationArena::Permanent);
6091+
AllocationArena arena = AllocationArena::Permanent,
6092+
SingleValueStmtExpr *SVE = nullptr);
60316093

60326094
public:
60336095
static TypeJoinExpr *
@@ -6042,6 +6104,12 @@ class TypeJoinExpr final : public Expr,
60426104
return createImpl(ctx, joinType.getPointer(), exprs, arena);
60436105
}
60446106

6107+
/// Create a join for the branch types of a SingleValueStmtExpr.
6108+
static TypeJoinExpr *
6109+
forBranchesOfSingleValueStmtExpr(ASTContext &ctx, Type joinType,
6110+
SingleValueStmtExpr *SVE,
6111+
AllocationArena arena);
6112+
60456113
SourceLoc getLoc() const { return SourceLoc(); }
60466114
SourceRange getSourceRange() const { return SourceRange(); }
60476115

@@ -6064,6 +6132,10 @@ class TypeJoinExpr final : public Expr,
60646132
getMutableElements()[i] = E;
60656133
}
60666134

6135+
/// If this is joining the expression branches for a SingleValueStmtExpr,
6136+
/// this returns the expr node. Otherwise, returns \c nullptr.
6137+
SingleValueStmtExpr *getSingleValueStmtExpr() const { return SVE; }
6138+
60676139
unsigned getNumElements() const { return Bits.TypeJoinExpr.NumElements; }
60686140

60696141
static bool classof(const Expr *E) {

include/swift/AST/ExprNodes.def

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ EXPR(LazyInitializer, Expr)
205205
EXPR(EditorPlaceholder, Expr)
206206
EXPR(ObjCSelector, Expr)
207207
EXPR(KeyPath, Expr)
208+
EXPR(SingleValueStmt, Expr)
208209
UNCHECKED_EXPR(KeyPathDot, Expr)
209210
UNCHECKED_EXPR(OneWay, Expr)
210211
EXPR(Tap, Expr)

include/swift/AST/Stmt.h

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,15 @@ class ASTContext;
3535
class ASTWalker;
3636
class Decl;
3737
class DeclContext;
38+
class Evaluator;
3839
class Expr;
3940
class FuncDecl;
4041
class Pattern;
4142
class PatternBindingDecl;
4243
class VarDecl;
4344
class CaseStmt;
4445
class DoCatchStmt;
46+
class IsSingleValueStmtResult;
4547
class SwitchStmt;
4648

4749
enum class StmtKind {
@@ -133,7 +135,12 @@ class alignas(8) Stmt : public ASTAllocated<Stmt> {
133135

134136
SourceRange getSourceRange() const;
135137
SourceLoc TrailingSemiLoc;
136-
138+
139+
/// Whether the statement can produce a single value, and as such may be
140+
/// treated as an expression.
141+
IsSingleValueStmtResult mayProduceSingleValue(Evaluator &eval) const;
142+
IsSingleValueStmtResult mayProduceSingleValue(ASTContext &ctx) const;
143+
137144
/// isImplicit - Determines whether this statement was implicitly-generated,
138145
/// rather than explicitly written in the AST.
139146
bool isImplicit() const { return Bits.Stmt.Implicit; }
@@ -204,6 +211,10 @@ class BraceStmt final : public Stmt,
204211

205212
ASTNode findAsyncNode();
206213

214+
/// If this brace is wrapping a single expression, returns it. Otherwise
215+
/// returns \c nullptr.
216+
Expr *getSingleExpressionElement() const;
217+
207218
static bool classof(const Stmt *S) { return S->getKind() == StmtKind::Brace; }
208219
};
209220

@@ -711,7 +722,14 @@ class IfStmt : public LabeledConditionalStmt {
711722

712723
Stmt *getElseStmt() const { return Else; }
713724
void setElseStmt(Stmt *s) { Else = s; }
714-
725+
726+
/// Retrieve the complete set of branches for this if statement, including
727+
/// else if statements.
728+
ArrayRef<Stmt *> getBranches(SmallVectorImpl<Stmt *> &scratch) const;
729+
730+
/// Whether the if statement has an unconditional \c else.
731+
bool isSyntacticallyExhaustive() const;
732+
715733
// Implement isa/cast/dyncast/etc.
716734
static bool classof(const Stmt *S) { return S->getKind() == StmtKind::If; }
717735
};
@@ -1283,7 +1301,10 @@ class SwitchStmt final : public LabeledStmt,
12831301
AsCaseStmtRange getCases() const {
12841302
return AsCaseStmtRange(getRawCases(), AsCaseStmtWithSkippingNonCaseStmts());
12851303
}
1286-
1304+
1305+
/// Retrieve the complete set of branches for this switch statement.
1306+
ArrayRef<Stmt *> getBranches(SmallVectorImpl<Stmt *> &scratch) const;
1307+
12871308
static bool classof(const Stmt *S) {
12881309
return S->getKind() == StmtKind::Switch;
12891310
}

include/swift/AST/TypeCheckRequests.h

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3830,6 +3830,128 @@ class PreCheckReturnStmtRequest
38303830
bool isCached() const { return true; }
38313831
};
38323832

3833+
/// The result of the query for whether a statement can produce a single value.
3834+
class IsSingleValueStmtResult {
3835+
public:
3836+
enum class Kind {
3837+
/// The statement may become a SingleValueStmtExpr.
3838+
Valid,
3839+
3840+
/// There are non-single-expression branches that do not end in a throw.
3841+
UnterminatedBranches,
3842+
3843+
/// The statement is an 'if' statement without an unconditional 'else'.
3844+
NonExhaustiveIf,
3845+
3846+
/// There are no single-expression branches.
3847+
NoExpressionBranches,
3848+
3849+
/// There is an unhandled statement branch. This should only be the case
3850+
/// for invalid AST.
3851+
UnhandledStmt,
3852+
3853+
/// There was a circular reference when evaluating the request. This can be
3854+
/// ignored, as we will have already diagnosed it.
3855+
CircularReference,
3856+
3857+
/// There is a 'break' or 'continue' within the statement that prevents it
3858+
/// from being treated as an expression.
3859+
InvalidJumps,
3860+
3861+
/// The statement has a jump label, which is invalid for an expression.
3862+
HasLabel
3863+
};
3864+
3865+
private:
3866+
Kind TheKind;
3867+
TinyPtrVector<Stmt *> InvalidJumps;
3868+
TinyPtrVector<Stmt *> UnterminatedBranches;
3869+
3870+
IsSingleValueStmtResult(Kind kind) : TheKind(kind) {
3871+
assert(kind != Kind::UnterminatedBranches && kind != Kind::InvalidJumps);
3872+
}
3873+
3874+
IsSingleValueStmtResult(Kind kind, TinyPtrVector<Stmt *> stmts)
3875+
: TheKind(kind) {
3876+
switch (kind) {
3877+
case Kind::UnterminatedBranches: {
3878+
UnterminatedBranches = std::move(stmts);
3879+
break;
3880+
}
3881+
case Kind::InvalidJumps: {
3882+
InvalidJumps = std::move(stmts);
3883+
break;
3884+
}
3885+
default:
3886+
llvm_unreachable("Unhandled case in switch!");
3887+
}
3888+
}
3889+
3890+
public:
3891+
static IsSingleValueStmtResult valid() {
3892+
return IsSingleValueStmtResult(Kind::Valid);
3893+
}
3894+
static IsSingleValueStmtResult
3895+
unterminatedBranches(TinyPtrVector<Stmt *> branches) {
3896+
return IsSingleValueStmtResult(Kind::UnterminatedBranches,
3897+
std::move(branches));
3898+
}
3899+
static IsSingleValueStmtResult nonExhaustiveIf() {
3900+
return IsSingleValueStmtResult(Kind::NonExhaustiveIf);
3901+
}
3902+
static IsSingleValueStmtResult noExpressionBranches() {
3903+
return IsSingleValueStmtResult(Kind::NoExpressionBranches);
3904+
}
3905+
static IsSingleValueStmtResult unhandledStmt() {
3906+
return IsSingleValueStmtResult(Kind::UnhandledStmt);
3907+
}
3908+
static IsSingleValueStmtResult circularReference() {
3909+
return IsSingleValueStmtResult(Kind::CircularReference);
3910+
}
3911+
static IsSingleValueStmtResult invalidJumps(TinyPtrVector<Stmt *> jumps) {
3912+
return IsSingleValueStmtResult(Kind::InvalidJumps, std::move(jumps));
3913+
}
3914+
static IsSingleValueStmtResult hasLabel() {
3915+
return IsSingleValueStmtResult(Kind::HasLabel);
3916+
}
3917+
3918+
Kind getKind() const { return TheKind; }
3919+
3920+
/// For an unterminated branch kind, retrieves the branch.
3921+
const TinyPtrVector<Stmt *> &getUnterminatedBranches() const {
3922+
assert(TheKind == Kind::UnterminatedBranches);
3923+
return UnterminatedBranches;
3924+
}
3925+
3926+
/// For an invalid jump kind, retrieves the list of invalid jumps.
3927+
const TinyPtrVector<Stmt *> &getInvalidJumps() const {
3928+
assert(TheKind == Kind::InvalidJumps);
3929+
return InvalidJumps;
3930+
}
3931+
3932+
explicit operator bool() const {
3933+
return TheKind == Kind::Valid;
3934+
}
3935+
};
3936+
3937+
/// Computes whether a given statement can be treated as a SingleValueStmtExpr.
3938+
class IsSingleValueStmtRequest
3939+
: public SimpleRequest<IsSingleValueStmtRequest,
3940+
IsSingleValueStmtResult(const Stmt *),
3941+
RequestFlags::Cached> {
3942+
public:
3943+
using SimpleRequest::SimpleRequest;
3944+
3945+
private:
3946+
friend SimpleRequest;
3947+
3948+
IsSingleValueStmtResult
3949+
evaluate(Evaluator &evaluator, const Stmt *stmt) const;
3950+
3951+
public:
3952+
bool isCached() const { return true; }
3953+
};
3954+
38333955
class GetTypeWrapperInitializer
38343956
: public SimpleRequest<GetTypeWrapperInitializer,
38353957
ConstructorDecl *(NominalTypeDecl *),

include/swift/AST/TypeCheckerTypeIDZone.def

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,9 @@ SWIFT_REQUEST(TypeChecker, ContinueTargetRequest,
446446
SWIFT_REQUEST(TypeChecker, PreCheckReturnStmtRequest,
447447
Stmt *(ReturnStmt *, DeclContext *),
448448
Cached, NoLocationInfo)
449+
SWIFT_REQUEST(TypeChecker, IsSingleValueStmtRequest,
450+
IsSingleValueStmtResult(const Stmt *),
451+
Cached, NoLocationInfo)
449452
SWIFT_REQUEST(TypeChecker, GetTypeWrapperInitializer,
450453
ConstructorDecl *(NominalTypeDecl *),
451454
Cached, NoLocationInfo)

0 commit comments

Comments
 (0)