Skip to content

Index

Apply dataclass

Bases: Value

a pure operator applied to values

Source code in src/finch/symbolic/value_numbering.py
@dataclass(eq=False, frozen=True)
class Apply(Value):
    """a pure operator applied to values"""

    op: Hashable
    args: tuple[Value, ...]

BasicBlock

Linear sequence of statements with a single entry and exit.

Successor/predecessor lists encode the CFG edges. Statements execute in order; no internal branching occurs within a BasicBlock.

Source code in src/finch/symbolic/dataflow.py
class BasicBlock:
    """Linear sequence of statements with a single entry and exit.

    Successor/predecessor lists encode the CFG edges. Statements execute in
    order; no internal branching occurs within a BasicBlock.
    """

    def __init__(self, id: str) -> None:
        self.id = id
        self.statements: list = []
        self.successors: list[BasicBlock] = []
        self.predecessors: list[BasicBlock] = []

    def add_statement(self, statement) -> None:
        self.statements.append(statement)

    def add_successor(self, successor: "BasicBlock") -> None:
        if successor not in self.successors:
            self.successors.append(successor)

        if self not in successor.predecessors:
            successor.predecessors.append(self)

    def __str__(self) -> str:
        """String representation of BasicBlock in LLVM style."""
        lines = []

        if self.successors:
            succ_names = [succ.id for succ in self.successors]
            succ_str = f" #succs=[{', '.join(succ_names)}]"
        else:
            succ_str = " #succs=[]"

        # Block header
        lines.append(f"{self.id}:{succ_str}")

        # Block statements
        lines.extend(f"    {stmt}" for stmt in self.statements)

        return "\n".join(lines)

__str__()

String representation of BasicBlock in LLVM style.

Source code in src/finch/symbolic/dataflow.py
def __str__(self) -> str:
    """String representation of BasicBlock in LLVM style."""
    lines = []

    if self.successors:
        succ_names = [succ.id for succ in self.successors]
        succ_str = f" #succs=[{', '.join(succ_names)}]"
    else:
        succ_str = " #succs=[]"

    # Block header
    lines.append(f"{self.id}:{succ_str}")

    # Block statements
    lines.extend(f"    {stmt}" for stmt in self.statements)

    return "\n".join(lines)

CallTerm dataclass

Bases: TermTree, ABC

A tree term which applies the operator computed by the expression op to args.

Source code in src/finch/symbolic/term.py
@dataclass(frozen=True, eq=True)
class CallTerm(TermTree, ABC):
    """
    A tree term which applies the operator computed by the expression `op` to `args`.
    """

    op: ExpressionTerm
    args: tuple[Term, ...]

Chain

Bases: Generic[T]

A rewriter which rewrites using each rewriter in itr. If all rewriters return nothing, return nothing.

Attributes:

Name Type Description
rws Iterable[RwCallable]

A collection of rewriter functions to apply.

Source code in src/finch/symbolic/rewriters.py
class Chain(Generic[T]):
    """
    A rewriter which rewrites using each rewriter in `itr`. If all rewriters
    return `nothing`, return `nothing`.

    Attributes:
        rws (Iterable[RwCallable]): A collection of rewriter functions to apply.
    """

    def __init__(self, rws: Iterable[RwCallable]):
        self.rws = rws

    def __call__(self, x: T) -> T | None:
        is_success = False
        for rw in self.rws:
            y = rw(x)
            if y is not None:
                is_success = True
                x = y
        if is_success:
            return x
        return None

CompilerMode dataclass

Safe mode checks shared dimensions and tensor extents; debug also checks buffer accesses.

Source code in src/finch/symbolic/stage.py
@dataclass(frozen=True)
class CompilerMode:
    """Safe mode checks shared dimensions and tensor extents; debug also checks
    buffer accesses."""

    safe: bool = False
    debug: bool = False

Constant dataclass

Bases: Value

a literal, interned by its exact type and bits, so 0.0 and -0.0 differ

Source code in src/finch/symbolic/value_numbering.py
@dataclass(eq=False, frozen=True)
class Constant(Value):
    """a literal, interned by its exact type and bits, so `0.0` and `-0.0` differ"""

    val: Any

    @staticmethod
    def canonicalize(a: Any, /) -> tuple[type, Hashable]:
        match a:
            case bool() | int():
                return type(a), a
            case float() | complex() | np.number() | np.bool_():
                return type(a), np.asarray(a).tobytes()
        return HashCons.canonicalize(a)

Context

Bases: ABC

Source code in src/finch/symbolic/environment.py
class Context(ABC):
    def __init__(self, namespace=None, preamble=None, epilogue=None, mode=None):
        self.namespace = namespace if namespace is not None else Namespace()
        self.preamble = preamble if preamble is not None else []
        self.epilogue = epilogue if epilogue is not None else []
        self.mode = mode if mode is not None else CompilerMode()

    def exec(self, thunk: Any):
        self.preamble.append(thunk)

    def post(self, thunk: Any):
        self.epilogue.append(thunk)

    def freshen(self, *tags):
        return self.namespace.freshen(*tags)

    def resolve(self, *names: str):
        return self.namespace.resolve(*names)

    def block(self):
        """
        Create a new block. Preambles and epilogues will stay within this block.
        """
        blk = self.__class__()
        blk.namespace = self.namespace
        blk.preamble = []
        blk.epilogue = []
        blk.mode = self.mode
        return blk

    @abstractmethod
    def emit(self):
        """
        Emit the code in this context.
        """
        ...

