File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -53,4 +53,28 @@ VisitorTests.test("RewritingNodeWithEmptyChild") {
53
53
} )
54
54
}
55
55
56
+ VisitorTests . test ( " SyntaxRewriter.visitAny " ) {
57
+ class VisitAnyRewriter : SyntaxRewriter {
58
+ let transform : ( TokenSyntax ) -> TokenSyntax
59
+ init ( transform: @escaping ( TokenSyntax ) -> TokenSyntax ) {
60
+ self . transform = transform
61
+ }
62
+ override func visitAny( _ node: Syntax ) -> Syntax ? {
63
+ if let tok = node as? TokenSyntax {
64
+ return transform ( tok)
65
+ }
66
+ return node
67
+ }
68
+ }
69
+ expectDoesNotThrow ( {
70
+ let parsed = try SourceFileSyntax . decodeSourceFileSyntax ( try
71
+ SwiftLang . parse ( getInput ( " near-empty.swift " ) ) )
72
+ let rewriter = VisitAnyRewriter ( transform: { _ in
73
+ return SyntaxFactory . makeIdentifier ( " " )
74
+ } )
75
+ let rewritten = rewriter. visit ( parsed)
76
+ expectEqual ( rewritten. description, " " )
77
+ } )
78
+ }
79
+
56
80
runAllTests ( )
Original file line number Diff line number Diff line change @@ -45,13 +45,28 @@ open class SyntaxRewriter {
45
45
/// - node: the node we are about to visit.
46
46
open func visitPre( _ node: Syntax ) { }
47
47
48
+ /// Override point to choose custom visitation dispatch instead of the
49
+ /// specialized `visit(_:)` methods. Use this instead of those methods if
50
+ /// you intend to dynamically dispatch rewriting behavior.
51
+ /// - note: If this method returns a non-nil result, the specialized
52
+ /// `visit(_:)` methods will not be called for this node.
53
+ open func visitAny( _ node: Syntax ) -> Syntax ? {
54
+ return nil
55
+ }
56
+
48
57
/// The function called after visting the node and its descendents.
49
58
/// - node: the node we just finished visiting.
50
59
open func visitPost( _ node: Syntax ) { }
51
60
52
61
public func visit( _ node: Syntax ) -> Syntax {
53
62
visitPre ( node)
54
63
defer { visitPost ( node) }
64
+
65
+ // If the global visitor returned non-nil, skip specialized dispatch.
66
+ if let newNode = visitAny ( node) {
67
+ return newNode
68
+ }
69
+
55
70
switch node. raw. kind {
56
71
case . token: return visit ( node as! TokenSyntax )
57
72
% for node in SYNTAX_NODES:
You can’t perform that action at this time.
0 commit comments