Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

qamomile.hugr

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

ClassDescription
HugrCompilationPlanDescribe the callable symbols emitted into one HUGR module.
HugrTargetPlan, lower, package, and validate a Guppy-compatible HUGR target.
HugrTranspilerCompile Qamomile programs to Guppy-compatible HUGR packages.

Classes

HugrCompilationPlan [source]

class HugrCompilationPlan

Describe the callable symbols emitted into one HUGR module.

Parameters:

NameTypeDescription
definitionstuple[CallableRef, ...]Reachable body-backed callable definitions emitted as HUGR functions.

Constructor

def __init__(self, definitions: tuple[CallableRef, ...]) -> None

Attributes


HugrTarget [source]

class HugrTarget

Plan, lower, package, and validate a Guppy-compatible HUGR target.

Attributes

Methods

compile
def compile(
    self,
    program: PreparedModule,
    plan: HugrCompilationPlan,
) -> CompiledProgram[Any]

Lower a prepared semantic module directly to a HUGR package.

Parameters:

NameTypeDescription
programPreparedModulePrepared hierarchical semantic program.
planHugrCompilationPlanCallable emission plan.

Returns:

CompiledProgram[Any] — CompiledProgram[Any]: HUGR package and target metadata.

Raises:

plan
def plan(self, program: PreparedModule) -> HugrCompilationPlan

Select reachable body-backed callables for HUGR functions.

Parameters:

NameTypeDescription
programPreparedModulePrepared hierarchical semantic program.

Returns:

HugrCompilationPlan — Stable callable-definition order.

Raises:

validate
def validate(self, artifact: Any) -> None

Validate a HUGR package with the native Rust-backed validator.

Parameters:

NameTypeDescription
artifactAnyhugr.package.Package to validate.

Raises:


HugrTranspiler [source]

class HugrTranspiler

Compile Qamomile programs to Guppy-compatible HUGR packages.

Parameters:

NameTypeDescription
configCompilerConfig | NoneShared semantic preparation configuration. Defaults to :class:CompilerConfig.

Constructor

def __init__(self, config: CompilerConfig | None = None) -> None

Initialize the direct program-graph transpiler.

Parameters:

NameTypeDescription
configCompilerConfig | NoneSemantic preparation configuration. Defaults to :class:CompilerConfig.

Attributes

Methods

