forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathASTTreeVisitor.swift
More file actions
61 lines (50 loc) · 1.48 KB
/
ASTTreeVisitor.swift
File metadata and controls
61 lines (50 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import Foundation
import SwiftTreeSitter
public enum ASTTreeVisitorContinueKind {
/// The visitor should visit the descendants of the current node.
case visitChildren
/// The visitor should avoid visiting the descendants of the current node.
case skipChildren
}
// A SwiftSyntax style tree visitor.
open class ASTTreeVisitor {
public let tree: ASTTree
public init(tree: ASTTree) {
self.tree = tree
}
public func walk() {
guard let cursor = tree.rootNode?.treeCursor else { return }
visit(cursor)
}
public func walk(_ node: ASTNode) {
let cursor = node.treeCursor
visit(cursor)
}
open func visit(_: ASTNode) -> ASTTreeVisitorContinueKind {
// do nothing
return .skipChildren
}
open func visitPost(_: ASTNode) {
// do nothing
}
private func visit(_ cursor: TreeCursor) {
guard let currentNode = cursor.currentNode else { return }
let continueKind = visit(currentNode)
switch continueKind {
case .skipChildren:
visitPost(currentNode)
case .visitChildren:
visitChildren(cursor)
visitPost(currentNode)
}
}
private func visitChildren(_ cursor: TreeCursor) {
let hasChild = cursor.goToFirstChild()
guard hasChild else { return }
visit(cursor)
while cursor.goToNextSibling() {
visit(cursor)
}
_ = cursor.gotoParent()
}
}