block()

Create a new block. Preambles and epilogues will stay within this block.

Source code in src/finch/symbolic/environment.py
def block(self):
    """
    Create a new block. Preambles and epilogues will stay within this block.
    """
    blk = self.__class__()
    blk.namespace = self.namespace
    blk.preamble = []
    blk.epilogue = []
    blk.mode = self.mode
    return blk

emit() abstractmethod

Emit the code in this context.

Source code in src/finch/symbolic/environment.py
@abstractmethod
def emit(self):
    """
    Emit the code in this context.
    """
    ...

ControlFlowGraph

Collection of BasicBlocks plus explicit ENTRY and EXIT nodes.

Provides helpers to allocate uniquely named blocks and holds the global block mapping used by dataflow analyses.

Source code in src/finch/symbolic/dataflow.py
class ControlFlowGraph:
    """Collection of BasicBlocks plus explicit ENTRY and EXIT nodes.

    Provides helpers to allocate uniquely named blocks and holds the global
    block mapping used by dataflow analyses.
    """

    def __init__(self) -> None:
        self.block_counter = 0
        self.block_name = ""
        self.blocks: dict[str, BasicBlock] = {}

        self.entry_block = self.new_block_custom("ENTRY")
        self.exit_block = self.new_block_custom("EXIT")

    def new_block(self) -> BasicBlock:
        bid = f"{self.block_name}_{self.block_counter}"
        self.block_counter += 1
        block = BasicBlock(bid)
        self.blocks[bid] = block
        return block

    def new_block_custom(self, name: str) -> BasicBlock:
        bid = f"{name}_{self.block_counter}"
        self.block_counter += 1
        block = BasicBlock(bid)
        self.blocks[bid] = block
        return block

    def __str__(self) -> str:
        """Print the CFG in LLVM style format."""
        blocks = list(self.blocks.values())

        # Use list comprehension with join for better performance
        block_strings = [str(block) for block in blocks]
        return "\n\n".join(block_strings)

__str__()

Print the CFG in LLVM style format.

Source code in src/finch/symbolic/dataflow.py
def __str__(self) -> str:
    """Print the CFG in LLVM style format."""
    blocks = list(self.blocks.values())

    # Use list comprehension with join for better performance
    block_strings = [str(block) for block in blocks]
    return "\n\n".join(block_strings)

DataFlowAnalysis

Bases: ABC

Base class for performing data flow analyses over a ControlFlowGraph.

This abstract class implements a generic work-list algorithm that can run either in a "forward" or "backward" direction. Subclasses must provide IR-specific semantics by implementing the abstract methods: transfer, join, stmt_str and direction, and may override boundary_state.

only blocks reachable from the boundary block (ENTRY for forward, EXIT for backward) are visited, and joins skip neighbors that weren't processed yet. so loops start optimistic and dead blocks (e.g. after a return) never get joined in. transfer must not mutate its input.

blocks are visited in reverse postorder, so a block is joined after the neighbors before it.

Key attributes - cfg: the ControlFlowGraph to analyze. - input_states: a mapping from basic block id to the state flowing into the block's transfer (its entry for forward, its exit for backward). - output_states: a mapping from basic block id to the state the block's transfer produces. - reached: ids of the blocks visited by analyze.