to_hugr
def to_hugr(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> Any

Return only the validated HUGR package artifact.

Parameters:

NameTypeDescription
kernelQKernelLikeTop-level qkernel-like entrypoint.
bindingsdict[str, Any] | NoneCompile-time bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

Anyhugr.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:

NameTypeDescription
kernelQKernelLikeTop-level qkernel-like entrypoint.
bindingsdict[str, Any] | NoneCompile-time bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names retained as HUGR function inputs. Defaults to None.

Returns:

CompiledProgram[Any] — CompiledProgram[Any]: Validated hugr.package.Package artifact.

Raises:


qamomile.hugr.lowerer

Direct lowering from prepared Qamomile semantics to Guppy-compatible HUGR.

Overview

FunctionDescription
array_physical_regionResolve a one-dimensional array to its ordered physical region.
control_pattern_for_valueReturn the LSB-first activation pattern for a control value.
is_close_zeroCheck if a given floating-point value is close to zero within a small tolerance.
pair_block_operandsPair all block inputs with category-grouped call-site operands.
reject_control_flow_quantum_discardReject control-flow-internal quantum rebinds that discard state.
resolve_root_array_indexFold a view-local element index into the root array’s index space.
resolve_root_qubit_addressResolve an array-element value to its root (array_uuid, index).
validate_region_argsValidate the SSA identities owned by a loop’s region arguments.
ClassDescription
ArrayValueAn array of typed IR values.
BinOpBinary arithmetic operation (ADD, SUB, MUL, DIV, FLOORDIV, MOD, POW, MIN).
BinOpKind
BlockUnified block representation for all pipeline stages.
CInitOperationInitialize the classical values (const, arguments etc)
CallPolicyDescribe the default lowering policy for a callable call.
CallTransformDescribe the requested transform of a callable implementation.
CallableDefinitionConflictErrorReport two incompatible definitions claiming one callable symbol.
CallableRefIdentify a callable independently of its Python object.
CompOpComparison operation (EQ, NEQ, LT, LE, GT, GE).
CompOpKind
CompilationMetadataRecord how a target artifact was produced.
CompiledProgramPackage an artifact with its ABI, diagnostics, and provenance.
ConcreteControlledUControlled-U with concrete (int) number of controls.
ControlledUOperationBase class for controlled-U operations.
DictValueA dictionary value stored as stable ordered entries.
EmitErrorError during backend code emission.
ForOperationRepresents a for loop operation.
GateOperationQuantum gate operation.
GateOperationType
GlobalPhaseOperationMultiply the complete quantum state by exp(i * phase).
HasNestedOpsMixin for operations that contain nested operation lists.
HugrCompilationPlanDescribe the callable symbols emitted into one HUGR module.
HugrTargetPlan, lower, package, and validate a Guppy-compatible HUGR target.
IfOperationRepresents an if-else conditional operation.
InlinePassInline qkernel callables to create an affine block.
InverseBlockOperationRepresent an inverse qkernel/block as a first-class IR operation.
InvokeOperationRepresent a composite, stdlib, or oracle call.
LoopCarriedRebindTrace-time record of a variable rebound inside a loop body.
MeasureOperation
MeasureVectorOperationMeasure a vector of qubits.
NotOp
PauliEvolveOpPauli evolution operation: exp(-i * gamma * H).
PreparedModuleHold a prepared entrypoint and its reachable callable definitions.
ProjectOperationProject a qubit in one Pauli basis and keep the projected state.
QInitOperationInitialize the qubit
ResetOperationReset a qubit to the |0> state and return the fresh handle.
ReturnOperationExplicit return operation marking the end of a block with return values.
SelectOperationQuantum multiplexer: apply case_blocks[i] when the index reads i.
TupleValueA tuple of IR values for structured data.
ValidateWhileContractPassValidates that all WhileOperation conditions are measurement-backed.
ValueA typed SSA value in the IR.
ValueBaseNominal base for every typed IR value.
ValueTypeBase class for all value types in the IR.
WhileOperationRepresents a while loop operation.

Constants

Functions

array_physical_region [source]

def array_physical_region(array: 'ArrayValue') -> tuple[str, tuple[int, ...]] | None

Resolve 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:

NameTypeDescription
arrayArrayValueRoot 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:

NameTypeDescription
control_valueint | NoneRequired computational-basis value. None means the ordinary all-ones control state.
num_controlsintConcrete 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:

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) -> bool

Check if a given floating-point value is close to zero within a small tolerance.

Parameters:

NameTypeDescription
valuefloatThe floating-point value to check.
abs_tolfloatAbsolute 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:

NameTypeDescription
blockBlockOperation-owned block whose inputs are being bound.
operandsSequence[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) -> None

Reject 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:

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:

NameTypeDescription
operationslist[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.
bindingsdict[str, Any] | NoneCompile-time parameter bindings used to resolve IfOperation conditions, matching what CompileTimeIfLoweringPass will later resolve. Defaults to None (no bindings).

Raises:


resolve_root_array_index [source]

def resolve_root_array_index(array: 'ArrayValue', index: int) -> tuple['ArrayValue', int] | None

Fold 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:

NameTypeDescription
arrayArrayValueArray the index is local to. May be a root array (slice_of unset) or an arbitrarily nested strided view.
indexintElement 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] | None

Resolve 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:

NameTypeDescription
valueValueThe 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:

NameTypeDescription
opForOperation | ForItemsOperation | WhileOperationLoop operation whose region arguments should be validated.

Returns:

tuple[RegionArg, ...] — tuple[RegionArg, ...]: The validated op.region_args tuple.

Raises:

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,
) -> None
Attributes
Methods
is_slice
def is_slice(self) -> bool

Return True if this array is a strided view of another array.

Returns:

boolTrue 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,
) -> None
Attributes

BinOpKind [source]

class BinOpKind(enum.Enum)
Attributes

Block [source]

class Block

Unified 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(),
) -> None
Attributes
Methods
call
def call(self, **kwargs: ValueLike = {}) -> 'InvokeOperation'

Create an inline callable invocation against this block.

Parameters:

NameTypeDescription
**kwargsValueLikeActual argument values keyed by self.label_args.

Returns:

'InvokeOperation' — Inline-policy invocation whose callable definition points at this block.

Raises:

is_affine
def is_affine(self) -> bool

Return 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()) -> None
Attributes

CallPolicy [source]

class CallPolicy(enum.Enum)

Describe the default lowering policy for a callable call.

Attributes

CallTransform [source]

class CallTransform(enum.Enum)

