Skip to content

Binding

wraps

wraps(parent: type[Statement])

Wraps a Statement to a Binding object which will be special cased in the lowering process.

This is useful for providing type hints by faking the call signature of a Statement.

Example

Directly writing a function with the statement will let Python linter think you intend to call the constructor of the statement class. However, given the context of a kernel, our intention is to actually "call" the statement, e.g the following will produce type errors with pyright or mypy:

from kirin.dialects import math
from kirin.prelude import basic_no_opt

@basic_no_opt
def main(x: float):
    return math.sin(x) # this is a statement, not a function

the @lowering.wraps decorator allows us to provide a type hint for the statement, e.g:

from kirin import lowering

@lowering.wraps(math.sin)
def sin(value: float) -> float: ...

@basic_no_opt
def main(x: float):
    return sin(x) # linter now thinks this is a function

sin(1.0) # this will raise a NotImplementedError("Binding of sin can only be called from a kernel")
Source code in src/kirin/lowering/python/binding.py
22
23
24
25
26
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
def wraps(parent: type["Statement"]):
    """Wraps a [`Statement`][kirin.ir.nodes.stmt.Statement] to a `Binding` object
    which will be special cased in the lowering process.

    This is useful for providing type hints by faking the call signature of a
    [`Statement`][kirin.ir.nodes.stmt.Statement].

    ## Example

    Directly writing a function with the statement will let Python linter think
    you intend to call the constructor of the statement class. However, given the
    context of a kernel, our intention is to actually "call" the statement, e.g
    the following will produce type errors with pyright or mypy:

    ```python
    from kirin.dialects import math
    from kirin.prelude import basic_no_opt

    @basic_no_opt
    def main(x: float):
        return math.sin(x) # this is a statement, not a function
    ```

    the `@lowering.wraps` decorator allows us to provide a type hint for the
    statement, e.g:

    ```python
    from kirin import lowering

    @lowering.wraps(math.sin)
    def sin(value: float) -> float: ...

    @basic_no_opt
    def main(x: float):
        return sin(x) # linter now thinks this is a function

    sin(1.0) # this will raise a NotImplementedError("Binding of sin can only be called from a kernel")
    ```
    """

    def wrapper(func: Callable[Params, RetType]) -> Binding[Params, RetType]:
        return Binding(parent)

    return wrapper