Skip to content

Commit cb7a6a0

Browse files
committed
improved readability & added explanation comment
1 parent b508e4b commit cb7a6a0

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

Sources/SwiftSyntaxMacroExpansion/MacroSystem.swift

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -132,16 +132,23 @@ private func expandFreestandingExpr(
132132
/// Adds the appropriate indentation on expanded code even if it's multi line.
133133
/// Makes sure original macro expression's trivia is maintained by adding it to expanded code.
134134
private func adjustIndentationOfFreestandingMacro(expandedCode: String, node: some FreestandingMacroExpansionSyntax) -> String {
135-
let indentationOfFirstLine = node.indentationOfFirstLine
136-
137-
var indentedSource =
138-
expandedCode
139-
.indented(by: indentationOfFirstLine)
140-
141-
if indentedSource.count >= indentationOfFirstLine.sourceLength.utf8Length {
142-
indentedSource.removeFirst(indentationOfFirstLine.sourceLength.utf8Length)
135+
136+
if expandedCode.isEmpty {
137+
return expandedCode.wrappingInTrivia(from: node)
143138
}
144-
139+
140+
let indentationOfFirstLine = node.indentationOfFirstLine
141+
let indentLength = indentationOfFirstLine.sourceLength.utf8Length
142+
143+
// we are doing 3 step adjustment here
144+
// step 1: add indentation to each line of expanded code
145+
// step 2: remove indentation from first line of expaned code
146+
// step 3: wrap the expanded code into macro expression's trivia. This trivia will contain appropriate existing
147+
// indentation. Note that if macro expression occurs in middle of the line then there will be no indentation or extra space.
148+
// Hence we are doing step 2
149+
150+
var indentedSource = expandedCode.indented(by: indentationOfFirstLine)
151+
indentedSource.removeFirst(indentLength)
145152
indentedSource = indentedSource.wrappingInTrivia(from: node)
146153

147154
return indentedSource

0 commit comments

Comments
 (0)