Describe the requested transform of a callable implementation.

Attributes

CallableDefinitionConflictError [source]

class CallableDefinitionConflictError(QamomileCompileError)

Report two incompatible definitions claiming one callable symbol.

Parameters:

NameTypeDescription
symbolstrFully 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) -> None

Initialize a callable-definition collision diagnosis.

Parameters:

NameTypeDescription
symbolstrFully qualified callable symbol with conflicting definitions.
Attributes

CallableRef [source]

class CallableRef

Identify a callable independently of its Python object.

Parameters:

NameTypeDescription
namespacestrStable namespace such as "qamomile.stdlib" or "user".
namestrStable callable name within the namespace.
versionstrSchema or behavior version for the callable.
Constructor
def __init__(self, namespace: str, name: str, version: str = '1') -> None
Attributes

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,
) -> None
Attributes

CompOpKind [source]

class CompOpKind(enum.Enum)
Attributes

CompilationMetadata [source]

class CompilationMetadata

Record how a target artifact was produced.

Parameters:

NameTypeDescription
targetstrStable compilation target name.
pipelinestrLowering-family or pipeline name.
propertiesMapping[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(),
) -> None
Attributes

CompiledProgram [source]

class CompiledProgram(Generic[ArtifactT])

Package an artifact with its ABI, diagnostics, and provenance.

Parameters:

NameTypeDescription
artifactArtifactTTarget-native circuit, graph, module, or package.
abiProgramABIRuntime-visible input and output contract.
metadataCompilationMetadataTarget and pipeline provenance.
diagnosticstuple[CompilationDiagnostic, ...]Non-fatal compilation diagnostics. Defaults to an empty tuple.
Constructor
def __init__(
    self,
    artifact: ArtifactT,
    abi: ProgramABI,
    metadata: CompilationMetadata,
    diagnostics: tuple[CompilationDiagnostic, ...] = (),
) -> None
Attributes

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,
) -> None
Attributes

ControlledUOperation [source]

class ControlledUOperation(Operation)

Base class for controlled-U operations.

Two concrete subclasses handle distinct operand layouts:

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(),
) -> None
Attributes
Methods
all_input_values
def all_input_values(self) -> list[ValueBase]
replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

DictValue [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()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> DictValue

EmitError [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:

NameTypeDescription
messagestrHuman-readable emission failure.
operationstr | NoneRelated operation description. Defaults to None.
Attributes

ForOperation [source]

class ForOperation(HasNestedOps, Operation)

Represents a for loop operation.

Example:

for i in range(start, stop, step):
    body
Constructor
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, ...] = (),
) -> None
Attributes
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]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the range-loop body and complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt range-loop operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

GateOperation [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,
) -> None
Attributes
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

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:

NameTypeDescription
operandslist[Value]Exactly one scalar FloatType phase angle in radians.
resultslist[Value]Must be empty because global phase changes no qubit identity.

Raises:

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

HasNestedOps [source]

class HasNestedOps

Mixin 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]]) -> Operation

Return 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]) -> Operation

Return 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:

NameTypeDescription
regionsSequence[Region]Replacement regions in nested_regions order.

Returns:

Operation — Rebuilt control-flow operation.

Raises:


HugrCompilationPlan [source]

class HugrCompilationPlan

Describe the callable symbols emitted into one HUGR module.

Parameters:

NameTypeDescription
definitionstuple[CallableRef, ...]Reachable body-backed callable definitions emitted as HUGR functions.
Constructor
def __init__(self, definitions: tuple[CallableRef, ...]) -> None
Attributes

HugrTarget [source]

class HugrTarget

Plan, lower, package, and validate a Guppy-compatible HUGR target.

Attributes
Methods
compile
def compile(
    self,
    program: PreparedModule,
    plan: HugrCompilationPlan,
) -> CompiledProgram[Any]

Lower a prepared semantic module directly to a HUGR package.

Parameters:

NameTypeDescription
programPreparedModulePrepared hierarchical semantic program.
planHugrCompilationPlanCallable emission plan.

Returns:

CompiledProgram[Any] — CompiledProgram[Any]: HUGR package and target metadata.

Raises:

plan
def plan(self, program: PreparedModule) -> HugrCompilationPlan

Select reachable body-backed callables for HUGR functions.

Parameters:

NameTypeDescription
programPreparedModulePrepared hierarchical semantic program.

Returns:

HugrCompilationPlan — Stable callable-definition order.

Raises:

