Skip to content

Let-expression traversal

These functions walk the let-expression AST with attention to binders: they find the free names of an expression (pure expressions) and substitute without capturing a variable. Replacing an outer x, for instance, must not replace an unrelated x bound by an inner lambda.

LetExprExtension lets a downstream IR expose additional binder-free nodes through the same operations. Its adapter provides children and reconstruction; canonical traversal retains control of scope and capture avoidance. substitute_let_expr can also use a separate replacement in direct index positions, so a target's index origin does not require another substitution implementation.

map_let_expr also accepts a descend predicate for target-specific traversal boundaries. A renderer can keep an indexed array opaque while rewriting its subscripts, then use the shared reconstruction for every other constructor. This separates array-layout policy from AST coverage; it does not replace the binder-aware substitution used for variable renaming.

let_expr_traversal

Exhaustive, binder-aware operations over the shared let-expression AST.

The native compiler, QIEC elaborator, and transpilation preflight all consume the same expression nodes. Keeping their recursive walks here makes adding a new node an explicit cross-surface change: an unrecognised variant raises instead of being silently treated as a leaf.

LetExprExtension

Bases: Protocol

Expose binder-free downstream expressions to canonical traversal.

An adapter lists every expression child in a stable order and rebuilds its node over children in that same order. It preserves all other fields. An extension cannot introduce a binder; binder scope and capture avoidance are defined by the shared surface AST, independently of the downstream IR.

children

children(node: LetExprNode) -> tuple[LetExprNode, ...] | None

Read the direct children of a supported extension.

PARAMETER DESCRIPTION
node

Expression that is not a canonical surface variant.

TYPE: LetExprNode

RETURNS DESCRIPTION
tuple[LetExprNode, ...] or None

All expression children in source order, or None for an unsupported node. An empty tuple denotes a supported leaf.

Source code in src/quivers/dsl/let_expr_traversal.py
def children(
    self, node: surface.LetExprNode
) -> tuple[surface.LetExprNode, ...] | None:
    """Read the direct children of a supported extension.

    Parameters
    ----------
    node : LetExprNode
        Expression that is not a canonical surface variant.

    Returns
    -------
    tuple[LetExprNode, ...] or None
        All expression children in source order, or None for an unsupported
        node. An empty tuple denotes a supported leaf.
    """
    ...

rebuild

rebuild(node: LetExprNode, children: tuple[LetExprNode, ...]) -> LetExprNode

Rebuild an extension without changing its non-expression metadata.

PARAMETER DESCRIPTION
node

Supported extension previously read by children.

TYPE: LetExprNode

children

Rewritten operands in the same order and arity.

TYPE: tuple[LetExprNode, ...]

RETURNS DESCRIPTION
LetExprNode

The reconstructed extension, retaining its other fields.

Source code in src/quivers/dsl/let_expr_traversal.py
def rebuild(
    self, node: surface.LetExprNode, children: tuple[surface.LetExprNode, ...]
) -> surface.LetExprNode:
    """Rebuild an extension without changing its non-expression metadata.

    Parameters
    ----------
    node : LetExprNode
        Supported extension previously read by children.
    children : tuple[LetExprNode, ...]
        Rewritten operands in the same order and arity.

    Returns
    -------
    LetExprNode
        The reconstructed extension, retaining its other fields.
    """
    ...

let_expr_children

let_expr_children(expr: LetExprNode, *, extension: LetExprExtension | None = None) -> tuple[LetExprNode, ...]

Return the immediate expression children of expr in source order.

PARAMETER DESCRIPTION
expr

The expression to take apart.

TYPE: LetExprNode

extension

Child/rebuild adapter for binder-free nodes owned by a downstream IR.

TYPE: LetExprExtension or None DEFAULT: None

RETURNS DESCRIPTION
tuple[LetExprNode, ...]

The direct subexpressions, empty for a leaf.

RAISES DESCRIPTION
TypeError

If expr is a let-expression variant this function does not cover.

