cqlib-core 0.1.0-beta.7

The high-performance core foundation for the CQLib quantum computing ecosystem.
Documentation
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
// 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.

//! Canonicalizer entry point and round orchestration.

use crate::circuit::value_instruction::storage_operation_to_value;
use crate::circuit::{
    Circuit, CircuitError, CircuitParam, ClassicalControlOp, ClassicalDataOp, ControlBody,
    Directive, ForOp, IfOp, Instruction, Operation, Parameter, StandardGate, SwitchCase, SwitchOp,
    ValueOperation, WhileOp,
};
use crate::compile::CompilerError;
use crate::compile::transform::RewriteEdits;
use crate::compile::transform::transformer::{TransformOutcome, Transformer};
use smallvec::{SmallVec, smallvec};
use std::borrow::Cow;

use super::config::CanonicalizeConfig;
use super::ops::{canonicalize_operation_qubits, is_strict_noop, push_operation};
use super::verify::{VerifyMode, verify_circuit};

/// Result of a canonicalization run.
#[derive(Debug, Clone, PartialEq)]
pub struct CanonicalizeResult {
    /// Canonicalized circuit.
    pub circuit: Circuit,
    /// Whether the output differs from the input representation.
    pub changed: bool,
    /// Number of canonicalization rounds executed.
    pub rounds: u8,
}

/// Canonicalizer entry point.
#[derive(Debug, Clone)]
pub struct Canonicalizer {
    config: CanonicalizeConfig,
}

impl Default for Canonicalizer {
    fn default() -> Self {
        Self::production()
    }
}

impl Canonicalizer {
    /// Creates a canonicalizer with the supplied configuration.
    pub const fn new(config: CanonicalizeConfig) -> Self {
        Self { config }
    }

    /// Creates a canonicalizer using production defaults.
    pub const fn production() -> Self {
        Self::new(CanonicalizeConfig::production())
    }

    /// Returns the active configuration.
    pub const fn config(&self) -> &CanonicalizeConfig {
        &self.config
    }

    /// Canonicalizes `circuit` and returns the rebuilt circuit plus run metadata.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cqlib_core::circuit::{Circuit, Qubit};
    /// use cqlib_core::compile::transform::Canonicalizer;
    ///
    /// let mut circuit = Circuit::new(1);
    /// circuit.h(Qubit::new(0)).unwrap();
    ///
    /// let result = Canonicalizer::production().run(&circuit).unwrap();
    /// assert_eq!(result.circuit.qubits(), circuit.qubits());
    /// assert!(result.rounds >= 1);
    /// let _changed = result.changed;
    /// ```
    pub fn run(&self, circuit: &Circuit) -> Result<CanonicalizeResult, CompilerError> {
        self.run_with_rewrite_edits(circuit)
            .map(|(result, _)| result)
    }

    pub(crate) fn transform_with_rewrite_edits(
        &self,
        circuit: &Circuit,
    ) -> Result<(TransformOutcome, RewriteEdits), CompilerError> {
        self.validate_run(circuit)?;
        if self.is_verified_canonical(circuit) {
            return Ok((
                TransformOutcome::Unchanged,
                RewriteEdits::linear(
                    circuit.operations().len(),
                    circuit.operations().len(),
                    Vec::new(),
                ),
            ));
        }

        let (result, edits) = self.run_with_rewrite_edits_validated(circuit)?;
        Ok((
            if result.changed {
                TransformOutcome::Changed(result.circuit)
            } else {
                TransformOutcome::Unchanged
            },
            edits,
        ))
    }

    fn run_with_rewrite_edits(
        &self,
        circuit: &Circuit,
    ) -> Result<(CanonicalizeResult, RewriteEdits), CompilerError> {
        self.validate_run(circuit)?;
        if self.is_verified_canonical(circuit) {
            return Ok((
                CanonicalizeResult {
                    circuit: circuit.clone(),
                    changed: false,
                    rounds: 1,
                },
                RewriteEdits::linear(
                    circuit.operations().len(),
                    circuit.operations().len(),
                    Vec::new(),
                ),
            ));
        }

        self.run_with_rewrite_edits_validated(circuit)
    }