validate
def validate(self, artifact: Any) -> None

Validate a HUGR package with the native Rust-backed validator.

Parameters:

NameTypeDescription
artifactAnyhugr.package.Package to validate.

Raises:


IfOperation [source]

class IfOperation(HasNestedOps, Operation)

Represents an if-else conditional operation.

Example:

if condition:
    true_body
else:
    false_body
Constructor
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, ...] = (),
) -> None
Attributes
Methods
add_merge
def add_merge(self, true_value: Value, false_value: Value, result: Value) -> None

Append 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:

NameTypeDescription
true_valueValueValue selected when the condition is true.
false_valueValueValue selected when the condition is false. Must have the same type as true_value.
resultValueFresh SSA value representing the merged output. Must have the same type as the branch values.

Raises:

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:

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]]) -> Operation

Return a copy with the true and false branch bodies replaced.

Parameters:

NameTypeDescription
new_listslist[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]) -> Operation

Rebuild both branches and their complete boundary interfaces.

Parameters:

NameTypeDescription
regionsSequence[Region]True and false replacement regions.

Returns:

Operation — Rebuilt conditional operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, result, branch-yield, and rebind-record values.

Parameters:

NameTypeDescription
mappingdict[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
Methods
run
def run(self, input: Block) -> Block

Inline 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,
) -> None
Attributes

InvokeOperation [source]

class InvokeOperation(Operation)

Represent a composite, stdlib, or oracle call.

Parameters:

NameTypeDescription
operandslist[ValueLike]Input values consumed by the call.
resultslist[ValueLike]Output values produced by the call.
targetCallableRefCallable identity.
transformCallTransformDirect, inverse, or controlled invocation.
attrsdict[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.
definitionCallableDef | NoneOptional 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,
) -> None

Initialize an invocation operation.

Parameters:

NameTypeDescription
operandsSequence[ValueLike] | NoneInput values consumed by the call. Defaults to None, meaning no operands.
resultsSequence[ValueLike] | NoneOutput values produced by the call. Defaults to None, meaning no results.
targetCallableRef | NoneCallable identity. Defaults to an anonymous user callable when omitted.
transformCallTransformRequested call transform. Defaults to CallTransform.DIRECT.
attrsdict[str, Any] | NoneSerializer-friendly call attributes. Defaults to an empty dict.
definitionCallableDef | NoneCallable definition. Defaults to None, in which case one is created from target.

Raises:

Attributes
Methods
effective_body
def effective_body(
    self,
    *,
    backend: str | None = None,
    strategy: str | None = None,
) -> Block | None

Return the implementation body selected for this invocation.

Parameters:

NameTypeDescription
backendstr | NoneBackend name to match. Defaults to None.
strategystr | NoneStrategy 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 | None

Return the selected implementation for this invocation.

Parameters:

NameTypeDescription
backendstr | NoneBackend name to match. Defaults to None, which only selects backend-generic implementations.
strategystr | NoneStrategy 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 LoopCarriedRebind

Trace-time record of a variable rebound inside a loop body.

Two rebind families share this record type, distinguished by the type of before:

Constructor
def __init__(
    self,
    var_name: str,
    before: ValueBase,
    after: ValueBase,
    before_synthesized: bool = False,
) -> None
Attributes

MeasureOperation [source]

class MeasureOperation(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

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()) -> None
Attributes

NotOp [source]

class NotOp(Operation)
Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

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()) -> None
Attributes

PreparedModule [source]

class PreparedModule

Hold a prepared entrypoint and its reachable callable definitions.

Parameters:

NameTypeDescription
entrypoint_refCallableRefStable symbol assigned to the program entrypoint.
entrypointBlockHierarchical semantic block for the entrypoint.
definitionsMapping[CallableRef, CallableDef]Reachable callable definitions keyed by their stable symbols.
definition_variantsMapping[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_graphMapping[CallableRef, frozenset[CallableRef]]Directed caller-to-callee relation, including the entrypoint symbol.
abiProgramABIClassical public input and output contract.
bindingsMapping[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],
) -> None
Attributes
Methods
body
def body(self, ref: CallableRef) -> Block

Return the semantic body associated with a program symbol.

Parameters:

NameTypeDescription
refCallableRefEntrypoint or callable symbol to resolve.

Returns:

Block — Hierarchical semantic body for ref.

Raises:

owned_snapshot
def owned_snapshot(self) -> PreparedModule

Create 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',
) -> None
Attributes

