Skip to content

Traits

FromPythonCall dataclass

FromPythonCall()

Bases: PythonLoweringTrait[StatementType, Call]

Trait for customizing lowering of Python calls to a statement.

Declared in a statement definition to indicate that the statement can be constructed from a Python call (i.e., a function call ast.Call in the Python AST).

Subclassing this trait allows for customizing the lowering of Python calls to the statement. The lower method should be implemented to parse the arguments from the Python call and construct the statement instance.

FromPythonRangeLike dataclass

FromPythonRangeLike()

Bases: FromPythonCall[StatementType]

Provides a default lowering implementation for built-in range-like function to a statement that takes three arguments: start, stop, and step.

FromPythonWith dataclass

FromPythonWith()

Bases: PythonLoweringTrait[StatementType, With]

Trait for customizing lowering of Python with statements to a statement.

Subclassing this trait allows for customizing the lowering of Python with statements to the statement. The lower method should be implemented to parse the arguments from the Python with statement and construct the statement instance.

FromPythonWithSingleItem dataclass

FromPythonWithSingleItem()

Bases: FromPythonWith[StatementType]

Trait for customizing lowering of the following Python with syntax to a statement:

with <stmt>[ as <name>]:
    <body>

where <stmt> is the statement being lowered, <name> is an optional name for the result of the statement, and <body> is the body of the with statement. The optional as <name> is not valid when the statement has no results.

This syntax is slightly different from the standard Python with statement in that <name> refers to the result of the statement, not the context manager. Thus typically one sould access <name> in <body> to use the result of the statement.

In some cases, however, <name> may be used as a reference of a special value self that is passed to the <body> of the statement. This is useful for statements that have a similar behavior to a closure.

PythonLoweringTrait dataclass

PythonLoweringTrait()

Bases: Trait[Statement], Generic[StmtType, ASTNode]

A trait that indicates that a statement can be lowered from Python AST.

lower_Call_inputs classmethod

lower_Call_inputs(
    stmt: type[StmtType],
    state: State[ast.AST],
    node: ast.Call,
) -> tuple[
    dict[str, ir.SSAValue | tuple[ir.SSAValue, ...]],
    dict[str, Any],
]

Lower the inputs of a Python call to corresponding SSA values or compile-time values (attributes).

Parameters:

Name Type Description Default
stmt type[StmtType]

The statement class to lower to.

required
state State[AST]

The lowering state.

required
node Call

The Python call node to lower.

required

Returns:

Type Description
dict[str, SSAValue | tuple[SSAValue, ...]]

A tuple containing two dictionaries:

dict[str, Any]
  • The first dictionary contains the standard arguments and their values.
tuple[dict[str, SSAValue | tuple[SSAValue, ...]], dict[str, Any]]
  • The second dictionary contains the keyword arguments and their values.

Raises:

Type Description
BuildError

If the Python call cannot be lowered to the statement.

Source code in src/kirin/lowering/python/traits.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
@classmethod
def lower_Call_inputs(
    cls, stmt: type[StmtType], state: State[ast.AST], node: ast.Call
) -> tuple[dict[str, ir.SSAValue | tuple[ir.SSAValue, ...]], dict[str, Any]]:
    """Lower the inputs of a Python call to corresponding SSA values or
    compile-time values (attributes).

    Args:
        stmt: The statement class to lower to.
        state: The lowering state.
        node: The Python call node to lower.

    Returns:
        A tuple containing two dictionaries:
        - The first dictionary contains the standard arguments and their values.
        - The second dictionary contains the keyword arguments and their values.

    Raises:
        lowering.BuildError: If the Python call cannot be lowered to the statement.
    """
    fs = fields(stmt)
    stmt_std_arg_names = fs.std_args.keys()
    stmt_kw_args_name = fs.kw_args.keys()
    stmt_attr_prop_names = fs.attr_or_props
    stmt_required_names = fs.required_names
    stmt_group_arg_names = fs.group_arg_names
    args, kwargs = {}, {}
    for name, value in zip(stmt_std_arg_names, node.args):
        cls.__parse_arg(state, stmt_group_arg_names, args, name, value)
    for kw in node.keywords:
        if not isinstance(kw.arg, str):
            raise BuildError("Expected string for keyword argument name")

        arg: str = kw.arg
        if arg in node.args:
            raise BuildError(
                f"Keyword argument {arg} is already present in positional arguments"
            )
        elif arg in stmt_std_arg_names or arg in stmt_kw_args_name:
            cls.__parse_arg(state, stmt_group_arg_names, kwargs, kw.arg, kw.value)
        elif arg in stmt_attr_prop_names:
            if (
                isinstance(kw.value, ast.Name)
                and state.current_frame.get_local(kw.value.id) is not None
            ):
                raise BuildError(
                    f"Expected global/constant value for attribute or property {arg}"
                )
            global_value = state.get_global(kw.value)
            if (decl := fs.attributes.get(arg)) is not None:
                if decl.annotation is Any:
                    kwargs[arg] = global_value.data
                else:
                    kwargs[arg] = global_value.expect(
                        get_origin(decl.annotation) or decl.annotation
                    )
            else:
                raise BuildError(f"Unexpected attribute or property {arg}")
        else:
            raise BuildError(f"Unexpected keyword argument {arg}")

    for name in stmt_required_names:
        if name not in args and name not in kwargs:
            raise BuildError(f"Missing required argument {name}")

    return args, kwargs