Skip to content

Commit 19b5dec

Browse files
committed
Support body macros that don’t return any statements
Previously, when a body macro returned no statements, we would return an empty expansion and not add the braces in `collapse`. Fix that.
1 parent 829e487 commit 19b5dec

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

Sources/SwiftSyntaxMacroExpansion/MacroExpansion.swift

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -463,15 +463,14 @@ public func collapse<Node: SyntaxProtocol>(
463463
attachedTo declarationNode: Node,
464464
indentationWidth: Trivia? = nil
465465
) -> String {
466-
if expansions.isEmpty {
467-
return ""
468-
}
469-
470466
var expansions = expansions
471467
var separator = "\n\n"
472468

473469
// Wrap the expansions in a set of braces.
474470
func wrapInBraces() {
471+
if expansions.isEmpty {
472+
expansions = [""]
473+
}
475474
// Default to 4 spaces if no indentation was passed.
476475
// In the future, we could consider inferring the indentation width from
477476
// the expansions to collapse.

Tests/SwiftSyntaxMacroExpansionTest/BodyMacroTests.swift

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,4 +125,32 @@ final class BodyMacroTests: XCTestCase {
125125
indentationWidth: indentationWidth
126126
)
127127
}
128+
129+
func testEmptyBodyMacro() {
130+
struct EmptyBodyMacro: BodyMacro {
131+
public static var formatMode: FormatMode { .disabled }
132+
133+
public static func expansion(
134+
of node: AttributeSyntax,
135+
providingBodyFor declaration: some DeclSyntaxProtocol & WithOptionalCodeBlockSyntax,
136+
in context: some MacroExpansionContext
137+
) throws -> [CodeBlockItemSyntax] {
138+
return []
139+
}
140+
}
141+
142+
assertMacroExpansion(
143+
"""
144+
@EmptyBody
145+
func f() {}
146+
""",
147+
expandedSource: """
148+
func f() {
149+
150+
}
151+
""",
152+
diagnostics: [],
153+
macros: ["EmptyBody": EmptyBodyMacro.self]
154+
)
155+
}
128156
}

0 commit comments

Comments
 (0)