Skip to content

[SE-0296] Enable async/await by default. #35784

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

Merged
merged 2 commits into from
Feb 6, 2021
Merged
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
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,30 @@ CHANGELOG

</details>

Swift Next
----------
* [SE-0296][]:

Asynchronous programming is now natively supported using async/await. Asynchronous functions can be defined using `async`:

```swift
func loadWebResource(_ path: String) async throws -> Resource { ... }
func decodeImage(_ r1: Resource, _ r2: Resource) async throws -> Image
func dewarpAndCleanupImage(_ i : Image) async -> Image
```

Calls to `async` functions may suspend, meaning that they give up the thread on which they are executing and will be scheduled to run again later. The potential for suspension on asynchronous calls requires the `await` keyword, similarly to the way in which `try` acknowledges a call to a `throws` function:

```swift
func processImageData() async throws -> Image {
let dataResource = try await loadWebResource("dataprofile.txt")
let imageResource = try await loadWebResource("imagedata.dat")
let imageTmp = try await decodeImage(dataResource, imageResource)
let imageResult = await dewarpAndCleanupImage(imageTmp)
return imageResult
}
```

Swift 5.4
---------

Expand Down Expand Up @@ -8178,6 +8202,7 @@ Swift 1.0
[SE-0284]: <https://github.com/apple/swift-evolution/blob/main/proposals/0284-multiple-variadic-parameters.md>
[SE-0286]: <https://github.com/apple/swift-evolution/blob/main/proposals/0286-forward-scan-trailing-closures.md>
[SE-0287]: <https://github.com/apple/swift-evolution/blob/main/proposals/0287-implicit-member-chains.md>
[SE-0296]: <https://github.com/apple/swift-evolution/blob/main/proposals/0296-async-await.md>

[SR-75]: <https://bugs.swift.org/browse/SR-75>
[SR-106]: <https://bugs.swift.org/browse/SR-106>
Expand Down
3 changes: 0 additions & 3 deletions include/swift/AST/DiagnosticsParse.def
Original file line number Diff line number Diff line change
Expand Up @@ -1229,9 +1229,6 @@ NOTE(super_in_closure_with_capture_here,none,
"'self' explicitly captured here", ())

WARNING(await_before_try,none, "'try' must precede 'await'", ())
WARNING(warn_await_keyword,none,
"future versions of Swift reserve the word 'await'; "
"if this name is unavoidable, use backticks to escape it", ())