Source code in src/finch/symbolic/dataflow.py
class DataFlowAnalysis(ABC):
    """
    Base class for performing data flow analyses over a ControlFlowGraph.

    This abstract class implements a generic work-list algorithm that can run either
    in a "forward" or "backward" direction. Subclasses must provide IR-specific
    semantics by implementing the abstract methods: transfer, join, stmt_str and
    direction, and may override boundary_state.

    only blocks reachable from the boundary block (ENTRY for forward, EXIT for
    backward) are visited, and joins skip neighbors that weren't processed yet.
    so loops start optimistic and dead blocks (e.g. after a `return`) never get
    joined in. `transfer` must not mutate its input.

    blocks are visited in reverse postorder, so a block is joined after the
    neighbors before it.

    Key attributes
    - cfg: the ControlFlowGraph to analyze.
    - input_states: a mapping from basic block id to the state flowing into the
        block's transfer (its entry for forward, its exit for backward).
    - output_states: a mapping from basic block id to the state the block's
        transfer produces.
    - reached: ids of the blocks visited by `analyze`.
    """

    def __init__(self, cfg: ControlFlowGraph):
        self.cfg: ControlFlowGraph = cfg
        self.input_states: dict[str, dict] = {
            block.id: {} for block in cfg.blocks.values()
        }
        self.output_states: dict[str, dict] = {
            block.id: {} for block in cfg.blocks.values()
        }
        self.reached: set[str] = set()

    def __str__(self) -> str:
        """
        Return a string representation describing the current dataflow
        analysis state over the control-flow graph (CFG).

        The output lists each basic block in the order
        produced by self.cfg.blocks.values().
        For every block the printed form is:

            <block.id>: #succs=[<succ_id>, ...]
                <stmt_representation_for_first_stmt>
                <stmt_representation_for_second_stmt>
                ...

        statements are annotated with the state flowing into their transfer
        (before them for forward, after them for backward), statements of
        unreached blocks without annotations.
        """
        lines: list[str] = []
        forward = self.direction() == "forward"

        for block in self.cfg.blocks.values():
            succ_names = [succ.id for succ in block.successors]
            lines.append(f"{block.id}: #succs=[{', '.join(succ_names)}]")

            if block.id not in self.reached:
                lines.extend(f"    {stmt}" for stmt in block.statements)
            else:
                # deep copy, so printing never changes the stored states
                state = copy.deepcopy(self.input_states[block.id])
                stmts = block.statements if forward else block.statements[::-1]
                annotated = []
                for stmt in stmts:
                    annotated.append(f"    {self.stmt_str(stmt, state)}")
                    state = self.transfer([stmt], state)
                lines.extend(annotated if forward else annotated[::-1])

            lines.append("")

        return "\n".join(lines)

    @abstractmethod
    def stmt_str(self, stmt, state: dict) -> str:
        """
        Format a single statement given the current lattice state.
        Implement in subclasses or IR-specific abstract bases.
        """
        ...

    @abstractmethod
    def transfer(self, stmts, state: dict) -> dict:
        """
        Transfer function for the data flow analysis.
        This should be implemented by subclasses.
        """
        ...

    @abstractmethod
    def join(self, state_1: dict, state_2: dict) -> dict:
        """
        Join function for the data flow analysis.
        This should be implemented by subclasses.
        """
        ...

    @abstractmethod
    def direction(self) -> str:
        """
        Return the direction of the data flow analysis, either "forward" or "backward".
        This should be implemented by subclasses.
        """
        ...

    def boundary_state(self) -> dict:
        """state at the cfg boundary: out of ENTRY (forward) or into EXIT (backward)"""
        return {}

    def analyze(self) -> None:
        """run the work list until the states of all reached blocks are stable"""
        forward = self.direction() == "forward"
        start = self.cfg.entry_block if forward else self.cfg.exit_block

        def upstream(block: BasicBlock) -> list[BasicBlock]:
            return block.predecessors if forward else block.successors

        def downstream(block: BasicBlock) -> list[BasicBlock]:
            return block.successors if forward else block.predecessors

        rank = _depth_first(start, downstream)

        work_list = [(rank[start.id], start.id)]
        queued = {start.id}
        while work_list:
            _, block_id = heapq.heappop(work_list)
            queued.remove(block_id)
            block = self.cfg.blocks[block_id]

            # join the states of processed upstream neighbors
            states = [
                self.output_states[b.id]
                for b in upstream(block)
                if b.id in self.reached
            ]
            if block is start:
                states.insert(0, self.boundary_state())
            input_state = states[0].copy()
            for other in states[1:]:
                input_state = self.join(input_state, other)
            self.input_states[block.id] = input_state

            output_state = self.transfer(block.statements, input_state)
            if (
                block.id in self.reached
                and output_state == self.output_states[block.id]
            ):
                continue
            self.reached.add(block.id)
            self.output_states[block.id] = output_state

            for neighbor in downstream(block):
                if neighbor.id not in queued:
                    queued.add(neighbor.id)
                    heapq.heappush(work_list, (rank[neighbor.id], neighbor.id))

__str__()

Return a string representation describing the current dataflow analysis state over the control-flow graph (CFG).

The output lists each basic block in the order produced by self.cfg.blocks.values(). For every block the printed form is:

<block.id>: #succs=[<succ_id>, ...]
    <stmt_representation_for_first_stmt>
    <stmt_representation_for_second_stmt>
    ...

statements are annotated with the state flowing into their transfer (before them for forward, after them for backward), statements of unreached blocks without annotations.

Source code in src/finch/symbolic/dataflow.py
def __str__(self) -> str:
    """
    Return a string representation describing the current dataflow
    analysis state over the control-flow graph (CFG).

    The output lists each basic block in the order
    produced by self.cfg.blocks.values().
    For every block the printed form is:

        <block.id>: #succs=[<succ_id>, ...]
            <stmt_representation_for_first_stmt>
            <stmt_representation_for_second_stmt>
            ...

    statements are annotated with the state flowing into their transfer
    (before them for forward, after them for backward), statements of
    unreached blocks without annotations.
    """
    lines: list[str] = []
    forward = self.direction() == "forward"

    for block in self.cfg.blocks.values():
        succ_names = [succ.id for succ in block.successors]
        lines.append(f"{block.id}: #succs=[{', '.join(succ_names)}]")

        if block.id not in self.reached:
            lines.extend(f"    {stmt}" for stmt in block.statements)
        else:
            # deep copy, so printing never changes the stored states
            state = copy.deepcopy(self.input_states[block.id])
            stmts = block.statements if forward else block.statements[::-1]
            annotated = []
            for stmt in stmts:
                annotated.append(f"    {self.stmt_str(stmt, state)}")
                state = self.transfer([stmt], state)
            lines.extend(annotated if forward else annotated[::-1])

        lines.append("")

    return "\n".join(lines)

