Skip to content

Core & Engine

This page documents the core base classes and the engine used to match sequences.

ast_pattern_engine.core

Pattern

Bases: AST

Base class for AST matching patterns.

Source code in src/ast_pattern_engine/core.py
class Pattern(ast.AST):
    """Base class for AST matching patterns."""

    # public API
    def match_node(
        self,
        node: object,
        bindings: dict[str, object] | None = None,
        *,
        _force_list: bool = False,
    ):
        """Match *node* and return updated *bindings* or *None*."""
        raise NotImplementedError

    # helpers
    @staticmethod
    def _to_list(val: Any) -> list[Any]:
        return val if isinstance(val, list) else [val]

match_node

match_node(
    node: object,
    bindings: dict[str, object] | None = None,
    *,
    _force_list: bool = False,
)

Match node and return updated bindings or None.

Source code in src/ast_pattern_engine/core.py
def match_node(
    self,
    node: object,
    bindings: dict[str, object] | None = None,
    *,
    _force_list: bool = False,
):
    """Match *node* and return updated *bindings* or *None*."""
    raise NotImplementedError

ast_pattern_engine.engine

match_sequence

match_sequence(
    patterns: Sequence[Pattern], nodes: list[Any]
) -> list[dict[str, Any]]

Return list of binding dicts for non-overlapping matches in nodes.

Parameters:

Name Type Description Default
patterns Sequence[Pattern]

The sequence of patterns to match.

required
nodes list[Any]

The list of AST nodes to match against.

required

Returns:

Type Description
list[dict[str, Any]]

List of binding dictionaries for each successful match.

Source code in src/ast_pattern_engine/engine.py
def match_sequence(
    patterns: Sequence[Pattern], nodes: list[Any]
) -> list[dict[str, Any]]:
    """Return list of binding dicts for non-overlapping matches in `nodes`.

    Args:
        patterns: The sequence of patterns to match.
        nodes: The list of AST nodes to match against.

    Returns:
        List of binding dictionaries for each successful match.
    """
    results: list[dict[str, Any]] = []
    i = 0
    while i < len(nodes):
        m = _match_patterns(patterns, nodes, i, {})
        if not m:
            i += 1
            continue
        b, new_pos = m[-1]
        results.append(b)
        i = new_pos
    return results