Lua.AST.Walker (Lua v1.0.0-rc.1)

View Source

AST 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

ast_node()

mapper()

@type mapper() :: (ast_node() -> ast_node())

order()

@type order() :: :pre | :post

reducer()

@type reducer() :: (ast_node(), acc :: any() -> any())

visitor()

@type visitor() :: (ast_node() -> any())

Functions

map(node, mapper)

@spec map(ast_node(), mapper()) :: ast_node()

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)

reduce(node, initial, reducer)

@spec reduce(ast_node(), acc, reducer()) :: acc when acc: any()

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)

walk(node, visitor, opts \\ [])

@spec walk(ast_node(), visitor(), keyword()) :: :ok

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)