analyze()

run the work list until the states of all reached blocks are stable

Source code in src/finch/symbolic/dataflow.py
def analyze(self) -> None:
    """run the work list until the states of all reached blocks are stable"""
    forward = self.direction() == "forward"
    start = self.cfg.entry_block if forward else self.cfg.exit_block

    def upstream(block: BasicBlock) -> list[BasicBlock]:
        return block.predecessors if forward else block.successors

    def downstream(block: BasicBlock) -> list[BasicBlock]:
        return block.successors if forward else block.predecessors

    rank = _depth_first(start, downstream)

    work_list = [(rank[start.id], start.id)]
    queued = {start.id}
    while work_list:
        _, block_id = heapq.heappop(work_list)
        queued.remove(block_id)
        block = self.cfg.blocks[block_id]

        # join the states of processed upstream neighbors
        states = [
            self.output_states[b.id]
            for b in upstream(block)
            if b.id in self.reached
        ]
        if block is start:
            states.insert(0, self.boundary_state())
        input_state = states[0].copy()
        for other in states[1:]:
            input_state = self.join(input_state, other)
        self.input_states[block.id] = input_state

        output_state = self.transfer(block.statements, input_state)
        if (
            block.id in self.reached
            and output_state == self.output_states[block.id]
        ):
            continue
        self.reached.add(block.id)
        self.output_states[block.id] = output_state

        for neighbor in downstream(block):
            if neighbor.id not in queued:
                queued.add(neighbor.id)
                heapq.heappush(work_list, (rank[neighbor.id], neighbor.id))

boundary_state()

state at the cfg boundary: out of ENTRY (forward) or into EXIT (backward)

Source code in src/finch/symbolic/dataflow.py
def boundary_state(self) -> dict:
    """state at the cfg boundary: out of ENTRY (forward) or into EXIT (backward)"""
    return {}

direction() abstractmethod

Return the direction of the data flow analysis, either "forward" or "backward". This should be implemented by subclasses.

Source code in src/finch/symbolic/dataflow.py
@abstractmethod
def direction(self) -> str:
    """
    Return the direction of the data flow analysis, either "forward" or "backward".
    This should be implemented by subclasses.
    """
    ...

join(state_1, state_2) abstractmethod

Join function for the data flow analysis. This should be implemented by subclasses.

Source code in src/finch/symbolic/dataflow.py
@abstractmethod
def join(self, state_1: dict, state_2: dict) -> dict:
    """
    Join function for the data flow analysis.
    This should be implemented by subclasses.
    """
    ...

stmt_str(stmt, state) abstractmethod

Format a single statement given the current lattice state. Implement in subclasses or IR-specific abstract bases.

Source code in src/finch/symbolic/dataflow.py
@abstractmethod
def stmt_str(self, stmt, state: dict) -> str:
    """
    Format a single statement given the current lattice state.
    Implement in subclasses or IR-specific abstract bases.
    """
    ...

transfer(stmts, state) abstractmethod

Transfer function for the data flow analysis. This should be implemented by subclasses.

Source code in src/finch/symbolic/dataflow.py
@abstractmethod
def transfer(self, stmts, state: dict) -> dict:
    """
    Transfer function for the data flow analysis.
    This should be implemented by subclasses.
    """
    ...

Fixpoint

Bases: Generic[T]

A rewriter which repeatedly applies rw to x until no changes are made. If the rewriter first returns nothing, returns nothing.

Attributes:

Name Type Description
rw RwCallable

The rewriter function to apply.

Source code in src/finch/symbolic/rewriters.py
class Fixpoint(Generic[T]):
    """
    A rewriter which repeatedly applies `rw` to `x` until no changes are made. If
    the rewriter first returns `nothing`, returns `nothing`.

    Attributes:
        rw (RwCallable): The rewriter function to apply.
    """

    def __init__(self, rw: RwCallable):
        self.rw = rw

    def __call__(self, x: T) -> T | None:
        y = self.rw(x)
        if y is not None:
            while y is not None and x != y:
                x = y
                y = self.rw(x)
            return x
        return None

Form

Bases: ABC

A Form represents the invariants that must hold for the inputs to be valid for a given stage. It will typically be a combination of a grammar and a set of constraints on the inputs. Stages should inherit from a Form to validate their inputs.

Source code in src/finch/symbolic/stage.py
class Form(ABC):
    """
    A Form represents the invariants that must hold for the inputs to be valid
    for a given stage. It will typically be a combination of a grammar and a
    set of constraints on the inputs. Stages should inherit from a Form to
    validate their inputs.
    """

    @abstractmethod
    def validate_inputs(cls, *inputs): ...

