ASTWalkObserver
public protocol ASTWalkObserver : Sendable
A type that is notified when nodes are entered and left during an AST traversal.
Use this protocol to implement algorithms that must traverse all or most AST nodes and perform
similar operations on each of them. Instances of types implementing this protocol are meant to
be passed as argument to AST.walk(_:notifying:).
For example:
struct V: ASTWalkObserver {
var outermostFunctions: [FunctionDecl.ID] = []
mutating func willEnter(_ n: AnyNodeID, in ast: AST) -> Bool {
if let d = FunctionDecl.ID(n) {
outermostFunctions.append(d)
return false
} else {
return true
}
}
}
var v = V()
for m in ast.modules { ast.walk(m, notifying: &v) }
print(v.outermostFunctions)
This program prints the IDs of the outermost function declarations in ast.
-
Called when
n, which is inast, is about to be entered; returnsfalseif traversal should skipn.Use this method to perform actions before a node is being traversed and/or customize how the AST is traversed. If the method returns
true,willEnterwill be before each child ofnis entered andwillExitwill be called whennis left. If it returnsfalse, neitherwillEnternorwillExitwill be called fornand its children. -
Called when
n, which is inast, is about to be left. -
willEnter(_:Extension methodin: ) -
willExit(_:Extension methodin: )
View on GitHub