Skip to content

Use root node for detached node lookup in location retrieval #2792

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 1 commit into from
Aug 9, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ extension BasicMacroExpansionContext: MacroExpansionContext {
// The syntax node came from the source file itself.
rootSourceFile = directRootSourceFile
offsetAdjustment = .zero
} else if let nodeInOriginalTree = sharedState.detachedNodes[Syntax(node)] {
} else if let nodeInOriginalTree = sharedState.detachedNodes[node.root] {
// The syntax node came from a disconnected root, so adjust for that.
rootSourceFile = nodeInOriginalTree.root.as(SourceFileSyntax.self)
offsetAdjustment = SourceLength(utf8Length: nodeInOriginalTree.position.utf8Offset)
Expand Down
46 changes: 46 additions & 0 deletions Tests/SwiftSyntaxMacroExpansionTest/BodyMacroTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -155,4 +155,50 @@ final class BodyMacroTests: XCTestCase {
macros: ["EmptyBody": EmptyBodyMacro.self]
)
}

func testBodyNodeLocationFromContext() {
struct SourceLocationMacro: BodyMacro {
public static var formatMode: FormatMode { .disabled }

public static func expansion(
of node: AttributeSyntax,
providingBodyFor declaration: some DeclSyntaxProtocol & WithOptionalCodeBlockSyntax,
in context: some MacroExpansionContext
) throws -> [CodeBlockItemSyntax] {
guard let statements = declaration.body?.statements else {
return []
}
let body =
if let location = context.location(of: statements, at: .afterLeadingTrivia, filePathMode: .filePath) {
CodeBlockItemListSyntax {
"#sourceLocation(file: \(location.file), line: \(location.line))"
statements
"#sourceLocation()"
}
} else {
statements
}
return body.map(\.self)
}
}

assertMacroExpansion(
"""
@SourceLocationMacro
func f() {
let x: Int = 1
}
""",
expandedSource:
"""
func f() {
#sourceLocation(file: "test.swift", line: 3)
let x: Int = 1
#sourceLocation()
}
""",
macros: ["SourceLocationMacro": SourceLocationMacro.self],
indentationWidth: indentationWidth
)
}
}