-
Notifications
You must be signed in to change notification settings - Fork 0
/
AttributeMacro.swift
68 lines (58 loc) · 2.44 KB
/
AttributeMacro.swift
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
/*
Created by David Spooner
*/
import SwiftSyntax
import SwiftSyntaxMacros
/// AttributeMacro enables defining NSAttributeDescriptions from compatible variables of a managed object class.
public struct AttributeMacro : ManagedPropertyMacro
{
// ManagedPropertyMacro
static func inferredMetadataConstructorArguments(for info: StoredPropertyInfo, with attr: AttributeSyntax) -> String?
{ "name: \"\(info.name)\", type: \(info.type.longName).self" + (info.value.map {", defaultValue: \($0)"} ?? "") }
// AccessorMacro
public static func expansion<Ctx, Dcl>(of node: AttributeSyntax, providingAccessorsOf dcl: Dcl, in ctx: Ctx) throws -> [AccessorDeclSyntax]
where Ctx: MacroExpansionContext, Dcl: DeclSyntaxProtocol
{
let info = try getStoredPropertyInfo(from: dcl)
switch info.type.as(OptionalTypeSyntax.self) {
case .none :
return [
"""
get {
switch self.value(forKey: "\(raw: info.name)") {
case .some(let objectValue) :
guard let encodedValue = objectValue as? \(raw: info.type).EncodingType else { fatalError("\(raw: info.name) is not of expected type ...") }
return \(raw: info.type).decodeStoredValue(encodedValue)
case .none :
fatalError("\(raw: info.name) is not initialized")
}
}
""",
"""
set {
self.setValue(newValue.storedValue(), forKey: "\(raw: info.name)")
}
""",
]
case .some(let optionalType) :
return [
"""
get {
switch self.value(forKey: "\(raw: info.name)") {
case .some(let objectValue) :
guard let encodedValue = objectValue as? \(raw: optionalType.wrappedType).EncodingType else { fatalError("\(raw: info.name) is not of expected type ...") }
return \(raw: optionalType.longName).inject(\(raw: optionalType.wrappedType).decodeStoredValue(encodedValue))
case .none :
return nil
}
}
""",
"""
set {
self.setValue(\(raw: optionalType.longName).project(newValue)?.storedValue(), forKey: "\(raw: info.name)")
}
""",
]
}
}
}