    fn is_verified_canonical(&self, circuit: &Circuit) -> bool {
        verify_circuit(
            circuit,
            VerifyMode::Output {
                config: &self.config,
            },
        )
        .is_ok()
    }

    fn validate_run(&self, circuit: &Circuit) -> Result<(), CompilerError> {
        verify_circuit(circuit, VerifyMode::Input)?;

        if self.config.round_limit() == 0 {
            return Err(CompilerError::InvalidInput(
                "canonicalize round_limit must be greater than zero".to_string(),
            ));
        }
        Ok(())
    }

    fn run_with_rewrite_edits_validated(
        &self,
        circuit: &Circuit,
    ) -> Result<(CanonicalizeResult, RewriteEdits), CompilerError> {
        // A single pass can expose new canonicalization opportunities. For
        // example, parameter simplification can turn `theta - theta` into a
        // fixed zero, which then lets the next pass remove a rotation. The loop
        // therefore proves a stable representation before reporting success.
        let mut current = Cow::Borrowed(circuit);
        let mut provenance = (0..circuit.operations().len())
            .map(Some)
            .collect::<Vec<_>>();
        for round in 1..=self.config.round_limit() {
            let (next, next_provenance) =
                CanonicalizeRound::new(current.as_ref(), &self.config, &provenance).run()?;
            verify_circuit(
                &next,
                VerifyMode::Output {
                    config: &self.config,
                },
            )?;

            if current.as_ref() == &next {
                let changed = circuit != &next;
                let edits = if changed {
                    RewriteEdits::from_operation_provenance(
                        circuit.operations().len(),
                        &next_provenance,
                    )
                } else {
                    RewriteEdits::linear(
                        circuit.operations().len(),
                        circuit.operations().len(),
                        Vec::new(),
                    )
                };
                return Ok((
                    CanonicalizeResult {
                        circuit: next,
                        changed,
                        rounds: round,
                    },
                    edits,
                ));
            }

            current = Cow::Owned(next);
            provenance = next_provenance;
        }

        Err(CompilerError::InvariantViolation(format!(
            "canonicalization did not reach a fixed point within {} rounds",
            self.config.round_limit()
        )))
    }
}

// Transformer integration keeps only the common outcome shape; callers
// that need canonicalization rounds should use `Canonicalizer::run` directly.
impl Transformer for Canonicalizer {
    fn name(&self) -> &'static str {
        "canonicalize"
    }

    fn transform(
        &self,
        circuit: &Circuit,
        _analysis: Option<&crate::compile::transform::CircuitAnalysis>,
    ) -> Result<TransformOutcome, CompilerError> {
        let result = self.run(circuit)?;
        Ok(if result.changed {
            TransformOutcome::Changed(result.circuit)
        } else {
            TransformOutcome::Unchanged
        })
    }
}

/// Canonicalizes a circuit using production defaults.
pub fn canonicalize_circuit(circuit: &Circuit) -> Result<CanonicalizeResult, CompilerError> {
    Canonicalizer::production().run(circuit)
}

struct CanonicalizeRound<'a> {
    source: &'a Circuit,
    config: &'a CanonicalizeConfig,
    source_provenance: &'a [Option<usize>],
    target: Circuit,
    top_phase: Parameter,
}

impl<'a> CanonicalizeRound<'a> {
    fn new(
        source: &'a Circuit,
        config: &'a CanonicalizeConfig,
        source_provenance: &'a [Option<usize>],
    ) -> Self {
        Self {
            source,
            config,
            source_provenance,
            target: Circuit::from_qubits(source.qubits()).expect("source qubits are unique"),
            top_phase: source.global_phase(),
        }
    }

