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 in ast, is about to be entered; returns false if traversal should skip n.

    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, willEnter will be before each child of n is entered and willExit will be called when n is left. If it returns false, neither willEnter nor willExit will be called for n and its children.

    Declaration

    Swift

    mutating func willEnter(_ n: AnyNodeID, in ast: AST) -> Bool
  • Called when n, which is in ast, is about to be left.

    Declaration

    Swift

    mutating func willExit(_ n: AnyNodeID, in ast: AST)
  • willEnter(_:in:) Extension method

    Declaration

    Swift

    public func willEnter(_ n: AnyNodeID, in ast: AST) -> Bool
  • willExit(_:in:) Extension method

    Declaration

    Swift

    public func willExit(_ n: AnyNodeID, in ast: AST)