Source code in src/quivers/dsl/let_expr_traversal.py
def let_expr_children(
    expr: surface.LetExprNode, *, extension: LetExprExtension | None = None
) -> tuple[surface.LetExprNode, ...]:
    """Return the immediate expression children of ``expr`` in source order.

    Parameters
    ----------
    expr : LetExprNode
        The expression to take apart.
    extension : LetExprExtension or None
        Child/rebuild adapter for binder-free nodes owned by a downstream IR.

    Returns
    -------
    tuple[LetExprNode, ...]
        The direct subexpressions, empty for a leaf.

    Raises
    ------
    TypeError
        If ``expr`` is a let-expression variant this function does not
        cover.
    """
    if isinstance(
        expr,
        surface.LetExprLiteral
        | surface.LetExprBool
        | surface.LetExprUnit
        | surface.LetExprVar
        | surface.LetExprString
        | LetExprHole,
    ):
        return ()
    if isinstance(expr, surface.LetExprBinOp):
        return (expr.left, expr.right)
    if isinstance(expr, surface.LetExprUnaryOp):
        return (expr.operand,)
    if isinstance(expr, surface.LetExprCall):
        return expr.args
    if isinstance(expr, surface.LetExprIndex):
        return (expr.array, *expr.indices)
    if isinstance(expr, surface.LetExprList | surface.LetExprTuple):
        return expr.items
    if isinstance(expr, surface.LetExprLambda):
        return (expr.body,)
    if isinstance(expr, surface.LetExprFactor):
        body = () if expr.body is None else (expr.body,)
        return (*body, *(case.value for case in expr.cases))
    if isinstance(expr, surface.LetExprMethodCall):
        return (expr.receiver, *expr.args)
    if isinstance(expr, surface.QiecConstructorValue):
        return expr.fields
    if isinstance(expr, surface.QiecAnnotatedValue):
        return (expr.value,)
    if isinstance(expr, LetExprRecord):
        base = () if expr.base is None else (expr.base,)
        return (*base, *(field.value for field in expr.fields))
    if isinstance(expr, LetExprInjection):
        return () if expr.payload is None else (expr.payload,)
    if isinstance(expr, LetExprProjection):
        return (expr.record,)
    if isinstance(expr, LetExprCaseValue):
        return tuple(branch.body for branch in expr.branches)
    if isinstance(expr, LetExprTabulation | LetExprReduction):
        return (expr.body,)
    if extension is not None and (children := extension.children(expr)) is not None:
        return children
    raise TypeError(
        f"let_expr_children: unsupported let-expression variant {type(expr).__name__}"
    )

walk_let_expr

walk_let_expr(expr: LetExprNode, *, extension: LetExprExtension | None = None) -> Iterator[LetExprNode]

Yield expr and all descendants in preorder.

PARAMETER DESCRIPTION
expr

The root of the walk.

TYPE: LetExprNode

extension

Child/rebuild adapter for binder-free downstream IR nodes.

TYPE: LetExprExtension or None DEFAULT: None

YIELDS DESCRIPTION
LetExprNode

expr first, then each subexpression before its own children.

RAISES DESCRIPTION
TypeError

If the walk reaches an unsupported let-expression variant.

Source code in src/quivers/dsl/let_expr_traversal.py
def walk_let_expr(
    expr: surface.LetExprNode, *, extension: LetExprExtension | None = None
) -> Iterator[surface.LetExprNode]:
    """Yield ``expr`` and all descendants in preorder.

    Parameters
    ----------
    expr : LetExprNode
        The root of the walk.
    extension : LetExprExtension or None
        Child/rebuild adapter for binder-free downstream IR nodes.

    Yields
    ------
    LetExprNode
        ``expr`` first, then each subexpression before its own children.

    Raises
    ------
    TypeError
        If the walk reaches an unsupported let-expression variant.
    """
    yield expr
    for child in let_expr_children(expr, extension=extension):
        yield from walk_let_expr(child, extension=extension)

map_let_expr

map_let_expr(expr: LetExprNode, transform: Callable[[LetExprNode], LetExprNode], *, extension: LetExprExtension | None = None, descend: Callable[[LetExprNode], bool] | None = None) -> LetExprNode

