diff --git a/CHANGELOG.md b/CHANGELOG.md index 8acea7111a641..918bae61612cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,30 @@ CHANGELOG +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 --------- @@ -8178,6 +8202,7 @@ Swift 1.0 [SE-0284]: [SE-0286]: [SE-0287]: +[SE-0296]: [SR-75]: [SR-106]: diff --git a/include/swift/AST/DiagnosticsParse.def b/include/swift/AST/DiagnosticsParse.def index deb6a00ae2da4..53bbe0d2e0f79 100644 --- a/include/swift/AST/DiagnosticsParse.def +++ b/include/swift/AST/DiagnosticsParse.def @@ -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, diff --git a/lib/IDE/CodeCompletion.cpp b/lib/IDE/CodeCompletion.cpp index affef50abdd7a..3a01057cd8738 100644 --- a/lib/IDE/CodeCompletion.cpp +++ b/lib/IDE/CodeCompletion.cpp @@ -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) { @@ -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); @@ -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; @@ -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(); } diff --git a/lib/IDE/Refactoring.cpp b/lib/IDE/Refactoring.cpp index 30dcb61aee213..72e4426c47905 100644 --- a/lib/IDE/Refactoring.cpp +++ b/lib/IDE/Refactoring.cpp @@ -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 @@ -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. @@ -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; diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp index 53c8a16aaf659..279cbfc3fa6bd 100644 --- a/lib/Parse/ParseExpr.cpp +++ b/lib/Parse/ParseExpr.cpp @@ -337,8 +337,7 @@ ParserResult 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; @@ -399,38 +398,33 @@ ParserResult 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 sub = - parseExprSequenceElement(diag::expected_expr_after_await, isExprBasic); - if (!sub.hasCodeCompletion() && !sub.isNull()) { - if (auto anyTry = dyn_cast(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 sub = + parseExprSequenceElement(diag::expected_expr_after_await, isExprBasic); + if (!sub.hasCodeCompletion() && !sub.isNull()) { + if (auto anyTry = dyn_cast(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; diff --git a/lib/Parse/ParsePattern.cpp b/lib/Parse/ParsePattern.cpp index d6e2d81da54df..0a64c8153acf0 100644 --- a/lib/Parse/ParsePattern.cpp +++ b/lib/Parse/ParsePattern.cpp @@ -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) || @@ -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()) diff --git a/lib/Parse/ParseStmt.cpp b/lib/Parse/ParseStmt.cpp index 36414a83fedfa..cee8cf9b6ae84 100644 --- a/lib/Parse/ParseStmt.cpp +++ b/lib/Parse/ParseStmt.cpp @@ -2128,10 +2128,10 @@ ParserResult 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(); diff --git a/lib/Parse/ParseType.cpp b/lib/Parse/ParseType.cpp index 331111267c408..204a4a1cd6bcb 100644 --- a/lib/Parse/ParseType.cpp +++ b/lib/Parse/ParseType.cpp @@ -1108,8 +1108,7 @@ ParserResult 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. diff --git a/test/Compatibility/unescaped_await.swift b/test/Compatibility/unescaped_await.swift deleted file mode 100644 index dc9caea9eba4a..0000000000000 --- a/test/Compatibility/unescaped_await.swift +++ /dev/null @@ -1,68 +0,0 @@ -// RUN: %target-typecheck-verify-swift - // now check that the fix-its, if applied, will fix the warnings. -// RUN: %empty-directory(%t.scratch) -// RUN: cp %s %t.scratch/fixits.swift -// RUN: %target-swift-frontend -typecheck %t.scratch/fixits.swift -fixit-all -emit-fixits-path %t.scratch/fixits.remap 2> /dev/null -// RUN: %{python} %utils/apply-fixit-edits.py %t.scratch -// RUN: %target-swift-frontend -typecheck %t.scratch/fixits.swift -warnings-as-errors -// RUN: %target-swift-frontend -typecheck %t.scratch/fixits.swift -warnings-as-errors -enable-experimental-concurrency - -// REQUIRES: concurrency - -func await(_ f : () -> Void) {} - -func ordinaryCalls() { - await({}) - // expected-warning@-1 {{future versions of Swift reserve the word 'await'; if this name is unavoidable, use backticks to escape it}} - - await {} - // expected-warning@-1 {{future versions of Swift reserve the word 'await'; if this name is unavoidable, use backticks to escape it}} - - let _ = `await` - let _ = `await`({}) - - let _ = await - // expected-warning@-1 {{future versions of Swift reserve the word 'await'; if this name is unavoidable, use backticks to escape it}} - - let k = Klass() - k.await() - _ = k.await -} - -func localVar() { - var await = 1 - - let two = await + await - // expected-warning@-1 2 {{future versions of Swift reserve the word 'await'; if this name is unavoidable, use backticks to escape it}} - - _ = await==two-await - // expected-warning@-1 2 {{future versions of Swift reserve the word 'await'; if this name is unavoidable, use backticks to escape it}} - - takesInout(await: &await) -} - -func takesUnitFunc(_ f : () -> Void) {} - -func takesInout(await : inout Int) { - await += 1 - // expected-warning@-1 {{future versions of Swift reserve the word 'await'; if this name is unavoidable, use backticks to escape it}} -} - -class Klass { - init() { await() } - // expected-warning@-1 {{future versions of Swift reserve the word 'await'; if this name is unavoidable, use backticks to escape it}} - - func await() { - - takesUnitFunc(await) - // expected-warning@-1 {{future versions of Swift reserve the word 'await'; if this name is unavoidable, use backticks to escape it}} - } - - func method() { - let _ = self.await - self.await() - - await() - // expected-warning@-1 {{future versions of Swift reserve the word 'await'; if this name is unavoidable, use backticks to escape it}} - } -} \ No newline at end of file diff --git a/test/Concurrency/await_typo_correction.swift b/test/Concurrency/await_typo_correction.swift index 45e4285cf41f0..cf24040487155 100644 --- a/test/Concurrency/await_typo_correction.swift +++ b/test/Concurrency/await_typo_correction.swift @@ -29,3 +29,8 @@ func async() throws { } try async() } } + +func varNamedAsync(async: Bool) async { + if async { } + let _ = async +} diff --git a/test/SourceKit/Refactoring/basic.swift b/test/SourceKit/Refactoring/basic.swift index 517ef34441327..92ba3e4a9d27e 100644 --- a/test/SourceKit/Refactoring/basic.swift +++ b/test/SourceKit/Refactoring/basic.swift @@ -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 @@ -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