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 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
import SwiftDiagnostics
import SwiftOperators
import SwiftSyntax
import SwiftSyntaxBuilder
import SwiftSyntaxMacros
public struct AddStructDeclMacro: DeclarationMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
return [
"""
struct MacroAddedStruct : TestEntity {}
"""
]
}
}
public struct AddPeerStructMacro: PeerMacro {
public static func expansion(
of node: AttributeSyntax,
providingPeersOf declaration: some DeclSyntaxProtocol,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
let name = declaration.declName
return [
"""
struct _Peer_\(name) : TestEntity {}
"""
]
}
}
public struct AddExtensionMacro: ExtensionMacro {
public static func expansion(
of node: AttributeSyntax,
attachedTo declaration: some DeclGroupSyntax,
providingExtensionsOf type: some TypeSyntaxProtocol,
conformingTo protocols: [TypeSyntax],
in context: some MacroExpansionContext
) throws -> [ExtensionDeclSyntax] {
let typeName = declaration.declGroupName
return protocols.map {
("""
extension \(typeName): \($0) {
struct _Extension_\($0): \($0) {}
}
""" as DeclSyntax)
.cast(ExtensionDeclSyntax.self)
}
}
}
extension DeclSyntaxProtocol {
var declName: TokenSyntax {
if let varDecl = self.as(VariableDeclSyntax.self),
let first = varDecl.bindings.first,
let pattern = first.pattern.as(IdentifierPatternSyntax.self) {
return pattern.identifier.trimmed
} else if let funcDecl = self.as(FunctionDeclSyntax.self) {
return funcDecl.name.trimmed
} else if let structDecl = self.as(StructDeclSyntax.self) {
return structDecl.name.trimmed
}
fatalError("Not implemented")
}
}
extension DeclGroupSyntax {
var declGroupName: TokenSyntax {
if let structDecl = self.as(StructDeclSyntax.self) {
return structDecl.name.trimmed
}
fatalError("Not implemented")
}
}
|