Rebuild expr bottom-up, applying transform at every node.

Each node is first rebuilt over its rewritten children and then passed to transform, so transform sees a node whose subexpressions are already rewritten. The rebuild is structural and does not track binders, so a rewrite of variable names belongs in substitute_let_expr.

PARAMETER DESCRIPTION
expr

The root of the rewrite.

TYPE: LetExprNode

transform

The rewrite applied to each rebuilt node.

TYPE: Callable[[LetExprNode], LetExprNode]

extension

Child/rebuild adapter for binder-free downstream IR nodes.

TYPE: LetExprExtension or None DEFAULT: None

descend

Whether to rewrite a node's children before applying transform. A false result leaves child traversal to the transform, for instance when a target indexes subscripts but keeps an existing array opaque.

TYPE: Callable[[LetExprNode], bool] or None DEFAULT: None

RETURNS DESCRIPTION
LetExprNode

The rewritten expression.

RAISES DESCRIPTION
TypeError

If the rewrite reaches an unsupported let-expression variant.

Source code in src/quivers/dsl/let_expr_traversal.py
def map_let_expr(
    expr: surface.LetExprNode,
    transform: Callable[[surface.LetExprNode], surface.LetExprNode],
    *,
    extension: LetExprExtension | None = None,
    descend: Callable[[surface.LetExprNode], bool] | None = None,
) -> surface.LetExprNode:
    """Rebuild ``expr`` bottom-up, applying ``transform`` at every node.

    Each node is first rebuilt over its rewritten children and then
    passed to ``transform``, so ``transform`` sees a node whose
    subexpressions are already rewritten. The rebuild is structural and
    does not track binders, so a rewrite of variable names belongs in
    `substitute_let_expr`.

    Parameters
    ----------
    expr : LetExprNode
        The root of the rewrite.
    transform : Callable[[LetExprNode], LetExprNode]
        The rewrite applied to each rebuilt node.
    extension : LetExprExtension or None
        Child/rebuild adapter for binder-free downstream IR nodes.
    descend : Callable[[LetExprNode], bool] or None
        Whether to rewrite a node's children before applying ``transform``.
        A false result leaves child traversal to the transform, for instance
        when a target indexes subscripts but keeps an existing array opaque.

    Returns
    -------
    LetExprNode
        The rewritten expression.

    Raises
    ------
    TypeError
        If the rewrite reaches an unsupported let-expression variant.
    """

    def rebuild(node: surface.LetExprNode) -> surface.LetExprNode:
        """Rebuild an expression with the rewrite applied below it.

        Parameters
        ----------
        node : surface.LetExprNode
            The expression.

        Returns
        -------
        surface.LetExprNode
            The rebuilt expression.
        """
        if descend is not None and not descend(node):
            return transform(node)
        if isinstance(
            node,
            surface.LetExprLiteral
            | surface.LetExprBool
            | surface.LetExprUnit
            | surface.LetExprVar
            | surface.LetExprString
            | LetExprHole,
        ):
            return transform(node)
        if isinstance(node, surface.LetExprBinOp):
            return transform(
                node.with_(left=rebuild(node.left), right=rebuild(node.right))
            )
        if isinstance(node, surface.LetExprUnaryOp):
            return transform(node.with_(operand=rebuild(node.operand)))
        if isinstance(node, surface.LetExprCall):
            return transform(node.with_(args=tuple(map(rebuild, node.args))))
        if isinstance(node, surface.LetExprIndex):
            return transform(
                node.with_(
                    array=rebuild(node.array),
                    indices=tuple(map(rebuild, node.indices)),
                )
            )
        if isinstance(node, surface.LetExprList | surface.LetExprTuple):
            return transform(node.with_(items=tuple(map(rebuild, node.items))))
        if isinstance(node, surface.LetExprLambda):
            return transform(node.with_(body=rebuild(node.body)))
        if isinstance(node, surface.LetExprFactor):
            return transform(
                node.with_(
                    body=None if node.body is None else rebuild(node.body),
                    cases=tuple(
                        case.with_(value=rebuild(case.value)) for case in node.cases
                    ),
                )
            )
        if isinstance(node, surface.LetExprMethodCall):
            return transform(
                node.with_(
                    receiver=rebuild(node.receiver),
                    args=tuple(map(rebuild, node.args)),
                )
            )
        if isinstance(node, surface.QiecConstructorValue):
            return transform(node.with_(fields=tuple(map(rebuild, node.fields))))
        if isinstance(node, surface.QiecAnnotatedValue):
            return transform(node.with_(value=rebuild(node.value)))
        if isinstance(node, LetExprRecord):
            return transform(
                node.with_(
                    base=None if node.base is None else rebuild(node.base),
                    fields=tuple(
                        field.with_(value=rebuild(field.value)) for field in node.fields
                    ),
                )
            )
        if isinstance(node, LetExprInjection):
            return transform(
                node.with_(
                    payload=None if node.payload is None else rebuild(node.payload)
                )
            )
        if isinstance(node, LetExprProjection):
            return transform(node.with_(record=rebuild(node.record)))
        if isinstance(node, LetExprCaseValue):
            return transform(
                node.with_(
                    branches=tuple(
                        branch.with_(body=rebuild(branch.body))
                        for branch in node.branches
                    )
                )
            )
        if isinstance(node, LetExprTabulation | LetExprReduction):
            return transform(node.with_(body=rebuild(node.body)))
        if extension is not None and (children := extension.children(node)) is not None:
            return transform(extension.rebuild(node, tuple(map(rebuild, children))))
        raise TypeError(
            f"map_let_expr: unsupported let-expression variant {type(node).__name__}"
        )

    return rebuild(expr)

