Skip to content

[SE-0276] Syntax and Parse updates #30811

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions include/swift/AST/DiagnosticsParse.def
Original file line number Diff line number Diff line change
Expand Up @@ -1086,6 +1086,8 @@ ERROR(expected_catch_where_expr,PointsToFirstBadToken,
ERROR(docatch_not_trycatch,PointsToFirstBadToken,
"the 'do' keyword is used to specify a 'catch' region",
())
ERROR(multi_pattern_catch_unsupported,none,"'catch' statements do not yet "
"support multiple patterns", ())

// C-Style For Stmt
ERROR(c_style_for_stmt_removed,none,
Expand Down
74 changes: 64 additions & 10 deletions lib/Parse/ParseStmt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1981,15 +1981,63 @@ ParserResult<CatchStmt> Parser::parseStmtCatch() {
SourceLoc catchLoc = consumeToken(tok::kw_catch);

SmallVector<VarDecl*, 4> boundDecls;

ParserStatus status;
GuardedPattern pattern;
parseGuardedPattern(*this, pattern, status, boundDecls,
GuardedPatternContext::Catch, /* isFirst */ true);
if (status.hasCodeCompletion()) {
return makeParserCodeCompletionResult<CatchStmt>();
Optional<MutableArrayRef<VarDecl *>> caseBodyDecls;
SmallVector<CaseLabelItem, 1> caseLabelItems;

{
SyntaxParsingContext ListContext(SyntaxContext, SyntaxKind::CatchItemList);
bool isFirst = true;
while (true) {
SyntaxParsingContext ItemContext(SyntaxContext, SyntaxKind::CatchItem);
GuardedPattern PatternResult;
parseGuardedPattern(*this, PatternResult, status, boundDecls,
GuardedPatternContext::Catch, isFirst);
if (status.hasCodeCompletion()) {
return makeParserCodeCompletionResult<CatchStmt>();
}
caseLabelItems.emplace_back(PatternResult.ThePattern,
PatternResult.WhereLoc, PatternResult.Guard);
isFirst = false;
if (!consumeIf(tok::comma))
break;
}

// Grab the first case label item pattern and use it to initialize the case
// body var decls.
// TODO: Uncomment when AST supports multi-pattern catches
// SmallVector<VarDecl *, 4> tmp;
// caseLabelItems.front().getPattern()->collectVariables(tmp);
// auto Result = Context.AllocateUninitialized<VarDecl *>(tmp.size());
// for (unsigned i : indices(tmp)) {
// auto *vOld = tmp[i];
// auto *vNew = new (Context) VarDecl(
// /*IsStatic*/ false, vOld->getIntroducer(), false
// /*IsCaptureList*/, vOld->getNameLoc(), vOld->getName(),
// vOld->getDeclContext());
// vNew->setHasNonPatternBindingInit();
// vNew->setImplicit();
// Result[i] = vNew;
// }
// caseBodyDecls.emplace(Result);
}

// Add a scope so that the parser can find our body bound decls if it emits
// optimized accesses.
// TODO: Uncomment when AST supports multi-pattern catches
// Optional<Scope> BodyScope;
// if (caseBodyDecls) {
// BodyScope.emplace(this, ScopeKind::CatchVars);
// for (auto *v : *caseBodyDecls) {
// setLocalDiscriminator(v);
// // If we had any bad redefinitions, we already diagnosed them against
// the
// // first case label item.
// if (v->hasName())
// addToScope(v, false /*diagnoseRedefinitions*/);
// }
//}

auto bodyResult = parseBraceItemList(diag::expected_lbrace_after_catch);
status |= bodyResult;
if (bodyResult.isNull()) {
Expand All @@ -1998,10 +2046,16 @@ ParserResult<CatchStmt> Parser::parseStmtCatch() {
/*implicit=*/ true));
}

auto result =
new (Context) CatchStmt(catchLoc, pattern.ThePattern, pattern.WhereLoc,
pattern.Guard, bodyResult.get());
return makeParserResult(status, result);
auto result = new (Context) CatchStmt(
catchLoc, caseLabelItems[0].getPattern(), caseLabelItems[0].getWhereLoc(),
caseLabelItems[0].getGuardExpr(), bodyResult.get());

if (caseLabelItems.size() > 1) {
diagnose(catchLoc, diag::multi_pattern_catch_unsupported);
return makeParserErrorResult(result);
} else {
return makeParserResult(status, result);
}
}

static bool isStmtForCStyle(Parser &P) {
Expand Down
7 changes: 7 additions & 0 deletions test/Parse/errors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,13 @@ func one() {
#endif
} catch { // don't warn, #if code should be scanned.
}

do {
throw opaque_error()
} catch MSV.Foo, MSV.CarriesInt(let num) { // expected-error {{'num' must be bound in every pattern}}
// expected-error@-1 {{'catch' statements do not yet support multiple patterns}}
} catch {
}
}

func takesAutoclosure(_ fn : @autoclosure () -> Int) {}
Expand Down
9 changes: 5 additions & 4 deletions test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
Original file line number Diff line number Diff line change
Expand Up @@ -328,10 +328,11 @@ do <CodeBlock>{<SwitchStmt>

func statementTests<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{<DoStmt>
do <CodeBlock>{
} </CodeBlock><CatchClause>catch <ExpressionPattern><TupleExpr>(<TupleExprElement><UnresolvedPatternExpr><ValueBindingPattern>var <IdentifierPattern>x</IdentifierPattern></ValueBindingPattern></UnresolvedPatternExpr>, </TupleExprElement><TupleExprElement><UnresolvedPatternExpr><ValueBindingPattern>let <IdentifierPattern>y</IdentifierPattern></ValueBindingPattern></UnresolvedPatternExpr></TupleExprElement>) </TupleExpr></ExpressionPattern><CodeBlock>{
} </CodeBlock></CatchClause><CatchClause>catch <WhereClause>where <BooleanLiteralExpr>false </BooleanLiteralExpr></WhereClause><CodeBlock>{
} </CodeBlock></CatchClause><CatchClause>catch <ValueBindingPattern>let <IdentifierPattern>e </IdentifierPattern></ValueBindingPattern><WhereClause>where <SequenceExpr><MemberAccessExpr><IdentifierExpr>e</IdentifierExpr>.foo </MemberAccessExpr><BinaryOperatorExpr>== </BinaryOperatorExpr><IdentifierExpr>bar </IdentifierExpr></SequenceExpr></WhereClause><CodeBlock>{
} </CodeBlock></CatchClause><CatchClause>catch <CodeBlock>{
} </CodeBlock><CatchClause>catch <CatchItem><ExpressionPattern><TupleExpr>(<TupleExprElement><UnresolvedPatternExpr><ValueBindingPattern>var <IdentifierPattern>x</IdentifierPattern></ValueBindingPattern></UnresolvedPatternExpr>, </TupleExprElement><TupleExprElement><UnresolvedPatternExpr><ValueBindingPattern>let <IdentifierPattern>y</IdentifierPattern></ValueBindingPattern></UnresolvedPatternExpr></TupleExprElement>) </TupleExpr></ExpressionPattern></CatchItem><CodeBlock>{
} </CodeBlock></CatchClause><CatchClause>catch <CatchItem><WhereClause>where <BooleanLiteralExpr>false </BooleanLiteralExpr></WhereClause></CatchItem><CodeBlock>{
} </CodeBlock></CatchClause><CatchClause>catch <CatchItem><ValueBindingPattern>let <IdentifierPattern>e </IdentifierPattern></ValueBindingPattern><WhereClause>where <SequenceExpr><MemberAccessExpr><IdentifierExpr>e</IdentifierExpr>.foo </MemberAccessExpr><BinaryOperatorExpr>== </BinaryOperatorExpr><IdentifierExpr>bar </IdentifierExpr></SequenceExpr></WhereClause></CatchItem><CodeBlock>{
} </CodeBlock></CatchClause><CatchClause>catch <CatchItem><ExpressionPattern><FunctionCallExpr><MemberAccessExpr>.a</MemberAccessExpr>(<TupleExprElement><UnresolvedPatternExpr><ValueBindingPattern>let <IdentifierPattern>a</IdentifierPattern></ValueBindingPattern></UnresolvedPatternExpr></TupleExprElement>)</FunctionCallExpr></ExpressionPattern>, </CatchItem><CatchItem><ExpressionPattern><FunctionCallExpr><MemberAccessExpr>.b</MemberAccessExpr>(<TupleExprElement><UnresolvedPatternExpr><ValueBindingPattern>let <IdentifierPattern>b</IdentifierPattern></ValueBindingPattern></UnresolvedPatternExpr></TupleExprElement>) </FunctionCallExpr></ExpressionPattern><WhereClause>where <SequenceExpr><IdentifierExpr>b </IdentifierExpr><BinaryOperatorExpr>== </BinaryOperatorExpr><StringLiteralExpr>"<StringSegment></StringSegment>" </StringLiteralExpr></SequenceExpr></WhereClause></CatchItem><CodeBlock>{
} </CodeBlock></CatchClause><CatchClause>catch <CatchItem></CatchItem><CodeBlock>{
}</CodeBlock></CatchClause></DoStmt><RepeatWhileStmt>
repeat <CodeBlock>{ } </CodeBlock>while <BooleanLiteralExpr>true</BooleanLiteralExpr></RepeatWhileStmt><RepeatWhileStmt>
LABEL: repeat <CodeBlock>{ } </CodeBlock>while <BooleanLiteralExpr>false</BooleanLiteralExpr></RepeatWhileStmt><WhileStmt>
Expand Down
1 change: 1 addition & 0 deletions test/Syntax/round_trip_parse_gen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ func statementTests() {
} catch (var x, let y) {
} catch where false {
} catch let e where e.foo == bar {
} catch .a(let a), .b(let b) where b == "" {
} catch {
}
repeat { } while true
Expand Down
8 changes: 8 additions & 0 deletions test/stmt/errors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,14 @@ class eight {
}()
}

func multiPattern() {
do {
throw opaque_error() // expected-error {{error is not handled because the enclosing catch is not exhaustive}}
} catch MSV.Foo, _ { // expected-error {{'catch' statements do not yet support multiple patterns}}
_ = e
}
}

protocol ThrowingProto {
func foo() throws
static func bar() throws
Expand Down
2 changes: 2 additions & 0 deletions utils/gyb_syntax_support/NodeSerializationCodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,8 @@
'PoundFilePathExpr': 240,
'DerivativeRegistrationAttributeArguments': 241,
'QualifiedDeclName': 242,
'CatchItem': 243,
'CatchItemList': 244,
}


Expand Down
24 changes: 19 additions & 5 deletions utils/gyb_syntax_support/StmtNodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,10 @@
Node('CaseItemList', kind='SyntaxCollection',
element='CaseItem'),

# catch-item-list -> catch-item catch-item-list?
Node('CatchItemList', kind='SyntaxCollection',
element='CatchItem'),

# condition -> expression
# | availability-condition
# | case-condition
Expand Down Expand Up @@ -315,6 +319,17 @@
is_optional=True),
]),

# catch-item -> pattern? where-clause? ','?
Node('CatchItem', kind='Syntax',
traits=['WithTrailingComma'],
children=[
Child('Pattern', kind='Pattern', is_optional=True),
Child('WhereClause', kind='WhereClause',
is_optional=True),
Child('TrailingComma', kind='CommaToken',
is_optional=True),
]),

# switch-case-label -> 'case' case-item-list ':'
Node('SwitchCaseLabel', kind='Syntax',
children=[
Expand All @@ -324,14 +339,13 @@
Child('Colon', kind='ColonToken'),
]),

# catch-clause 'catch' pattern? where-clause? code-block
# catch-clause 'catch' case-item-list? code-block
Node('CatchClause', kind='Syntax',
traits=['WithCodeBlock'],
children=[
Child('CatchKeyword', kind='CatchToken'),
Child('Pattern', kind='Pattern',
is_optional=True),
Child('WhereClause', kind='WhereClause',
is_optional=True),
Child('CatchItems', kind='CatchItemList',
collection_element_name='CatchItem', is_optional=True),
Child('Body', kind='CodeBlock'),
]),

Expand Down