1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// This code is part of Cqlib.
//
// (C) Copyright China Telecom Quantum Group 2025-2026
//
// This code is licensed under the Apache License, Version 2.0. You may
// obtain a copy of this license in the LICENSE.txt file in the root directory
// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
//
// Any modifications or derivative works of this code must retain this
// copyright notice, and modified files need to carry a notice indicating
// that they have been altered from the originals.
//! Compiler pipeline for lowering and optimizing quantum circuits.
//!
//! This module is the public entry point for cqlib circuit compilation. It
//! takes a logical [`Circuit`](crate::circuit::Circuit), applies a deterministic
//! staged lowering workflow, and returns a rebuilt circuit together with
//! step-level diagnostics.
//!
//! The compiler workflow is intentionally a staged lowering pipeline rather
//! than a dynamic pass manager. High-level circuit representations are lowered
//! through stable compiler layers:
//!
//! ```text
//! logical circuit
//! -> canonicalized logical IR
//! -> expanded circuit-backed definitions
//! -> decomposed unitary and multi-controlled gates
//! -> global commutation-set cancellation
//! -> knowledge-rule optimization
//! -> optional physical layout and SABRE routing
//! -> optional target-basis translation
//! -> canonicalized output
//! -> exact device instruction lowering
//! -> native-input canonicalization and fixed-point optimization
//! -> target-specific candidate validation
//! -> optional validated SABRE Pareto selection
//! ```
//!
//! The last step applies only to [`CompileMode::Enhanced`] with a strict
//! [`CompileTarget::Device`]. Candidate zero is finalized and validated first;
//! every exploratory route then repeats the same post-routing suffix through
//! validation. Selection performs no further circuit transform and either
//! retains candidate zero or chooses an already validated Pareto improvement.
//!
//! # Public Entry Points
//!
//! - [`compile`] is the recommended user-facing API.
//! - [`CompileConfig`] describes optimization effort, one explicit
//! [`CompileTarget`], and resource policy.
//! - [`CompileResult`] returns the compiled circuit and the workflow step
//! report.
//! - [`CompilerWorkflow`] is useful when callers want to construct and inspect
//! a workflow explicitly.
//!
//! Lower-level modules such as [`transform`], [`sabre`], [`knowledge`], and
//! [`commutation`] expose reusable compiler infrastructure. They are intended
//! for advanced users and internal composition; ordinary compilation should
//! start with [`compile`].
//!
//! # Target Constraints
//!
//! [`CompileTarget::Logical`] keeps logical operations,
//! [`CompileTarget::Basis`] lowers to an explicit basis, and
//! [`CompileTarget::Device`] routes and lowers for one device. The
//! [`CompileTarget::TopologyBasis`] target routes on a device topology and
//! lowers to a non-empty caller-supplied basis without claiming native-device
//! compatibility. Strict device compilation
//! uses an exact-plan-aware SABRE
//! movement graph and checks local
//! unary and ordered two-qubit capabilities during routing. Its following
//! device-lowering stage emits the shared exact-qargs plans, then
//! [`Device::validate_circuit`](crate::device::Device::validate_circuit)
//! validates the completed output.
//! A successful device compilation therefore never returns a circuit rejected
//! by the configured device.
//!
//! [`DeviceCompileTarget::initial_layout`] may skip automatic initial-layout
//! selection. [`DeviceCompileTarget::seed`] controls only device layout and
//! routing heuristics. [`CompileResult::device_metadata`] records the initial
//! and final layouts whenever compilation performs device-topology routing.
//!
//! # Classical Control and High-Level Operations
//!
//! The workflow preserves classical-control structure. Transforms that support
//! control-flow bodies recurse into them and report whether they changed the IR
//! through [`TransformOutcome`](transform::TransformOutcome). The workflow does
//! not pre-scan control-flow trees to decide whether a transform should run.
//! This module does not currently lower dynamic classical control into a
//! hardware runtime instruction format.
//!
//! # Step Reports
//!
//! [`WorkflowStepReport`] records the workflow-local stage and step name, plus
//! whether the step changed the circuit, was skipped, or emitted a short
//! reason. Step names describe workflow positions such as `route.sabre` or
//! `translate.target_basis`; they are not required to equal
//! [`Transformer::name`](transform::Transformer::name).
//!
//! For an enhanced strict-device run, the returned reports describe the retained
//! baseline or winning candidate path followed by `select.sabre_pareto_beam`;
//! they are not an exhaustive trace of every discarded exploratory branch.
//!
//! # Examples
//!
//! Compile a logical circuit with default logical optimization:
//!
//! ```rust
//! use cqlib_core::circuit::{Circuit, Qubit};
//! use cqlib_core::compile::{CompileConfig, CompileMode, CompileTarget, compile};
//! use cqlib_core::compile::resource::ResourcePolicy;
//!
//! let mut circuit = Circuit::new(2);
//! circuit.h(Qubit::new(0)).unwrap();
//! circuit.cx(Qubit::new(0), Qubit::new(1)).unwrap();
//!
//! let result = compile(
//! &circuit,
//! CompileConfig {
//! mode: CompileMode::Normal,
//! target: CompileTarget::Logical,
//! resource_policy: ResourcePolicy::default(),
//! },
//! )
//! .unwrap();
//!
//! assert_eq!(result.mode, CompileMode::Normal);
//! assert!(!result.steps.is_empty());
//! ```
//!
//! Compile to an explicit target basis:
//!
//! ```rust
//! use cqlib_core::circuit::{Circuit, Instruction, Qubit, StandardGate};
//! use cqlib_core::compile::{CompileConfig, CompileMode, CompileTarget, compile};
//! use cqlib_core::compile::resource::ResourcePolicy;
//!
//! let mut circuit = Circuit::new(2);
//! circuit.h(Qubit::new(0)).unwrap();
//! circuit.cx(Qubit::new(0), Qubit::new(1)).unwrap();
//!
//! let result = compile(
//! &circuit,
//! CompileConfig {
//! mode: CompileMode::Normal,
//! target: CompileTarget::Basis(vec![
//! Instruction::Standard(StandardGate::H),
//! Instruction::Standard(StandardGate::CZ),
//! ]),
//! resource_policy: ResourcePolicy::default(),
//! },
//! )
//! .unwrap();
//!
//! assert!(
//! result
//! .steps
//! .iter()
//! .any(|step| step.name == "translate.target_basis" && step.changed)
//! );
//! ```
//!
//! Compile for a device topology:
//!
//! ```rust
//! use cqlib_core::circuit::{Circuit, Qubit};
//! use cqlib_core::compile::{CompileConfig, CompileMode, CompileTarget, DeviceCompileTarget, compile};
//! use cqlib_core::compile::resource::ResourcePolicy;
//! use cqlib_core::device::Device;
//! use cqlib_core::circuit::{Instruction, StandardGate};
//!
//! let mut circuit = Circuit::new(2);
//! circuit.cx(Qubit::new(0), Qubit::new(1)).unwrap();
//! let device = Device::bidirectional_line("line-2", 2)
//! .unwrap()
//! .with_native_gates(vec![Instruction::Standard(StandardGate::CX)])
//! .unwrap();
//!
//! let result = compile(
//! &circuit,
//! CompileConfig {
//! mode: CompileMode::Normal,
//! target: CompileTarget::Device(DeviceCompileTarget {
//! device,
//! initial_layout: None,
//! seed: Some(7),
//! }),
//! resource_policy: ResourcePolicy::default(),
//! },
//! )
//! .unwrap();
//!
//! assert!(
//! result
//! .steps
//! .iter()
//! .any(|step| step.name == "route.sabre" && !step.skipped)
//! );
//! ```
//!
//! Route from a supplied initial layout:
//!
//! ```rust
//! use cqlib_core::circuit::{Circuit, Qubit};
//! use cqlib_core::compile::{CompileConfig, CompileMode, CompileTarget, DeviceCompileTarget, compile};
//! use cqlib_core::compile::resource::ResourcePolicy;
//! use cqlib_core::device::{Device, Layout};
//!
//! let mut circuit = Circuit::new(1);
//! circuit.h(Qubit::new(0)).unwrap();
//! let layout = Layout::from_pairs(&[(0, 2)], 3).unwrap();
//!
//! let result = compile(
//! &circuit,
//! CompileConfig {
//! mode: CompileMode::Normal,
//! target: CompileTarget::Device(DeviceCompileTarget {
//! device: Device::line("line-3", 3)
//! .unwrap()
//! .with_native_gates(vec![
//! cqlib_core::circuit::Instruction::Standard(
//! cqlib_core::circuit::StandardGate::H,
//! ),
//! ])
//! .unwrap(),
//! initial_layout: Some(layout),
//! seed: Some(11),
//! }),
//! resource_policy: ResourcePolicy::default(),
//! },
//! )
//! .unwrap();
//!
//! assert_eq!(result.circuit.operations()[0].qubits.as_slice(), &[Qubit::new(2)]);
//! ```
//!
//! Inspect workflow step reports:
//!
//! ```rust
//! use cqlib_core::circuit::Circuit;
//! use cqlib_core::compile::{CompileConfig, CompileMode, CompileTarget, compile};
//! use cqlib_core::compile::resource::ResourcePolicy;
//!
//! let result = compile(
//! &Circuit::new(1),
//! CompileConfig {
//! mode: CompileMode::Enhanced,
//! target: CompileTarget::Logical,
//! resource_policy: ResourcePolicy::default(),
//! },
//! )
//! .unwrap();
//!
//! let routing = result
//! .steps
//! .iter()
//! .find(|step| step.name == "route.sabre")
//! .unwrap();
//! assert!(routing.skipped);
//! ```
pub
pub
pub
/// Tolerance for proving equality between compiler parameter expressions.
pub const PARAMETER_EQ_TOLERANCE: f64 = 1e-12;
pub
/// Tolerance for treating a scalar as numerically zero.
pub const NUMERIC_ZERO_TOLERANCE: f64 = 1e-14;
/// Tolerance for checking whether a candidate phase ratio has unit norm.
pub const UNIT_PHASE_NORM_TOLERANCE: f64 = 1e-8;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;