    fn run(mut self) -> Result<(Circuit, Vec<Option<usize>>), CompilerError> {
        self.top_phase = self.canonicalize_parameter(self.top_phase.clone())?;
        let mut top_level = Vec::with_capacity(self.source.operations().len());
        let mut provenance = Vec::with_capacity(self.source.operations().len());

        // Top-level `GPhase` operations are not retained as operations. Their
        // phase contribution is accumulated here and materialized into
        // `Circuit::global_phase` after all operations have been rebuilt.
        for (source_order, operation) in self.source.operations().iter().enumerate() {
            let rewritten = self.rewrite_operation(operation, ScopeKind::TopLevel)?;
            let preserves_source = rewritten.preserves_source;
            self.top_phase = self.accumulate_phase(self.top_phase.clone(), rewritten.phase)?;
            for operation in rewritten.operations {
                let old_len = top_level.len();
                push_operation(&mut top_level, operation, self.config);
                match top_level.len().saturating_sub(old_len) {
                    1 => provenance.push(
                        preserves_source
                            .then_some(self.source_provenance[source_order])
                            .flatten(),
                    ),
                    0 => {
                        // Adjacent barrier folding makes the retained output
                        // depend on both source operations.
                        if let Some(last) = provenance.last_mut() {
                            *last = None;
                        }
                    }
                    _ => unreachable!("canonicalization emits at most one operation per input"),
                }
            }
        }

        let phase = self.canonicalize_parameter(self.top_phase.clone())?;
        let operations = top_level
            .into_iter()
            .map(|operation| self.value_operation(operation))
            .collect::<Result<Vec<_>, _>>()?;
        Ok((
            rebuild_circuit_from_value_operations(self.source, operations, phase)?,
            provenance,
        ))
    }

    fn canonicalize_body(&mut self, body: &[Operation]) -> Result<Vec<Operation>, CompilerError> {
        let mut out = Vec::with_capacity(body.len());
        let mut body_phase = Parameter::from(0.0);

        // Body-local phase is conditional on the enclosing control-flow branch
        // or loop iteration, so it cannot be lifted to circuit global phase.
        // The canonical body representation keeps it as one leading `GPhase`.
        for operation in body {
            let rewritten = self.rewrite_operation(operation, ScopeKind::ControlFlowBody)?;
            body_phase = self.accumulate_phase(body_phase, rewritten.phase)?;
            for operation in rewritten.operations {
                push_operation(&mut out, operation, self.config);
            }
        }

        body_phase = self.canonicalize_parameter(body_phase)?;
        if !compiler_parameter(body_phase.is_exact_zero())? {
            let param = self.intern_parameter(body_phase)?;
            out.insert(
                0,
                Operation {
                    instruction: Instruction::Standard(StandardGate::GPhase),
                    qubits: smallvec![],
                    params: smallvec![param],
                    label: None,
                },
            );
        }

        Ok(out)
    }

    fn canonicalize_parameter(&mut self, parameter: Parameter) -> Result<Parameter, CompilerError> {
        if parameter.is_canonical_positive_zero() {
            return Ok(parameter);
        }
        compiler_parameter(parameter.canonicalized())
    }

    fn accumulate_phase(
        &mut self,
        current: Parameter,
        contribution: Parameter,
    ) -> Result<Parameter, CompilerError> {
        if contribution.is_canonical_positive_zero() {
            return Ok(current);
        }
        self.canonicalize_parameter(current + contribution)
    }

