/
ObservableMacro.swift
369 lines (322 loc) · 11.5 KB
/
ObservableMacro.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import SwiftSyntax
import SwiftSyntaxMacros
import SwiftDiagnostics
import SwiftOperators
import SwiftSyntaxBuilder
public struct ObservableMacro {
static let moduleName = "Observation"
static let conformanceName = "Observable"
static var qualifiedConformanceName: String {
return "\(moduleName).\(conformanceName)"
}
static var observableConformanceType: TypeSyntax {
"\(raw: qualifiedConformanceName)"
}
static let registrarTypeName = "ObservationRegistrar"
static var qualifiedRegistrarTypeName: String {
return "\(moduleName).\(registrarTypeName)"
}
static let trackedMacroName = "ObservationTracked"
static let ignoredMacroName = "ObservationIgnored"
static let registrarVariableName = "_$observationRegistrar"
static func registrarVariable(_ observableType: TokenSyntax) -> DeclSyntax {
return
"""
@\(raw: ignoredMacroName) private let \(raw: registrarVariableName) = \(raw: qualifiedRegistrarTypeName)()
"""
}
static func accessFunction(_ observableType: TokenSyntax) -> DeclSyntax {
return
"""
internal nonisolated func access<Member>(
keyPath: KeyPath<\(observableType), Member>
) {
\(raw: registrarVariableName).access(self, keyPath: keyPath)
}
"""
}
static func withMutationFunction(_ observableType: TokenSyntax) -> DeclSyntax {
return
"""
internal nonisolated func withMutation<Member, MutationResult>(
keyPath: KeyPath<\(observableType), Member>,
_ mutation: () throws -> MutationResult
) rethrows -> MutationResult {
try \(raw: registrarVariableName).withMutation(of: self, keyPath: keyPath, mutation)
}
"""
}
static var ignoredAttribute: AttributeSyntax {
AttributeSyntax(
leadingTrivia: .space,
atSign: .atSignToken(),
attributeName: IdentifierTypeSyntax(name: .identifier(ignoredMacroName)),
trailingTrivia: .space
)
}
}
struct ObservationDiagnostic: DiagnosticMessage {
enum ID: String {
case invalidApplication = "invalid type"
case missingInitializer = "missing initializer"
}
var message: String
var diagnosticID: MessageID
var severity: DiagnosticSeverity
init(message: String, diagnosticID: SwiftDiagnostics.MessageID, severity: SwiftDiagnostics.DiagnosticSeverity = .error) {
self.message = message
self.diagnosticID = diagnosticID
self.severity = severity
}
init(message: String, domain: String, id: ID, severity: SwiftDiagnostics.DiagnosticSeverity = .error) {
self.message = message
self.diagnosticID = MessageID(domain: domain, id: id.rawValue)
self.severity = severity
}
}
extension DiagnosticsError {
init<S: SyntaxProtocol>(syntax: S, message: String, domain: String = "Observation", id: ObservationDiagnostic.ID, severity: SwiftDiagnostics.DiagnosticSeverity = .error) {
self.init(diagnostics: [
Diagnostic(node: Syntax(syntax), message: ObservationDiagnostic(message: message, domain: domain, id: id, severity: severity))
])
}
}
extension DeclModifierListSyntax {
func privatePrefixed(_ prefix: String) -> DeclModifierListSyntax {
let modifier: DeclModifierSyntax = DeclModifierSyntax(name: "private", trailingTrivia: .space)
return [modifier] + filter {
switch $0.name.tokenKind {
case .keyword(let keyword):
switch keyword {
case .fileprivate: fallthrough
case .private: fallthrough
case .internal: fallthrough
case .public:
return false
default:
return true
}
default:
return true
}
}
}
init(keyword: Keyword) {
self.init([DeclModifierSyntax(name: .keyword(keyword))])
}
}
extension TokenSyntax {
func privatePrefixed(_ prefix: String) -> TokenSyntax {
switch tokenKind {
case .identifier(let identifier):
return TokenSyntax(.identifier(prefix + identifier), leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence)
default:
return self
}
}
}
extension PatternBindingListSyntax {
func privatePrefixed(_ prefix: String) -> PatternBindingListSyntax {
var bindings = self.map { $0 }
for index in 0..<bindings.count {
let binding = bindings[index]
if let identifier = binding.pattern.as(IdentifierPatternSyntax.self) {
bindings[index] = PatternBindingSyntax(
leadingTrivia: binding.leadingTrivia,
pattern: IdentifierPatternSyntax(
leadingTrivia: identifier.leadingTrivia,
identifier: identifier.identifier.privatePrefixed(prefix),
trailingTrivia: identifier.trailingTrivia
),
typeAnnotation: binding.typeAnnotation,
initializer: binding.initializer,
accessorBlock: binding.accessorBlock,
trailingComma: binding.trailingComma,
trailingTrivia: binding.trailingTrivia)
}
}
return PatternBindingListSyntax(bindings)
}
}
extension VariableDeclSyntax {
func privatePrefixed(_ prefix: String, addingAttribute attribute: AttributeSyntax) -> VariableDeclSyntax {
let newAttributes = attributes + [.attribute(attribute)]
return VariableDeclSyntax(
leadingTrivia: leadingTrivia,
attributes: newAttributes,
modifiers: modifiers.privatePrefixed(prefix),
bindingSpecifier: TokenSyntax(bindingSpecifier.tokenKind, leadingTrivia: .space, trailingTrivia: .space, presence: .present),
bindings: bindings.privatePrefixed(prefix),
trailingTrivia: trailingTrivia
)
}
var isValidForObservation: Bool {
!isComputed && isInstance && !isImmutable && identifier != nil
}
}
extension ObservableMacro: MemberMacro {
public static func expansion<
Declaration: DeclGroupSyntax,
Context: MacroExpansionContext
>(
of node: AttributeSyntax,
providingMembersOf declaration: Declaration,
in context: Context
) throws -> [DeclSyntax] {
guard let identified = declaration.asProtocol(NamedDeclSyntax.self) else {
return []
}
let observableType = identified.name
if declaration.isEnum {
// enumerations cannot store properties
throw DiagnosticsError(syntax: node, message: "'@Observable' cannot be applied to enumeration type '\(observableType.text)'", id: .invalidApplication)
}
if declaration.isStruct {
// structs are not yet supported; copying/mutation semantics tbd
throw DiagnosticsError(syntax: node, message: "'@Observable' cannot be applied to struct type '\(observableType.text)'", id: .invalidApplication)
}
if declaration.isActor {
// actors cannot yet be supported for their isolation
throw DiagnosticsError(syntax: node, message: "'@Observable' cannot be applied to actor type '\(observableType.text)'", id: .invalidApplication)
}
var declarations = [DeclSyntax]()
declaration.addIfNeeded(ObservableMacro.registrarVariable(observableType), to: &declarations)
declaration.addIfNeeded(ObservableMacro.accessFunction(observableType), to: &declarations)
declaration.addIfNeeded(ObservableMacro.withMutationFunction(observableType), to: &declarations)
return declarations
}
}
extension ObservableMacro: MemberAttributeMacro {
public static func expansion<
Declaration: DeclGroupSyntax,
MemberDeclaration: DeclSyntaxProtocol,
Context: MacroExpansionContext
>(
of node: AttributeSyntax,
attachedTo declaration: Declaration,
providingAttributesFor member: MemberDeclaration,
in context: Context
) throws -> [AttributeSyntax] {
guard let property = member.as(VariableDeclSyntax.self), property.isValidForObservation,
property.identifier != nil else {
return []
}
// dont apply to ignored properties or properties that are already flagged as tracked
if property.hasMacroApplication(ObservableMacro.ignoredMacroName) ||
property.hasMacroApplication(ObservableMacro.trackedMacroName) {
return []
}
return [
AttributeSyntax(attributeName: IdentifierTypeSyntax(name: .identifier(ObservableMacro.trackedMacroName)))
]
}
}
extension ObservableMacro: 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] {
// This method can be called twice - first with an empty `protocols` when
// no conformance is needed, and second with a `MissingTypeSyntax` instance.
if protocols.isEmpty {
return []
}
let decl: DeclSyntax = """
extension \(raw: type.trimmedDescription): \(raw: qualifiedConformanceName) {}
"""
let ext = decl.cast(ExtensionDeclSyntax.self)
if let availability = declaration.attributes.availability {
return [ext.with(\.attributes, availability)]
} else {
return [ext]
}
}
}
public struct ObservationTrackedMacro: AccessorMacro {
public static func expansion<
Context: MacroExpansionContext,
Declaration: DeclSyntaxProtocol
>(
of node: AttributeSyntax,
providingAccessorsOf declaration: Declaration,
in context: Context
) throws -> [AccessorDeclSyntax] {
guard let property = declaration.as(VariableDeclSyntax.self),
property.isValidForObservation,
let identifier = property.identifier else {
return []
}
if property.hasMacroApplication(ObservableMacro.ignoredMacroName) {
return []
}
let initAccessor: AccessorDeclSyntax =
"""
@storageRestrictions(initializes: _\(identifier))
init(initialValue) {
_\(identifier) = initialValue
}
"""
let getAccessor: AccessorDeclSyntax =
"""
get {
access(keyPath: \\.\(identifier))
return _\(identifier)
}
"""
let setAccessor: AccessorDeclSyntax =
"""
set {
withMutation(keyPath: \\.\(identifier)) {
_\(identifier) = newValue
}
}
"""
return [initAccessor, getAccessor, setAccessor]
}
}
extension ObservationTrackedMacro: PeerMacro {
public static func expansion<
Context: MacroExpansionContext,
Declaration: DeclSyntaxProtocol
>(
of node: SwiftSyntax.AttributeSyntax,
providingPeersOf declaration: Declaration,
in context: Context
) throws -> [DeclSyntax] {
guard let property = declaration.as(VariableDeclSyntax.self),
property.isValidForObservation else {
return []
}
if property.hasMacroApplication(ObservableMacro.ignoredMacroName) ||
property.hasMacroApplication(ObservableMacro.trackedMacroName) {
return []
}
let storage = DeclSyntax(property.privatePrefixed("_", addingAttribute: ObservableMacro.ignoredAttribute))
return [storage]
}
}
public struct ObservationIgnoredMacro: AccessorMacro {
public static func expansion<
Context: MacroExpansionContext,
Declaration: DeclSyntaxProtocol
>(
of node: AttributeSyntax,
providingAccessorsOf declaration: Declaration,
in context: Context
) throws -> [AccessorDeclSyntax] {
return []
}
}