Skip to content

Lowering

Python dataclass

Python(
    dialects: (
        ir.DialectGroup | Iterable[ir.Dialect | ModuleType]
    ),
    *,
    keys: list[str] | None = None
)

Bases: LoweringABC[AST]

Python lowering transform.

This class is used to lower Python AST nodes to IR statements via a visitor pattern.

Note

the visitor pattern is not using the ast.NodeVisitor class because it customize the visit method to pass the lowering state and the source information to the visitor methods.

Source code in src/kirin/lowering/python/lowering.py
38
39
40
41
42
43
44
45
46
47
48
def __init__(
    self,
    dialects: ir.DialectGroup | Iterable[ir.Dialect | ModuleType],
    *,
    keys: list[str] | None = None,
):
    if isinstance(dialects, ir.DialectGroup):
        self.dialects = dialects
    else:
        self.dialects = ir.DialectGroup(dialects)
    self.registry = self.dialects.registry.ast(keys=keys or ["main", "default"])

dialects instance-attribute

dialects = dialects

dialects to lower to

lower_global

lower_global(
    state: State[ast.AST], node: ast.AST
) -> LoweringABC.Result

Transform a given global expression to a SSAValue.

This method is overridden by the subclass to transform a given global AST expression to a value as LoweringABC.Result.

The subclass must implement this method to transform a given global AST expression to a SSAValue.

Source code in src/kirin/lowering/python/lowering.py
134
135
def lower_global(self, state: State[ast.AST], node: ast.AST) -> LoweringABC.Result:
    return LoweringABC.Result(GlobalExprEval(state.current_frame).visit(node))

visit

visit(state: State[ast.AST], node: ast.AST) -> Result

Entry point of AST visitors.

Parameters:

Name Type Description Default
state State[ASTNodeType]

lowering state

required
node ASTNodeType

AST node to be lowered

required

Returns: SSAValue: if the node can be assigned to a variable syntax-wise, what is the SSAValue. Statement: if the node is a single statement that has a single result value. This is equivalent to returning stmt.results[0]. None: If the node cannot be assigned to a variable syntax-wise. Raises: lowering.BuildError: if the node cannot be lowered.

Source code in src/kirin/lowering/python/lowering.py
138
139
140
141
142
143
144
def visit(self, state: State[ast.AST], node: ast.AST) -> Result:
    if hasattr(node, "lineno"):
        state.source = SourceInfo.from_ast(node, state.file)
    name = node.__class__.__name__
    if name in self.registry.ast_table:
        return self.registry.ast_table[name].lower(state, node)
    return getattr(self, f"visit_{name}", self.generic_visit)(state, node)