    fn rewrite_operation(
        &mut self,
        operation: &Operation,
        scope: ScopeKind,
    ) -> Result<RewriteResult, CompilerError> {
        let operation_instruction = operation.instruction.clone();
        let operation_qubits = operation.qubits.clone();
        let operation_label = operation.label.clone();
        let mut instruction = operation.instruction.clone();
        if self.config.canonicalizes_instruction_form() {
            instruction = instruction.canonicalize_form();
        }

        if self.config.recurses_control_flow() {
            instruction = self.rewrite_control_flow_instruction(instruction)?;
        }

        // Simplify runtime classical expressions embedded in data ops.
        if let Instruction::ClassicalData(data) = &instruction {
            instruction = Instruction::ClassicalData(simplify_classical_data_op(data));
        }

        let qubits = canonicalize_operation_qubits(&instruction, &operation.qubits, self.config);
        let semantic_params = operation
            .params
            .iter()
            .map(|param| self.source.resolve_parameter(param))
            .collect::<Result<Vec<_>, _>>()?;

        if self.config.folds_gphase()
            && matches!(instruction, Instruction::Standard(StandardGate::GPhase))
        {
            let phase = semantic_params
                .first()
                .cloned()
                .unwrap_or_else(|| Parameter::from(0.0));
            return Ok(RewriteResult::phase(phase));
        }

        if self.config.drops_noops() && is_strict_noop(&instruction, &semantic_params)? {
            return Ok(RewriteResult::drop());
        }

        let params = semantic_params
            .iter()
            .cloned()
            .map(|param| self.intern_parameter(param))
            .collect::<Result<SmallVec<[CircuitParam; 1]>, _>>()?;

        let mut label = operation.label.clone();
        if self.config.canonicalizes_barriers()
            && matches!(instruction, Instruction::Directive(Directive::Barrier))
        {
            label = None;
        }

        let mut operation = Operation {
            instruction,
            qubits,
            params,
            label,
        };

        // The operation-level qubit list is derived from the canonicalized body,
        // not preserved from input. This prevents deleted body no-ops from
        // keeping dead qubits visible to later analysis passes.
        if matches!(scope, ScopeKind::TopLevel | ScopeKind::ControlFlowBody)
            && let Instruction::ClassicalControl(control) = &operation.instruction
        {
            operation.qubits = control.used_qubits().into_iter().collect();
        }

        let resolved_output_params = operation
            .params
            .iter()
            .map(|parameter| self.target.resolve_parameter(parameter))
            .collect::<Result<Vec<_>, _>>()?;
        let preserves_source = operation.instruction == operation_instruction
            && operation.qubits == operation_qubits
            && operation.label == operation_label
            && resolved_output_params == semantic_params;

        Ok(RewriteResult::keep(operation, preserves_source))
    }

    fn rewrite_control_flow_instruction(
        &mut self,
        instruction: Instruction,
    ) -> Result<Instruction, CompilerError> {
        match instruction {
            Instruction::ClassicalControl(control) => Ok(Instruction::ClassicalControl(
                self.rewrite_control_flow(control)?,
            )),
            _ => Ok(instruction),
        }
    }

    /// Rebuilds one structured classical-control operation after body
    /// rewriting and expression simplification.
    fn rewrite_control_flow(
        &mut self,
        control: ClassicalControlOp,
    ) -> Result<ClassicalControlOp, CompilerError> {
        match control {
            ClassicalControlOp::If(op) => {
                let then_body = self.canonicalize_control_body(op.then_body())?;
                let else_body = op
                    .else_body()
                    .map(|body| self.canonicalize_control_body(body))
                    .transpose()?;
                Ok(ClassicalControlOp::If(
                    IfOp::new(op.condition().simplified(), then_body, else_body)
                        .map_err(CompilerError::Circuit)?,
                ))
            }
            ClassicalControlOp::While(op) => {
                let body = self.canonicalize_control_body(op.body())?;
                Ok(ClassicalControlOp::While(
                    WhileOp::new(op.condition().simplified(), body)
                        .map_err(CompilerError::Circuit)?,
                ))
            }
            ClassicalControlOp::For(op) => {
                let body = self.canonicalize_control_body(op.body())?;
                Ok(ClassicalControlOp::For(
                    ForOp::new(
                        op.var(),
                        op.start().simplified(),
                        op.stop().simplified(),
                        op.step().simplified(),
                        body,
                    )
                    .map_err(CompilerError::Circuit)?,
                ))
            }
            ClassicalControlOp::Switch(op) => {
                let mut cases = Vec::with_capacity(op.cases().len());
                for case in op.cases() {
                    cases.push(SwitchCase::new(
                        case.value(),
                        self.canonicalize_control_body(case.body())?,
                    ));
                }
                let default = op
                    .default()
                    .map(|body| self.canonicalize_control_body(body))
                    .transpose()?;
                Ok(ClassicalControlOp::Switch(
                    SwitchOp::new(op.target().simplified(), cases, default)
                        .map_err(CompilerError::Circuit)?,
                ))
            }
            ClassicalControlOp::Break => Ok(ClassicalControlOp::Break),
            ClassicalControlOp::Continue => Ok(ClassicalControlOp::Continue),
        }
    }

