Skip to content

Commit 0dba9a7

Browse files
committed
Add BasicMacroExpansionContext.detach for use in the compiler
1 parent cbb8993 commit 0dba9a7

File tree

2 files changed

+20
-18
lines changed

2 files changed

+20
-18
lines changed

Sources/SwiftSyntaxMacros/BasicMacroExpansionContext.swift

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,14 +65,28 @@ public class BasicMacroExpansionContext {
6565
/// Used in conjunction with `expansionDiscriminator`.
6666
private var uniqueNames: [String: Int] = [:]
6767

68+
}
69+
70+
extension BasicMacroExpansionContext {
6871
/// Note that the given node that was at the given position in the provided
6972
/// source file has been disconnected and is now a new root.
70-
internal func addDisconnected(
71-
_ node: Syntax,
73+
private func addDisconnected<Node: SyntaxProtocol>(
74+
_ node: Node,
7275
at offset: AbsolutePosition,
7376
in sourceFile: SourceFileSyntax
7477
) {
75-
disconnectedNodes[node] = (sourceFile, offset.utf8Offset)
78+
disconnectedNodes[Syntax(node)] = (sourceFile, offset.utf8Offset)
79+
}
80+
81+
/// Detach the given node, and record where it came from.
82+
public func detach<Node: SyntaxProtocol>(_ node: Node) -> Node {
83+
let detached = node.detach()
84+
85+
if let rootSourceFile = node.root.as(SourceFileSyntax.self) {
86+
addDisconnected(detached, at: node.position, in: rootSourceFile)
87+
}
88+
89+
return detached
7690
}
7791
}
7892

Sources/SwiftSyntaxMacros/Syntax+MacroEvaluation.swift

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -28,23 +28,11 @@ extension SyntaxProtocol {
2828
/// Detach the current node and inform the macro expansion context,
2929
/// if it needs to know.
3030
fileprivate func detach(in context: MacroExpansionContext) -> Self {
31-
let detached = detach()
32-
33-
// Testing contexts want to know where the detach occurred so they can
34-
// track it.
35-
//
36-
// TODO: Should this be generalized?
37-
if let testingContext = context as? BasicMacroExpansionContext,
38-
let parentSourceFile = root.as(SourceFileSyntax.self)
39-
{
40-
testingContext.addDisconnected(
41-
Syntax(detached),
42-
at: position,
43-
in: parentSourceFile
44-
)
31+
if let basicContext = context as? BasicMacroExpansionContext {
32+
return basicContext.detach(self)
4533
}
4634

47-
return detached
35+
return self.detach()
4836
}
4937
}
5038

0 commit comments

Comments
 (0)