[Macros] Add an overload of findSyntaxNodeInSourceFile that accepts

a predicate.

The new overload is used during macro expansion to find the nearest
syntax node that is either a `DeclSyntax` or a `ClosureExprSyntax`.
This avoids an issue where calling the overload that accepts a
specific type may find an outer, unrelated declaration or closure.
This commit is contained in:
Holly Borla
2025-03-20 18:58:47 -07:00
parent e2aed1f3d1
commit b005df366a
2 changed files with 48 additions and 21 deletions

View File

@@ -583,22 +583,15 @@ func expandAttachedMacro(
return 1
}
func findNode<T: SyntaxProtocol>(type: T.Type) -> T? {
findSyntaxNodeInSourceFile(
sourceFilePtr: declarationSourceFilePtr,
sourceLocationPtr: declarationSourceLocPointer,
type: T.self
)
}
// Dig out the node for the closure or declaration to which the custom
// attribute is attached.
let node: Syntax
if let closureNode = findNode(type: ClosureExprSyntax.self) {
node = Syntax(closureNode)
} else if let declNode = findNode(type: DeclSyntax.self) {
node = Syntax(declNode)
} else {
let node = findSyntaxNodeInSourceFile(
sourceFilePtr: declarationSourceFilePtr,
sourceLocationPtr: declarationSourceLocPointer,
where: { $0.is(DeclSyntax.self) || $0.is(ClosureExprSyntax.self) }
)
guard let node else {
return 1
}