    /// Canonicalizes a structured control-flow body and wraps it back in `ControlBody`.
    fn canonicalize_control_body(
        &mut self,
        body: &ControlBody,
    ) -> Result<ControlBody, CompilerError> {
        Ok(ControlBody::new(self.canonicalize_body(body.operations())?))
    }

    fn intern_parameter(&mut self, param: Parameter) -> Result<CircuitParam, CompilerError> {
        Ok(self.target.map_param(param)?)
    }

    /// Resolves canonical operation parameters into value-level operations.
    ///
    /// Final circuit construction goes through [`Circuit::from_operations`] so
    /// the rebuilt circuit can inherit the source circuit's classical-handle
    /// identity and validate `ClassicalData`/`ClassicalControl` operations.
    fn value_operation(&self, operation: Operation) -> Result<ValueOperation, CompilerError> {
        storage_operation_to_value(operation, &|param| self.target.parameter_value(param))
            .map_err(CompilerError::Circuit)
    }
}

/// Simplifies the runtime classical expression inside a [`ClassicalDataOp`].
fn simplify_classical_data_op(op: &ClassicalDataOp) -> ClassicalDataOp {
    match op {
        ClassicalDataOp::Store { target, value } => ClassicalDataOp::Store {
            target: *target,
            value: value.simplified(),
        },
        ClassicalDataOp::MeasureBit { result } => ClassicalDataOp::MeasureBit { result: *result },
        ClassicalDataOp::MeasureBits { result } => ClassicalDataOp::MeasureBits { result: *result },
    }
}

fn compiler_parameter<T>(
    result: Result<T, crate::circuit::error::ParameterError>,
) -> Result<T, CompilerError> {
    result.map_err(|error| CompilerError::Circuit(CircuitError::InvalidParameter(error)))
}

/// Rebuilds a circuit while preserving runtime classical tables and handles.
fn rebuild_circuit_from_value_operations(
    source: &Circuit,
    operations: Vec<ValueOperation>,
    global_phase: Parameter,
) -> Result<Circuit, CompilerError> {
    let mut target = Circuit::from_operations(
        source.qubits(),
        operations,
        Some(source.classical_vars().to_vec()),
        Some(source.classical_values().to_vec()),
    )
    .map_err(CompilerError::Circuit)?;
    target.set_global_phase(global_phase);
    Ok(target)
}

#[derive(Debug, Clone, Copy)]
enum ScopeKind {
    TopLevel,
    ControlFlowBody,
}

#[derive(Debug, Clone)]
struct RewriteResult {
    operations: Vec<Operation>,
    phase: Parameter,
    preserves_source: bool,
}

impl RewriteResult {
    fn keep(operation: Operation, preserves_source: bool) -> Self {
        Self {
            operations: vec![operation],
            phase: Parameter::from(0.0),
            preserves_source,
        }
    }

    fn drop() -> Self {
        Self {
            operations: Vec::new(),
            phase: Parameter::from(0.0),
            preserves_source: false,
        }
    }

    fn phase(phase: Parameter) -> Self {
        Self {
            operations: Vec::new(),
            phase,
            preserves_source: false,
        }
    }
}