QInitOperation [source]

class QInitOperation(Operation)

Initialize the qubit

Constructor
def __init__(self, operands: list[Value] = list(), results: list[Value] = list()) -> None
Attributes

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()) -> None
Attributes

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()) -> None
Attributes

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,
) -> None
Attributes
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]) -> Operation

Replace operand and symbolic-width values by UUID.

Parameters:

NameTypeDescription
mappingdict[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()))(),
) -> None
Attributes
Methods
is_constant
def is_constant(self) -> bool
next_version
def next_version(self) -> TupleValue

ValidateWhileContractPass [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:

  1. A Value with BitType

  2. Measurement-backed: produced by MeasureOperation directly, or an IfOperation merge 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
Methods
run
def run(self, block: Block) -> Block

Validate 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, ...] = (),
) -> None
Attributes
Methods
is_array_element
def is_array_element(self) -> bool
next_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 ValueBase

Nominal 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
Methods
get_const
def get_const(self) -> int | float | bool | None

Return 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) -> bool

Return whether this value carries a scalar constant.

Returns:

bool — Whether scalar constant metadata is present.

is_parameter
def is_parameter(self) -> bool

Return whether this value represents a runtime parameter.

Returns:

bool — Whether parameter metadata is present.

next_version
def next_version(self) -> ValueBase

Create 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 | None

Return 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) -> bool
is_object
def is_object(self) -> bool
is_quantum
def is_quantum(self) -> bool
label
def label(self) -> str

WhileOperation [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, ...] = (),
) -> None
Attributes
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]]) -> Operation
rebuild_regions
def rebuild_regions(self, regions: Sequence[Region]) -> Operation

Rebuild the while body and its complete boundary interface.

Parameters:

NameTypeDescription
regionsSequence[Region]Exactly one replacement body region.

Returns:

Operation — Rebuilt while operation.

Raises:

replace_values
def replace_values(self, mapping: dict[str, ValueBase]) -> Operation

Substitute operand, rebind-record, and region-arg values.

Parameters:

NameTypeDescription
mappingdict[str, ValueBase]UUID-keyed substitution map.

Returns:

Operation — The rewritten operation.


qamomile.hugr.transpiler

Public Qamomile-to-HUGR transpiler facade.

Overview

ClassDescription
CompiledProgramPackage an artifact with its ABI, diagnostics, and provenance.
CompilerConfigConfigure semantic preparation and target-independent rewrites.
HugrTargetPlan, lower, package, and validate a Guppy-compatible HUGR target.
HugrTranspilerCompile Qamomile programs to Guppy-compatible HUGR packages.
QKernelLikeDescribe the frontend surface required by compiler entrypoints.
QamomileCompilerPrepare Qamomile semantics and dispatch explicit target compilation.

Classes

CompiledProgram [source]

class CompiledProgram(Generic[ArtifactT])

Package an artifact with its ABI, diagnostics, and provenance.

Parameters:

NameTypeDescription
artifactArtifactTTarget-native circuit, graph, module, or package.
abiProgramABIRuntime-visible input and output contract.
metadataCompilationMetadataTarget and pipeline provenance.
diagnosticstuple[CompilationDiagnostic, ...]Non-fatal compilation diagnostics. Defaults to an empty tuple.
Constructor
def __init__(
    self,
    artifact: ArtifactT,
    abi: ProgramABI,
    metadata: CompilationMetadata,
    diagnostics: tuple[CompilationDiagnostic, ...] = (),
) -> None
Attributes

CompilerConfig [source]

class CompilerConfig

Configure semantic preparation and target-independent rewrites.

Parameters:

NameTypeDescription
decompositionDecompositionConfigComposite-gate decomposition choices. Defaults to the standard decomposition configuration.
substitutionsSubstitutionConfigCallable substitution rules. Defaults to no substitutions.
Constructor
def __init__(
    self,
    decomposition: DecompositionConfig = DecompositionConfig(),
    substitutions: SubstitutionConfig = SubstitutionConfig(),
) -> None
Attributes
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:

NameTypeDescription
strategy_overridesdict[str, str] | NoneGate-name to strategy mapping. Defaults to an empty mapping.
**kwargsAnyAdditional :class:CompilerConfig constructor arguments.

Returns:

'CompilerConfig' — Configuration containing matching decomposition and substitution rules.


HugrTarget [source]

class HugrTarget

Plan, lower, package, and validate a Guppy-compatible HUGR target.