free_let_names

free_let_names(expr: LetExprNode, *, bound: frozenset[str] = frozenset(), include_callees: bool = False, extension: LetExprExtension | None = None) -> tuple[str, ...]

Return free value names in first-use order.

Lambda parameters and factor indices bind in their bodies. Call names are declarations by default; callers that model a callee as a host value can include them explicitly.

PARAMETER DESCRIPTION
expr

The expression to scan.

TYPE: LetExprNode

bound

Names already bound around expr, which are not free.

TYPE: frozenset[str] DEFAULT: frozenset()

include_callees

Whether the function name of a call counts as a free name.

TYPE: bool DEFAULT: False

extension

Child/rebuild adapter for binder-free downstream IR nodes.

TYPE: LetExprExtension or None DEFAULT: None

RETURNS DESCRIPTION
tuple[str, ...]

Each free name once, in the order of its first occurrence.

RAISES DESCRIPTION
TypeError

If the scan reaches an unsupported let-expression variant.

Source code in src/quivers/dsl/let_expr_traversal.py
def free_let_names(
    expr: surface.LetExprNode,
    *,
    bound: frozenset[str] = frozenset(),
    include_callees: bool = False,
    extension: LetExprExtension | None = None,
) -> tuple[str, ...]:
    """Return free value names in first-use order.

    Lambda parameters and factor indices bind in their bodies. Call names are
    declarations by default; callers that model a callee as a host value can
    include them explicitly.

    Parameters
    ----------
    expr : LetExprNode
        The expression to scan.
    bound : frozenset[str]
        Names already bound around ``expr``, which are not free.
    include_callees : bool
        Whether the function name of a call counts as a free name.
    extension : LetExprExtension or None
        Child/rebuild adapter for binder-free downstream IR nodes.

    Returns
    -------
    tuple[str, ...]
        Each free name once, in the order of its first occurrence.

    Raises
    ------
    TypeError
        If the scan reaches an unsupported let-expression variant.
    """
    found: list[str] = []

    def visit(node: surface.LetExprNode, local_bound: frozenset[str]) -> None:
        if isinstance(node, surface.LetExprVar):
            if node.name not in local_bound and node.name not in found:
                found.append(node.name)
            return
        if isinstance(node, surface.LetExprCall):
            if (
                include_callees
                and node.func not in local_bound
                and node.func not in found
            ):
                found.append(node.func)
            for argument in node.args:
                visit(argument, local_bound)
            return
        if isinstance(node, surface.LetExprLambda):
            visit(node.body, local_bound | {node.param})
            return
        if isinstance(node, surface.LetExprFactor):
            inner = local_bound | {binder.var for binder in node.binders}
            if node.body is not None:
                visit(node.body, inner)
            for case in node.cases:
                visit(case.value, inner)
            return
        if isinstance(node, LetExprTabulation | LetExprReduction):
            visit(node.body, local_bound | {binder.name for binder in node.binders})
            return
        if isinstance(node, LetExprCaseValue):
            for branch in node.branches:
                visit(
                    branch.body,
                    local_bound
                    if branch.binder is None
                    else local_bound | {branch.binder},
                )
            return
        for child in let_expr_children(node, extension=extension):
            visit(child, local_bound)

    visit(expr, bound)
    return tuple(found)

