File tree Expand file tree Collapse file tree 2 files changed +47
-1
lines changed
Sources/SwiftSyntaxMacroExpansion
Tests/SwiftSyntaxMacroExpansionTest Expand file tree Collapse file tree 2 files changed +47
-1
lines changed Original file line number Diff line number Diff 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)
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments