# Copyright 2026 Qaiji-IR core developer: Ye Jun <yjmaxpayne@hotmail.com>
# SPDX-License-Identifier: Apache-2.0
"""Immutable native schedule declarations."""
from __future__ import annotations
import math
import re
from collections.abc import Callable
from dataclasses import dataclass, fields
from typing import Any, ClassVar, NoReturn, cast, get_args
from qaiji.core.classical import ClassicalVar
from qaiji.core.classical_expr import (
Binary,
BinaryOp,
BitType,
ClassicalExpr,
ClassicalType,
ClassicalTypeError,
Const,
FixedType,
Not,
TimeType,
Var,
type_of,
)
from .errors import NativeInputError
NATIVE_SCHEDULE_SCHEMA_VERSION = "qaiji.native_schedule.v0"
NATIVE_SCHEDULE_SCHEMA_CLASSICAL = "qaiji.native_schedule.v1"
NATIVE_RULESET_VERSION = "qaiji.cz_basis.v1"
_LIMIT = 10**4096
_KINDS = ("I", "Z", "RZ", "RX90", "CZ", "MEASURE")
def _fail(code: str, path: str, message: str) -> NoReturn:
raise NativeInputError(code, path, message)
def _uint(value: Any, path: str, positive: bool = False) -> int:
if type(value) is not int:
_fail("integer", path, "Expected a built-in integer.")
if value < int(positive) or value >= _LIMIT:
_fail("range", path, "Integer outside the supported range.")
return cast(int, value)
def _number(value: Any, path: str) -> float:
if type(value) not in (int, float):
_fail("number", path, "Expected a finite built-in number.")
try:
result = float(value)
except OverflowError:
_fail("number", path, "Number cannot be represented as binary64.")
if not math.isfinite(result):
_fail("number", path, "Expected a finite number.")
return result
def _text(value: Any, path: str) -> str:
if type(value) is not str:
_fail("type", path, "Expected a built-in string.")
if not value:
_fail("text", path, "Expected nonempty text.")
return cast(str, value)
def _identifier(value: Any, path: str) -> str:
result = _text(value, path)
if not result.isidentifier():
_fail("identifier", path, "Expected a register identifier.")
return result
def _sequence(value: Any, path: str, convert: Callable[[Any, str], Any]) -> tuple[Any, ...]:
if type(value) not in (list, tuple):
_fail("container", path, "Expected a list or tuple.")
return tuple(convert(item, f"{path}[{i}]") for i, item in enumerate(value))
def _copy[T](value: Any, cls: type[T], path: str) -> T:
if not isinstance(value, cls):
_fail("type", path, f"Expected {cls.__name__}.")
try:
return cls(**{field.name: getattr(value, field.name) for field in fields(cls)}) # type: ignore[arg-type]
except NativeInputError as error:
raise NativeInputError(error.code, path + error.path[1:], str(error)) from error
def _set(obj: Any, name: str, convert: Callable[[Any, str], Any]) -> None:
object.__setattr__(obj, name, convert(getattr(obj, name), "$." + name))
def _optional(convert: Callable[[Any, str], Any]) -> Callable[[Any, str], Any]:
return lambda value, path: None if value is None else convert(value, path)
def _objects[T](cls: type[T]) -> Callable[[Any, str], tuple[T, ...]]:
return lambda value, path: _sequence(value, path, lambda item, at: _copy(item, cls, at))
def _kind(value: Any, path: str) -> str:
result = _text(value, path)
if result not in _KINDS:
_fail("enum", path, "Unknown native operation kind.")
return result
def _qubits(value: Any, path: str) -> tuple[int, ...]:
return _sequence(value, path, _uint)
def _resources(value: Any, path: str) -> tuple[str, ...]:
result = _sequence(value, path, _text)
if not result or len(set(result)) != len(result):
_fail("resources", path, "Resources must be nonempty and distinct.")
return result
def _operands(kind: str, qubits: tuple[int, ...]) -> None:
if len(qubits) != (2 if kind == "CZ" else 1):
_fail("arity", "$.qubits", "Incorrect number of qubits.")
if len(set(qubits)) != len(qubits):
_fail("arity", "$.qubits", "Qubits must be distinct.")
def _duration(kind: str, duration: int) -> None:
if (kind in ("I", "Z", "RZ")) != (duration == 0):
_fail("duration", "$.duration_ns", "Duration does not match operation kind.")
def _classical_type(value: Any, path: str) -> ClassicalType:
"""检查经典类型的种类与各整数字段。"""
if type(value) is BitType:
return value
if type(value) is FixedType:
_uint(value.width, path + ".width", True)
_uint(value.frac_bits, path + ".frac_bits")
if type(value.signed) is not bool:
_fail("classical_type", path + ".signed", "Expected a built-in boolean.")
return value
if type(value) is TimeType:
_uint(value.width, path + ".width", True)
return value
_fail("classical_type", path, "Expected a classical type.")
def _expr(value: Any, path: str) -> ClassicalExpr:
"""逐层检查经典表达式的节点种类与叶子字段;类型推断在调度图检查中进行。"""
if type(value) is Const:
_classical_type(value.type, path + ".type")
if type(value.value) is not int:
_fail("integer", path + ".value", "Expected a built-in integer.")
if abs(value.value) >= _LIMIT:
_fail("range", path + ".value", "Integer outside the supported range.")
# 记录可能绕过了构造器的范围检查,所以重新构造一次。
try:
Const(value.value, value.type)
except (TypeError, ValueError, OverflowError) as error:
_fail("classical_value", path + ".value", str(error))
elif type(value) is Var:
_text(value.name, path + ".name")
elif type(value) is Not:
_expr(value.operand, path + ".operand")
elif type(value) is Binary:
# 先检查类型:成员判断会调用对象自己的 ``__eq__``。
if type(value.op) is not str or value.op not in get_args(BinaryOp):
_fail("classical_expr", path + ".op", "Expected a known operator name.")
_expr(value.lhs, path + ".lhs")
_expr(value.rhs, path + ".rhs")
else:
_fail("classical_expr", path, "Expected a classical expression.")
return cast(ClassicalExpr, value)
def _classical_var(value: Any, path: str) -> ClassicalVar:
if type(value) is not ClassicalVar:
_fail("type", path, "Expected ClassicalVar.")
_identifier(value.name, path + ".name")
_classical_type(value.type, path + ".type")
return value
[文档]
@dataclass(frozen=True, slots=True, kw_only=True)
class SourceLocation:
gate_index: int
body_offset: int | None
__hash__: ClassVar[Any] = None
def __post_init__(self) -> None:
_set(self, "gate_index", _uint)
_set(self, "body_offset", _optional(_uint))
[文档]
@dataclass(frozen=True, slots=True, kw_only=True)
class RegisterDecl:
name: str
size: int
__hash__: ClassVar[Any] = None
def __post_init__(self) -> None:
_set(self, "name", _identifier)
_set(self, "size", lambda v, p: _uint(v, p, True))
[文档]
@dataclass(frozen=True, slots=True, kw_only=True)
class NativeOperation:
kind: str
qubits: tuple[int, ...]
params: tuple[float, ...]
source: SourceLocation
ordinal: int
start_ns: int
duration_ns: int
resources: tuple[str, ...]
condition_id: str | None
__hash__: ClassVar[Any] = None
def __post_init__(self) -> None:
_set(self, "kind", _kind)
_set(self, "qubits", _qubits)
_set(self, "params", lambda v, p: _sequence(v, p, _number))
_set(self, "source", lambda v, p: _copy(v, SourceLocation, p))
for name in ("ordinal", "start_ns", "duration_ns"):
_set(self, name, _uint)
_set(self, "resources", _resources)
_set(self, "condition_id", _optional(_text))
_operands(self.kind, self.qubits)
if len(self.params) != int(self.kind in ("RZ", "RX90")):
_fail("arity", "$.params", "Incorrect number of parameters.")
for i, angle in enumerate(self.params):
if abs(angle) > math.tau:
_fail("range", f"$.params[{i}]", "Angle outside the supported range.")
_duration(self.kind, self.duration_ns)
if self.kind == "MEASURE" and self.source.body_offset is not None:
_fail("event", "$.source", "Conditional bodies cannot measure.")
[文档]
@dataclass(frozen=True, slots=True, kw_only=True)
class SourceGroup:
source: SourceLocation
rule_id: str
op_start: int
op_stop: int
phase_rad: float
__hash__: ClassVar[Any] = None
def __post_init__(self) -> None:
_set(self, "source", lambda v, p: _copy(v, SourceLocation, p))
_set(self, "rule_id", _text)
_set(self, "op_start", _uint)
_set(self, "op_stop", _uint)
_set(self, "phase_rad", _number)
if self.op_stop <= self.op_start:
_fail("span", "$.op_stop", "Groups must contain operations.")
[文档]
@dataclass(frozen=True, slots=True, kw_only=True)
class MeasurementEvent:
event_id: str
source: SourceLocation
operation_index: int
qubit: int
register_name: str
bit_index: int
end_ns: int
ready_ns: int
__hash__: ClassVar[Any] = None
def __post_init__(self) -> None:
_set(self, "event_id", _text)
_set(self, "source", lambda v, p: _copy(v, SourceLocation, p))
_set(self, "register_name", _identifier)
for name in ("operation_index", "qubit", "bit_index", "end_ns", "ready_ns"):
_set(self, name, _uint)
if self.source.body_offset is not None:
_fail("event", "$.source", "Conditional bodies cannot measure.")
if self.ready_ns < self.end_ns:
_fail("event", "$.ready_ns", "A result cannot be ready before measurement ends.")
[文档]
@dataclass(frozen=True, slots=True, kw_only=True)
class ConditionRead:
bit_index: int
event_id: str
__hash__: ClassVar[Any] = None
def __post_init__(self) -> None:
_set(self, "bit_index", _uint)
_set(self, "event_id", _text)
[文档]
@dataclass(frozen=True, slots=True, kw_only=True)
class ConditionRegion:
condition_id: str
gate_index: int
register_name: str | None
width: int | None
value: int | None
reads: tuple[ConditionRead, ...]
op_start: int
op_stop: int
start_ns: int
end_ns: int
bit_index: int | None = None
predicate: ClassicalExpr | None = None
"""结果为 ``BitType`` 的谓词;给出时寄存器字段与 ``bit_index`` 都为 ``None``。"""
__hash__: ClassVar[Any] = None
def __post_init__(self) -> None:
_set(self, "condition_id", _text)
for name in ("gate_index", "op_start", "op_stop", "start_ns", "end_ns"):
_set(self, name, _uint)
_set(self, "reads", _objects(ConditionRead))
if self.condition_id != f"c{self.gate_index}":
_fail("condition_id", "$.condition_id", "Condition ID must match its source index.")
_set(self, "predicate", _optional(_expr))
register = (self.register_name, self.width, self.value, self.bit_index)
if self.predicate is not None or register == (None,) * 4:
if self.predicate is None or register != (None,) * 4:
_fail("condition_form", "$.predicate", "Give either a predicate or a register.")
else:
self._check_register_form()
if self.op_stop < self.op_start:
_fail("span", "$.op_stop", "Reversed operation span.")
if self.end_ns < self.start_ns:
_fail("span", "$.end_ns", "Reversed time span.")
def _check_register_form(self) -> None:
_set(self, "register_name", _identifier)
_set(self, "value", _uint)
_set(self, "width", lambda v, p: _uint(v, p, True))
_set(self, "bit_index", _optional(_uint))
assert self.width is not None and self.value is not None
if self.width == 1 and self.bit_index == 0:
object.__setattr__(self, "bit_index", None)
if self.bit_index is None:
if self.value.bit_length() > self.width:
_fail("condition_value", "$.value", "Condition value exceeds register width.")
if tuple(read.bit_index for read in self.reads) != tuple(range(self.width)):
_fail("read_bits", "$.reads", "Reads must contain each bit in register order.")
else:
if self.bit_index >= self.width:
_fail("register_reference", "$.bit_index", "Bit outside register.")
if self.value not in (0, 1):
_fail("condition_value", "$.value", "Bit condition value must be 0 or 1.")
if tuple(read.bit_index for read in self.reads) != (self.bit_index,):
_fail("read_bits", "$.reads", "Reads must contain only the tested bit.")
[文档]
@dataclass(frozen=True, slots=True, kw_only=True)
class ClassicalAssignment:
"""源序第 ``gate_index`` 个节点:把 ``expr`` 的值写入经典变量 ``target``。
``reads`` 按比特序列出表达式引用的每个寄存器比特所读的测量事件;``at_ns`` 是值可用的时刻。
"""
gate_index: int
target: str
expr: ClassicalExpr
reads: tuple[ConditionRead, ...]
at_ns: int
__hash__: ClassVar[Any] = None
def __post_init__(self) -> None:
_set(self, "gate_index", _uint)
_set(self, "target", _identifier)
_set(self, "expr", _expr)
_set(self, "reads", _objects(ConditionRead))
_set(self, "at_ns", _uint)
[文档]
@dataclass(frozen=True, slots=True, kw_only=True)
class NativeScheduleIR:
source_kernel_ref: str
num_qubits: int
registers: tuple[RegisterDecl, ...]
operations: tuple[NativeOperation, ...]
groups: tuple[SourceGroup, ...]
events: tuple[MeasurementEvent, ...]
conditions: tuple[ConditionRegion, ...]
end_ns: int
schema_version: str = NATIVE_SCHEDULE_SCHEMA_VERSION
ruleset_version: str = NATIVE_RULESET_VERSION
classical_vars: tuple[ClassicalVar, ...] = ()
assignments: tuple[ClassicalAssignment, ...] = ()
tracked_qubits: tuple[int, ...] = ()
__hash__: ClassVar[Any] = None
[文档]
def to_json(self) -> str:
"""Serialize a revalidated projection of the declared schedule fields."""
from .jsonio import to_json
return to_json(self)
[文档]
@staticmethod
def from_json(text: str) -> NativeScheduleIR:
"""Restore a complete schedule from strict JSON text."""
from .jsonio import from_json
return from_json(text)
def __post_init__(self) -> None:
for name in ("schema_version", "ruleset_version", "source_kernel_ref"):
_set(self, name, _text)
if self.schema_version not in (
NATIVE_SCHEDULE_SCHEMA_VERSION,
NATIVE_SCHEDULE_SCHEMA_CLASSICAL,
):
_fail("enum", "$.schema_version", "Unknown schedule schema version.")
if self.ruleset_version != NATIVE_RULESET_VERSION:
_fail("enum", "$.ruleset_version", "Unknown native ruleset version.")
if re.fullmatch(r"sha256:[0-9a-f]{64}", self.source_kernel_ref) is None:
_fail("ref", "$.source_kernel_ref", "Invalid source kernel reference.")
_set(self, "num_qubits", lambda v, p: _uint(v, p, True))
_set(self, "end_ns", _uint)
for name, cls in (
("registers", RegisterDecl),
("operations", NativeOperation),
("groups", SourceGroup),
("events", MeasurementEvent),
("conditions", ConditionRegion),
("assignments", ClassicalAssignment),
):
_set(self, name, _objects(cls))
_set(self, "classical_vars", lambda v, p: _sequence(v, p, _classical_var))
_set(self, "tracked_qubits", _qubits)
# 字面量须等于规范字面量,不静默改写:旧字面量含经典特性报 SCHEMA,新字面量不含则报
# NON_CANONICAL。
if self.schema_version != _schema_literal(self):
if self.schema_version == NATIVE_SCHEDULE_SCHEMA_CLASSICAL:
_fail(
"NON_CANONICAL", "$.schema_version", "Schema v1 requires a classical feature."
)
_fail(
"SCHEMA",
"$.schema_version",
f"Schedules with classical features use {NATIVE_SCHEDULE_SCHEMA_CLASSICAL}.",
)
_schedule_graph(self)
def _classical_feature(schedule: NativeScheduleIR) -> tuple[str, str] | None:
"""返回首个经典特性的(代码, 路径),没有时返回 ``None``;不支持经典特性的消费方据此拒收。
赋值必须有已声明的目标变量,所以 ``classical_vars`` 排在最后,否则永远不会报告 ``assignments``。
"""
if schedule.tracked_qubits:
return "tracked_qubits", "$.tracked_qubits"
if schedule.assignments:
return "assignments", "$.assignments"
for i, region in enumerate(schedule.conditions):
if region.predicate is not None:
return "predicate", f"$.conditions[{i}].predicate"
if schedule.classical_vars:
return "classical_vars", "$.classical_vars"
return None
def _has_classical_features(schedule: NativeScheduleIR) -> bool:
"""判定调度是否含经典变量、经典赋值、追踪比特或谓词条件;字面量选择与规范性检查都只调用本函数。"""
return _classical_feature(schedule) is not None
def _schema_literal(schedule: NativeScheduleIR) -> str:
"""按经典特性返回调度的规范 schema 字面量。"""
if _has_classical_features(schedule):
return NATIVE_SCHEDULE_SCHEMA_CLASSICAL
return NATIVE_SCHEDULE_SCHEMA_VERSION
def _schedule_graph(schedule: NativeScheduleIR) -> None:
registers: dict[str, int] = {}
for i, register in enumerate(schedule.registers):
if register.name in registers:
_fail("duplicate_register", f"$.registers[{i}].name", "Duplicate register.")
registers[register.name] = register.size
for i, op in enumerate(schedule.operations):
for j, qubit in enumerate(op.qubits):
if qubit >= schedule.num_qubits:
_fail(
"qubit_range", f"$.operations[{i}].qubits[{j}]", "Qubit outside the schedule."
)
for i, qubit in enumerate(schedule.tracked_qubits):
if qubit >= schedule.num_qubits:
_fail("qubit_range", f"$.tracked_qubits[{i}]", "Qubit outside the schedule.")
if list(schedule.tracked_qubits) != sorted(set(schedule.tracked_qubits)):
_fail("tracked_order", "$.tracked_qubits", "Tracked qubits must be sorted and distinct.")
_group_graph(schedule)
_event_graph(schedule, registers)
_condition_graph(schedule, registers)
_classical_graph(schedule, registers)
if not schedule.operations and schedule.end_ns != 0:
_fail("span", "$.end_ns", "An empty schedule must end at zero.")
def _group_graph(schedule: NativeScheduleIR) -> None:
cursor = 0
sources: set[tuple[int, int | None]] = set()
for i, group in enumerate(schedule.groups):
path = f"$.groups[{i}]"
key = (group.source.gate_index, group.source.body_offset)
if key in sources:
_fail("duplicate_source", path + ".source", "Duplicate group source.")
sources.add(key)
if group.op_start != cursor:
_fail("group_reference", path + ".op_start", "Group spans must be contiguous.")
if group.op_stop > len(schedule.operations):
_fail("group_reference", path + ".op_stop", "Group span exceeds operations.")
for ordinal, index in enumerate(range(group.op_start, group.op_stop)):
operation = schedule.operations[index]
if operation.source != group.source:
_fail(
"group_reference",
f"$.operations[{index}].source",
"Operation source differs from its group.",
)
if operation.ordinal != ordinal:
_fail(
"group_reference", f"$.operations[{index}].ordinal", "Incorrect group ordinal."
)
cursor = group.op_stop
if cursor != len(schedule.operations):
_fail("group_reference", "$.groups", "Groups must cover all operations.")
def _event_graph(schedule: NativeScheduleIR, registers: dict[str, int]) -> None:
ids: set[str] = set()
measured: set[int] = set()
for i, event in enumerate(schedule.events):
path = f"$.events[{i}]"
if event.event_id in ids:
_fail("duplicate_event", path + ".event_id", "Duplicate event ID.")
ids.add(event.event_id)
if event.event_id != f"m{i}":
_fail("event", path + ".event_id", "Event IDs must follow list order.")
if event.operation_index >= len(schedule.operations) or event.operation_index in measured:
_fail(
"event_reference",
path + ".operation_index",
"Invalid or repeated measurement reference.",
)
operation = schedule.operations[event.operation_index]
if operation.kind != "MEASURE":
_fail(
"event_reference", path + ".operation_index", "Event must refer to a measurement."
)
if event.qubit != operation.qubits[0]:
_fail("event_reference", path + ".qubit", "Event qubit differs from measurement.")
if event.source != operation.source:
_fail("event_reference", path + ".source", "Event source differs from measurement.")
measured.add(event.operation_index)
if event.register_name not in registers:
_fail("register_reference", path + ".register_name", "Unknown register.")
if event.bit_index >= registers[event.register_name]:
_fail("register_reference", path + ".bit_index", "Bit outside register.")
if measured != {i for i, op in enumerate(schedule.operations) if op.kind == "MEASURE"}:
_fail("event_reference", "$.events", "Every measurement requires one event.")
def _condition_graph(schedule: NativeScheduleIR, registers: dict[str, int]) -> None:
regions: dict[str, ConditionRegion] = {}
events = {event.event_id for event in schedule.events}
for i, region in enumerate(schedule.conditions):
path = f"$.conditions[{i}]"
if region.condition_id in regions:
_fail("duplicate_condition", path + ".condition_id", "Duplicate condition ID.")
regions[region.condition_id] = region
if region.register_name is not None:
if region.register_name not in registers:
_fail("register_reference", path + ".register_name", "Unknown register.")
if region.width != registers[region.register_name]:
_fail(
"register_reference", path + ".width", "Condition width differs from register."
)
if region.op_stop > len(schedule.operations):
_fail("condition_reference", path + ".op_stop", "Condition span exceeds operations.")
for j, read in enumerate(region.reads):
if read.event_id not in events:
_fail(
"event_reference", f"{path}.reads[{j}].event_id", "Unknown measurement event."
)
for index in range(region.op_start, region.op_stop):
op = schedule.operations[index]
if op.condition_id != region.condition_id:
_fail(
"condition_reference",
f"$.operations[{index}].condition_id",
"Condition span and operation ID differ.",
)
for i, op in enumerate(schedule.operations):
path = f"$.operations[{i}]"
if op.condition_id is None:
if op.source.body_offset is not None:
_fail(
"condition_reference",
path + ".condition_id",
"Body operation requires a condition.",
)
continue
matched = regions.get(op.condition_id)
if matched is None:
_fail("condition_reference", path + ".condition_id", "Unknown condition.")
if not matched.op_start <= i < matched.op_stop:
_fail(
"condition_reference",
path + ".condition_id",
"Operation outside its condition span.",
)
if op.source.gate_index != matched.gate_index or op.source.body_offset is None:
_fail(
"condition_reference",
path + ".source",
"Operation source differs from condition body.",
)
def _classical_types(
schedule: NativeScheduleIR, registers: dict[str, int]
) -> dict[str, ClassicalType]:
"""返回寄存器、寄存器比特与经典变量的类型表,规则与 L3 电路相同。"""
types: dict[str, ClassicalType] = {}
for name, size in registers.items():
types[name] = BitType() if size == 1 else FixedType(size, 0, signed=False)
types.update((f"{name}[{i}]", BitType()) for i in range(size))
for i, variable in enumerate(schedule.classical_vars):
if variable.name in types:
_fail("duplicate_register", f"$.classical_vars[{i}].name", "Duplicate classical name.")
types[variable.name] = variable.type
return types
def _register_bit(name: str, registers: dict[str, int]) -> tuple[str, int | None] | None:
"""把寄存器名或 ``名[i]`` 解析为 ``(寄存器, 比特)``;比特为 ``None`` 表示整个寄存器。"""
if name in registers:
return name, None
register, _, index = name.partition("[")
if register in registers and index[:-1].isdigit() and name == f"{register}[{index}":
return register, int(index[:-1])
return None
def _referenced_bits(
expr: ClassicalExpr, registers: dict[str, int], order: dict[str, int]
) -> list[tuple[str, int]]:
"""按(寄存器声明序,比特)列出表达式引用的寄存器比特。"""
found: set[tuple[str, int]] = set()
stack: list[ClassicalExpr] = [expr]
while stack:
node = stack.pop()
if isinstance(node, Var):
reference = _register_bit(node.name, registers)
if reference is not None:
name, bit = reference
bits = range(registers[name]) if bit is None else (bit,)
found.update((name, b) for b in bits)
elif isinstance(node, Not):
stack.append(node.operand)
elif isinstance(node, Binary):
stack.extend((node.lhs, node.rhs))
return sorted(found, key=lambda item: (order[item[0]], item[1]))
def _referenced_variables(expr: ClassicalExpr, registers: dict[str, int]) -> set[str]:
"""收集表达式引用的经典变量名,即不指向寄存器或其比特的名字。"""
if isinstance(expr, Var):
return {expr.name} if _register_bit(expr.name, registers) is None else set()
if isinstance(expr, Not):
return _referenced_variables(expr.operand, registers)
if isinstance(expr, Binary):
left = _referenced_variables(expr.lhs, registers)
return left | _referenced_variables(expr.rhs, registers)
return set()
def _reducible(predicate: ClassicalExpr, registers: dict[str, int]) -> bool:
"""谓词恰为「寄存器或比特等于常数」(含单独的比特引用)时可归一为等值形式。"""
candidates = [predicate]
if isinstance(predicate, Binary) and predicate.op == "EQ":
for side, other in ((predicate.lhs, predicate.rhs), (predicate.rhs, predicate.lhs)):
if isinstance(other, Const):
candidates.append(side)
return any(
isinstance(node, Var) and _register_bit(node.name, registers) is not None
for node in candidates
)
def _check_typed(expr: ClassicalExpr, types: dict[str, ClassicalType], path: str) -> ClassicalType:
try:
return type_of(expr, types)
except ClassicalTypeError as error:
_fail("classical_type", path, str(error))
def _check_reads(
schedule: NativeScheduleIR,
expr: ClassicalExpr,
reads: tuple[ConditionRead, ...],
registers: dict[str, int],
path: str,
) -> None:
order = {register.name: i for i, register in enumerate(schedule.registers)}
bits = _referenced_bits(expr, registers, order)
if tuple(read.bit_index for read in reads) != tuple(bit for _, bit in bits):
_fail("read_bits", path, "Reads must list each referenced register bit in order.")
events = {event.event_id: event for event in schedule.events}
for j, (read, (name, bit)) in enumerate(zip(reads, bits, strict=True)):
event = events.get(read.event_id)
if event is None or (event.register_name, event.bit_index) != (name, bit):
_fail("read_bits", f"{path}[{j}]", "Read event does not write the referenced bit.")
def _classical_graph(schedule: NativeScheduleIR, registers: dict[str, int]) -> None:
# 类型表的大小随寄存器位数增长,没有经典特性时不建表。
if not _has_classical_features(schedule):
return
types = _classical_types(schedule, registers)
for i, region in enumerate(schedule.conditions):
if region.predicate is None:
continue
path = f"$.conditions[{i}]"
if _check_typed(region.predicate, types, path + ".predicate") != BitType():
_fail("classical_type", path + ".predicate", "Predicate must have type BitType.")
if _reducible(region.predicate, registers):
_fail(
"NON_CANONICAL",
path + ".predicate",
"Register-equality predicates use the register form.",
)
_check_reads(schedule, region.predicate, region.reads, registers, path + ".reads")
declared = {variable.name: variable.type for variable in schedule.classical_vars}
sources = {region.gate_index for region in schedule.conditions}
sources.update(group.source.gate_index for group in schedule.groups)
previous = -1
for i, assignment in enumerate(schedule.assignments):
path = f"$.assignments[{i}]"
if assignment.gate_index <= previous:
_fail("assignment_order", path + ".gate_index", "Assignments must follow source order.")
previous = assignment.gate_index
if assignment.gate_index in sources:
_fail("duplicate_source", path + ".gate_index", "Duplicate assignment source.")
if assignment.target not in declared:
_fail("classical_reference", path + ".target", "Unknown classical variable.")
if _check_typed(assignment.expr, types, path + ".expr") != declared[assignment.target]:
_fail("classical_type", path + ".expr", "Expression type differs from its target.")
_check_reads(schedule, assignment.expr, assignment.reads, registers, path + ".reads")