free_let_callees

free_let_callees(expr: LetExprNode, *, bound: frozenset[str] = frozenset(), extension: LetExprExtension | None = None) -> tuple[str, ...]

Return the free callee names of calls in first-use order.

A call f(...) whose f is not bound by an enclosing lambda parameter or factor index contributes f.

PARAMETER DESCRIPTION
expr

The expression to scan.

TYPE: LetExprNode

bound

Names already bound around expr, which are not free.

TYPE: frozenset[str] DEFAULT: frozenset()

extension

Child/rebuild adapter for binder-free downstream IR nodes.

TYPE: LetExprExtension or None DEFAULT: None

RETURNS DESCRIPTION
tuple[str, ...]

Each free callee once, in the order of its first occurrence.

RAISES DESCRIPTION
TypeError

If the scan reaches an unsupported let-expression variant.

Source code in src/quivers/dsl/let_expr_traversal.py
def free_let_callees(
    expr: surface.LetExprNode,
    *,
    bound: frozenset[str] = frozenset(),
    extension: LetExprExtension | None = None,
) -> tuple[str, ...]:
    """Return the free callee names of calls in first-use order.

    A call ``f(...)`` whose ``f`` is not bound by an enclosing lambda
    parameter or factor index contributes ``f``.

    Parameters
    ----------
    expr : LetExprNode
        The expression to scan.
    bound : frozenset[str]
        Names already bound around ``expr``, which are not free.
    extension : LetExprExtension or None
        Child/rebuild adapter for binder-free downstream IR nodes.

    Returns
    -------
    tuple[str, ...]
        Each free callee once, in the order of its first occurrence.

    Raises
    ------
    TypeError
        If the scan reaches an unsupported let-expression variant.
    """
    found: list[str] = []

    def visit(node: surface.LetExprNode, local_bound: frozenset[str]) -> None:
        if isinstance(node, surface.LetExprCall):
            if node.func not in local_bound and node.func not in found:
                found.append(node.func)
        elif isinstance(node, surface.LetExprLambda):
            visit(node.body, local_bound | {node.param})
            return
        elif isinstance(node, surface.LetExprFactor):
            inner = local_bound | {binder.var for binder in node.binders}
            for child in let_expr_children(node, extension=extension):
                visit(child, inner)
            return
        elif isinstance(node, LetExprTabulation | LetExprReduction):
            visit(node.body, local_bound | {binder.name for binder in node.binders})
            return
        elif isinstance(node, LetExprCaseValue):
            for branch in node.branches:
                visit(
                    branch.body,
                    local_bound
                    if branch.binder is None
                    else local_bound | {branch.binder},
                )
            return
        for child in let_expr_children(node, extension=extension):
            visit(child, local_bound)

    visit(expr, bound)
    return tuple(found)

substitute_let_expr

substitute_let_expr(expr: LetExprNode, substitution: Mapping[str, LetExprNode], *, callees: Mapping[str, str] | None = None, index_substitution: Mapping[str, LetExprNode] | None = None, extension: LetExprExtension | None = None) -> LetExprNode

Substitute expressions for free variables in expr without capture.

A lambda parameter or factor binder that would capture a free name of a replacement is renamed to a fresh name first.

PARAMETER DESCRIPTION
expr

The expression to rewrite.

TYPE: LetExprNode

substitution