HashCons

Source code in src/finch/symbolic/hashcons.py
class HashCons:
    def __new__(cls, *args: Any) -> Self:
        hash_key = cls.hash_key(*args)
        if (cached := _table.get(hash_key)) is not None:
            return cached
        ret = super().__new__(cls)
        _table[hash_key] = ret
        return ret

    __eq__ = object.__eq__
    __hash__ = object.__hash__

    def __copy__(self) -> Self:
        return self

    def __deepcopy__(self, memo: dict) -> Self:
        return self

    @staticmethod
    def canonicalize(a: T, /) -> tuple[type[T], Hashable]:
        """
        Canonicalize an instance of this class into a (type, hashable) pair.

        Generic version provided, but one can override for speed.
        """
        if isinstance(a, numbers.Real):
            return type(a), _nan_to_none(float(a))

        if isinstance(a, numbers.Complex):
            return type(a), (_nan_to_none(float(a.real)), _nan_to_none(float(a.imag)))

        if isinstance(a, Hashable):
            return type(a), a

        return type(a), id(a)

    @classmethod
    def hash_key(cls, *args: Any) -> tuple[Hashable, ...]:
        """
        The hash key for this class, when it is constructed with `*args`.

        Generic version provided, but one can specialize for speed.
        """
        return (cls, *(cls.canonicalize(a) for a in args))

canonicalize(a) staticmethod

Canonicalize an instance of this class into a (type, hashable) pair.

Generic version provided, but one can override for speed.

Source code in src/finch/symbolic/hashcons.py
@staticmethod
def canonicalize(a: T, /) -> tuple[type[T], Hashable]:
    """
    Canonicalize an instance of this class into a (type, hashable) pair.

    Generic version provided, but one can override for speed.
    """
    if isinstance(a, numbers.Real):
        return type(a), _nan_to_none(float(a))

    if isinstance(a, numbers.Complex):
        return type(a), (_nan_to_none(float(a.real)), _nan_to_none(float(a.imag)))

    if isinstance(a, Hashable):
        return type(a), a

    return type(a), id(a)

hash_key(*args) classmethod

The hash key for this class, when it is constructed with *args.

Generic version provided, but one can specialize for speed.

Source code in src/finch/symbolic/hashcons.py
@classmethod
def hash_key(cls, *args: Any) -> tuple[Hashable, ...]:
    """
    The hash key for this class, when it is constructed with `*args`.

    Generic version provided, but one can specialize for speed.
    """
    return (cls, *(cls.canonicalize(a) for a in args))

Leaf dataclass

Bases: Value

the value a location holds, e.g. a variable

Source code in src/finch/symbolic/value_numbering.py
@dataclass(eq=False, frozen=True)
class Leaf(Value):
    """the value a location holds, e.g. a variable"""

    name: Hashable

LiteralTerm dataclass

Bases: Term, Generic[T]

A leaf term which wraps the constant val.

Source code in src/finch/symbolic/term.py
@dataclass(eq=True, frozen=True)
class LiteralTerm(Term, Generic[T]):
    """
    A leaf term which wraps the constant `val`.
    """

    val: T

Memo

Bases: Generic[T]

A rewriter which caches the results of rw in cache and returns the result.

Attributes:

Name Type Description
rw RwCallable

The rewriter function to apply.

cache dict

A dictionary to store cached results.

Source code in src/finch/symbolic/rewriters.py
class Memo(Generic[T]):
    """
    A rewriter which caches the results of `rw` in `cache` and returns the
    result.

    Attributes:
        rw (RwCallable): The rewriter function to apply.
        cache (dict): A dictionary to store cached results.
    """

    def __init__(self, rw: RwCallable, cache: dict | None = None):
        self.rw = rw
        self.cache = cache if cache is not None else {}

    def __call__(self, x: T) -> T | None:
        if x not in self.cache:
            self.cache[x] = self.rw(x)
        return self.cache[x]

NamedTerm

Bases: Term, ABC

A named program node, e.g. a variable, function, or index.

Source code in src/finch/symbolic/environment.py
class NamedTerm(Term, ABC):
    """
    A named program node, e.g. a variable, function, or index.
    """

    @property
    @abstractmethod
    def symbol(self) -> str: ...

Namespace

Namespace

A namespace for managing variable names and aesthetic fresh variable generation. You can construct a namespace from an existing tree of Terms to avoid name collisions.