Attributes
Methods
compile
def compile(
    self,
    program: PreparedModule,
    plan: HugrCompilationPlan,
) -> CompiledProgram[Any]

Lower a prepared semantic module directly to a HUGR package.

Parameters:

NameTypeDescription
programPreparedModulePrepared hierarchical semantic program.
planHugrCompilationPlanCallable emission plan.

Returns:

CompiledProgram[Any] — CompiledProgram[Any]: HUGR package and target metadata.

Raises:

plan
def plan(self, program: PreparedModule) -> HugrCompilationPlan

Select reachable body-backed callables for HUGR functions.

Parameters:

NameTypeDescription
programPreparedModulePrepared hierarchical semantic program.

Returns:

HugrCompilationPlan — Stable callable-definition order.

Raises:

validate
def validate(self, artifact: Any) -> None

Validate a HUGR package with the native Rust-backed validator.

Parameters:

NameTypeDescription
artifactAnyhugr.package.Package to validate.

Raises:


HugrTranspiler [source]

class HugrTranspiler

Compile Qamomile programs to Guppy-compatible HUGR packages.

Parameters:

NameTypeDescription
configCompilerConfig | NoneShared semantic preparation configuration. Defaults to :class:CompilerConfig.
Constructor
def __init__(self, config: CompilerConfig | None = None) -> None

Initialize the direct program-graph transpiler.

Parameters:

NameTypeDescription
configCompilerConfig | NoneSemantic preparation configuration. Defaults to :class:CompilerConfig.
Attributes
Methods
to_hugr
def to_hugr(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> Any

Return only the validated HUGR package artifact.

Parameters:

NameTypeDescription
kernelQKernelLikeTop-level qkernel-like entrypoint.
bindingsdict[str, Any] | NoneCompile-time bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

Anyhugr.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:

NameTypeDescription
kernelQKernelLikeTop-level qkernel-like entrypoint.
bindingsdict[str, Any] | NoneCompile-time bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names retained as HUGR function inputs. Defaults to None.

Returns:

CompiledProgram[Any] — CompiledProgram[Any]: Validated hugr.package.Package artifact.

Raises:


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
Methods
build
def build(self, parameters: list[str] | None = None, **kwargs: Any = {}) -> Block

Build a traced body block.

Parameters:

NameTypeDescription
parameterslist[str] | NoneRuntime parameter names to preserve. Defaults to None.
**kwargsAnyCompile-time bindings for non-parameter arguments.

Returns:

Block — Traced hierarchical body block.


QamomileCompiler [source]

class QamomileCompiler

Prepare Qamomile semantics and dispatch explicit target compilation.

Parameters:

NameTypeDescription
configCompilerConfig | NoneShared frontend and substitution configuration. Defaults to :class:CompilerConfig.
Constructor
def __init__(self, config: CompilerConfig | None = None) -> None

Initialize the target-neutral compiler.

Parameters:

NameTypeDescription
configCompilerConfig | NoneShared frontend configuration. Defaults to :class:CompilerConfig.
Attributes
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:

NameTypeDescription
kernelQKernelLikeTop-level qkernel-like entrypoint.
targetCompilationTarget[PlanT, ArtifactT]Target planner, lowerer, materializer, and validator.
bindingsdict[str, Any] | NoneCompile-time bindings. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

CompiledProgram[ArtifactT] — CompiledProgram[ArtifactT]: Validated target-native artifact.

Raises:

prepare
def prepare(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> PreparedModule

Prepare a hierarchical semantic module without destroying calls.

Parameters:

NameTypeDescription
kernelQKernelLikeTop-level qkernel-like entrypoint.
bindingsdict[str, Any] | NoneCompile-time bindings used for tracing and shape resolution. Defaults to None.
parameterslist[str] | NoneRuntime parameter names. Defaults to None.

Returns:

PreparedModule — Program-level semantic input for target planning.

Raises:

to_block
def to_block(
    self,
    kernel: QKernelLike,
    bindings: dict[str, Any] | None = None,
    parameters: list[str] | None = None,
) -> Block

Trace a qkernel-like object into a hierarchical semantic block.

Parameters:

NameTypeDescription
kernelQKernelLikeFrontend object to trace.
bindingsdict[str, Any] | NoneCompile-time argument values. Defaults to None.
parameterslist[str] | NoneArgument names retained as runtime parameters. Defaults to None.

Returns:

Block — Hierarchical Qamomile semantic block.

Raises: