Skip to content

Commit 5db504a

Browse files
committed
Fix all errors in macro examples code
1 parent 3c160b9 commit 5db504a

15 files changed

+167
-143
lines changed

Examples/Package.swift

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,22 @@ let package = Package(
4949
],
5050
path: "Sources/MacroExamples/Implementation"
5151
),
52+
.testTarget(
53+
name: "MacroExamplesImplementationTests",
54+
dependencies: [
55+
"MacroExamplesImplementation"
56+
],
57+
path: "Tests/MacroExamples/Implementation"
58+
),
59+
]
60+
)
61+
62+
// The following targets are added only if the OS is macOS. This is because Swift macros are currently
63+
// not available on other platforms. As a result, we're guarding these targets with `#if os(macOS)`
64+
// to ensure that they are only included in the package when building on a macOS system.
65+
#if os(macOS)
66+
package.targets.append(
67+
contentsOf: [
5268
.target(
5369
name: "MacroExamplesInterface",
5470
dependencies: [
@@ -63,15 +79,9 @@ let package = Package(
6379
],
6480
path: "Sources/MacroExamples/Playground"
6581
),
66-
.testTarget(
67-
name: "MacroExamplesImplementationTests",
68-
dependencies: [
69-
"MacroExamplesImplementation"
70-
],
71-
path: "Tests/MacroExamples/Implementation"
72-
),
7382
]
7483
)
84+
#endif
7585

7686
// This is a fake target that depends on all targets in the package.
7787
// We need to define it manually because the `Examples-Package` target doesn't exist for `swift build`.

Examples/Sources/MacroExamples/Implementation/AddAsyncMacro.swift

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -77,18 +77,16 @@ public struct AddAsyncMacro: PeerMacro {
7777
newParameterList.append(newParameterListLastParameter.with(\.trailingTrivia, []).with(\.trailingComma, nil))
7878

7979
// Drop the @addAsync attribute from the new declaration.
80-
let newAttributeList = AttributeListSyntax(
81-
funcDecl.attributes?.filter {
82-
guard case let .attribute(attribute) = $0,
83-
let attributeType = attribute.attributeName.as(IdentifierTypeSyntax.self),
84-
let nodeType = node.attributeName.as(IdentifierTypeSyntax.self)
85-
else {
86-
return true
87-
}
80+
let newAttributeList = funcDecl.attributes.filter {
81+
guard case let .attribute(attribute) = $0,
82+
let attributeType = attribute.attributeName.as(IdentifierTypeSyntax.self),
83+
let nodeType = node.attributeName.as(IdentifierTypeSyntax.self)
84+
else {
85+
return true
86+
}
8887

89-
return attributeType.name.text != nodeType.name.text
90-
} ?? []
91-
)
88+
return attributeType.name.text != nodeType.name.text
89+
}
9290

9391
let callArguments: [String] = newParameterList.map { param in
9492
let argName = param.secondName ?? param.firstName
@@ -114,11 +112,11 @@ public struct AddAsyncMacro: PeerMacro {
114112
let newBody: ExprSyntax =
115113
"""
116114
117-
\(isResultReturn ? "try await withCheckedThrowingContinuation { continuation in" : "await withCheckedContinuation { continuation in")
118-
\(funcDecl.name)(\(raw: callArguments.joined(separator: ", "))) { \(returnType != nil ? "returnValue in" : "")
119-
120-
\(isResultReturn ? switchBody : "continuation.resume(returning: \(returnType != nil ? "returnValue" : "()"))")
121-
115+
\(raw: isResultReturn ? "try await withCheckedThrowingContinuation { continuation in" : "await withCheckedContinuation { continuation in")
116+
\(raw: funcDecl.name)(\(raw: callArguments.joined(separator: ", "))) { \(raw: returnType != nil ? "returnValue in" : "")
117+
118+
\(raw: isResultReturn ? switchBody : "continuation.resume(returning: \(raw: returnType != nil ? "returnValue" : "()"))")
119+
122120
}
123121
}
124122
@@ -131,7 +129,11 @@ public struct AddAsyncMacro: PeerMacro {
131129
funcDecl.signature
132130
.with(
133131
\.effectSpecifiers,
134-
FunctionEffectSpecifiersSyntax(leadingTrivia: .space, asyncSpecifier: "async", throwsSpecifier: isResultReturn ? " throws" : nil) // add async
132+
FunctionEffectSpecifiersSyntax(
133+
leadingTrivia: .space,
134+
asyncSpecifier: .keyword(.async),
135+
throwsSpecifier: isResultReturn ? .keyword(.throws) : nil
136+
) // add async
135137
)
136138
.with(
137139
\.returnClause,

Examples/Sources/MacroExamples/Implementation/AddCompletionHandlerMacro.swift

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -125,18 +125,16 @@ public struct AddCompletionHandlerMacro: PeerMacro {
125125
"""
126126

127127
// Drop the @addCompletionHandler attribute from the new declaration.
128-
let newAttributeList = AttributeListSyntax(
129-
funcDecl.attributes?.filter {
130-
guard case let .attribute(attribute) = $0,
131-
let attributeType = attribute.attributeName.as(IdentifierTypeSyntax.self),
132-
let nodeType = node.attributeName.as(IdentifierTypeSyntax.self)
133-
else {
134-
return true
135-
}
128+
let newAttributeList = funcDecl.attributes.filter {
129+
guard case let .attribute(attribute) = $0,
130+
let attributeType = attribute.attributeName.as(IdentifierTypeSyntax.self),
131+
let nodeType = node.attributeName.as(IdentifierTypeSyntax.self)
132+
else {
133+
return true
134+
}
136135

137-
return attributeType.name.text != nodeType.name.text
138-
} ?? []
139-
)
136+
return attributeType.name.text != nodeType.name.text
137+
}
140138

141139
let newFunc =
142140
funcDecl

Examples/Sources/MacroExamples/Implementation/CodableKey.swift

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,13 @@
1313
import SwiftSyntax
1414
import SwiftSyntaxMacros
1515

16-
public struct CodableKey: MemberMacro {
16+
public struct CodableKey: PeerMacro {
1717
public static func expansion(
1818
of node: AttributeSyntax,
19-
providingMembersOf declaration: some DeclGroupSyntax,
19+
providingPeersOf declaration: some DeclSyntaxProtocol,
2020
in context: some MacroExpansionContext
2121
) throws -> [DeclSyntax] {
2222
// Does nothing, used only to decorate members with data
2323
return []
2424
}
25-
2625
}

Examples/Sources/MacroExamples/Implementation/CustomCodable.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public struct CustomCodable: MemberMacro {
3232
}
3333

3434
// if it has a CodableKey macro on it
35-
if let customKeyMacro = member.decl.as(VariableDeclSyntax.self)?.attributes?.first(where: { element in
35+
if let customKeyMacro = member.decl.as(VariableDeclSyntax.self)?.attributes.first(where: { element in
3636
element.as(AttributeSyntax.self)?.attributeName.as(IdentifierTypeSyntax.self)?.description == "CodableKey"
3737
}) {
3838

Examples/Sources/MacroExamples/Implementation/DictionaryIndirectionMacro.swift

Lines changed: 38 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,44 @@ import SwiftSyntaxMacros
1515

1616
public struct DictionaryStorageMacro {}
1717

18-
extension DictionaryStorageMacro: AccessorMacro {
18+
extension DictionaryStorageMacro: MemberMacro {
19+
public static func expansion(
20+
of node: AttributeSyntax,
21+
providingMembersOf declaration: some DeclGroupSyntax,
22+
in context: some MacroExpansionContext
23+
) throws -> [DeclSyntax] {
24+
let storage: DeclSyntax = "var _storage: [String: Any] = [:]"
25+
return [
26+
storage.with(\.leadingTrivia, [.newlines(1), .spaces(2)])
27+
]
28+
}
29+
}
30+
31+
extension DictionaryStorageMacro: MemberAttributeMacro {
32+
public static func expansion(
33+
of node: AttributeSyntax,
34+
attachedTo declaration: some DeclGroupSyntax,
35+
providingAttributesFor member: some DeclSyntaxProtocol,
36+
in context: some MacroExpansionContext
37+
) throws -> [AttributeSyntax] {
38+
guard let property = member.as(VariableDeclSyntax.self),
39+
property.isStoredProperty
40+
else {
41+
return []
42+
}
43+
44+
return [
45+
AttributeSyntax(
46+
attributeName: IdentifierTypeSyntax(
47+
name: .identifier("DictionaryStorageProperty")
48+
)
49+
)
50+
.with(\.leadingTrivia, [.newlines(1), .spaces(2)])
51+
]
52+
}
53+
}
54+
55+
public struct DictionaryStoragePropertyMacro: AccessorMacro {
1956
public static func expansion<
2057
Context: MacroExpansionContext,
2158
Declaration: DeclSyntaxProtocol
@@ -58,40 +95,3 @@ extension DictionaryStorageMacro: AccessorMacro {
5895
]
5996
}
6097
}
61-
62-
extension DictionaryStorageMacro: MemberMacro {
63-
public static func expansion(
64-
of node: AttributeSyntax,
65-
providingMembersOf declaration: some DeclGroupSyntax,
66-
in context: some MacroExpansionContext
67-
) throws -> [DeclSyntax] {
68-
let storage: DeclSyntax = "var _storage: [String: Any] = [:]"
69-
return [
70-
storage.with(\.leadingTrivia, [.newlines(1), .spaces(2)])
71-
]
72-
}
73-
}
74-
75-
extension DictionaryStorageMacro: MemberAttributeMacro {
76-
public static func expansion(
77-
of node: AttributeSyntax,
78-
attachedTo declaration: some DeclGroupSyntax,
79-
providingAttributesFor member: some DeclSyntaxProtocol,
80-
in context: some MacroExpansionContext
81-
) throws -> [AttributeSyntax] {
82-
guard let property = member.as(VariableDeclSyntax.self),
83-
property.isStoredProperty
84-
else {
85-
return []
86-
}
87-
88-
return [
89-
AttributeSyntax(
90-
attributeName: IdentifierTypeSyntax(
91-
name: .identifier("DictionaryStorage")
92-
)
93-
)
94-
.with(\.leadingTrivia, [.newlines(1), .spaces(2)])
95-
]
96-
}
97-
}

Examples/Sources/MacroExamples/Implementation/MetaEnumMacro.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public struct MetaEnumMacro {
3030

3131
parentTypeName = enumDecl.name.with(\.trailingTrivia, [])
3232

33-
access = enumDecl.modifiers?.first(where: \.isNeededAccessLevelModifier)
33+
access = enumDecl.modifiers.first(where: \.isNeededAccessLevelModifier)
3434

3535
childCases = enumDecl.caseElements.map { parentCase in
3636
parentCase.with(\.parameterClause, nil)

Examples/Sources/MacroExamples/Implementation/NewTypeMacro.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ extension NewTypeMacro: MemberMacro {
3737
throw CustomError.message("@NewType can only be applied to a struct declarations.")
3838
}
3939

40-
let access = declaration.modifiers?.first(where: \.isNeededAccessLevelModifier)
40+
let access = declaration.modifiers.first(where: \.isNeededAccessLevelModifier)
4141

4242
return [
4343
"\(access)typealias RawValue = \(rawType)",

Examples/Sources/MacroExamples/Implementation/ObservableMacro.swift

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -120,13 +120,15 @@ public struct ObservableMacro: MemberMacro, MemberAttributeMacro {
120120

121121
}
122122

123-
extension ObservableMacro: ConformanceMacro {
124-
public static func expansion<Declaration, Context>(
123+
extension ObservableMacro: ExtensionMacro {
124+
public static func expansion(
125125
of node: AttributeSyntax,
126-
providingConformancesOf declaration: Declaration,
127-
in context: Context
128-
) throws -> [(TypeSyntax, GenericWhereClauseSyntax?)] where Declaration: DeclGroupSyntax, Context: MacroExpansionContext {
129-
return [("Observable", nil)]
126+
attachedTo declaration: some DeclGroupSyntax,
127+
providingExtensionsOf type: some TypeSyntaxProtocol,
128+
conformingTo protocols: [TypeSyntax],
129+
in context: some MacroExpansionContext
130+
) throws -> [ExtensionDeclSyntax] {
131+
[try ExtensionDeclSyntax("extension \(type): Observable {}")]
130132
}
131133
}
132134

Examples/Sources/MacroExamples/Implementation/OptionSetMacro.swift

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -134,14 +134,16 @@ public struct OptionSetMacro {
134134
}
135135
}
136136

137-
extension OptionSetMacro: ConformanceMacro {
137+
extension OptionSetMacro: ExtensionMacro {
138138
public static func expansion(
139-
of attribute: AttributeSyntax,
140-
providingConformancesOf decl: some DeclGroupSyntax,
139+
of node: AttributeSyntax,
140+
attachedTo declaration: some DeclGroupSyntax,
141+
providingExtensionsOf type: some TypeSyntaxProtocol,
142+
conformingTo protocols: [TypeSyntax],
141143
in context: some MacroExpansionContext
142-
) throws -> [(TypeSyntax, GenericWhereClauseSyntax?)] {
144+
) throws -> [ExtensionDeclSyntax] {
143145
// Decode the expansion arguments.
144-
guard let (structDecl, _, _) = decodeExpansion(of: attribute, attachedTo: decl, in: context) else {
146+
guard let (structDecl, _, _) = decodeExpansion(of: node, attachedTo: declaration, in: context) else {
145147
return []
146148
}
147149

@@ -152,7 +154,7 @@ extension OptionSetMacro: ConformanceMacro {
152154
return []
153155
}
154156

155-
return [("OptionSet", nil)]
157+
return [try ExtensionDeclSyntax("extension \(type): OptionSet {}")]
156158
}
157159
}
158160

@@ -177,7 +179,7 @@ extension OptionSetMacro: MemberMacro {
177179
}
178180

179181
// Dig out the access control keyword we need.
180-
let access = decl.modifiers?.first(where: \.isNeededAccessLevelModifier)
182+
let access = decl.modifiers.first(where: \.isNeededAccessLevelModifier)
181183

182184
let staticVars = caseElements.map { (element) -> DeclSyntax in
183185
"""

0 commit comments

Comments
 (0)