-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathAddCompletionHandlerMacro.swift
More file actions
63 lines (56 loc) · 2.25 KB
/
AddCompletionHandlerMacro.swift
File metadata and controls
63 lines (56 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import MacroToolkit
import SwiftDiagnostics
import SwiftSyntax
import SwiftSyntaxMacros
// Modified from: https://github.com/DougGregor/swift-macro-examples/blob/f61ac7cdca8dc3557e53f86e7e03df1353908d3e/MacroExamplesPlugin/AddCompletionHandlerMacro.swift
public struct AddCompletionHandlerMacro: PeerMacro {
public static func expansion<
Context: MacroExpansionContext,
Declaration: DeclSyntaxProtocol
>(
of node: AttributeSyntax,
providingPeersOf declaration: Declaration,
in context: Context
) throws -> [DeclSyntax] {
guard let function = Function(declaration) else {
throw MacroError("@AddCompletionHandler only works on functions")
}
guard function.isAsync else {
let newSignature = function._syntax.withAsyncModifier().signature
let diagnostic = DiagnosticBuilder(for: function._syntax.funcKeyword)
.message("can only add a completion-handler variant to an 'async' function")
.messageID(domain: "AddCompletionHandlerMacro", id: "MissingAsync")
.suggestReplacement(
"add 'async'",
old: function._syntax.signature,
new: newSignature
)
.build()
context.diagnose(diagnostic)
return []
}
let completionHandlerParameter =
FunctionParameter(
name: "completionHandler",
type: "@escaping (\(raw: function.returnType?.description ?? "")) -> Void"
)
let callArguments = function.parameters.asPassthroughArguments
let newFunc =
function._syntax
.withAsyncModifier(false)
.withReturnType(nil)
.withParameters(function.parameters + [completionHandlerParameter])
.withBody([
"""
Task {
completionHandler(
await \(raw: function.identifier)(\(raw: callArguments.joined(separator: ", ")))
)
}
"""
])
.withAttributes(function.attributes.removing(node))
.withLeadingBlankLine()
return [DeclSyntax(newFunc)]
}
}