-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCallableMacro.swift
More file actions
55 lines (49 loc) · 1.83 KB
/
CallableMacro.swift
File metadata and controls
55 lines (49 loc) · 1.83 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
import Foundation
import SwiftSyntax
import SwiftSyntaxMacros
public struct CallableMacro: PeerMacro {
public static func expansion(
of node: AttributeSyntax,
providingPeersOf declaration: some DeclSyntaxProtocol,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
guard let `protocol` = declaration.as(ProtocolDeclSyntax.self) else {
throw MacroExpansionErrorMessage("@Callable can only be attached to protocols.")
}
let protocolName = `protocol`.name.trimmedDescription
let serviceName = protocolName.trimmingSuffix("Protocol").trimmingSuffix("Service")
let functions = `protocol`.memberBlock.members.compactMap { item in
return item.decl.as(FunctionDeclSyntax.self)
}
let configureFunc = try FunctionDeclSyntax("""
public func configure\(raw: protocolName)<\(raw: serviceName): \(raw: protocolName)>(
transport: some ServiceTransport<\(raw: serviceName)>
)
""") {
for function in functions {
FunctionCallExprSyntax(
callee: "transport.register" as ExprSyntax,
trailingClosure: ClosureExprSyntax {
"$0.\(function.name)" as ExprSyntax
}
) {
LabeledExprSyntax(
label: "path",
expression: "\(serviceName)/\(function.name)".makeLiteralSyntax()
)
}
}
}
return [DeclSyntax(configureFunc)]
}
}
extension String {
fileprivate func trimmingSuffix(_ suffix: String) -> String {
if self.hasSuffix(suffix) {
var copy = self
copy.removeLast(suffix.count)
return copy
}
return self
}
}