-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathCustomCodableMacro.swift
More file actions
42 lines (36 loc) · 1.44 KB
/
CustomCodableMacro.swift
File metadata and controls
42 lines (36 loc) · 1.44 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
import MacroToolkit
import SwiftSyntax
import SwiftSyntaxMacros
// Modified from: https://github.com/DougGregor/swift-macro-examples/blob/f61ac7cdca8dc3557e53f86e7e03df1353908d3e/MacroExamplesPlugin/CustomCodable.swift
public struct CustomCodableMacro: MemberMacro {
public static func expansion(
of node: AttributeSyntax,
providingMembersOf declaration: some DeclGroupSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
let decl = DeclGroup(declaration)
let cases = decl.members.compactMap(\.asVariable).compactMap { (variable) -> String? in
guard let propertyName = destructureSingle(variable.identifiers) else {
return nil
}
if let customKeyMacro = variable.attributes.first(called: "CodableKey") {
guard
let attribute = customKeyMacro.asMacroAttribute,
let customKeyValue = destructureSingle(attribute.arguments.map(\.expr))
else {
return nil
}
return "case \(propertyName) = \(customKeyValue._syntax)"
} else {
return "case \(propertyName)"
}
}
let codingKeys: DeclSyntax =
"""
enum CodingKeys: String, CodingKey {
\(raw: cases.joined(separator: "\n"))
}
"""
return [codingKeys]
}
}