Source code in src/finch/symbolic/environment.py
class Namespace:
    """
        Namespace

    A namespace for managing variable names and aesthetic fresh variable
    generation.  You can construct a namespace from an existing tree of `Term`s
    to avoid name collisions.
    """

    def __init__(self, root=None):
        self.counts = defaultdict(int)
        self.resolutions = {}
        if root is not None:
            for node in PostOrderDFS(root):
                if isinstance(node, NamedTerm):
                    self.freshen(node.symbol)

    def freshen(self, *tags) -> str:
        """
        Generate a fresh variable name based on the provided tags.
        """
        name = "_".join(str(tag) for tag in tags)
        m = re.match(r"^(.*)_(\d+)$", name)
        if m is None:
            tag = name
            n = 1
        else:
            tag = m.group(1)
            n = int(m.group(2))
        n = max(self.counts[tag] + 1, n)
        self.counts[tag] = n
        if n == 1:
            return tag
        return f"{tag}_{n}"

    def resolve(self, *names: str):
        """
        Resolve a list of namespaced variable names to a unique name.
        e.g. `resolve("a", "b")` might return `a_b_1` if `a_b` has already been
        used in scope.
        """
        self.resolutions.setdefault(names, lambda: self.freshen(*names))

freshen(*tags)

Generate a fresh variable name based on the provided tags.

Source code in src/finch/symbolic/environment.py
def freshen(self, *tags) -> str:
    """
    Generate a fresh variable name based on the provided tags.
    """
    name = "_".join(str(tag) for tag in tags)
    m = re.match(r"^(.*)_(\d+)$", name)
    if m is None:
        tag = name
        n = 1
    else:
        tag = m.group(1)
        n = int(m.group(2))
    n = max(self.counts[tag] + 1, n)
    self.counts[tag] = n
    if n == 1:
        return tag
    return f"{tag}_{n}"

resolve(*names)

Resolve a list of namespaced variable names to a unique name. e.g. resolve("a", "b") might return a_b_1 if a_b has already been used in scope.

Source code in src/finch/symbolic/environment.py
def resolve(self, *names: str):
    """
    Resolve a list of namespaced variable names to a unique name.
    e.g. `resolve("a", "b")` might return `a_b_1` if `a_b` has already been
    used in scope.
    """
    self.resolutions.setdefault(names, lambda: self.freshen(*names))

PostWalk

A rewriter which recursively rewrites the arguments of each node using rw, then rewrites the resulting node. If all rewriters return nothing, returns nothing.

Attributes:

Name Type Description
rw RwCallable

The rewriter function to apply.

Source code in src/finch/symbolic/rewriters.py
class PostWalk:
    """
    A rewriter which recursively rewrites the arguments of each node using
    `rw`, then rewrites the resulting node. If all rewriters return `nothing`,
    returns `nothing`.

    Attributes:
        rw (RwCallable): The rewriter function to apply.
    """

    def __init__(self, rw: RwCallable):
        self.rw = rw

    def __call__(self, x: T) -> T | None:
        if isinstance(x, TermTree):
            args = x.children
            new_args = list(map(self, args))
            if all(arg is None for arg in new_args):
                return self.rw(x)
            y = x.make_term(
                x.head(), *map(lambda x1, x2: default_rewrite(x1, x2), new_args, args)
            )
            assert isinstance(y, type(x))
            return default_rewrite(self.rw(y), y)
        return self.rw(x)

PreWalk

A rewriter which recursively rewrites each node using rw, then rewrites the arguments of the resulting node. If all rewriters return nothing, returns nothing.

Attributes:

Name Type Description
rw RwCallable

The rewriter function to apply.

Source code in src/finch/symbolic/rewriters.py
class PreWalk:
    """
    A rewriter which recursively rewrites each node using `rw`, then rewrites
    the arguments of the resulting node. If all rewriters return `nothing`,
    returns `nothing`.

    Attributes:
        rw (RwCallable): The rewriter function to apply.
    """

    def __init__(self, rw: RwCallable):
        self.rw = rw

    def __call__(self, x: T) -> T | None:
        y = self.rw(x)
        if y is not None:
            if isinstance(y, TermTree):
                args = y.children
                return y.make_term(
                    y.head(), *[default_rewrite(self(arg), arg) for arg in args]
                )
            return y
        if isinstance(x, TermTree):
            args = x.children
            new_args = list(map(self, args))
            if not all(arg is None for arg in new_args):
                ret = x.make_term(
                    x.head(),
                    *map(lambda x1, x2: default_rewrite(x1, x2), new_args, args),
                )
                assert isinstance(ret, type(x))
                return ret
        return None

Rewrite

Bases: Generic[T]

A rewriter which returns the original argument even if rw returns nothing.

Attributes:

Name Type Description
rw RwCallable

The rewriter function to apply.

Source code in src/finch/symbolic/rewriters.py
class Rewrite(Generic[T]):
    """
    A rewriter which returns the original argument even if `rw` returns nothing.

    Attributes:
        rw (RwCallable): The rewriter function to apply.
    """

    def __init__(self, rw: RwCallable):
        self.rw = rw

    def __call__(self, x: T) -> T:
        return default_rewrite(self.rw(x), x)

ScopedDict

Bases: Generic[T]

A dictionary that allows for scoped variable resolution.

