8000 Fix bug that caused the rootId of a node to not be updated if it was … · swiftlang/swift-syntax@67837fb · GitHub
[go: up one dir, main page]

Skip to content

Commit 67837fb

Browse files
committed
Fix bug that caused the rootId of a node to not be updated if it was created by a replacing* function
When creating a node using e.g. `replacingTrailingTrivia`, it would still have the same the same rootId as before. Because of this `SyntaxRewriter` would not detect the node as having changed, thus failing to replace it in the rewritten tree.
1 parent 2c32b74 commit 67837fb

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

Sources/SwiftSyntax/SyntaxData.swift

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -188,8 +188,10 @@ struct AbsoluteRawSyntax {
188188
return nil
189189
}
190190

191-
func replacingSelf(_ newRaw: RawSyntax) -> AbsoluteRawSyntax {
192-
return .init(raw: newRaw, info: info)
191+
func replacingSelf(_ newRaw: RawSyntax, newRootId: UInt32) -> AbsoluteRawSyntax {
192+
let nodeId = SyntaxIdentifier(rootId: newRootId, indexInTree: info.nodeId.indexInTree)
193+
let newInfo = AbsoluteSyntaxInfo(position: info.position, nodeId: nodeId)
194+
return .init(raw: newRaw, info: newInfo)
193195
}
194196

195197
static func forRoot(_ raw: RawSyntax) -> AbsoluteRawSyntax {
@@ -334,7 +336,7 @@ struct SyntaxData {
334336
if let parent = parent {
335337
let parentData = parent.data.replacingChild(newRaw, at: indexInParent)
336338
let newParent = Syntax(parentData)
337-
return SyntaxData(absoluteRaw.replacingSelf(newRaw), parent: newParent)
339+
return SyntaxData(absoluteRaw.replacingSelf(newRaw, newRootId: parentData.nodeId.rootId), parent: newParent)
338340
} else {
339341
// Otherwise, we're already the root, so return the new root data.
340342
return .forRoot(newRaw)

Tests/SwiftSyntaxTest/SyntaxVisitorTests.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,19 @@ public class SyntaxVisitorTests: XCTestCase {
9494
XCTAssertEqual(hashBefore, parsed.hashValue)
9595
}())
9696
}
97+
98+
public func testRewriteTrivia() {
99+
class TriviaRemover: SyntaxRewriter {
100+
override func visit(_ token: TokenSyntax) -> Syntax {
101+
return Syntax(token.withTrailingTrivia(.zero))
102+
}
103+
}
104+
105+
XCTAssertNoThrow(try {
106+
let parsed = try SyntaxParser.parse(source: "let a = 5")
107+
let visitor = TriviaRemover()
108+
let rewritten = visitor.visit(parsed)
109+
XCTAssertEqual(rewritten.description, "leta=5")
110+
}())
111+
}
97112
}

0 commit comments

Comments
 (0)
0