Skip to content

[Macros] Implement expansion of conformance macros #1773

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion Sources/SwiftSyntaxMacros/MacroSystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -178,14 +178,23 @@ class MacroApplication<Context: MacroExpansionContext>: SyntaxRewriter {
let newItem = visit(item.item)
newItems.append(item.with(\.item, newItem))

// Expand any peer declarations triggered by macros used as attributes.
// Expand any peer declarations or conformances triggered by macros used
// as attributes.
if case let .decl(decl) = item.item {
let peers = expandPeers(of: decl)
newItems.append(
contentsOf: peers.map {
newDecl in CodeBlockItemSyntax(item: .decl(newDecl))
}
)

if let declGroup = decl.asProtocol(DeclGroupSyntax.self) {
newItems.append(
contentsOf: expandConformances(of: declGroup).map {
newDecl in CodeBlockItemSyntax(item: .decl(newDecl))
}
)
}
}
}

Expand Down Expand Up @@ -394,6 +403,43 @@ extension MacroApplication {
return peers
}

// If any of the custom attributes associated with the given declaration
// refer to conformance macros, expand them and return the resulting
// set of extension declarations.
private func expandConformances(of decl: DeclGroupSyntax) -> [DeclSyntax] {
let extendedType: Syntax
if let identified = decl.asProtocol(IdentifiedDeclSyntax.self) {
extendedType = Syntax(identified.identifier.trimmed)
} else if let ext = decl.as(ExtensionDeclSyntax.self) {
extendedType = Syntax(ext.extendedType.trimmed)
} else {
return []
}

var extensions: [DeclSyntax] = []
let macroAttributes = getMacroAttributes(attachedTo: decl.as(DeclSyntax.self)!, ofType: ConformanceMacro.Type.self)
for (attribute, conformanceMacro) in macroAttributes {
do {
let newConformances = try conformanceMacro.expansion(of: attribute, providingConformancesOf: decl, in: context)

for (type, whereClause) in newConformances {
var ext: DeclSyntax = """
extension \(extendedType): \(type) { }
"""
if let whereClause {
ext = DeclSyntax((ext.cast(ExtensionDeclSyntax.self)).with(\.genericWhereClause, whereClause))
}

extensions.append(DeclSyntax(ext))
}
} catch {
context.addDiagnostics(from: error, node: attribute)
}
}

return extensions
}

/// Expands any attached custom attributes that refer to member declaration macros,
/// and returns result of adding those members to the given declaration.
private func expandMembers<Decl: DeclGroupSyntax & DeclSyntaxProtocol>(
Expand Down
47 changes: 47 additions & 0 deletions Tests/SwiftSyntaxMacrosTest/MacroSystemTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,16 @@ public struct DeclsFromStringsMacro: DeclarationMacro {
}
}

public struct SendableConformanceMacro: ConformanceMacro {
public static func expansion(
of node: AttributeSyntax,
providingConformancesOf declaration: some DeclGroupSyntax,
in context: some MacroExpansionContext
) throws -> [(TypeSyntax, GenericWhereClauseSyntax?)] {
return [("Sendable", nil)]
}
}

public struct DeclsFromStringsMacroNoAttrs: DeclarationMacro {
public static var propagateFreestandingMacroAttributes: Bool { false }
public static var propagateFreestandingMacroModifiers: Bool { false }
Expand Down Expand Up @@ -715,6 +725,7 @@ public let testMacros: [String: Macro.Type] = [
"wrapStoredProperties": WrapStoredProperties.self,
"customTypeWrapper": CustomTypeWrapperMacro.self,
"unwrap": UnwrapMacro.self,
"AddSendable": SendableConformanceMacro.self,
]

final class MacroSystemTests: XCTestCase {
Expand Down Expand Up @@ -1156,4 +1167,40 @@ final class MacroSystemTests: XCTestCase {
)

}

func testConformanceExpansion() {
assertMacroExpansion(
"""
@AddSendable
struct MyType {
}
""",
expandedSource: """

struct MyType {
}
extension MyType: Sendable {
}
""",
macros: testMacros,
indentationWidth: indentationWidth
)

assertMacroExpansion(
"""
@AddSendable
extension A.B {
}
""",
expandedSource: """

extension A.B {
}
extension A.B: Sendable {
}
""",
macros: testMacros,
indentationWidth: indentationWidth
)
}
}