Spec: docs/superpowers/specs/2026-10-27-term-traversal-design.md. Rule IDs such as [TT-1] refer to it.
Child order [TT-1]: LamAbs body; Apply function, then argument; Force body; Delay body; Constr arguments in order; Case scrutinee, then branches in order.
Whole-tree combinators (visit, foreach, exists, foldLeft, transformUp, transformDown, freeVars) recurse on the JVM stack, one frame per tree level, like the hand-written walks they replace. An explicit stack measured 1.5 to 2.2 times slower, so stack safety is deferred (spec, [TT-14]). They allocate nothing per visited node, except for the nodes a rewrite rebuilds [TT-16].
Rewrites keep identity: when nothing below a node changed, the node itself is returned (eq) [TT-12]. Identity-keyed caches in the optimizer passes depend on that.
The combinators are inline with inline callbacks [TT-19]. Each call site gets its own local recursive function with the callback body in it, so there is no megamorphic Function1 call per node. For example, t.exists(p) expands to:
def go(n: Term): Boolean = ||
go(t)
The combinators are extension methods on Term. Import the ones a file uses by name, for example import scalus.uplc.internal.TermTraversal.{exists, mapChildren}. They are not members of the public Term type. freeVars is a plain method, TermTraversal.freeVars(t), because TermAnalysis already provides a freeVars extension.
Like mapChildren, and also passes the child index [TT-2]: Apply 0 = function, 1 = argument; Case 0 = scrutinee, 1..n = branches; Constr 0..n-1 = arguments; one-child nodes 0.
Like mapChildren, and also passes the child index [TT-2]: Apply 0 = function, 1 = argument; Case 0 = scrutinee, 1..n = branches; Constr 0..n-1 = arguments; one-child nodes 0.
Top-down rewrite: calls f on a node, then rewrites the children of the result [TT-10]. Calls f once per node and does not call it again on its own result [TT-11]. Returns t itself when nothing changed [TT-12].
Top-down rewrite: calls f on a node, then rewrites the children of the result [TT-10]. Calls f once per node and does not call it again on its own result [TT-11]. Returns t itself when nothing changed [TT-12].
Bottom-up rewrite: rewrites all children of a node, then calls f on the rebuilt node [TT-9]. Calls f once per node [TT-11]. Returns t itself when nothing changed [TT-12].
Bottom-up rewrite: rewrites all children of a node, then calls f on the rebuilt node [TT-9]. Calls f once per node [TT-11]. Returns t itself when nothing changed [TT-12].
Attributes
inline def visit(inline enter: Term => Boolean)(inline exit: Term => Unit): Unit
Walks t in pre-order.
Walks t in pre-order.
Calls enter on a node before its children [TT-3]. When enter returns false, the children of that node are skipped [TT-4]. Calls exit once on every entered node, after all its children [TT-5]. A pass can keep scope state in enter/exit, for example push a binder on LamAbs enter and pop it on exit.