Source code in src/finch/symbolic/environment.py
class ScopedDict(Generic[T]):
    """
    A dictionary that allows for scoped variable resolution.
    """

    def __init__(
        self,
        bindings: dict[str, T] | None = None,
        parent: Optional["ScopedDict[T]"] = None,
    ):
        if bindings is None:
            bindings = {}
        self.bindings: dict[str, T] = bindings
        self.parent: ScopedDict[T] | None = parent

    def __getitem__(self, key: str) -> T:
        if key in self.bindings:
            return self.bindings[key]
        if self.parent is not None:
            return self.parent[key]
        raise KeyError(f"Key '{key}' not found in scoped dictionary.")

    def set_in_ancestor(self, leaf, key: str, value: T) -> None:
        if key in self.bindings:
            self.bindings[key] = value
        elif self.parent is not None:
            self.parent.set_in_ancestor(leaf, key, value)
        else:
            leaf.bindings[key] = value

    def del_in_ancestor(self, leaf, key: str) -> None:
        if key in self.bindings:
            del self.bindings[key]
        elif self.parent is not None:
            self.parent.del_in_ancestor(leaf, key)
        else:
            del leaf.bindings[key]

    def __setitem__(self, key: str, value: T) -> None:
        self.set_in_ancestor(self, key, value)

    def __contains__(self, key: str) -> bool:
        return key in self.bindings or (self.parent is not None and key in self.parent)

    def __delitem__(self, key: str) -> None:
        self.del_in_ancestor(self, key)

    def scope(self) -> "ScopedDict[T]":
        """
        Create a new scoped dictionary that inherits from this one.
        """
        return ScopedDict(parent=self)

scope()

Create a new scoped dictionary that inherits from this one.

Source code in src/finch/symbolic/environment.py
def scope(self) -> "ScopedDict[T]":
    """
    Create a new scoped dictionary that inherits from this one.
    """
    return ScopedDict(parent=self)

Term

Source code in src/finch/symbolic/term.py
class Term:
    @abstractmethod
    def head(self) -> Callable[..., Self]:
        """Return the head type of the S-expression."""
        ...

    @classmethod
    @abstractmethod
    def make_term(cls, head: Callable[..., Self], *children: Term) -> Self:
        """
        Construct a new term in the same family of terms with the given head type and
        children. This function should satisfy
        `x == x.make_term(x.head(), *x.children)`
        """
        ...

head() abstractmethod

Return the head type of the S-expression.

Source code in src/finch/symbolic/term.py
@abstractmethod
def head(self) -> Callable[..., Self]:
    """Return the head type of the S-expression."""
    ...

make_term(head, *children) abstractmethod classmethod

Construct a new term in the same family of terms with the given head type and children. This function should satisfy x == x.make_term(x.head(), *x.children)

Source code in src/finch/symbolic/term.py
@classmethod
@abstractmethod
def make_term(cls, head: Callable[..., Self], *children: Term) -> Self:
    """
    Construct a new term in the same family of terms with the given head type and
    children. This function should satisfy
    `x == x.make_term(x.head(), *x.children)`
    """
    ...

TermTree dataclass

Bases: Term, ABC

Source code in src/finch/symbolic/term.py
@dataclass(frozen=True, eq=True)
class TermTree(Term, ABC):
    @property
    @abstractmethod
    def children(self) -> Sequence[Term]:
        """Return the children (AKA tail) of the S-expression."""
        ...

children abstractmethod property

Return the children (AKA tail) of the S-expression.

UnvalidatedForm

Bases: Form

UnvalidatedForm does not perform any validation on the input logic. This is essentially a to-do for validation and should be replaced.

Source code in src/finch/symbolic/stage.py
class UnvalidatedForm(Form):
    """
    UnvalidatedForm does not perform any validation on the input logic.
    This is essentially a to-do for validation and should be replaced.
    """

    def validate_inputs(self, *inputs):
        return

Value

Bases: HashCons

how a value is computed

Source code in src/finch/symbolic/value_numbering.py
class Value(HashCons):
    """how a value is computed"""

ValueUniverse

a finite set of values, closed under taking args. a state is a tuple giving each value the index of the first value in its class.

