Skip to content

Commit 09e8a17

Browse files
committed
Parse: Only accept certain literals as enum case raw values
Just checking for LiteralExpr is too broad, because Sema doesn't know what to do with RegexLiteralExpr for example.
1 parent accf6af commit 09e8a17

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

lib/Parse/ParseDecl.cpp

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9229,6 +9229,20 @@ ParserResult<EnumDecl> Parser::parseDeclEnum(ParseDeclOptions Flags,
92299229
return DCC.fixupParserResult(Status, ED);
92309230
}
92319231

9232+
static bool isValidEnumRawValueLiteral(LiteralExpr *expr) {
9233+
if (expr == nullptr)
9234+
return false;
9235+
9236+
if (!isa<IntegerLiteralExpr>(expr) &&
9237+
!isa<FloatLiteralExpr>(expr) &&
9238+
!isa<StringLiteralExpr>(expr) &&
9239+
!isa<BooleanLiteralExpr>(expr) &&
9240+
!isa<NilLiteralExpr>(expr))
9241+
return false;
9242+
9243+
return true;
9244+
}
9245+
92329246
/// Parse a 'case' of an enum.
92339247
///
92349248
/// \verbatim
@@ -9346,8 +9360,7 @@ Parser::parseDeclEnumCase(ParseDeclOptions Flags,
93469360
}
93479361
// The raw value must be syntactically a simple literal.
93489362
LiteralRawValueExpr = dyn_cast<LiteralExpr>(RawValueExpr.getPtrOrNull());
9349-
if (!LiteralRawValueExpr
9350-
|| isa<InterpolatedStringLiteralExpr>(LiteralRawValueExpr)) {
9363+
if (!isValidEnumRawValueLiteral(LiteralRawValueExpr)) {
93519364
diagnose(RawValueExpr.getPtrOrNull()->getLoc(),
93529365
diag::nonliteral_enum_case_raw_value);
93539366
LiteralRawValueExpr = nullptr;
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// RUN: %target-typecheck-verify-swift
2+
3+
_ = a.init
4+
_ = b.init
5+
6+
enum a : Int { case x = #/ /# } // expected-error {{raw value for enum case must be a literal}}
7+
enum b : String { case x = #file } // expected-error {{raw value for enum case must be a literal}}

0 commit comments

Comments
 (0)