Skip to content

parser

Parser for FinchLogic programs as LogicNode.str prints them, so that parse_logic(str(prgm)) == prgm whenever the literals of prgm print as values (see format_literal). Literals are read as a small subset of Python, whose names are looked up in a namespace of operators, numpy scalar types, finch dtypes and fills, rather than evaluated.

parse_logic(text, namespace=None)

Parse a program, or an expression, as LogicNode.str prints it. Names in literals are looked up in LITERALS, updated with namespace if given, which can name values that don't print as text, such as tensors.

Source code in src/finch/finch_logic/parser.py
def parse_logic(text: str, namespace: Mapping[str, Any] | None = None) -> lgc.LogicNode:
    """
    Parse a program, or an expression, as LogicNode.__str__ prints it. Names in
    literals are looked up in LITERALS, updated with namespace if given, which
    can name values that don't print as text, such as tensors.
    """
    tree = logic_parser.parse(text if text.endswith("\n") else text + "\n")
    reader = _LogicReader({**LITERALS, **(namespace or {})})
    match tree:
        case Tree("program", stmts):
            return reader.block(stmts)
        case Tree("expression", [expr]):
            return reader.expression(expr)
        case _:
            raise ValueError(f"Expected a program or an expression, got {tree}")