Skip to content

Commit 5170a2d

Browse files
authored
Merge pull request #2792 from mateusrodriguesxyz/root-detached-node
Use root node for detached node lookup in location retrieval
2 parents f8075da + 75177e0 commit 5170a2d

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

Sources/SwiftSyntaxMacroExpansion/BasicMacroExpansionContext.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ extension BasicMacroExpansionContext: MacroExpansionContext {
210210
// The syntax node came from the source file itself.
211211
rootSourceFile = directRootSourceFile
212212
offsetAdjustment = .zero
213-
} else if let nodeInOriginalTree = sharedState.detachedNodes[Syntax(node)] {
213+
} else if let nodeInOriginalTree = sharedState.detachedNodes[node.root] {
214214
// The syntax node came from a disconnected root, so adjust for that.
215215
rootSourceFile = nodeInOriginalTree.root.as(SourceFileSyntax.self)
216216
offsetAdjustment = SourceLength(utf8Length: nodeInOriginalTree.position.utf8Offset)

Tests/SwiftSyntaxMacroExpansionTest/BodyMacroTests.swift

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,4 +155,50 @@ final class BodyMacroTests: XCTestCase {
155155
macros: ["EmptyBody": EmptyBodyMacro.self]
156156
)
157157
}
158+
159+
func testBodyNodeLocationFromContext() {
160+
struct SourceLocationMacro: BodyMacro {
161+
public static var formatMode: FormatMode { .disabled }
162+
163+
public static func expansion(
164+
of node: AttributeSyntax,
165+
providingBodyFor declaration: some DeclSyntaxProtocol & WithOptionalCodeBlockSyntax,
166+
in context: some MacroExpansionContext
167+
) throws -> [CodeBlockItemSyntax] {
168+
guard let statements = declaration.body?.statements else {
169+
return []
170+
}
171+
let body =
172+
if let location = context.location(of: statements, at: .afterLeadingTrivia, filePathMode: .filePath) {
173+
CodeBlockItemListSyntax {
174+
"#sourceLocation(file: \(location.file), line: \(location.line))"
175+
statements
176+
"#sourceLocation()"
177+
}
178+
} else {
179+
statements
180+
}
181+
return body.map(\.self)
182+
}
183+
}
184+
185+
assertMacroExpansion(
186+
"""
187+
@SourceLocationMacro
188+
func f() {
189+
let x: Int = 1
190+
}
191+
""",
192+
expandedSource:
193+
"""
194+
func f() {
195+
#sourceLocation(file: "test.swift", line: 3)
196+
let x: Int = 1
197+
#sourceLocation()
198+
}
199+
""",
200+
macros: ["SourceLocationMacro": SourceLocationMacro.self],
201+
indentationWidth: indentationWidth
202+
)
203+
}
158204
}

0 commit comments

Comments
 (0)