Skip to content

[Macros] Update the name and argument list for the @Task function body macro. #80187

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 1 commit into from
Mar 24, 2025
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
2 changes: 1 addition & 1 deletion lib/Macros/Sources/SwiftMacros/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ add_swift_macro_library(SwiftMacros
OptionSetMacro.swift
DebugDescriptionMacro.swift
DistributedResolvableMacro.swift
StartTaskMacro.swift
TaskMacro.swift
SyntaxExtensions.swift
TaskLocalMacro.swift
SwiftifyImportMacro.swift
Expand Down
13 changes: 0 additions & 13 deletions lib/Macros/Sources/SwiftMacros/OptionSetMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,19 +47,6 @@ private let optionsEnumNameArgumentLabel = "optionsName"
/// eventually be overridable.
private let defaultOptionsEnumName = "Options"

extension LabeledExprListSyntax {
/// Retrieve the first element with the given label.
func first(labeled name: String) -> Element? {
return first { element in
if let label = element.label, label.text == name {
return true
}

return false
}
}
}

public struct OptionSetMacro {
/// Decodes the arguments to the macro expansion.
///
Expand Down
67 changes: 0 additions & 67 deletions lib/Macros/Sources/SwiftMacros/StartTaskMacro.swift

This file was deleted.

15 changes: 14 additions & 1 deletion lib/Macros/Sources/SwiftMacros/SyntaxExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,17 @@ extension ImplicitlyUnwrappedOptionalTypeSyntax {
trailingTrivia: self.trailingTrivia
)
}
}
}

extension LabeledExprListSyntax {
/// Retrieve the first element with the given label.
func first(labeled name: String) -> Element? {
return first { element in
if let label = element.label, label.text == name {
return true
}

return false
}
}
}
126 changes: 126 additions & 0 deletions lib/Macros/Sources/SwiftMacros/TaskMacro.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import SwiftDiagnostics
import SwiftParser
import SwiftSyntax
import SwiftSyntaxBuilder
import SwiftSyntaxMacros

extension MacroExpansionContext {
func diagnose(
_ diag: TaskMacroDiagnostic,
at node: some SyntaxProtocol
) {
diagnose(Diagnostic(
node: Syntax(node),
message: diag
))
}
}

enum TaskMacroDiagnostic: String, DiagnosticMessage {
case noImplementation
= "'@Task' macro can only be used on functions with an implementation"
case unsupportedGlobalActor
= "'@Task' global actor must be written 'GlobalActorType'.shared"

var message: String { rawValue }

var severity: DiagnosticSeverity { .error }

var diagnosticID: MessageID {
MessageID(domain: "_Concurrency", id: "TaskMacro.\(self)")
}
}


public struct TaskMacro: BodyMacro {
public static func expansion(
of node: AttributeSyntax,
statements: CodeBlockItemListSyntax,
in context: some MacroExpansionContext
) throws -> [CodeBlockItemSyntax] {
var globalActor: TokenSyntax? = nil
var argumentList: LabeledExprListSyntax = []
if case .argumentList(let arguments) = node.arguments {
if let actor = arguments.first(labeled: "on") {
guard let member = actor.expression.as(MemberAccessExprSyntax.self),
let declRef = member.base?.as(DeclReferenceExprSyntax.self) else {
context.diagnose(.unsupportedGlobalActor, at: actor)
return []
}

argumentList = LabeledExprListSyntax(arguments.dropFirst())
globalActor = declRef.baseName
} else {
argumentList = arguments
}
}

let signature: ClosureSignatureSyntax? =
if let globalActor {
.init(attributes: "@\(globalActor) ")
} else {
nil
}

let parens: (left: TokenSyntax, right: TokenSyntax)? =
if !argumentList.isEmpty {
(.leftParenToken(), .rightParenToken())
} else {
nil
}

let taskInit = FunctionCallExprSyntax(
calledExpression: DeclReferenceExprSyntax(
baseName: "Task"
),
leftParen: parens?.left,
arguments: argumentList,
rightParen: parens?.right,
trailingClosure: ClosureExprSyntax(
signature: signature,
statements: statements
)
)

return ["\(taskInit)"]
}

public static func expansion(
of node: AttributeSyntax,
providingBodyFor declaration: some DeclSyntaxProtocol & WithOptionalCodeBlockSyntax,
in context: some MacroExpansionContext
) throws -> [CodeBlockItemSyntax] {
guard let taskBody = declaration.body else {
context.diagnose(.noImplementation, at: node)
return []
}

return try expansion(
of: node,
statements: taskBody.statements,
in: context)
}

public static func expansion(
of node: AttributeSyntax,
providingBodyFor closure: ClosureExprSyntax,
in context: some MacroExpansionContext
) throws -> [CodeBlockItemSyntax] {
try expansion(
of: node,
statements: closure.statements,
in: context)
}
}
4 changes: 2 additions & 2 deletions lib/Sema/TypeCheckMacros.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1903,10 +1903,10 @@ ExpandBodyMacroRequest::evaluate(Evaluator &evaluator,
if (bufferID)
return;

// '@StartTask' is gated behind the 'ConcurrencySyntaxSugar'
// '@Task' is gated behind the 'ConcurrencySyntaxSugar'
// experimental feature.
if (macro->getParentModule()->getName().is("_Concurrency") &&
macro->getBaseIdentifier().is("StartTask") &&
macro->getBaseIdentifier().is("Task") &&
!ctx.LangOpts.hasFeature(Feature::ConcurrencySyntaxSugar)) {
ctx.Diags.diagnose(
customAttr->getLocation(),
Expand Down
20 changes: 18 additions & 2 deletions stdlib/public/Concurrency/Actor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,26 @@ internal func _enqueueOnMain(_ job: UnownedJob)
@freestanding(expression)
public macro isolation<T>() -> T = Builtin.IsolationMacro

/// Wrap the function body in a new top-level task on behalf of the
/// given actor.
@available(SwiftStdlib 5.1, *)
@attached(body)
public macro StartTask() =
#externalMacro(module: "SwiftMacros", type: "StartTaskMacro")
public macro Task(
on actor: any GlobalActor,
name: String? = nil,
priority: TaskPriority? = nil
) =
#externalMacro(module: "SwiftMacros", type: "TaskMacro")

/// Wrap the function body in a new top-level task on behalf of the
/// current actor.
@available(SwiftStdlib 5.1, *)
@attached(body)
public macro Task(
name: String? = nil,
priority: TaskPriority? = nil
) =
#externalMacro(module: "SwiftMacros", type: "TaskMacro")

// NOTE: We put SwiftSetting under $Macro since #SwiftSettings() is a macro.
@available(SwiftStdlib 9999, *)
Expand Down
Loading