The replacement for each free variable name.

TYPE: Mapping[str, LetExprNode]

callees

The replacement name for each free callee of a call f(...). A callee bound by an enclosing lambda or factor is not free and keeps its name; a binder that would capture a replacement callee name is renamed like any other capture.

TYPE: Mapping[str, str] or None DEFAULT: None

index_substitution

Optional overrides in the direct index positions of an indexing node. All other positions use substitution. This preserves the separate value and index origins of a target language without a second walk.

TYPE: Mapping[str, LetExprNode] or None DEFAULT: None

extension

Child/rebuild adapter for binder-free downstream IR nodes. Extensions add structural cases; scope and capture avoidance remain in this walk.

TYPE: LetExprExtension or None DEFAULT: None

RETURNS DESCRIPTION
LetExprNode

expr with every free occurrence of a key replaced.

RAISES DESCRIPTION
TypeError

If the rewrite reaches an unsupported let-expression variant.

Source code in src/quivers/dsl/let_expr_traversal.py
def substitute_let_expr(
    expr: surface.LetExprNode,
    substitution: Mapping[str, surface.LetExprNode],
    *,
    callees: Mapping[str, str] | None = None,
    index_substitution: Mapping[str, surface.LetExprNode] | None = None,
    extension: LetExprExtension | None = None,
) -> surface.LetExprNode:
    """Substitute expressions for free variables in ``expr`` without capture.

    A lambda parameter or factor binder that would capture a free name of a
    replacement is renamed to a fresh name first.

    Parameters
    ----------
    expr : LetExprNode
        The expression to rewrite.
    substitution : Mapping[str, LetExprNode]
        The replacement for each free variable name.
    callees : Mapping[str, str] or None
        The replacement name for each free callee of a call
        ``f(...)``. A callee bound by an enclosing lambda or factor is
        not free and keeps its name; a binder that would capture a
        replacement callee name is renamed like any other capture.
    index_substitution : Mapping[str, LetExprNode] or None
        Optional overrides in the direct index positions of an indexing node.
        All other positions use ``substitution``. This preserves the separate
        value and index origins of a target language without a second walk.
    extension : LetExprExtension or None
        Child/rebuild adapter for binder-free downstream IR nodes. Extensions
        add structural cases; scope and capture avoidance remain in this walk.

    Returns
    -------
    LetExprNode
        ``expr`` with every free occurrence of a key replaced.

    Raises
    ------
    TypeError
        If the rewrite reaches an unsupported let-expression variant.
    """
    callee_map: Mapping[str, str] = {} if callees is None else callees
    index_map = (
        substitution
        if index_substitution is None
        else dict(substitution) | dict(index_substitution)
    )

    def free_names(
        node: surface.LetExprNode, *, include_callees: bool = False
    ) -> tuple[str, ...]:
        """Read free names through the same structural extension boundary."""
        return free_let_names(
            node, include_callees=include_callees, extension=extension
        )

    occupied = set(free_names(expr, include_callees=True))
    replacement_maps = (
        (substitution,) if index_map is substitution else (substitution, index_map)
    )
    for replacements in replacement_maps:
        for replacement in replacements.values():
            occupied.update(free_names(replacement, include_callees=True))
    occupied.update(callee_map.values())
    for node in walk_let_expr(expr, extension=extension):
        if isinstance(node, surface.LetExprLambda):
            occupied.add(node.param)
        elif isinstance(node, surface.LetExprFactor):
            occupied.update(binder.var for binder in node.binders)
        elif isinstance(node, LetExprTabulation | LetExprReduction):
            occupied.update(binder.name for binder in node.binders)
        elif isinstance(node, LetExprCaseValue):
            occupied.update(
                branch.binder for branch in node.branches if branch.binder is not None
            )

    def fresh(base: str) -> str:
        suffix = 1
        candidate = f"{base}_{suffix}"
        while candidate in occupied:
            suffix += 1
            candidate = f"{base}_{suffix}"
        occupied.add(candidate)
        return candidate

    def replacement_names(
        active: Mapping[str, surface.LetExprNode],
        active_indices: Mapping[str, surface.LetExprNode],
        active_callees: Mapping[str, str],
        body: surface.LetExprNode,
    ) -> set[str]:
        used_keys = set(free_names(body))
        replacements_by_slot = (
            (active,) if active_indices is active else (active, active_indices)
        )
        names = {
            name
            for replacements in replacements_by_slot
            for key in used_keys & replacements.keys()
            for name in free_names(replacements[key], include_callees=True)
        }
        used_callees = set(free_names(body, include_callees=True))
        names.update(
            active_callees[key] for key in used_callees & active_callees.keys()
        )
        return names

    def replace(
        node: surface.LetExprNode,
        active: Mapping[str, surface.LetExprNode],
        active_callees: Mapping[str, str],
        active_indices: Mapping[str, surface.LetExprNode],
        *,
        in_index_slot: bool = False,
    ) -> surface.LetExprNode:
        if isinstance(node, surface.LetExprVar):
            table = active_indices if in_index_slot else active
            replaced = table.get(node.name)
            if replaced is not None:
                return replaced
            head, _, members = node.name.partition(".")
            if members and head in table:
                return _member_access(table[head], members, node)
            return node

        def rewrite(child: surface.LetExprNode) -> surface.LetExprNode:
            """Recurse into an ordinary value position, retaining active scopes."""
            return replace(child, active, active_callees, active_indices)

        if isinstance(
            node,
            surface.LetExprLiteral
            | surface.LetExprBool
            | surface.LetExprUnit
            | surface.LetExprString
            | LetExprHole,
        ):
            return node
        if isinstance(node, surface.LetExprBinOp):
            return node.with_(
                left=rewrite(node.left),
                right=rewrite(node.right),
            )
        if isinstance(node, surface.LetExprUnaryOp):
            return node.with_(operand=rewrite(node.operand))
        if isinstance(node, surface.LetExprCall):
            return node.with_(
                func=active_callees.get(node.func, node.func),
                args=tuple(map(rewrite, node.args)),
            )
        if isinstance(node, surface.LetExprIndex):
            return node.with_(
                array=rewrite(node.array),
                indices=tuple(
                    replace(
                        item, active, active_callees, active_indices, in_index_slot=True
                    )
                    for item in node.indices
                ),
            )
        if isinstance(node, surface.LetExprList | surface.LetExprTuple):
            return node.with_(items=tuple(map(rewrite, node.items)))
        if isinstance(node, surface.LetExprLambda):
            inner = {key: value for key, value in active.items() if key != node.param}
            inner_indices = (
                inner
                if active_indices is active
                else {
                    key: value
                    for key, value in active_indices.items()
                    if key != node.param
                }
            )
            inner_callees = {
                key: value for key, value in active_callees.items() if key != node.param
            }
            param = node.param
            body = node.body
            if param in replacement_names(inner, inner_indices, inner_callees, body):
                renamed = fresh(param)
                alpha = {
                    param: surface.LetExprVar(
                        name=renamed, line=node.line, col=node.col
                    )
                }
                body = replace(
                    body,
                    alpha,
                    {param: renamed},
                    alpha,
                )
                param = renamed
            return node.with_(
                param=param, body=replace(body, inner, inner_callees, inner_indices)
            )
        if isinstance(node, surface.LetExprFactor):
            bound = {binder.var for binder in node.binders}
            inner = {key: value for key, value in active.items() if key not in bound}
            inner_indices = (
                inner
                if active_indices is active
                else {
                    key: value
                    for key, value in active_indices.items()
                    if key not in bound
                }
            )
            inner_callees = {
                key: value for key, value in active_callees.items() if key not in bound
            }
            bodies = (() if node.body is None else (node.body,)) + tuple(
                case.value for case in node.cases
            )
            captures = {
                name
                for body in bodies
                for name in replacement_names(inner, inner_indices, inner_callees, body)
            }
            binders = list(node.binders)
            body = node.body
            cases = node.cases
            for position, binder in enumerate(binders):
                if binder.var not in captures:
                    continue
                renamed = fresh(binder.var)
                alpha = {
                    binder.var: surface.LetExprVar(
                        name=renamed,
                        line=binder.line,
                        col=binder.col,
                    )
                }
                alpha_callees = {binder.var: renamed}
                body = (
                    None if body is None else replace(body, alpha, alpha_callees, alpha)
                )
                cases = tuple(
                    case.with_(value=replace(case.value, alpha, alpha_callees, alpha))
                    for case in cases
                )
                binders[position] = binder.with_(var=renamed)
            return node.with_(
                binders=tuple(binders),
                body=None
                if body is None
                else replace(body, inner, inner_callees, inner_indices),
                cases=tuple(
                    case.with_(
                        value=replace(case.value, inner, inner_callees, inner_indices)
                    )
                    for case in cases
                ),
            )
        if isinstance(node, LetExprTabulation | LetExprReduction):
            bound = {binder.name for binder in node.binders}
            inner = {key: value for key, value in active.items() if key not in bound}
            inner_indices = (
                inner
                if active_indices is active
                else {
                    key: value
                    for key, value in active_indices.items()
                    if key not in bound
                }
            )
            inner_callees = {
                key: value for key, value in active_callees.items() if key not in bound
            }
            captures = replacement_names(inner, inner_indices, inner_callees, node.body)
            axis_binders = list(node.binders)
            body = node.body
            for position, binder in enumerate(axis_binders):
                if binder.name not in captures:
                    continue
                renamed = fresh(binder.name)
                alpha = {
                    binder.name: surface.LetExprVar(
                        name=renamed, line=binder.line, col=binder.col
                    )
                }
                body = replace(body, alpha, {binder.name: renamed}, alpha)
                axis_binders[position] = binder.with_(name=renamed)
            return node.with_(
                binders=tuple(axis_binders),
                body=replace(body, inner, inner_callees, inner_indices),
            )
        if isinstance(node, surface.LetExprMethodCall):
            return node.with_(
                receiver=rewrite(node.receiver),
                args=tuple(map(rewrite, node.args)),
            )
        if isinstance(node, surface.QiecConstructorValue):
            return node.with_(fields=tuple(map(rewrite, node.fields)))
        if isinstance(node, surface.QiecAnnotatedValue):
            return node.with_(value=rewrite(node.value))
        if isinstance(node, LetExprRecord):
            return node.with_(
                base=None if node.base is None else rewrite(node.base),
                fields=tuple(
                    field.with_(value=rewrite(field.value)) for field in node.fields
                ),
            )
        if isinstance(node, LetExprInjection):
            return node.with_(
                payload=None if node.payload is None else rewrite(node.payload)
            )
        if isinstance(node, LetExprProjection):
            return node.with_(record=rewrite(node.record))
        if isinstance(node, LetExprCaseValue):
            branches = []
            for branch in node.branches:
                if branch.binder is None:
                    branches.append(branch.with_(body=rewrite(branch.body)))
                    continue
                binder = branch.binder
                inner = {key: value for key, value in active.items() if key != binder}
                inner_indices = (
                    inner
                    if active_indices is active
                    else {
                        key: value
                        for key, value in active_indices.items()
                        if key != binder
                    }
                )
                inner_callees = {
                    key: value for key, value in active_callees.items() if key != binder
                }
                body = branch.body
                if binder in replacement_names(
                    inner, inner_indices, inner_callees, body
                ):
                    renamed = fresh(binder)
                    alpha = {
                        binder: surface.LetExprVar(
                            name=renamed, line=branch.line, col=branch.col
                        )
                    }
                    body = replace(body, alpha, {binder: renamed}, alpha)
                    binder = renamed
                branches.append(
                    branch.with_(
                        binder=binder,
                        body=replace(body, inner, inner_callees, inner_indices),
                    )
                )
            return node.with_(branches=tuple(branches))
        if extension is not None and (children := extension.children(node)) is not None:
            return extension.rebuild(node, tuple(map(rewrite, children)))
        raise TypeError(
            f"substitute_let_expr: unsupported let-expression variant "
            f"{type(node).__name__}"
        )

    return replace(expr, substitution, callee_map, index_map)