HUGR program-graph target for Qamomile.
The backend lowers prepared hierarchical Qamomile semantics directly to a
HUGR package. It deliberately bypasses circuit segmentation and CircuitProgram
so function boundaries, typed dataflow, and hybrid control can be preserved.
Generated quantum operations use the same tket.* extensions as Guppy,
making the result interoperable with the Guppy/HUGR ecosystem.
Overview¶
| Class | Description |
|---|---|
HugrCompilationPlan | Describe the callable symbols emitted into one HUGR module. |
HugrTarget | Plan, lower, package, and validate a Guppy-compatible HUGR target. |
HugrTranspiler | Compile Qamomile programs to Guppy-compatible HUGR packages. |
Classes¶
HugrCompilationPlan [source]¶
class HugrCompilationPlanDescribe the callable symbols emitted into one HUGR module.
Parameters:
| Name | Type | Description |
|---|---|---|
definitions | tuple[CallableRef, ...] | Reachable body-backed callable definitions emitted as HUGR functions. |
Constructor¶
def __init__(self, definitions: tuple[CallableRef, ...]) -> NoneAttributes¶
definitions: tuple[CallableRef, ...]
HugrTarget [source]¶
class HugrTargetPlan, lower, package, and validate a Guppy-compatible HUGR target.
Attributes¶
name: str Return the stable compilation target name.
Methods¶
compile¶
def compile(
self,
program: PreparedModule,
plan: HugrCompilationPlan,
) -> CompiledProgram[Any]Lower a prepared semantic module directly to a HUGR package.
Parameters:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared hierarchical semantic program. |
plan | HugrCompilationPlan | Callable emission plan. |
Returns:
CompiledProgram[Any] — CompiledProgram[Any]: HUGR package and target metadata.
Raises:
ImportError— If HUGR or TKET extension packages are unavailable.EmitError— If a semantic operation has no HUGR lowering yet.
plan¶
def plan(self, program: PreparedModule) -> HugrCompilationPlanSelect reachable body-backed callables for HUGR functions.
Parameters:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared hierarchical semantic program. |
Returns:
HugrCompilationPlan — Stable callable-definition order.
Raises:
CallableDefinitionConflictError— If one source callable produced multiple specialized bodies that cannot share one HUGR symbol.
validate¶
def validate(self, artifact: Any) -> NoneValidate a HUGR package with the native Rust-backed validator.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | Any | hugr.package.Package to validate. |
Raises:
ImportError— If the HUGR package is unavailable.HugrCliError— If HUGR validation rejects the package.
HugrTranspiler [source]¶
class HugrTranspilerCompile Qamomile programs to Guppy-compatible HUGR packages.
Parameters:
| Name | Type | Description |
|---|---|---|
config | CompilerConfig | None | Shared semantic preparation configuration. Defaults to :class:CompilerConfig. |
Constructor¶
def __init__(self, config: CompilerConfig | None = None) -> NoneInitialize the direct program-graph transpiler.
Parameters:
| Name | Type | Description |
|---|---|---|
config | CompilerConfig | None | Semantic preparation configuration. Defaults to :class:CompilerConfig. |
Attributes¶
compilertarget
Methods¶
to_hugr¶
def to_hugr(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> AnyReturn only the validated HUGR package artifact.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Top-level qkernel-like entrypoint. |
bindings | dict[str, Any] | None | Compile-time bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
Any — hugr.package.Package artifact.
transpile¶
def transpile(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> CompiledProgram[Any]Transpile a qkernel directly to a validated HUGR package.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Top-level qkernel-like entrypoint. |
bindings | dict[str, Any] | None | Compile-time bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names retained as HUGR function inputs. Defaults to None. |
Returns:
CompiledProgram[Any] — CompiledProgram[Any]: Validated hugr.package.Package artifact.
Raises:
ImportError— If HUGR dependencies are unavailable.QamomileCompileError— If semantic preparation or HUGR lowering rejects the program.HugrCliError— If target-native validation rejects the package.
qamomile.hugr.lowerer¶
Direct lowering from prepared Qamomile semantics to Guppy-compatible HUGR.
Overview¶
| Function | Description |
|---|---|
array_physical_region | Resolve a one-dimensional array to its ordered physical region. |
control_pattern_for_value | Return the LSB-first activation pattern for a control value. |
is_close_zero | Check if a given floating-point value is close to zero within a small tolerance. |
pair_block_operands | Pair all block inputs with category-grouped call-site operands. |
reject_control_flow_quantum_discard | Reject control-flow-internal quantum rebinds that discard state. |
resolve_root_array_index | Fold a view-local element index into the root array’s index space. |
resolve_root_qubit_address | Resolve an array-element value to its root (array_uuid, index). |
validate_region_args | Validate the SSA identities owned by a loop’s region arguments. |
| Class | Description |
|---|---|
ArrayValue | An array of typed IR values. |
BinOp | Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN). |
BinOpKind | |
Block | Unified block representation for all pipeline stages. |
CInitOperation | Initialize the classical values (const, arguments etc) |
CallPolicy | Describe the default lowering policy for a callable call. |
CallTransform | Describe the requested transform of a callable implementation. |
CallableDefinitionConflictError | Report two incompatible definitions claiming one callable symbol. |
CallableRef | Identify a callable independently of its Python object. |
CompOp | Comparison operation (EQ, NEQ, LT, LE, GT, GE). |
CompOpKind | |
CompilationMetadata | Record how a target artifact was produced. |
CompiledProgram | Package an artifact with its ABI, diagnostics, and provenance. |
ConcreteControlledU | Controlled-U with concrete (int) number of controls. |
ControlledUOperation | Base class for controlled-U operations. |
DictValue | A dictionary value stored as stable ordered entries. |
EmitError | Error during backend code emission. |
ForOperation | Represents a for loop operation. |
GateOperation | Quantum gate operation. |
GateOperationType | |
GlobalPhaseOperation | Multiply the complete quantum state by exp(i * phase). |
HasNestedOps | Mixin for operations that contain nested operation lists. |
HugrCompilationPlan | Describe the callable symbols emitted into one HUGR module. |
HugrTarget | Plan, lower, package, and validate a Guppy-compatible HUGR target. |
IfOperation | Represents an if-else conditional operation. |
InlinePass | Inline qkernel callables to create an affine block. |
InverseBlockOperation | Represent an inverse qkernel/block as a first-class IR operation. |
InvokeOperation | Represent a composite, stdlib, or oracle call. |
LoopCarriedRebind | Trace-time record of a variable rebound inside a loop body. |
MeasureOperation | |
MeasureVectorOperation | Measure a vector of qubits. |
NotOp | |
PauliEvolveOp | Pauli evolution operation: exp(-i * gamma * H). |
PreparedModule | Hold a prepared entrypoint and its reachable callable definitions. |
ProjectOperation | Project a qubit in one Pauli basis and keep the projected state. |
QInitOperation | Initialize the qubit |
ResetOperation | Reset a qubit to the |0> state and return the fresh handle. |
ReturnOperation | Explicit return operation marking the end of a block with return values. |
SelectOperation | Quantum multiplexer: apply case_blocks[i] when the index reads i. |
TupleValue | A tuple of IR values for structured data. |
ValidateWhileContractPass | Validates that all WhileOperation conditions are measurement-backed. |
Value | A typed SSA value in the IR. |
ValueBase | Nominal base for every typed IR value. |
ValueType | Base class for all value types in the IR. |
WhileOperation | Represents a while loop operation. |
Constants¶
ValueLike:TypeAlias='Value | ArrayValue | TupleValue | DictValue'
Functions¶
array_physical_region [source]¶
def array_physical_region(array: 'ArrayValue') -> tuple[str, tuple[int, ...]] | NoneResolve a one-dimensional array to its ordered physical region.
The region is expressed independently of SSA version UUIDs: the first
element is the root array’s logical_id and the second is the ordered
tuple of root-space indices addressed by the array. This makes a root
register and its full view compare equal while keeping partial, strided,
reordered, and different-root registers distinct.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Root array or nested sliced view to resolve. The array must be one-dimensional and have a compile-time integer length; every slice bound in its ancestry must also be constant. |
Returns:
tuple[str, tuple[int, ...]] | None — tuple[str, tuple[int, ...]] | None: (root_logical_id, indices)
when the complete ordered coverage is statically known, otherwise
None. Symbolic shapes or slice bounds remain unresolved so
callers can defer to emit-time physical mappings.
control_pattern_for_value [source]¶
def control_pattern_for_value(control_value: int | None, num_controls: int) -> tuple[int, ...]Return the LSB-first activation pattern for a control value.
Parameters:
| Name | Type | Description |
|---|---|---|
control_value | int | None | Required computational-basis value. None means the ordinary all-ones control state. |
num_controls | int | Concrete positive control-register width. |
Returns:
tuple[int, ...] — tuple[int, ...]: One 0/1 activation bit per flattened control,
with the first control represented by bit zero.
Raises:
TypeError— Ifcontrol_valueis not a PythonintorNone.ValueError— If the width or activation value is invalid.
Example:
>>> control_pattern_for_value(2, 2)
(0, 1)
>>> control_pattern_for_value(None, 2)
(1, 1)is_close_zero [source]¶
def is_close_zero(value: float, abs_tol: float = 1e-15) -> boolCheck if a given floating-point value is close to zero within a small tolerance.
Parameters:
| Name | Type | Description |
|---|---|---|
value | float | The floating-point value to check. |
abs_tol | float | Absolute tolerance passed to :func:math.isclose. Defaults to 1e-15. |
Returns:
bool — True if the value is close to zero, False otherwise.
pair_block_operands [source]¶
def pair_block_operands(
block: Block,
operands: Sequence[ValueBase],
) -> list[tuple[ValueBase, ValueBase]]Pair all block inputs with category-grouped call-site operands.
Parameters:
| Name | Type | Description |
|---|---|---|
block | Block | Operation-owned block whose inputs are being bound. |
operands | Sequence[ValueBase] | Call-site operands after any controls that are external to block have been removed. |
Returns:
list[tuple[ValueBase, ValueBase]] — list[tuple[ValueBase, ValueBase]]: Formal/actual pairs in the block’s
list[tuple[ValueBase, ValueBase]] — declaration order.
reject_control_flow_quantum_discard [source]¶
def reject_control_flow_quantum_discard(operations: list[Operation], bindings: dict[str, Any] | None = None) -> NoneReject control-flow-internal quantum rebinds that discard state.
The decoration-time rebind analyzer intentionally suppresses
branch-internal violations (its snapshot-restore scope truncates them)
so that compile-time-if branch-selection rebinds stay legal. That
leaves a runtime hole: rebinding a quantum variable inside a runtime
branch — to a fresh allocation (if cond: q = qmc.qubit("fresh"))
or to any other quantum value (if cond: q = other, including in
both branches at once) — silently drops the variable’s pre-branch
state exactly when a rebinding branch is taken. The frontend records
every branch-internal quantum binding change on the IfOperation
(BranchRebind, preserving the pre-branch value even when it no
longer appears in any merge); this check verifies each record against
each runtime execution path and raises QubitRebindError — the
same AffineTypeError the decoration-time analyzer raises for a
top-level rebind from a different quantum source, since this is that
exact affine violation surfacing at runtime inside a branch — when
the pre-branch value has no owner on a rebinding path: not consumed
inside the taken branch, not carried out through any merge of
that side, and not referenced by any operation outside the if.
Scalar Qubit and whole-register Vector[Qubit] rebinds are
covered alike.
Loop bodies are covered more strictly than branches (see
:func:_check_loop_quantum_discards): the frontend records quantum
rebinds on ForOperation / ForItemsOperation /
WhileOperation (LoopCarriedRebind entries whose before is
quantum), and each record is rejected unless it carries the incoming
value forward on the same wires, is a covered loop-invariant rebind,
or is the terminal fresh-allocation pattern where nested
QInitOperation reset/prepare-zero emission gives
qmc.qubit() fresh-per-iteration semantics. In-body consumption
of the incoming value itself is not an exemption: the read
re-executes against the traced register every iteration and matches
Python semantics only for the first one. A loop-body rebind needs no
runtime/compile-time classification, so loops are checked
wherever they appear on a live (non-pruned) path,
trip-count-agnostically, exactly like the classical loop-carried
check.
IfOperations are classified with the same condition resolution
CompileTimeIfLoweringPass uses (via bindings), including for
ifs nested inside runtime branches. A rebind confined to a
compile-time branch stays legal when the surrounding control flow is
compile-time too: rebinding to an alternative register under a
compile-time flag is the documented branch-selection idiom, and a
dead branch is eliminated entirely. A compile-time-TAKEN rebind
nested inside a runtime branch inherits that branch’s runtime
conditionality and is checked (and rejected when it discards). Only
ifs whose condition transitively derives from a measurement result
are checked — the same taint analysis the classical-lowering pipeline
uses, so expression-derived runtime conditions (~bit,
a & b) are covered; a non-measurement, non-compile-time condition
cannot drive runtime branching and is rejected at emit by the shared
condition resolution (though for this discard shape the emit-side merge
physical-resource check can fire first with its generic message).
What stays allowed:
consuming the original inside the branch before rebinding (
if cond: qmc.measure(q); q = qmc.qubit(...)). Scalar consumption is judged at the wire’s final in-branch version (:func:_wire_terminally_consumed), so gating the original and then dropping the gated state (if cond: q = qmc.x(q); q = qmc.qubit("fresh")) is a discard, not a consumption; whole-register rebinds keep the coarser any-touch granularity, where element or view reads count;ordinary quantum rebinds through gates (
q = qmc.h(q)) — the pre-branch value is carried out through the merge;rebinds whose pre-branch value is still owned outside the if (a value consumed before the if, or an alias referenced after it);
handle exchanges where every pre-branch value is carried by some merge of the same side (
q1, q2 = q2, q1).
The check is deliberately conservative toward allowing where it
cannot be exact. Merge lineage is over-approximated: producers without
a positional qubit model (composite gates, controlled blocks, casts)
contribute all of their quantum inputs as possible roots, so the
carried exemption can only grow — a rejection requires the
pre-branch value to be provably absent from every merge lineage.
Outside-ownership evidence is path-sensitive with respect to
enclosing ifs (a read on the sibling branch of an enclosing runtime
if does not exempt), but path-insensitive for non-ancestor runtime
ifs elsewhere: a value conditionally consumed downstream counts as
owned. Rebinds inside compile-time-TAKEN ifs nested in a runtime
branch are promoted to the enclosing if’s check trip-count- and
loop-agnostically; because the lowering pass erases those nested ifs
(and their records), the promoted rebinds are only caught by the
pre-fold PartialEvaluationPass hook, not by the AnalyzePass
safety net.
Scope contract: the scan recurses through control-flow nesting only
(IfOperation branches and HasNestedOps bodies). Boxed
implementation blocks — InvokeOperation bodies and implementations,
InverseBlockOperation.implementation_block,
ControlledUOperation.block — are NOT descended into: they stay
HIERARCHICAL recipe blocks outside the entrypoint pipeline, exactly
like every other transpile-time rebind check
(reject_loop_carried_classical_rebinds, AffineValidationPass,
both built on the same HasNestedOps walk). A discard written
inside a composite’s recipe kernel is therefore only covered by the
decoration-time top-level analyzer, with the same branch/loop
suppression as everywhere else pre-IR.
Exposed at module scope because it runs from two passes:
PartialEvaluationPass calls it before folding and if-lowering
(with bindings, so compile-time branches are classified exactly as
the lowering pass will lower them), and AnalyzePass calls it again
as a safety net for pipelines that skip partial_eval.
Parameters:
| Name | Type | Description |
|---|---|---|
operations | list[Operation] | Operations to scan. Recurses through all control flow; every runtime if and every loop at any nesting depth on a live path is checked. |
bindings | dict[str, Any] | None | Compile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings). |
Raises:
QubitRebindError— If a runtime if branch rebinds a quantum variable whose pre-branch value has no consumer in that branch, no merge carrying it out of that side, and no reference outside the if — or a loop body rebinds a quantum variable whose incoming value it never consumes and whose pre-loop value has no owner outside the loop.
resolve_root_array_index [source]¶
def resolve_root_array_index(array: 'ArrayValue', index: int) -> tuple['ArrayValue', int] | NoneFold a view-local element index into the root array’s index space.
Walks the slice_of chain root-ward, composing each strided view’s
affine map parent_index = start + step * local_index. This is the
array-level counterpart of :func:resolve_root_qubit_address (which
starts from an array-element Value); both must stay consistent with
the composite carrier keys "<root_uuid>_<root_index>" registered by
QInitOperation at emit time.
Parameters:
| Name | Type | Description |
|---|---|---|
array | ArrayValue | Array the index is local to. May be a root array (slice_of unset) or an arbitrarily nested strided view. |
index | int | Element index in array’s own index space. |
Returns:
tuple['ArrayValue', int] | None — tuple[ArrayValue, int] | None: (root_array, composed_index) when
every slice bound on the chain is compile-time constant and
satisfies the frontend contract (non-negative slice_start,
positive slice_step). None when any slice_start /
slice_step on the chain is missing, symbolic, or violates
that contract; callers must then defer resolution rather than
guess. Out-of-contract bounds would compose index onto a
wrong root slot, so they are refused here too (the frontend
rejects them at trace time; this guard covers programmatically
constructed IR).
resolve_root_qubit_address [source]¶
def resolve_root_qubit_address(value: 'Value') -> tuple[str, int] | NoneResolve an array-element value to its root (array_uuid, index).
Walks the parent_array / slice_of chain and composes the nested
affine slice maps, so view[i] resolves to
(root_uuid, start + step * i) for the composed (start, step). The
returned pair is the build-stable identity of the physical qubit slot: the
root array’s QInitOperation always registers it as
QubitAddress(root_uuid, index), so this address resolves even when the
element’s own (per-version) UUID was never registered.
The transpiler’s resource allocator uses the same walk to resolve gate and measurement operands; this shared helper keeps both call sites consistent.
Parameters:
| Name | Type | Description |
|---|---|---|
value | Value | The value to resolve. Expected to be an array element (parent_array set with a single constant element_indices entry). |
Returns:
tuple[str, int] | None — tuple[str, int] | None: (root_array_uuid, composed_index) when
value is an array element with a constant index whose entire
slice_of chain has constant slice_start / slice_step.
None when value is not an array element, when its index is
non-constant, or when any slice bound in the chain is non-constant
(those cases are deferred to the emit-time resolver, which has
bindings available). Also None for a negative constant index
or a chain frame with negative slice_start / non-positive
slice_step — composing those would silently address a wrong
root slot, so they are refused rather than guessed (the frontend
rejects them at trace time; this guard covers programmatically
constructed IR).
validate_region_args [source]¶
def validate_region_args(op: ForOperation | ForItemsOperation | WhileOperation) -> tuple[RegionArg, ...]Validate the SSA identities owned by a loop’s region arguments.
A loop owns several definition namespaces: its iteration variables,
every RegionArg.block_arg, and every RegionArg.result. Those
identities must be pairwise disjoint. Otherwise different stages can
assign incompatible meanings to one UUID: a UUID-keyed environment has
only one slot, so binding either the iteration variable or the carried
value overwrites the other and makes both reads observe the same value.
Parameters:
| Name | Type | Description |
|---|---|---|
op | ForOperation | ForItemsOperation | WhileOperation | Loop operation whose region arguments should be validated. |
Returns:
tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.
Raises:
ValueError— If result counts or positions disagree, slot types differ, or any loop-owned definition identity collides with another definition or with a region initializer/body yield.
Classes¶
ArrayValue [source]¶
class ArrayValue(Value[T])An array of typed IR values.
When slice_of is set, this array is a strided view over another
array. Element accesses on a sliced ArrayValue resolve to
physical slots on the root parent via the affine map
parent_index = slice_start + slice_step * view_local_index,
applied recursively along slice_of chains. The emit-time
resolver walks this chain to produce the final qubit index; passes
that substitute or clone values must treat slice_of /
slice_start / slice_step as Value references that need to
track through the same mapping as parent_array.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
shape: tuple[Value, ...] = tuple(),
slice_of: 'ArrayValue | None' = None,
slice_start: 'Value | None' = None,
slice_step: 'Value | None' = None,
) -> NoneAttributes¶
logical_id: strmetadata: ValueMetadataname: strshape: tuple[Value, ...]slice_of: ‘ArrayValue | None’slice_start: ‘Value | None’slice_step: ‘Value | None’type: Tuuid: str
Methods¶
is_slice¶
def is_slice(self) -> boolReturn True if this array is a strided view of another array.
Returns:
bool — True iff slice_of is non-None.
next_version¶
def next_version(self) -> ArrayValue[T]BinOp [source]¶
class BinOp(BinaryOperationBase)Binary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: BinOpKind | None = None,
) -> NoneAttributes¶
kind: BinOpKind | Noneoperation_kind: OperationKindsignature: Signature
BinOpKind [source]¶
class BinOpKind(enum.Enum)Attributes¶
ADDDIVFLOORDIVMINMODMULPOWSUB
Block [source]¶
class BlockUnified block representation for all pipeline stages.
Replaces the older traced and callable IR wrappers with a single structure.
The kind field indicates which pipeline stage this block is at.
Constructor¶
def __init__(
self,
name: str = '',
label_args: list[str] = list(),
input_values: list[ValueLike] = list(),
output_values: list[ValueLike] = list(),
output_names: list[str] = list(),
operations: list['Operation'] = list(),
kind: BlockKind = BlockKind.HIERARCHICAL,
parameters: dict[str, Value] = dict(),
param_slots: tuple[ParamSlot, ...] = tuple(),
static_bindings: tuple[StaticBindingSlot, ...] = tuple(),
) -> NoneAttributes¶
effects: ‘KernelEffect’ Return lazily cached semantic effects for this block.input_values: list[ValueLike]kind: BlockKindlabel_args: list[str]measurement_result_indices: frozenset[int] Return public output positions derived from measurement.name: stroperations: list[‘Operation’]output_names: list[str]output_values: list[ValueLike]param_slots: tuple[ParamSlot, ...]parameters: dict[str, Value]static_bindings: tuple[StaticBindingSlot, ...]
Methods¶
call¶
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'Create an inline callable invocation against this block.
Parameters:
| Name | Type | Description |
|---|---|---|
**kwargs | ValueLike | Actual argument values keyed by self.label_args. |
Returns:
'InvokeOperation' — Inline-policy invocation whose callable
definition points at this block.
Raises:
KeyError— If a required label inself.label_argsis missing fromkwargs.
is_affine¶
def is_affine(self) -> boolReturn whether this block has passed affine validation.
Returns:
bool — True for AFFINE and ANALYZED blocks.
unbound_parameters¶
def unbound_parameters(self) -> list[str]Return list of unbound parameter names.
CInitOperation [source]¶
class CInitOperation(Operation)Initialize the classical values (const, arguments etc)
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
CallPolicy [source]¶
class CallPolicy(enum.Enum)Describe the default lowering policy for a callable call.
Attributes¶
INLINENATIVE_FIRSTPRESERVE_BOX
CallTransform [source]¶
class CallTransform(enum.Enum)Describe the requested transform of a callable implementation.
Attributes¶
CONTROLLEDDIRECTINVERSE
CallableDefinitionConflictError [source]¶
class CallableDefinitionConflictError(QamomileCompileError)Report two incompatible definitions claiming one callable symbol.
Parameters:
| Name | Type | Description |
|---|---|---|
symbol | str | Fully qualified callable symbol with conflicting bodies. |
Example:
Correct — give independently implemented callables distinct origins
or explicit namespaces::
configure_composite(left, namespace="example.left")
configure_composite(right, namespace="example.right")
Incorrect — attaching two different bodies to the same explicit
symbol causes this error during preparation::
configure_composite(left, namespace="example.shared", name="op")
configure_composite(right, namespace="example.shared", name="op")Constructor¶
def __init__(self, symbol: str) -> NoneInitialize a callable-definition collision diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
symbol | str | Fully qualified callable symbol with conflicting definitions. |
Attributes¶
symbol: str
CallableRef [source]¶
class CallableRefIdentify a callable independently of its Python object.
Parameters:
| Name | Type | Description |
|---|---|---|
namespace | str | Stable namespace such as "qamomile.stdlib" or "user". |
name | str | Stable callable name within the namespace. |
version | str | Schema or behavior version for the callable. |
Constructor¶
def __init__(self, namespace: str, name: str, version: str = '1') -> NoneAttributes¶
name: strnamespace: strversion: str
CompOp [source]¶
class CompOp(BinaryOperationBase)Comparison operation (EQ, NEQ, LT, LE, GT, GE).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
kind: CompOpKind | None = None,
) -> NoneAttributes¶
kind: CompOpKind | Noneoperation_kind: OperationKindsignature: Signature
CompOpKind [source]¶
class CompOpKind(enum.Enum)Attributes¶
EQGEGTLELTNEQ
CompilationMetadata [source]¶
class CompilationMetadataRecord how a target artifact was produced.
Parameters:
| Name | Type | Description |
|---|---|---|
target | str | Stable compilation target name. |
pipeline | str | Lowering-family or pipeline name. |
properties | Mapping[str, Any] | Additional immutable-by-contract target metadata. Defaults to an empty mapping. |
Constructor¶
def __init__(
self,
target: str,
pipeline: str,
properties: Mapping[str, Any] = dict(),
) -> NoneAttributes¶
pipeline: strproperties: Mapping[str, Any]target: str
CompiledProgram [source]¶
class CompiledProgram(Generic[ArtifactT])Package an artifact with its ABI, diagnostics, and provenance.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | ArtifactT | Target-native circuit, graph, module, or package. |
abi | ProgramABI | Runtime-visible input and output contract. |
metadata | CompilationMetadata | Target and pipeline provenance. |
diagnostics | tuple[CompilationDiagnostic, ...] | Non-fatal compilation diagnostics. Defaults to an empty tuple. |
Constructor¶
def __init__(
self,
artifact: ArtifactT,
abi: ProgramABI,
metadata: CompilationMetadata,
diagnostics: tuple[CompilationDiagnostic, ...] = (),
) -> NoneAttributes¶
abi: ProgramABIartifact: ArtifactTdiagnostics: tuple[CompilationDiagnostic, ...]metadata: CompilationMetadata
ConcreteControlledU [source]¶
class ConcreteControlledU(ControlledUOperation)Controlled-U with concrete (int) number of controls.
Operand layout: [ctrl_0, ..., ctrl_n, tgt_0, ..., tgt_m, params...]
Result layout: [ctrl_0', ..., ctrl_n', tgt_0', ..., tgt_m']
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: int = 1,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
control_operands: list[Value]control_value: int | Nonenum_controls: intparam_operands: list[Value] Get classical/object operands after the concrete control prefix.signature: Signaturetarget_operands: list[Value]
ControlledUOperation [source]¶
class ControlledUOperation(Operation)Base class for controlled-U operations.
Two concrete subclasses handle distinct operand layouts:
ConcreteControlledU: Fixednum_controls: int, individual qubit operands.SymbolicControlledU: Symbolicnum_controls: Value, vector-based control operands; optionalcontrol_indicesselects a subset of the control vector to act as controls (the rest pass through).
All isinstance(op, ControlledUOperation) checks match every subclass.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
power: int | Value = 1,
block: Block | None = None,
num_controls: int | Value = 1,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
) -> NoneAttributes¶
block: Block | Nonecallable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_operands: list[Value] Get the control qubit values.is_symbolic_num_controls: bool Whether num_controls is symbolic (Value) rather than concrete.num_controls: int | Valueoperation_kind: OperationKindparam_operands: list[Value] Get the controlled operation’s classical/object arguments.power: int | Valuesignature: Signaturetarget_operands: list[Value] Get the target qubit values (arguments to U).
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationDictValue [source]¶
class DictValue(_MetadataValueMixin, ValueBase)A dictionary value stored as stable ordered entries.
Constructor¶
def __init__(
self,
name: str,
entries: tuple[tuple[TupleValue | Value, Value], ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
entries: tuple[tuple[TupleValue | Value, Value], ...]logical_id: strmetadata: ValueMetadataname: strtype: DictTypeuuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> DictValueEmitError [source]¶
class EmitError(QamomileCompileError)Error during backend code emission.
Constructor¶
def __init__(self, message: str, operation: str | None = None)Initialize a backend emission diagnosis.
Parameters:
| Name | Type | Description |
|---|---|---|
message | str | Human-readable emission failure. |
operation | str | None | Related operation description. Defaults to None. |
Attributes¶
operation
ForOperation [source]¶
class ForOperation(HasNestedOps, Operation)Represents a for loop operation.
Example:
for i in range(start, stop, step):
bodyConstructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
loop_var: str = '',
loop_var_value: Value | None = None,
operations: list[Operation] = list(),
loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
region_args: tuple[RegionArg, ...] = (),
captures: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]loop_var: strloop_var_value: Value | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]Include loop_var_value so cloning/substitution stays consistent.
Without this override, UUIDRemapper would clone every body
reference to the loop variable to a fresh UUID, but leave
loop_var_value pointing at the un-cloned original — emit-time
UUID-keyed lookups for the loop variable would then miss.
Loop-carried rebind records and region arguments are included
for the same reason.
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return the range-loop body with its explicit interface.
Returns:
tuple[Region, ...] — tuple[Region, ...]: One body region containing the induction
value, carried-value formals, captures, and carried yields.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the range-loop body and complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt range-loop operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationGateOperation [source]¶
class GateOperation(Operation)Quantum gate operation.
For rotation gates (RX, RY, RZ, P, CP, RZZ), the angle parameter is
stored as the last element of operands. Use the theta
property for typed read access and the rotation / fixed factory
class-methods for type-safe construction.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
gate_type: GateOperationType | None = None,
) -> NoneAttributes¶
gate_type: GateOperationType | Noneoperation_kind: OperationKindqubit_operands: list[Value] Qubit operands (excluding the theta parameter if present).signature: Signaturetheta: Value | None Angle parameter for rotation gates, orNonefor fixed gates.
Methods¶
fixed¶
@classmethod
def fixed(
cls,
gate_type: GateOperationType,
qubits: list[Value],
results: list[Value],
) -> 'GateOperation'Create a fixed gate (H, X, CX, SWAP, …) with no angle parameter.
rotation¶
@classmethod
def rotation(
cls,
gate_type: GateOperationType,
qubits: list[Value],
theta: Value,
results: list[Value],
) -> 'GateOperation'Create a rotation gate (RX, RY, RZ, P, CP, RZZ) with an angle.
GateOperationType [source]¶
class GateOperationType(enum.Enum)Attributes¶
CPCXCZHPRXRYRZRZZSSDGSWAPTTDGTOFFOLIXYZ
GlobalPhaseOperation [source]¶
class GlobalPhaseOperation(Operation)Multiply the complete quantum state by exp(i * phase).
Global phase has no target qubit and does not create a new quantum value. Keeping the phase as the operation’s sole ordinary operand lets generic IR passes substitute, serialize, and analyze it without a special value-field protocol. A surrounding controlled-unitary lowering turns the operation into an observable phase gate on the accumulated controls.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[Value] | Exactly one scalar FloatType phase angle in radians. |
results | list[Value] | Must be empty because global phase changes no qubit identity. |
Raises:
ValueError— If the operand/result layout is invalid or the phase is not a scalarFloatTypevalue.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Classify global phase as a quantum operation.phase: Value Return the scalar phase-angle operand.signature: Signature Return the zero-qubit operation signature.
HasNestedOps [source]¶
class HasNestedOpsMixin for operations that contain nested operation lists.
nested_regions() is the canonical traversal API because it exposes
operations together with block arguments, captures, and yields.
nested_op_lists() / rebuild_nested() remain compatibility helpers
for specialized consumers while they migrate to the region interface.
Methods¶
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]Return all nested operation lists in this control flow op.
nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return uniform views of every nested operation region.
Subclasses with explicit block arguments, captures, or yields override
this method. The fallback keeps legacy operation-owned blocks visible
while consumers migrate from nested_op_lists.
Returns:
tuple[Region, ...] — tuple[Region, ...]: Region views in nested_op_lists order.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> OperationReturn a copy with nested operation lists replaced.
new_lists must have the same length/order as nested_op_lists().
rebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationReturn a copy with replacement region operation sequences.
Concrete control-flow operations override this method to rebuild both their body operations and boundary values. The fallback supports legacy region owners whose boundary remains operation-specific.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Replacement regions in nested_regions order. |
Returns:
Operation — Rebuilt control-flow operation.
Raises:
ValueError— If the replacement region count differs from the operation’s current region count.
HugrCompilationPlan [source]¶
class HugrCompilationPlanDescribe the callable symbols emitted into one HUGR module.
Parameters:
| Name | Type | Description |
|---|---|---|
definitions | tuple[CallableRef, ...] | Reachable body-backed callable definitions emitted as HUGR functions. |
Constructor¶
def __init__(self, definitions: tuple[CallableRef, ...]) -> NoneAttributes¶
definitions: tuple[CallableRef, ...]
HugrTarget [source]¶
class HugrTargetPlan, lower, package, and validate a Guppy-compatible HUGR target.
Attributes¶
name: str Return the stable compilation target name.
Methods¶
compile¶
def compile(
self,
program: PreparedModule,
plan: HugrCompilationPlan,
) -> CompiledProgram[Any]Lower a prepared semantic module directly to a HUGR package.
Parameters:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared hierarchical semantic program. |
plan | HugrCompilationPlan | Callable emission plan. |
Returns:
CompiledProgram[Any] — CompiledProgram[Any]: HUGR package and target metadata.
Raises:
ImportError— If HUGR or TKET extension packages are unavailable.EmitError— If a semantic operation has no HUGR lowering yet.
plan¶
def plan(self, program: PreparedModule) -> HugrCompilationPlanSelect reachable body-backed callables for HUGR functions.
Parameters:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared hierarchical semantic program. |
Returns:
HugrCompilationPlan — Stable callable-definition order.
Raises:
CallableDefinitionConflictError— If one source callable produced multiple specialized bodies that cannot share one HUGR symbol.
validate¶
def validate(self, artifact: Any) -> NoneValidate a HUGR package with the native Rust-backed validator.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | Any | hugr.package.Package to validate. |
Raises:
ImportError— If the HUGR package is unavailable.HugrCliError— If HUGR validation rejects the package.
IfOperation [source]¶
class IfOperation(HasNestedOps, Operation)Represents an if-else conditional operation.
Example:
if condition:
true_body
else:
false_bodyConstructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
true_operations: list[Operation] = list(),
false_operations: list[Operation] = list(),
true_yields: list[Value] = list(),
false_yields: list[Value] = list(),
branch_rebinds: tuple[BranchRebind, ...] = (),
true_captures: tuple[ValueBase, ...] = (),
false_captures: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
branch_rebinds: tuple[BranchRebind, ...]condition: Valuefalse_captures: tuple[ValueBase, ...]false_operations: list[Operation]false_yields: list[Value]operation_kind: OperationKindsignature: Signaturetrue_captures: tuple[ValueBase, ...]true_operations: list[Operation]true_yields: list[Value]
Methods¶
add_merge¶
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> NoneAppend a branch-merge slot to this if-else.
The only sanctioned construction path for merges: it keeps the
yield lists and results index-aligned so iter_merges can
rely on the invariants it checks.
Parameters:
| Name | Type | Description |
|---|---|---|
true_value | Value | Value selected when the condition is true. |
false_value | Value | Value selected when the condition is false. Must have the same type as true_value. |
result | Value | Fresh SSA value representing the merged output. Must have the same type as the branch values. |
Raises:
RuntimeError— If the condition operand has not been attached to this operation yet (operands[0]must exist before merges are added), or the branch / result types do not match.
all_input_values¶
def all_input_values(self) -> list[ValueBase]Include branch-yield values and rebind records for cloning/substitution.
The yields are subclass-specific Value fields (not operands —
see the class docstring), so generic passes reach them through
this override, mirroring ForItemsOperation.key_var_values.
Branch rebind records follow the loop operations’ rationale: the
recorded pre-branch values reference program values by identity,
so inline cloning must remap them in lockstep with operands.
Read-based checks must not treat the records as reads (see
_op_read_uuids in the analyze pass module).
Returns:
list[ValueBase] — list[ValueBase]: Base input values plus the true/false
yields and rebind-record values.
iter_merges¶
def iter_merges(self) -> Iterator[IfMerge]Iterate the branch-merge slots of this if-else.
This is the single read API for merge semantics: passes must consume merges through it (never through the yield lists directly) so the underlying storage can change without touching consumers.
Yields:
IfMerge — One entry per merged output, in result order.
Raises:
RuntimeError— If the stored merge data is internally inconsistent (the yield-list lengths differ from the result count, or the condition operand is missing while merges are attached). This indicates IR corruption, not a user error. The per-merge corruption modes of the old embedded-operation storage (a foreign entry, a malformed or mismatched condition, a result copy diverging fromresults[i]) cannot be represented in the yield-list storage and need no checks.
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]Return the two branch bodies (merge yields are not operations).
Returns:
list[list[Operation]] — list[list[Operation]]: [true_operations, false_operations].
The branch-merge yields are values, not operations, so
they are intentionally absent here.
nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return the true and false branch interfaces.
Returns:
tuple[Region, ...] — tuple[Region, ...]: True and false regions in that order, with
branch-local captures and merge yields.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> OperationReturn a copy with the true and false branch bodies replaced.
Parameters:
| Name | Type | Description |
|---|---|---|
new_lists | list[list[Operation]] | The replacement branch bodies in nested_op_lists order ([true_operations, false_operations]). |
Returns:
Operation — A copy of this if-else with the branch bodies
swapped and all other fields (yields, rebinds) preserved.
rebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild both branches and their complete boundary interfaces.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | True and false replacement regions. |
Returns:
Operation — Rebuilt conditional operation.
Raises:
ValueError— If region count, block arguments, or yield signatures are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, result, branch-yield, and rebind-record values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
InlinePass [source]¶
class InlinePass(Pass[Block, Block])Inline qkernel callables to create an affine block.
This pass recursively inlines function calls while preserving control flow structures (For, If, While).
Input: Block with BlockKind.HIERARCHICAL (may contain callable calls) Output: Block with BlockKind.AFFINE (no inline callable calls)
Attributes¶
name: str
Methods¶
run¶
def run(self, input: Block) -> BlockInline all inline-policy callable invocations.
Self-recursive qkernel invocations are unrolled one level per call:
the inner self-call is substituted but left intact so the outer
fixed-point loop can fold the base-case if between iterations.
The output kind is AFFINE when no inlineable calls remain,
otherwise HIERARCHICAL.
InverseBlockOperation [source]¶
class InverseBlockOperation(Operation)Represent an inverse qkernel/block as a first-class IR operation.
The operation stores both the original forward block and a Qamomile-built
inverse implementation block. Emitters may use source_block with a
backend-native inverse/adjoint primitive, then fall back to
implementation_block when native inversion is unavailable.
Operands are ordered as scalar control qubits, target quantum operands,
then classical/object parameters. Results mirror the quantum operand
layout: control results first, then one target result per target operand.
Vector target operands therefore count as one operand/result while
contributing their scalar width to num_target_qubits.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_control_qubits: int = 0,
num_target_qubits: int = 0,
custom_name: str = '',
source_block: Block | None = None,
implementation_block: Block | None = None,
callable_ref: CallableRef | None = None,
callable_attrs: dict[str, Any] = dict(),
control_value: int | None = None,
) -> NoneAttributes¶
callable_attrs: dict[str, Any]callable_ref: CallableRef | Nonecontrol_qubits: list[‘Value’] Return control quantum operands.control_value: int | Nonecustom_name: strimplementation_block: Block | Nonename: str Return a human-readable inverse operation name.num_control_qubits: intnum_target_qubits: intoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return classical/object parameter operands.signature: Signature Return the operation signature.source_block: Block | Nonetarget_qubits: list[‘Value’] Return target quantum operands.
InvokeOperation [source]¶
class InvokeOperation(Operation)Represent a composite, stdlib, or oracle call.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | list[ValueLike] | Input values consumed by the call. |
results | list[ValueLike] | Output values produced by the call. |
target | CallableRef | Callable identity. |
transform | CallTransform | Direct, inverse, or controlled invocation. |
attrs | dict[str, Any] | Compile-time attributes for strategy, arity, and resource/lowering decisions. control_value is reserved for a controlled invocation’s LSB-first activation value. Values must be serializer-friendly. |
definition | CallableDef | None | Optional callable definition. |
Constructor¶
def __init__(
self,
operands: Sequence[ValueLike] | None = None,
results: Sequence[ValueLike] | None = None,
*,
target: CallableRef | None = None,
transform: CallTransform = CallTransform.DIRECT,
attrs: dict[str, Any] | None = None,
definition: CallableDef | None = None,
) -> NoneInitialize an invocation operation.
Parameters:
| Name | Type | Description |
|---|---|---|
operands | Sequence[ValueLike] | None | Input values consumed by the call. Defaults to None, meaning no operands. |
results | Sequence[ValueLike] | None | Output values produced by the call. Defaults to None, meaning no results. |
target | CallableRef | None | Callable identity. Defaults to an anonymous user callable when omitted. |
transform | CallTransform | Requested call transform. Defaults to CallTransform.DIRECT. |
attrs | dict[str, Any] | None | Serializer-friendly call attributes. Defaults to an empty dict. |
definition | CallableDef | None | Callable definition. Defaults to None, in which case one is created from target. |
Raises:
TypeError— If a controlled invocation’scontrol_valueis not a PythonintorNone.ValueError— Ifcontrol_valueis used on a non-controlled call or does not fit the controlled invocation’s width.
Attributes¶
attrs: dict[str, Any]body: Block | None Return the callable’s default body from its definition.body_ref: CallableBodyRef | None Return the callable’s deferred body reference.control_qubits: list[‘Value’] Return the control-qubit operands.control_value: int | None Return the controlled invocation’s activation value.custom_name: str Return the display name for custom callable boxes.default_policy: CallPolicy Return the callable’s default lowering policy.definition: CallableDef | Noneeffects: ‘KernelEffect’ Return cached effects of the selected callable implementation.gate_type: CompositeGateType Return the standard composite classification for this invocation.measurement_result_indices: frozenset[int] Return invocation result positions derived from measurement.name: str Return the display name for this invocation.num_control_qubits: int Return the number of leading control-qubit operands.num_target_qubits: int Return the number of target-qubit operands.operandsoperation_kind: OperationKind Return the operation kind.parameters: list[‘Value’] Return non-qubit parameter operands.resultssignature: Signature Return the operation signature.strategy_name: str | None Return the selected lowering/resource strategy name.target: CallableReftarget_qubits: list[‘Value’] Return the target-qubit operands.transform: CallTransform
Methods¶
effective_body¶
def effective_body(
self,
*,
backend: str | None = None,
strategy: str | None = None,
) -> Block | NoneReturn the implementation body selected for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
backend | str | None | Backend name to match. Defaults to None. |
strategy | str | None | Strategy name to match. Defaults to the invocation’s strategy_name attribute. |
Returns:
Block | None — Block | None: Selected implementation body, or the callable’s
Block | None — default body when no transform-specific implementation exists.
Block | None — A compiler may synthesize inverse or controlled behavior from this
Block | None — fallback body.
implementation_for¶
def implementation_for(
self,
*,
backend: str | None = None,
strategy: str | None = None,
) -> CallableImplementation | NoneReturn the selected implementation for this invocation.
Parameters:
| Name | Type | Description |
|---|---|---|
backend | str | None | Backend name to match. Defaults to None, which only selects backend-generic implementations. |
strategy | str | None | Strategy name to match. Defaults to None, meaning the invocation’s strategy_name attribute is used. |
Returns:
CallableImplementation | None — CallableImplementation | None: Matching implementation candidate,
CallableImplementation | None — or None when the callable definition has no match.
LoopCarriedRebind [source]¶
class LoopCarriedRebindTrace-time record of a variable rebound inside a loop body.
Two rebind families share this record type, distinguished by the
type of before:
Classical scalar (
beforeclassical): the frontend traces a loop body exactly once, so a Python-level reassignment liketotal = total + iproduces IR whose right-hand side reads the fixed pre-loop value instead of the previous iteration’s value. Most such carries are now represented as explicitRegionArgs (see above) and are fully supported; a classical record is only created for the shapes region binding declines —while-body carries (a runtime while loop cannot be unrolled) and measurement-backedBitcarries — and the transpiler’s classical loop-carried check rejects those with a targeted error instead of silently miscompiling.Quantum (
beforequantum): the loop body left the variable bound to a different quantum resource (logical_idchange — a fresh allocation or another register, not a gate self-update). The transpiler’s control-flow discard check (reject_control_flow_quantum_discard) rejects the ones whose incoming state the body never consumes.
Constructor¶
def __init__(
self,
var_name: str,
before: ValueBase,
after: ValueBase,
before_synthesized: bool = False,
) -> NoneAttributes¶
after: ValueBasebefore: ValueBasebefore_synthesized: boolvar_name: str
MeasureOperation [source]¶
class MeasureOperation(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
MeasureVectorOperation [source]¶
class MeasureVectorOperation(Operation)Measure a vector of qubits.
Takes a Vector[Qubit] (ArrayValue) and produces a Vector[Bit] (ArrayValue). This operation measures all qubits in the vector as a single operation.
operands: [ArrayValue of qubits] results: [ArrayValue of bits]
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
NotOp [source]¶
class NotOp(Operation)Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
input: Valueoperation_kind: OperationKindoutput: Valuesignature: Signature
PauliEvolveOp [source]¶
class PauliEvolveOp(Operation)Pauli evolution operation: exp(-i * gamma * H).
This operation applies the time evolution of a Pauli Hamiltonian to a quantum register.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
evolved_qubits: Value The evolved quantum register result.gamma: Value The evolution time parameter.observable: Value The Observable parameter operand.operation_kind: OperationKind PauliEvolveOp is QUANTUM - transforms quantum state.qubits: Value The quantum register operand.signature: Signature
PreparedModule [source]¶
class PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
Parameters:
| Name | Type | Description |
|---|---|---|
entrypoint_ref | CallableRef | Stable symbol assigned to the program entrypoint. |
entrypoint | Block | Hierarchical semantic block for the entrypoint. |
definitions | Mapping[CallableRef, CallableDef] | Reachable callable definitions keyed by their stable symbols. |
definition_variants | Mapping[CallableRef, tuple[CallableDef, ...]] | Every distinct body observed for a symbol. Multiple variants of one origin may be valid for circuit-family inlining but must be handled or rejected by targets that emit one function per symbol. |
call_graph | Mapping[CallableRef, frozenset[CallableRef]] | Directed caller-to-callee relation, including the entrypoint symbol. |
abi | ProgramABI | Classical public input and output contract. |
bindings | Mapping[str, Any] | Compile-time values retained for direct program-graph targets. Circuit-family targets receive the same values through their emit pass. |
Constructor¶
def __init__(
self,
entrypoint_ref: CallableRef,
entrypoint: Block,
definitions: Mapping[CallableRef, CallableDef],
definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]],
call_graph: Mapping[CallableRef, frozenset[CallableRef]],
abi: ProgramABI,
bindings: Mapping[str, Any],
) -> NoneAttributes¶
abi: ProgramABIbindings: Mapping[str, Any]call_graph: Mapping[CallableRef, frozenset[CallableRef]]definition_variants: Mapping[CallableRef, tuple[CallableDef, ...]]definitions: Mapping[CallableRef, CallableDef]entrypoint: Blockentrypoint_ref: CallableRef
Methods¶
body¶
def body(self, ref: CallableRef) -> BlockReturn the semantic body associated with a program symbol.
Parameters:
| Name | Type | Description |
|---|---|---|
ref | CallableRef | Entrypoint or callable symbol to resolve. |
Returns:
Block — Hierarchical semantic body for ref.
Raises:
KeyError— Ifrefis neither the entrypoint nor a reachable body-backed callable definition.
owned_snapshot¶
def owned_snapshot(self) -> PreparedModuleCreate a deep, target-owned snapshot of prepared semantics.
The semantic IR intentionally remains mutable while compiler passes are being developed. Copying the entrypoint and definition registry as one object graph preserves shared callable bodies while preventing one target from mutating the source module observed by another.
Returns:
PreparedModule — Deep snapshot with read-only definition and call
graph registries.
ProjectOperation [source]¶
class ProjectOperation(Operation)Project a qubit in one Pauli basis and keep the projected state.
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
axis: str = 'z',
) -> NoneAttributes¶
axis: stroperation_kind: OperationKindsignature: Signature
QInitOperation [source]¶
class QInitOperation(Operation)Initialize the qubit
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
ResetOperation [source]¶
class ResetOperation(Operation)Reset a qubit to the |0> state and return the fresh handle.
Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKindsignature: Signature
ReturnOperation [source]¶
class ReturnOperation(Operation)Explicit return operation marking the end of a block with return values.
This operation represents an explicit return statement in the IR. It takes the values to be returned as operands and produces no results (it is a terminal operation that transfers control flow back to the caller).
operands: [Value, ...] - The values to return (may be empty for void returns) results: [] - Always empty (terminal operation)
Example:
A function that returns two values (a UInt and a Float):
ReturnOperation(
operands=[uint_value, float_value],
results=[],
)
The signature would be:
operands=[ParamHint("return_0", UIntType()), ParamHint("return_1", FloatType())]
results=[]Constructor¶
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> NoneAttributes¶
operation_kind: OperationKind Return CLASSICAL as this is a control flow operation without quantum effects.signature: Signature Return the signature with operands for each return value and no results.
SelectOperation [source]¶
class SelectOperation(Operation)Quantum multiplexer: apply case_blocks[i] when the index reads i.
Concrete operand layout:
[idx_0, ..., idx_{k-1}, tgt_0, ..., tgt_m, params...].
Symbolic-width operand layout:
[idx_arg_0, ..., idx_arg_{a-1}, tgt_0, ..., tgt_m, params...].
Results mirror the quantum operand grouping.
A concrete index register is normalized to one scalar Qubit operand
per physical index qubit. A symbolic-width register instead retains each
leading caller argument as one scalar or array operand until its bound
shape is known. Whole-Vector[Qubit] / scalar targets follow and keep
their shapes, and classical parameters shared across every case come last.
Index bit order is LSB-first: idx_0 is the least-significant
bit, matching Qamomile’s qubit-zero convention. Case i is selected
when index qubit j reads bit j of i. len(case_blocks)
need not be a power of two; index values >= len(case_blocks) apply
no operation (identity).
Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
num_index_qubits: int | Value = 0,
case_blocks: list[Block] = list(),
num_index_args: int = 0,
) -> NoneAttributes¶
case_blocks: list[Block]index_operands: list[Value] Return the grouped index-prefix operands.is_symbolic_num_index_qubits: bool Return whether the index width is a symbolic IR value.num_cases: int Return the number of selectable cases.num_index_args: intnum_index_qubits: int | Valueoperation_kind: OperationKind Return the operation kind.param_operands: list[Value] Return the shared classical parameter operands.signature: Signature Return the operation signature.target_operands: list[Value] Return the quantum target operands applied by every case.
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]Return every value consumed by the SELECT operation.
Returns:
list[ValueBase] — list[ValueBase]: Ordinary operands plus the symbolic index-width
value when present.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationReplace operand and symbolic-width values by UUID.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed replacement values. |
Returns:
Operation — Rebuilt SELECT operation with matching values replaced.
TupleValue [source]¶
class TupleValue(_MetadataValueMixin, ValueBase)A tuple of IR values for structured data.
Constructor¶
def __init__(
self,
name: str,
elements: tuple[ValueLike, ...] = tuple(),
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
) -> NoneAttributes¶
elements: tuple[ValueLike, ...]logical_id: strmetadata: ValueMetadataname: strtype: ‘TupleType’uuid: str
Methods¶
is_constant¶
def is_constant(self) -> boolnext_version¶
def next_version(self) -> TupleValueValidateWhileContractPass [source]¶
class ValidateWhileContractPass(Pass[Block, Block])Validates that all WhileOperation conditions are measurement-backed.
Builds a producer map (result UUID → producing Operation instance) and checks every WhileOperation operand against it. A valid condition must be:
A
ValuewithBitTypeMeasurement-backed: produced by
MeasureOperationdirectly, or anIfOperationmerge output where every reachable leaf source is itself measurement-backed.
Both operands[0] (initial condition) and operands[1]
(loop-carried condition) are validated.
Raises ValidationError for any non-measurement while pattern.
Attributes¶
name: str
Methods¶
run¶
def run(self, block: Block) -> BlockValidate all WhileOperations and return block unchanged.
Value [source]¶
class Value(_MetadataValueMixin, ValueBase, Generic[T])A typed SSA value in the IR.
The name field is display-only: it labels the value for
visualization and error messages and has no role in identity. Identity
is carried by uuid (per-version) and logical_id (across
versions).
An empty string (name="") is the anonymous marker used by
auto-generated tmp values (arithmetic results, comparison results,
coerced constants). Compiler-internal identity and writes use UUIDs or
explicit parameter metadata. Compatibility readers may consult a non-empty
label only after those identity channels, so anonymous temporaries cannot
collide through a shared display key.
Constructor¶
def __init__(
self,
type: T,
name: str,
version: int = 0,
metadata: ValueMetadata = ValueMetadata(),
uuid: str = (lambda: str(uuid.uuid4()))(),
logical_id: str = (lambda: str(uuid.uuid4()))(),
parent_array: ArrayValue | None = None,
element_indices: tuple[Value, ...] = (),
) -> NoneAttributes¶
element_indices: tuple[Value, ...]logical_id: strmetadata: ValueMetadataname: strparent_array: ArrayValue | Nonetype: Tuuid: strversion: int
Methods¶
is_array_element¶
def is_array_element(self) -> boolnext_version¶
def next_version(self) -> Value[T]Create a new Value with incremented version and fresh UUID.
Metadata is intentionally preserved across versions so that
parameter bindings and constant annotations remain accessible
after the value is updated (e.g. by a gate application or a
classical operation). The logical_id also stays the same:
it identifies the same logical variable across SSA versions,
independently of backend resource allocation. This applies to
every Value regardless of its type (Qubit, Float,
Bit, ...) -- it is not specific to qubits.
ValueBase [source]¶
class ValueBaseNominal base for every typed IR value.
Runtime compiler passes inspect values in their innermost loops. A nominal base keeps those checks constant-time; a runtime-checkable protocol would repeatedly scan the protocol members on Python versions that do not cache structural checks.
Attributes¶
logical_id: strmetadata: ValueMetadataname: strtype: ValueType Return the static IR type carried by this value.uuid: str
Methods¶
get_const¶
def get_const(self) -> int | float | bool | NoneReturn the scalar constant carried by this value.
Returns:
int | float | bool | None — int | float | bool | None: Constant value, or None when the
value is not constant.
is_constant¶
def is_constant(self) -> boolReturn whether this value carries a scalar constant.
Returns:
bool — Whether scalar constant metadata is present.
is_parameter¶
def is_parameter(self) -> boolReturn whether this value represents a runtime parameter.
Returns:
bool — Whether parameter metadata is present.
next_version¶
def next_version(self) -> ValueBaseCreate the next SSA version of this value.
Returns:
ValueBase — A value with a fresh version UUID and preserved logical
identity.
parameter_name¶
def parameter_name(self) -> str | NoneReturn the public parameter name carried by this value.
Returns:
str | None — str | None: Parameter name, or None for a non-parameter value.
ValueType [source]¶
class ValueType(abc.ABC)Base class for all value types in the IR.
Type instances are compared by class - all instances of the same type class are considered equal. This allows using type instances as dictionary keys where all QubitType() instances match.
Methods¶
is_classical¶
def is_classical(self) -> boolis_object¶
def is_object(self) -> boolis_quantum¶
def is_quantum(self) -> boollabel¶
def label(self) -> strWhileOperation [source]¶
class WhileOperation(HasNestedOps, Operation)Represents a while loop operation.
Only measurement-backed conditions are supported: the condition must
be a Bit value produced by qmc.measure(). Non-measurement
conditions (classical variables, constants, comparisons) are rejected
by ValidateWhileContractPass before reaching backend emit.
Example::
bit = qmc.measure(q)
while bit:
q = qmc.h(q)
bit = qmc.measure(q)Constructor¶
def __init__(
self,
operands: list[Value] = list(),
results: list[Value] = list(),
operations: list[Operation] = list(),
max_iterations: int | None = None,
loop_carried_rebinds: tuple[LoopCarriedRebind, ...] = (),
region_args: tuple[RegionArg, ...] = (),
captures: tuple[ValueBase, ...] = (),
) -> NoneAttributes¶
captures: tuple[ValueBase, ...]loop_carried_rebinds: tuple[LoopCarriedRebind, ...]max_iterations: int | Noneoperation_kind: OperationKindoperations: list[Operation]region_args: tuple[RegionArg, ...]signature: Signature
Methods¶
all_input_values¶
def all_input_values(self) -> list[ValueBase]Include rebind records and region args for cloning/substitution.
Same rationale as ForOperation.all_input_values: rebind
records and region arguments reference body/pre-loop values by
identity, so inline cloning must remap them in lockstep with
body operands.
Returns:
list[ValueBase] — list[ValueBase]: Base input values plus rebind-record and
region-argument values.
nested_op_lists¶
def nested_op_lists(self) -> list[list[Operation]]nested_regions¶
def nested_regions(self) -> tuple[Region, ...]Return the while body with explicit boundary values.
Returns:
tuple[Region, ...] — tuple[Region, ...]: One body region whose block arguments and
yields are aligned with region_args. The updated
condition, when present, is appended as the final yield.
rebuild_nested¶
def rebuild_nested(self, new_lists: list[list[Operation]]) -> Operationrebuild_regions¶
def rebuild_regions(self, regions: Sequence[Region]) -> OperationRebuild the while body and its complete boundary interface.
Parameters:
| Name | Type | Description |
|---|---|---|
regions | Sequence[Region] | Exactly one replacement body region. |
Returns:
Operation — Rebuilt while operation.
Raises:
ValueError— If arity or boundary value kinds are inconsistent.
replace_values¶
def replace_values(self, mapping: dict[str, ValueBase]) -> OperationSubstitute operand, rebind-record, and region-arg values.
Parameters:
| Name | Type | Description |
|---|---|---|
mapping | dict[str, ValueBase] | UUID-keyed substitution map. |
Returns:
Operation — The rewritten operation.
qamomile.hugr.transpiler¶
Public Qamomile-to-HUGR transpiler facade.
Overview¶
| Class | Description |
|---|---|
CompiledProgram | Package an artifact with its ABI, diagnostics, and provenance. |
CompilerConfig | Configure semantic preparation and target-independent rewrites. |
HugrTarget | Plan, lower, package, and validate a Guppy-compatible HUGR target. |
HugrTranspiler | Compile Qamomile programs to Guppy-compatible HUGR packages. |
QKernelLike | Describe the frontend surface required by compiler entrypoints. |
QamomileCompiler | Prepare Qamomile semantics and dispatch explicit target compilation. |
Classes¶
CompiledProgram [source]¶
class CompiledProgram(Generic[ArtifactT])Package an artifact with its ABI, diagnostics, and provenance.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | ArtifactT | Target-native circuit, graph, module, or package. |
abi | ProgramABI | Runtime-visible input and output contract. |
metadata | CompilationMetadata | Target and pipeline provenance. |
diagnostics | tuple[CompilationDiagnostic, ...] | Non-fatal compilation diagnostics. Defaults to an empty tuple. |
Constructor¶
def __init__(
self,
artifact: ArtifactT,
abi: ProgramABI,
metadata: CompilationMetadata,
diagnostics: tuple[CompilationDiagnostic, ...] = (),
) -> NoneAttributes¶
abi: ProgramABIartifact: ArtifactTdiagnostics: tuple[CompilationDiagnostic, ...]metadata: CompilationMetadata
CompilerConfig [source]¶
class CompilerConfigConfigure semantic preparation and target-independent rewrites.
Parameters:
| Name | Type | Description |
|---|---|---|
decomposition | DecompositionConfig | Composite-gate decomposition choices. Defaults to the standard decomposition configuration. |
substitutions | SubstitutionConfig | Callable substitution rules. Defaults to no substitutions. |
Constructor¶
def __init__(
self,
decomposition: DecompositionConfig = DecompositionConfig(),
substitutions: SubstitutionConfig = SubstitutionConfig(),
) -> NoneAttributes¶
decomposition: DecompositionConfigsubstitutions: SubstitutionConfig
Methods¶
with_strategies¶
@classmethod
def with_strategies(
cls,
strategy_overrides: dict[str, str] | None = None,
**kwargs: Any = {},
) -> 'CompilerConfig'Create configuration with named decomposition strategies.
Parameters:
| Name | Type | Description |
|---|---|---|
strategy_overrides | dict[str, str] | None | Gate-name to strategy mapping. Defaults to an empty mapping. |
**kwargs | Any | Additional :class:CompilerConfig constructor arguments. |
Returns:
'CompilerConfig' — Configuration containing matching decomposition
and substitution rules.
HugrTarget [source]¶
class HugrTargetPlan, lower, package, and validate a Guppy-compatible HUGR target.
Attributes¶
name: str Return the stable compilation target name.
Methods¶
compile¶
def compile(
self,
program: PreparedModule,
plan: HugrCompilationPlan,
) -> CompiledProgram[Any]Lower a prepared semantic module directly to a HUGR package.
Parameters:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared hierarchical semantic program. |
plan | HugrCompilationPlan | Callable emission plan. |
Returns:
CompiledProgram[Any] — CompiledProgram[Any]: HUGR package and target metadata.
Raises:
ImportError— If HUGR or TKET extension packages are unavailable.EmitError— If a semantic operation has no HUGR lowering yet.
plan¶
def plan(self, program: PreparedModule) -> HugrCompilationPlanSelect reachable body-backed callables for HUGR functions.
Parameters:
| Name | Type | Description |
|---|---|---|
program | PreparedModule | Prepared hierarchical semantic program. |
Returns:
HugrCompilationPlan — Stable callable-definition order.
Raises:
CallableDefinitionConflictError— If one source callable produced multiple specialized bodies that cannot share one HUGR symbol.
validate¶
def validate(self, artifact: Any) -> NoneValidate a HUGR package with the native Rust-backed validator.
Parameters:
| Name | Type | Description |
|---|---|---|
artifact | Any | hugr.package.Package to validate. |
Raises:
ImportError— If the HUGR package is unavailable.HugrCliError— If HUGR validation rejects the package.
HugrTranspiler [source]¶
class HugrTranspilerCompile Qamomile programs to Guppy-compatible HUGR packages.
Parameters:
| Name | Type | Description |
|---|---|---|
config | CompilerConfig | None | Shared semantic preparation configuration. Defaults to :class:CompilerConfig. |
Constructor¶
def __init__(self, config: CompilerConfig | None = None) -> NoneInitialize the direct program-graph transpiler.
Parameters:
| Name | Type | Description |
|---|---|---|
config | CompilerConfig | None | Semantic preparation configuration. Defaults to :class:CompilerConfig. |
Attributes¶
compilertarget
Methods¶
to_hugr¶
def to_hugr(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> AnyReturn only the validated HUGR package artifact.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Top-level qkernel-like entrypoint. |
bindings | dict[str, Any] | None | Compile-time bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
Any — hugr.package.Package artifact.
transpile¶
def transpile(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> CompiledProgram[Any]Transpile a qkernel directly to a validated HUGR package.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Top-level qkernel-like entrypoint. |
bindings | dict[str, Any] | None | Compile-time bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names retained as HUGR function inputs. Defaults to None. |
Returns:
CompiledProgram[Any] — CompiledProgram[Any]: Validated hugr.package.Package artifact.
Raises:
ImportError— If HUGR dependencies are unavailable.QamomileCompileError— If semantic preparation or HUGR lowering rejects the program.HugrCliError— If target-native validation rejects the package.
QKernelLike [source]¶
class QKernelLike(Protocol)Describe the frontend surface required by compiler entrypoints.
This protocol is intentionally structural. It lets decorator-created
composites reuse the qkernel inspection and build interface without making
them inherit from QKernel or exposing the compiler-facing callable
descriptor model as a frontend concept.
Attributes¶
block: Block Return the cached hierarchical body block.effects: KernelEffect Return cached semantic effects of the qkernel body.input_types: dict[str, Any] Return frontend input annotations by parameter name.name: str Return the user-facing callable name.output_types: list[Any] Return frontend output annotations.signature: inspect.Signature Return the Python call signature.
Methods¶
build¶
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> BlockBuild a traced body block.
Parameters:
| Name | Type | Description |
|---|---|---|
parameters | list[str] | None | Runtime parameter names to preserve. Defaults to None. |
**kwargs | Any | Compile-time bindings for non-parameter arguments. |
Returns:
Block — Traced hierarchical body block.
QamomileCompiler [source]¶
class QamomileCompilerPrepare Qamomile semantics and dispatch explicit target compilation.
Parameters:
| Name | Type | Description |
|---|---|---|
config | CompilerConfig | None | Shared frontend and substitution configuration. Defaults to :class:CompilerConfig. |
Constructor¶
def __init__(self, config: CompilerConfig | None = None) -> NoneInitialize the target-neutral compiler.
Parameters:
| Name | Type | Description |
|---|---|---|
config | CompilerConfig | None | Shared frontend configuration. Defaults to :class:CompilerConfig. |
Attributes¶
config
Methods¶
compile¶
def compile(
self,
kernel: QKernelLike,
target: CompilationTarget[PlanT, ArtifactT],
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> CompiledProgram[ArtifactT]Compile a qkernel with an explicit target implementation.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Top-level qkernel-like entrypoint. |
target | CompilationTarget[PlanT, ArtifactT] | Target planner, lowerer, materializer, and validator. |
bindings | dict[str, Any] | None | Compile-time bindings. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Validated target-native artifact.
Raises:
Exception— If semantic preparation, target compilation, or target-native validation fails.
prepare¶
def prepare(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> PreparedModulePrepare a hierarchical semantic module without destroying calls.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Top-level qkernel-like entrypoint. |
bindings | dict[str, Any] | None | Compile-time bindings used for tracing and shape resolution. Defaults to None. |
parameters | list[str] | None | Runtime parameter names. Defaults to None. |
Returns:
PreparedModule — Program-level semantic input for target planning.
Raises:
ValueError— If bindings overlap runtime parameters.EntrypointValidationError— If the top-level kernel has quantum inputs or outputs.
to_block¶
def to_block(
self,
kernel: QKernelLike,
bindings: dict[str, Any] | None = None,
parameters: list[str] | None = None,
) -> BlockTrace a qkernel-like object into a hierarchical semantic block.
Parameters:
| Name | Type | Description |
|---|---|---|
kernel | QKernelLike | Frontend object to trace. |
bindings | dict[str, Any] | None | Compile-time argument values. Defaults to None. |
parameters | list[str] | None | Argument names retained as runtime parameters. Defaults to None. |
Returns:
Block — Hierarchical Qamomile semantic block.
Raises:
ValueError— Ifbindingsandparametersoverlap or frontend argument construction fails.TypeError— If specialization is requested for a block-only qkernel-like object that has nobuildmethod.