from collections.abc import Callable, Iterator, Sequence
from copy import copy
from dataclasses import dataclass, field
from typing import Any, Literal, Self, no_type_check, overload
from guppylang import guppy
from guppylang.defs import GuppyFunctionDefinition
from guppylang.library import link_name
from hugr import Hugr, build
from hugr.ext import OpDef, TypeDef
from hugr.ops import FuncDecl, FuncDefn
from hugr.package import Package, link_packages
from hugr.tys import ExtType, Type
from tket.extensions import measurement
from guppyft._bindings import RsHugr
from guppyft._bindings import _implement_ops as _implement_ops_binding
from guppyft._trace import trace_function, tracing
from guppyft._util import get_link_name
from ._util import to_rs_hugr
[docs]
class OpReplacements:
_ops: dict[
tuple[str, str],
tuple[GuppyFunctionDefinition[Any, Any] | Hugr[Any] | None, str],
]
_check_eliminated: list[str]
"""Stores the operations to replace during op implementation and the implementation
functions. A function can be set to `None` to indicate that a declaration with the
given name should be generated instead."""
[docs]
def __init__(self) -> None:
self._ops = {}
self._check_eliminated = []
def __iter__(
self,
) -> Iterator[
tuple[
tuple[str, str],
tuple[GuppyFunctionDefinition[Any, Any] | Hugr[Any] | None, str],
]
]:
return iter(self._ops.items())
def iter_eliminated(self) -> Iterator[str]:
return self._check_eliminated.__iter__()
def _insert_for_op(
self,
op: tuple[str, str] | OpDef,
value: tuple[GuppyFunctionDefinition[Any, Any] | Hugr[Any] | None, str],
) -> Self:
if isinstance(op, OpDef):
op = (op.get_extension().name, op.name)
self._ops[op] = value
return self
def with_func(
self,
op: tuple[str, str] | OpDef,
func: GuppyFunctionDefinition[Any, Any],
) -> Self:
[func_module] = func.compile_function().modules
return self._insert_for_op(op, (func_module, get_link_name(func)))
def with_funcs(
self, funcs: dict[tuple[str, str], GuppyFunctionDefinition[Any, Any]]
) -> Self:
for op, func in funcs.items():
self.with_func(op, func)
return self
def with_generated_decl(
self,
op: tuple[str, str] | OpDef,
func_name: str,
) -> Self:
return self._insert_for_op(op, (None, func_name))
def with_generated_decls(self, names: dict[tuple[str, str], str]) -> Self:
for op, name in names.items():
self.with_generated_decl(op, name)
return self
def _hugr_names_missing_implementations(self) -> dict[str, tuple[str, str]]:
return {
f_name: op_key
for op_key, (func_opt, f_name) in self._ops.items()
if func_opt is None
}
def gen_missing_decls_from_lib(self, lib: Package) -> Self:
if not (missing := self._hugr_names_missing_implementations()):
return self
for lib_module in lib.modules:
for _, data in lib_module.nodes():
op = data.op
if (
isinstance(op, (FuncDefn, FuncDecl))
and op.visibility == "Public"
and op.f_name in missing
):
op_key = missing.pop(op.f_name)
mod = build.Module()
mod.declare_function(op.f_name, op.signature, op.visibility)
self._ops[op_key] = (mod.hugr, op.f_name)
if not missing:
return self
return self
def register_for_elimination_check(self, ext_id: str) -> None:
self._check_eliminated.append(ext_id)
def check_finished(self) -> None:
missing = self._hugr_names_missing_implementations()
if missing:
missing_str = [
f"{f_name} (for {ext_name}.{op_name})"
for f_name, (ext_name, op_name) in missing.items()
]
msg = f"Function declarations are missing: {', '.join(missing_str)}"
raise ValueError(f"Op replacement spec is unfinished: {msg}")
[docs]
class TyReplacements:
tys: set[tuple[str, str]]
[docs]
def __init__(self) -> None:
self.tys = set()
def with_type(self, ty: Type | tuple[str, str]) -> Self:
match ty:
case TypeDef():
self.tys.add((ty.get_extension().name, ty.name))
case ExtType():
self.tys.add((ty.type_def.get_extension().name, ty.type_def.name))
case tuple():
self.tys.add(ty)
case _:
raise TypeError(f"TyReplacements: Unexpected Type: {ty}, {type(ty)}")
return self
def with_types(self, tys: Sequence[Type | tuple[str, str]]) -> Self:
for ty in tys:
self.with_type(ty)
return self
def with_defaults(self) -> Self:
return self.with_types([measurement.measurement_t, ("prelude", "qubit")])
[docs]
@dataclass(frozen=True, kw_only=True)
class ImplementOpsSpec:
"""A specification for the implement ops pass, supplying implementations to a set of
HUGR extension ops."""
ops: OpReplacements
"""The operations to replace."""
tys: TyReplacements = field(
default_factory=lambda: TyReplacements().with_defaults()
)
"""The types to replace."""
build_wrapper: Callable[
[GuppyFunctionDefinition[[], None]], GuppyFunctionDefinition[[], None]
] = field(default=lambda x: x)
"""Allows creating a wrapper around the transformed program, e.g. to setup and
teardown the environment required for the op implementations."""
libs: list[Package | bytes] = field(default_factory=list)
"""Additional libraries required to run the transformed program, either as a HUGR
package or the same in serialised form (using Package.to_bytes)."""
adapt_rotation_inputs: bool = False
"""Expect Guppy `angle` tuples for top-level HUGR rotation inputs in implementations
and generated declarations. Call sites insert `to_halfturns` and wrap the resulting
floats in tuples. Other input and output types are unchanged."""
def _implement_ops(
pkg_bytes: bytes,
ops: OpReplacements,
tys: set[tuple[str, str]],
*,
adapt_rotation_inputs: bool = False,
) -> bytes:
rs_hugr = RsHugr.from_bytes(pkg_bytes)
rs_ops: dict[tuple[str, str], tuple[RsHugr, str]] = {}
for key, (func_opt, name) in ops:
assert func_opt is not None
rs_ops[key] = (to_rs_hugr(func_opt), name)
_implement_ops_binding(
rs_hugr,
rs_ops,
tys,
list(ops.iter_eliminated()),
adapt_rotation_inputs=adapt_rotation_inputs,
)
return rs_hugr.to_bytes()
@overload
def implement_ops(
hugr_pkg: Package, spec: ImplementOpsSpec, *, as_bytes: Literal[False] = False
) -> Package: ...
@overload
def implement_ops(
hugr_pkg: Package, spec: ImplementOpsSpec, *, as_bytes: Literal[True]
) -> bytes: ...
@overload
def implement_ops(
hugr_pkg: Package, spec: ImplementOpsSpec, *, as_bytes: bool
) -> Package | bytes: ...
[docs]
@trace_function("implement_ops")
def implement_ops(
hugr_pkg: Package, spec: ImplementOpsSpec, *, as_bytes: bool = False
) -> Package | bytes:
"""Enriches the given package using the given spec by replacing all operations in
the program with function calls to the functions in `spec.ops`.
Args:
hugr_pkg: A package containing a single module.
spec: The specification for the operation implementation.
as_bytes: Whether to return bytes instead of a `Package`, skipping final
deserialization.
Returns:
The enriched function as an executable HUGR package, or its serialized
representation when `as_bytes` is `True`.
"""
assert len(hugr_pkg.modules) == 1
# Only the entrypoint is changed before serialization; graph rewrites happen
# on a separate Rust HUGR, so a shallow copy preserves the input entrypoint.
copy_pkg = Package([copy(hugr_pkg.modules[0])], hugr_pkg.extensions)
hugr = copy_pkg.modules[0]
entrypoint_op = hugr.entrypoint_op()
assert isinstance(entrypoint_op, (FuncDefn, FuncDecl)), (
"Provided a non-function entrypoint HUGR!"
)
# Reset entrypoint, marking module as non-executable, to avoid linking conflicts
hugr.entrypoint = hugr.module_root
# Run rewrite, replacing ops with function calls to the functions in `spec.ops`
spec.ops.check_finished()
with tracing("serialise_user_pkg"):
copy_pkg_bytes = copy_pkg.to_bytes()
with tracing("implement"):
hugr_pkg_bytes = _implement_ops(
copy_pkg_bytes,
spec.ops,
spec.tys.tys,
adapt_rotation_inputs=spec.adapt_rotation_inputs,
)
with tracing("build_wrapper"):
# Build, compile, and link wrapper program
@guppy.declare
@link_name(entrypoint_op.f_name)
@no_type_check
def func_decl() -> None: ...
# We have to ensure the build wrapper is a function definition rather than a
# declaration, so that the package contains an entrypoint. Guppy compiles
# declarations to module-rooted HUGRs.
wrapper = spec.build_wrapper(func_decl)
@guppy
def outer_wrapper() -> None:
wrapper()
pkg: Package = outer_wrapper.compile()
with tracing("serialise_libs"):
libraries = [
lib if isinstance(lib, bytes) else lib.to_bytes() for lib in spec.libs
]
with tracing("link_libs"):
pkg_bytes = link_packages(pkg.to_bytes(), hugr_pkg_bytes, *libraries)
if as_bytes:
return pkg_bytes
with tracing("deserialise_product"):
return Package.from_bytes(pkg_bytes)
[docs]
@dataclass(frozen=True)
class ImplementOps:
_runner: Callable[[Package, bool], Package | bytes]
@overload
def __call__(
self, pkg: Package, *, as_bytes: Literal[False] = False
) -> Package: ...
@overload
def __call__(self, pkg: Package, *, as_bytes: Literal[True]) -> bytes: ...
@overload
def __call__(self, pkg: Package, *, as_bytes: bool) -> Package | bytes: ...
[docs]
@trace_function("implement_ops_call")
def __call__(self, pkg: Package, as_bytes: bool = False) -> Package | bytes:
return self._runner(pkg, as_bytes)
@staticmethod
def for_spec(spec: ImplementOpsSpec) -> "ImplementOps":
return ImplementOps.for_spec_generator(lambda _: spec)
@staticmethod
def for_spec_generator(
spec_gen: Callable[[Package], ImplementOpsSpec],
) -> "ImplementOps":
def _runner(pkg: Package, as_bytes: bool) -> Package | bytes:
with tracing("spec_gen"):
spec = spec_gen(pkg)
return implement_ops(pkg, spec, as_bytes=as_bytes)
return ImplementOps(_runner)