// Tuples and parenthesized expressions
ERROR(expected_expr_in_expr_list,none,
Expand Down
14 changes: 5 additions & 9 deletions lib/IDE/CodeCompletion.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5818,15 +5818,12 @@ static void addObserverKeywords(CodeCompletionResultSink &Sink) {
addKeyword(Sink, "didSet", CodeCompletionKeywordKind::None);
}

static void addExprKeywords(CodeCompletionResultSink &Sink,
bool IsConcurrencyEnabled) {
static void addExprKeywords(CodeCompletionResultSink &Sink) {
// Expr keywords.
addKeyword(Sink, "try", CodeCompletionKeywordKind::kw_try);
addKeyword(Sink, "try!", CodeCompletionKeywordKind::kw_try);
addKeyword(Sink, "try?", CodeCompletionKeywordKind::kw_try);
if (IsConcurrencyEnabled) {
addKeyword(Sink, "await", CodeCompletionKeywordKind::None);
}
addKeyword(Sink, "await", CodeCompletionKeywordKind::None);
}

static void addOpaqueTypeKeyword(CodeCompletionResultSink &Sink) {
Expand Down Expand Up @@ -5865,8 +5862,7 @@ void CodeCompletionCallbacksImpl::addKeywords(CodeCompletionResultSink &Sink,
break;

case CompletionKind::EffectsSpecifier: {
if (!llvm::is_contained(ParsedKeywords, "async") &&
Context.LangOpts.EnableExperimentalConcurrency)
if (!llvm::is_contained(ParsedKeywords, "async"))
addKeyword(Sink, "async", CodeCompletionKeywordKind::None);
if (!llvm::is_contained(ParsedKeywords, "throws"))
addKeyword(Sink, "throws", CodeCompletionKeywordKind::kw_throws);
Expand Down Expand Up @@ -5902,7 +5898,7 @@ void CodeCompletionCallbacksImpl::addKeywords(CodeCompletionResultSink &Sink,
case CompletionKind::ForEachSequence:
addSuperKeyword(Sink);
addLetVarKeywords(Sink);
addExprKeywords(Sink, Context.LangOpts.EnableExperimentalConcurrency);
addExprKeywords(Sink);
addAnyTypeKeyword(Sink, CurDeclContext->getASTContext().TheAnyType);
break;

Expand Down Expand Up @@ -6729,7 +6725,7 @@ void CodeCompletionCallbacksImpl::doneParsing() {
addStmtKeywords(Sink, MaybeFuncBody);
addSuperKeyword(Sink);
addLetVarKeywords(Sink);
addExprKeywords(Sink, Context.LangOpts.EnableExperimentalConcurrency);
addExprKeywords(Sink);
addAnyTypeKeyword(Sink, Context.TheAnyType);
DoPostfixExprBeginning();
}
Expand Down
9 changes: 0 additions & 9 deletions lib/IDE/Refactoring.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5219,9 +5219,6 @@ bool RefactoringActionConvertCallToAsyncAlternative::isApplicable(
const ResolvedCursorInfo &CursorInfo, DiagnosticEngine &Diag) {
using namespace asyncrefactorings;

if (!CursorInfo.SF->getASTContext().LangOpts.EnableExperimentalConcurrency)
return false;

// Currently doesn't check that the call is in an async context. This seems
// possibly useful in some situations, so we'll see what the feedback is.
// May need to change in the future
Expand Down Expand Up @@ -5263,9 +5260,6 @@ bool RefactoringActionConvertToAsync::isApplicable(
const ResolvedCursorInfo &CursorInfo, DiagnosticEngine &Diag) {
using namespace asyncrefactorings;

if (!CursorInfo.SF->getASTContext().LangOpts.EnableExperimentalConcurrency)
return false;

// As with the call refactoring, should possibly only apply if there's
// actually calls to async alternatives. At the moment this will just add
// `async` if there are no calls, which is probably fine.
Expand Down Expand Up @@ -5295,9 +5289,6 @@ bool RefactoringActionAddAsyncAlternative::isApplicable(
const ResolvedCursorInfo &CursorInfo, DiagnosticEngine &Diag) {
using namespace asyncrefactorings;

if (!CursorInfo.SF->getASTContext().LangOpts.EnableExperimentalConcurrency)
return false;

auto *FD = findFunction(CursorInfo);
if (!FD)
return false;
Expand Down
56 changes: 25 additions & 31 deletions lib/Parse/ParseExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -337,8 +337,7 @@ ParserResult<Expr> Parser::parseExprSequence(Diag<> Message,
case tok::identifier: {
// 'async' followed by 'throws' or '->' implies that we have an arrow
// expression.
if (!(shouldParseExperimentalConcurrency() &&
Tok.isContextualKeyword("async") &&
if (!(Tok.isContextualKeyword("async") &&
peekToken().isAny(tok::arrow, tok::kw_throws)))
goto done;

Expand Down Expand Up @@ -399,38 +398,33 @@ ParserResult<Expr> Parser::parseExprSequenceElement(Diag<> message,
SyntaxParsingContext ElementContext(SyntaxContext,
SyntaxContextKind::Expr);

if (shouldParseExperimentalConcurrency()) {
// A function called "async" is possible, so we don't want to replace it
// with await.
bool isReplaceableAsync = Tok.isContextualKeyword("async") &&
!peekToken().is(tok::l_paren);
if (Tok.isContextualKeyword("await") || isReplaceableAsync) {
// Error on a replaceable async
if (isReplaceableAsync) {
diagnose(Tok.getLoc(), diag::expected_await_not_async)
.fixItReplace(Tok.getLoc(), "await");
}
SourceLoc awaitLoc = consumeToken();
ParserResult<Expr> sub =
parseExprSequenceElement(diag::expected_expr_after_await, isExprBasic);
if (!sub.hasCodeCompletion() && !sub.isNull()) {
if (auto anyTry = dyn_cast<AnyTryExpr>(sub.get())) {
// "try" must precede "await".
diagnose(awaitLoc, diag::await_before_try)
.fixItRemove(awaitLoc)
.fixItInsert(anyTry->getSubExpr()->getStartLoc(), "await ");
}

ElementContext.setCreateSyntax(SyntaxKind::AwaitExpr);
sub = makeParserResult(new (Context) AwaitExpr(awaitLoc, sub.get()));
// Check whether the user mistyped "async" for "await", but only in cases
// where we are sure that "async" would be ill-formed as an identifier.
bool isReplaceableAsync = Tok.isContextualKeyword("async") &&
!peekToken().isAtStartOfLine() &&
(peekToken().is(tok::identifier) || peekToken().is(tok::kw_try));
if (Tok.isContextualKeyword("await") || isReplaceableAsync) {
// Error on a replaceable async
if (isReplaceableAsync) {
diagnose(Tok.getLoc(), diag::expected_await_not_async)
.fixItReplace(Tok.getLoc(), "await");
}
SourceLoc awaitLoc = consumeToken();
ParserResult<Expr> sub =
parseExprSequenceElement(diag::expected_expr_after_await, isExprBasic);
if (!sub.hasCodeCompletion() && !sub.isNull()) {
if (auto anyTry = dyn_cast<AnyTryExpr>(sub.get())) {
// "try" must precede "await".
diagnose(awaitLoc, diag::await_before_try)
.fixItRemove(awaitLoc)
.fixItInsert(anyTry->getSubExpr()->getStartLoc(), "await ");
}

return sub;
ElementContext.setCreateSyntax(SyntaxKind::AwaitExpr);
sub = makeParserResult(new (Context) AwaitExpr(awaitLoc, sub.get()));
}
} else if (Tok.isContextualKeyword("await")) {
// warn that future versions of Swift will parse this token differently.
diagnose(Tok.getLoc(), diag::warn_await_keyword)
.fixItReplace(Tok.getLoc(), "`await`");

return sub;
}

SourceLoc tryLoc;
Expand Down
6 changes: 2 additions & 4 deletions lib/Parse/ParsePattern.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -825,8 +825,7 @@ bool Parser::isEffectsSpecifier(const Token &T) {
// NOTE: If this returns 'true', that token must be handled in
// 'parseEffectsSpecifiers()'.

if (shouldParseExperimentalConcurrency() &&
T.isContextualKeyword("async"))
if (T.isContextualKeyword("async"))
return true;

if (T.isAny(tok::kw_throws, tok::kw_rethrows) ||
Expand All @@ -844,8 +843,7 @@ ParserStatus Parser::parseEffectsSpecifiers(SourceLoc existingArrowLoc,

while (true) {
// 'async'
if (shouldParseExperimentalConcurrency() &&
Tok.isContextualKeyword("async")) {
if (Tok.isContextualKeyword("async")) {

if (asyncLoc.isValid()) {
diagnose(Tok, diag::duplicate_effects_specifier, Tok.getText())
Expand Down
6 changes: 3 additions & 3 deletions lib/Parse/ParseStmt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2128,10 +2128,10 @@ ParserResult<Stmt> Parser::parseStmtForEach(LabeledStmtInfo LabelInfo) {
SourceLoc TryLoc;

if (shouldParseExperimentalConcurrency() &&
Tok.isContextualKeyword("await")) {
Tok.isContextualKeyword("await")) {
AwaitLoc = consumeToken();
} if (shouldParseExperimentalConcurrency() &&
Tok.is(tok::kw_try)) {
} else if (shouldParseExperimentalConcurrency() &&
Tok.is(tok::kw_try)) {
TryLoc = consumeToken();
if (Tok.isContextualKeyword("await")) {
AwaitLoc = consumeToken();
Expand Down
3 changes: 1 addition & 2 deletions lib/Parse/ParseType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1108,8 +1108,7 @@ ParserResult<TypeRepr> Parser::parseTypeTupleBody() {

bool isFunctionType =
Tok.isAny(tok::arrow, tok::kw_throws, tok::kw_rethrows) ||
(shouldParseExperimentalConcurrency() &&
Tok.isContextualKeyword("async"));
Tok.isContextualKeyword("async");

// If there were any labels, figure out which labels should go into the type
// representation.
Expand Down
68 changes: 0 additions & 68 deletions test/Compatibility/unescaped_await.swift

This file was deleted.

5 changes: 5 additions & 0 deletions test/Concurrency/await_typo_correction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,8 @@ func async() throws { }
try async()
}
}

func varNamedAsync(async: Bool) async {
if async { }
let _ = async
}
12 changes: 2 additions & 10 deletions test/SourceKit/Refactoring/basic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,8 @@ func hasCallToAsyncAlternative() {
// RUN: %sourcekitd-test -req=cursor -pos=117:16 -cursor-action %s -- %s | %FileCheck %s -check-prefix=CHECK-GLOBAL
// RUN: %sourcekitd-test -req=cursor -pos=117:17 -cursor-action %s -- %s | %FileCheck %s -check-prefix=CHECK-GLOBAL

// RUN: %sourcekitd-test -req=cursor -pos=119:6 -cursor-action %s -- -Xfrontend -enable-experimental-concurrency %s | %FileCheck %s -check-prefix=CHECK-ASYNC
// RUN: %sourcekitd-test -req=cursor -pos=121:3 -cursor-action %s -- -Xfrontend -enable-experimental-concurrency %s | %FileCheck %s -check-prefix=CHECK-CALLASYNC
// RUN: %sourcekitd-test -req=cursor -pos=119:6 -cursor-action %s -- %s | %FileCheck %s -check-prefix=CHECK-NOASYNC
// RUN: %sourcekitd-test -req=cursor -pos=121:3 -cursor-action %s -- %s | %FileCheck %s -check-prefix=CHECK-NOASYNC
// RUN: %sourcekitd-test -req=cursor -pos=119:6 -cursor-action %s -- %s | %FileCheck %s -check-prefix=CHECK-ASYNC
// RUN: %sourcekitd-test -req=cursor -pos=121:3 -cursor-action %s -- %s | %FileCheck %s -check-prefix=CHECK-CALLASYNC

// RUN: %sourcekitd-test -req=cursor -pos=35:10 -end-pos=35:16 -cursor-action %s -- %s | %FileCheck %s -check-prefix=CHECK-RENAME-EXTRACT
// RUN: %sourcekitd-test -req=cursor -pos=35:10 -end-pos=35:16 -cursor-action %s -- %s | %FileCheck %s -check-prefix=CHECK-RENAME-EXTRACT
Expand Down Expand Up @@ -258,10 +256,4 @@ func hasCallToAsyncAlternative() {
// CHECK-ASYNC-NOT: source.refactoring.kind.convert.func-to-async
// CHECK-CALLASYNC: ACTIONS END

// CHECK-NOASYNC: ACTIONS BEGIN
// CHECK-NOASYNC-NOT: source.refactoring.kind.add.async-alternative
// CHECK-NOASYNC-NOT: source.refactoring.kind.convert.func-to-async
// CHECK-NOASYNC-NOT: source.refactoring.kind.convert.call-to-async
// CHECK-NOASYNC: ACTIONS END

// REQUIRES: OS=macosx || OS=linux-gnu