除非,我們今天將 [a]
改寫成 [a = a]
除了前面介紹的 visitor 以外
我們可以透過實作 SyntaxRewriter
去更改特定語法
我們可以透過 AST Explorer 得知
[weak a = a]
是 ClosureCaptureItemSyntax
語法
以及得知其語法架構
/// ClosureCaptureItemSyntax
/// specifier name assignToken expression
/// weak a = a [weak a = a]
/// weak a [weak a]
於是我們就可以開始偷偷改 code
= a
a
是 ID
node.expression.as(IdentifierExprSyntax.self)
withXXX
將特定語法替換掉
with(KeyPath)
import Foundation
import SwiftSyntax
final public class CaptureListRewriter: SyntaxRewriter {
public override func visit(_ node: ClosureCaptureItemSyntax) -> ClosureCaptureItemSyntax {
guard node.name == nil, node.assignToken == nil else {
return node
}
guard let name = node.expression.as(IdentifierExprSyntax.self)?.identifier else {
return node
}
return node
.withName(name.withoutTrivia())
.withAssignToken(TokenSyntax.equalToken(leadingTrivia: .space, trailingTrivia: .space))
}
}
let newSource = rewriter.visit(source)