Source code in src/finch/symbolic/value_numbering.py
class ValueUniverse:
    """
    a finite set of values, closed under taking args. a state is a tuple giving
    each value the index of the first value in its class.
    """

    def __init__(self, values: Iterable[Value]):
        self.values: list[Value] = []
        self.indices: dict[Value, int] = {}
        self.applies: list[tuple[int, Hashable, tuple[int, ...]]] = []
        self._reads: list[frozenset[Leaf]] = []
        for value in values:
            self._add(value)
        # the values a write to each leaf changes, the leaf first
        self.kills: dict[Leaf, list[int]] = {}
        for i, reads in enumerate(self._reads):
            for leaf in reads:
                self.kills.setdefault(leaf, []).append(i)

    def _add(self, value: Value) -> int:
        index = self.indices.get(value)
        if index is not None:
            return index
        reads: frozenset[Leaf] = frozenset()
        match value:
            case Apply(op, args):
                arg_ids = tuple(self._add(arg) for arg in args)
                reads = reads.union(*(self._reads[i] for i in arg_ids))
                self.applies.append((len(self.values), op, arg_ids))
            case Leaf():
                reads = frozenset((value,))
        index = self.indices[value] = len(self.values)
        self.values.append(value)
        self._reads.append(reads)
        return index

    def empty(self) -> tuple[int, ...]:
        """the state with no equalities"""
        return tuple(range(len(self.values)))

    def number(self, state: tuple[int, ...], value: Value) -> int | None:
        """the class of `value` in `state`, or None if it isn't in the universe"""
        index = self.indices.get(value)
        return None if index is None else state[index]

    def meet(
        self, state_1: tuple[int, ...], state_2: tuple[int, ...]
    ) -> tuple[int, ...]:
        """the equalities both states have"""
        # two congruences meet in a congruence, so there's nothing to close
        first: dict[tuple[int, int], int] = {}
        return tuple(
            first.setdefault(pair, i)
            for i, pair in enumerate(zip(state_1, state_2, strict=True))
        )

    def assign(
        self, state: tuple[int, ...], leaf: Leaf, value: Value | None = None
    ) -> tuple[int, ...]:
        """the state after writing `value` to `leaf`, or an unknown value if None"""
        killed = self.kills.get(leaf)
        if killed is None:
            return state
        target = self.indices[leaf]
        source = None if value is None else self.indices.get(value)
        if source == target:
            return state
        labels = list(state)
        for i in killed:
            labels[i] = len(labels) + i
        # members of the class of `value` that the write didn't change still
        # hold it, e.g. `t` in `t = add(x, 1); x = add(x, 1)`
        if source is not None and state[source] in labels:
            labels[target] = state[source]
        # only values reading the leaf can become congruent to something
        return self._close(labels, congruence=len(killed) > 1)

    def _close(self, labels: list[int], congruence: bool) -> tuple[int, ...]:
        """the state with classes given by `labels`, closed under congruence"""
        parent = list(range(len(labels)))

        def find(i: int) -> int:
            while parent[i] != i:
                parent[i] = parent[parent[i]]
                i = parent[i]
            return i

        first: dict[int, int] = {}
        for i, label in enumerate(labels):
            parent[i] = first.setdefault(label, i)
        changed = congruence
        while changed:
            changed = False
            signatures: dict[tuple, int] = {}
            for i, op, args in self.applies:
                other = signatures.setdefault((op, *(find(j) for j in args)), i)
                root, other_root = find(i), find(other)
                if root != other_root:
                    # the smaller index stays the root, so roots are canonical
                    parent[max(root, other_root)] = min(root, other_root)
                    changed = True
        return tuple(find(i) for i in range(len(parent)))

assign(state, leaf, value=None)

the state after writing value to leaf, or an unknown value if None

Source code in src/finch/symbolic/value_numbering.py
def assign(
    self, state: tuple[int, ...], leaf: Leaf, value: Value | None = None
) -> tuple[int, ...]:
    """the state after writing `value` to `leaf`, or an unknown value if None"""
    killed = self.kills.get(leaf)
    if killed is None:
        return state
    target = self.indices[leaf]
    source = None if value is None else self.indices.get(value)
    if source == target:
        return state
    labels = list(state)
    for i in killed:
        labels[i] = len(labels) + i
    # members of the class of `value` that the write didn't change still
    # hold it, e.g. `t` in `t = add(x, 1); x = add(x, 1)`
    if source is not None and state[source] in labels:
        labels[target] = state[source]
    # only values reading the leaf can become congruent to something
    return self._close(labels, congruence=len(killed) > 1)

empty()

the state with no equalities

Source code in src/finch/symbolic/value_numbering.py
def empty(self) -> tuple[int, ...]:
    """the state with no equalities"""
    return tuple(range(len(self.values)))

meet(state_1, state_2)

the equalities both states have

Source code in src/finch/symbolic/value_numbering.py
def meet(
    self, state_1: tuple[int, ...], state_2: tuple[int, ...]
) -> tuple[int, ...]:
    """the equalities both states have"""
    # two congruences meet in a congruence, so there's nothing to close
    first: dict[tuple[int, int], int] = {}
    return tuple(
        first.setdefault(pair, i)
        for i, pair in enumerate(zip(state_1, state_2, strict=True))
    )

number(state, value)

the class of value in state, or None if it isn't in the universe

Source code in src/finch/symbolic/value_numbering.py
def number(self, state: tuple[int, ...], value: Value) -> int | None:
    """the class of `value` in `state`, or None if it isn't in the universe"""
    index = self.indices.get(value)
    return None if index is None else state[index]

intree(n1, n2)

Return True iff n1 occurs in the subtree rooted at n2.

Source code in src/finch/symbolic/traversal.py
def intree(n1, n2):
    """
    Return True iff `n1` occurs in the subtree rooted at `n2`.
    """
    return any(node == n1 for node in PostOrderDFS(n2))

isdescendant(n1, n2)

True iff n1 is a strict descendant of n2.

Source code in src/finch/symbolic/traversal.py
def isdescendant(n1, n2):
    """
    True iff `n1` is a strict descendant of `n2`.
    """
    if n1 == n2:
        return False
    return intree(n1, n2)