Lua.AST.Walker (Lua v1.0.0-rc.1)
View SourceAST traversal utilities using the visitor pattern.
Provides functions for walking, mapping, and reducing over AST nodes.
Examples
# Simple traversal (side effects)
Walker.walk(ast, fn node ->
IO.inspect(node)
end)
# Transform AST (double all numbers)
Walker.map(ast, fn
%Expr.Number{value: n} = node -> %{node | value: n * 2}
node -> node
end)
# Accumulate values (collect all variable names)
Walker.reduce(ast, [], fn
%Expr.Var{name: name}, acc -> [name | acc]
_node, acc -> acc
end)
# Post-order traversal
Walker.walk(ast, fn node -> ... end, order: :post)
Summary
Functions
Maps over the AST, transforming nodes with the mapper function.
Reduces the AST to a single value by calling the reducer function for each node.
Walks the AST, calling the visitor function for each node.
Types
@type ast_node() :: Lua.AST.Chunk.t() | Lua.AST.Block.t() | Lua.AST.Expr.t() | Lua.AST.Statement.t()
@type order() :: :pre | :post
Functions
Maps over the AST, transforming nodes with the mapper function.
The mapper is called in post-order (children before parent) to ensure transformations propagate upward correctly.
Examples
# Double all numbers
Walker.map(ast, fn
%Expr.Number{value: n} = node -> %{node | value: n * 2}
node -> node
end)
Reduces the AST to a single value by calling the reducer function for each node.
The reducer is called in pre-order by default.
Examples
# Collect all variable names
Walker.reduce(ast, [], fn
%Expr.Var{name: name}, acc -> [name | acc]
_node, acc -> acc
end)
# Count all nodes
Walker.reduce(ast, 0, fn _node, acc -> acc + 1 end)
Walks the AST, calling the visitor function for each node.
The visitor is called in pre-order by default (parent before children).
Use order: :post for post-order traversal (children before parent).
Options
:order-:pre(default) or:post
Examples
Walker.walk(ast, fn
%Expr.Number{value: n} -> IO.puts("Found number: #{n}")
_node -> :ok
end)