Skip to content

Commit 4591811

Browse files
vguerrarintaro
authored andcommitted
[Diagnostics] Add a fix-it for try instead of throws in function decl… (#27647)
* [Diagnostics] Add a fix-it for try instead of throws in function decls and types. Sometimes one would misstype `throws` for `try` so we provide a fix-it for that. It might happen in two cases: In function declarations: ```swift func foo() try {} ``` In function types: ```swift let f = () try -> Int ``` Resolves SR-11574.
1 parent 491d3c3 commit 4591811

File tree

3 files changed

+9
-3
lines changed

3 files changed

+9
-3
lines changed

lib/Parse/ParsePattern.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -782,7 +782,7 @@ Parser::parseFunctionSignature(Identifier SimpleName,
782782
} else if (Tok.is(tok::kw_rethrows)) {
783783
throwsLoc = consumeToken();
784784
rethrows = true;
785-
} else if (Tok.is(tok::kw_throw)) {
785+
} else if (Tok.isAny(tok::kw_throw, tok::kw_try)) {
786786
throwsLoc = consumeToken();
787787
diagnose(throwsLoc, diag::throw_in_function_type)
788788
.fixItReplace(throwsLoc, "throws");

lib/Parse/ParseType.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -399,11 +399,11 @@ ParserResult<TypeRepr> Parser::parseType(Diag<> MessageID,
399399
// Don't consume 'throws', if the next token is not '->', so we can emit a
400400
// more useful diagnostic when parsing a function decl.
401401
SourceLoc throwsLoc;
402-
if (Tok.isAny(tok::kw_throws, tok::kw_rethrows, tok::kw_throw) &&
402+
if (Tok.isAny(tok::kw_throws, tok::kw_rethrows, tok::kw_throw, tok::kw_try) &&
403403
peekToken().is(tok::arrow)) {
404404
if (Tok.isNot(tok::kw_throws)) {
405405
// 'rethrows' is only allowed on function declarations for now.
406-
// 'throw' is probably a typo for 'throws'.
406+
// 'throw' or 'try' are probably typos for 'throws'.
407407
Diag<> DiagID = Tok.is(tok::kw_rethrows) ?
408408
diag::rethrowing_function_type : diag::throw_in_function_type;
409409
diagnose(Tok.getLoc(), DiagID)

test/Parse/errors.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,3 +127,9 @@ func fixitThrow2() throws {
127127
}
128128

129129
let fn: () -> throws Void // expected-error{{'throws' may only occur before '->'}} {{12-12=throws }} {{15-22=}}
130+
131+
// SR-11574
132+
func fixitTry0<T>(a: T) try where T:ExpressibleByStringLiteral {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{25-28=throws}}
133+
func fixitTry1<T>(a: T) try {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{25-28=throws}}
134+
func fixitTry2() try {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{18-21=throws}}
135+
let fixitTry3 : () try -> Int // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{20-23=throws}}

0 commit comments

Comments
 (0)