wai-quantum 0.3.38

A deterministic quantum stack in pure Rust: byte-exact circuit simulation (statevector / stabilizer / tensor-network MPS / sparse-Pauli backends), sparse Pauli dynamics at utility scale (arbitrary angles, 1024 qubits), belief-propagation tensor networks on the hardware graph, error mitigation, qLDPC decoding, noise learning, circuit-equivalence proofs, a phasor interference-ML layer, information-theoretic limits, noisy channels and state tomography, and signed energy-accounted receipts. No QPU, no cloud, no system libraries — identical results native, in the browser, and as a WASI component at the edge.
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! **QIR export** — emit a circuit as QIR (Quantum Intermediate Representation),
//! the LLVM-based interchange the QIR Alliance defines and quantum toolchains
//! consume.
//!
//! This is the interop half of [`crate::quantum_toolchain::to_qasm`]: OpenQASM is
//! the human-facing source language, QIR is the compiler-facing IR. Emitting both
//! means a circuit built here can be handed to any toolchain that reads either.
//!
//! # What is emitted
//!
//! A base-profile-shaped module: opaque `%Qubit`/`%Result` types, `declare`s for
//! exactly the intrinsics used, an `entry_point` function with the QIR profile
//! attributes and `required_num_qubits`, then one `call` per gate, then a
//! measurement of every qubit with `__quantum__rt__result_record_output`.
//!
//! Angles are written as LLVM **hex float literals** (`double 0x400921FB…`), the
//! exact 64-bit pattern — a decimal rendering could round, and this stack does not
//! round.
//!
//! # Gate mapping, and where it is exact
//!
//! `X Y Z H S S† T T† CNOT CZ` map to their standard intrinsics one-to-one.
//! The rest are rewritten into that set:
//!
//! | Source | Emitted as | Exactness |
//! |---|---|---|
//! | `CY(c,t)` | `s__adj(t); cnot(c,t); s(t)` | exact |
//! | `CCX(a,b,t)` | the standard 6-CNOT + T/T† decomposition | exact |
//! | `CCZ(a,b,t)` | `h(t); CCX; h(t)` | exact |
//! | `P(k)` | `rz(2π/2ᵏ)` | exact **up to global phase** |
//! | `CP(k)` | `rz`/`cnot` controlled-phase decomposition | exact **up to global phase** |
//!
//! `Rz(θ) = P(θ)·e^{−iθ/2}`, so the `P`/`CP` mappings differ from the source by a
//! global phase, which is physically unobservable — every measurement
//! distribution is identical.
//!
//! # How this is checked
//!
//! - The exact rewrites (`CY`, `CCX`, `CCZ`) are verified against the simulator
//!   on **every basis state**, comparing by fidelity rather than by statevector
//!   hash — see the note on the test helper for why hash equality would be the
//!   wrong question to ask of a fixed-point simulator.
//! - The `CP` mapping cannot be replayed through the simulator (there is no `Rz`
//!   gate), so it is verified independently as a 4x4 complex matrix: the test
//!   asserts the deviation is a single *global* phase across all basis states and
//!   that no amplitude leaks between them.
//! - The emitted modules are validated by a real LLVM assembler: every algorithm
//!   in the catalog round-trips through `llvm-as` (LLVM 22) with no diagnostics.
//!
//! # Ingest
//!
//! [`from_qir`] parses a module back into a [`Circuit`], so interop runs both
//! ways. Of the ten algorithms in the catalog, nine return with a **bit-identical
//! statevector** and one (Grover) returns *equivalent* — its Toffoli decomposes,
//! and the decomposition rounds differently in fixed point even though the two
//! are the same operator.
//!
//! Ingest folds the emitted controlled-phase pattern back into a `CP` gate. That
//! peephole is not cosmetic: the decomposition contains a **negative** `rz`, which
//! the dyadic gate set cannot represent on its own, so without it every
//! QFT-shaped module — phase estimation, Shor — would be refused.

use crate::quantum::{BaseGate, Circuit, Gate};
use std::f64::consts::PI;

/// LLVM's exact hex form for a double (`0x` + the raw 64-bit pattern).
fn hexf(v: f64) -> String {
    format!("0x{:016X}", v.to_bits())
}

fn qubit(i: u8) -> String {
    format!("%Qubit* inttoptr (i64 {i} to %Qubit*)")
}

/// The angle a `P(k)` / `CP(k)` gate applies: `2π / 2^k`.
fn p_angle(k: u16) -> f64 {
    2.0 * PI / (1u64 << k.min(62)) as f64
}

/// One emitted QIR instruction.
struct Emitter {
    body: Vec<String>,
    used: Vec<&'static str>,
}

impl Emitter {
    fn new() -> Self {
        Emitter { body: Vec::new(), used: Vec::new() }
    }
    fn mark(&mut self, intrinsic: &'static str) {
        if !self.used.contains(&intrinsic) {
            self.used.push(intrinsic);
        }
    }
    /// A single-qubit intrinsic call.
    fn one(&mut self, name: &'static str, q: u8) {
        self.mark(name);
        self.body.push(format!("  call void @{name}({})", qubit(q)));
    }
    /// A two-qubit intrinsic call (control first).
    fn two(&mut self, name: &'static str, c: u8, t: u8) {
        self.mark(name);
        self.body.push(format!("  call void @{name}({}, {})", qubit(c), qubit(t)));
    }
    /// `rz(theta, q)` with an exact hex-float angle.
    fn rz(&mut self, theta: f64, q: u8) {
        self.mark("__quantum__qis__rz__body");
        self.body.push(format!(
            "  call void @__quantum__qis__rz__body(double {}, {})",
            hexf(theta),
            qubit(q)
        ));
    }

    /// Controlled-Y as `S†; CNOT; S` on the target — exact.
    fn cy(&mut self, c: u8, t: u8) {
        self.one("__quantum__qis__s__adj", t);
        self.two("__quantum__qis__cnot__body", c, t);
        self.one("__quantum__qis__s__body", t);
    }

    /// Controlled-phase via `rz`/`cnot` — exact up to global phase.
    fn cp(&mut self, theta: f64, c: u8, t: u8) {
        self.rz(theta / 2.0, c);
        self.two("__quantum__qis__cnot__body", c, t);
        self.rz(-theta / 2.0, t);
        self.two("__quantum__qis__cnot__body", c, t);
        self.rz(theta / 2.0, t);
    }

    /// The standard 6-CNOT Toffoli — exact.
    fn ccx(&mut self, a: u8, b: u8, t: u8) {
        const H: &str = "__quantum__qis__h__body";
        const T: &str = "__quantum__qis__t__body";
        const TD: &str = "__quantum__qis__t__adj";
        const CN: &str = "__quantum__qis__cnot__body";
        self.one(H, t);
        self.two(CN, b, t);
        self.one(TD, t);
        self.two(CN, a, t);
        self.one(T, t);
        self.two(CN, b, t);
        self.one(TD, t);
        self.two(CN, a, t);
        self.one(T, b);
        self.one(T, t);
        self.one(H, t);
        self.two(CN, a, b);
        self.one(T, a);
        self.one(TD, b);
        self.two(CN, a, b);
    }

    fn gate(&mut self, g: &Gate) {
        let t = g.target;
        match (g.base, g.controls.as_slice()) {
            (BaseGate::I, _) => {}
            (BaseGate::X, []) => self.one("__quantum__qis__x__body", t),
            (BaseGate::Y, []) => self.one("__quantum__qis__y__body", t),
            (BaseGate::Z, []) => self.one("__quantum__qis__z__body", t),
            (BaseGate::H, []) => self.one("__quantum__qis__h__body", t),
            (BaseGate::S, []) => self.one("__quantum__qis__s__body", t),
            (BaseGate::Sdg, []) => self.one("__quantum__qis__s__adj", t),
            (BaseGate::T, []) => self.one("__quantum__qis__t__body", t),
            (BaseGate::Tdg, []) => self.one("__quantum__qis__t__adj", t),
            (BaseGate::P, []) => self.rz(p_angle(g.param), t),
            (BaseGate::X, [c]) => self.two("__quantum__qis__cnot__body", *c, t),
            (BaseGate::Z, [c]) => self.two("__quantum__qis__cz__body", *c, t),
            (BaseGate::Y, [c]) => self.cy(*c, t),
            (BaseGate::P, [c]) => self.cp(p_angle(g.param), *c, t),
            (BaseGate::X, [a, b]) => self.ccx(*a, *b, t),
            (BaseGate::Z, [a, b]) => {
                self.one("__quantum__qis__h__body", t);
                self.ccx(*a, *b, t);
                self.one("__quantum__qis__h__body", t);
            }
            // Anything outside the mapped set is reported rather than silently
            // dropped — a wrong circuit is worse than a refused one.
            (base, ctrls) => self.body.push(format!(
                "  ; UNMAPPED {base:?} controls={ctrls:?} target={t} — this module is NOT faithful"
            )),
        }
    }
}

/// The declaration line for an intrinsic.
fn declaration(name: &str) -> String {
    match name {
        "__quantum__qis__rz__body" => format!("declare void @{name}(double, %Qubit*)"),
        "__quantum__qis__cnot__body" | "__quantum__qis__cz__body" => {
            format!("declare void @{name}(%Qubit*, %Qubit*)")
        }
        "__quantum__qis__mz__body" => format!("declare void @{name}(%Qubit*, %Result*)"),
        "__quantum__rt__result_record_output" => format!("declare void @{name}(%Result*, i8*)"),
        _ => format!("declare void @{name}(%Qubit*)"),
    }
}

/// Emit `c` as a QIR module. `measure_all` appends an `mz` + result record for
/// every qubit (what a base-profile consumer expects to find).
pub fn to_qir(c: &Circuit, measure_all: bool) -> String {
    let mut e = Emitter::new();
    for g in &c.ops {
        e.gate(g);
    }
    let n = c.n_qubits;
    if measure_all {
        for q in 0..n {
            e.mark("__quantum__qis__mz__body");
            e.body.push(format!(
                "  call void @__quantum__qis__mz__body({}, %Result* inttoptr (i64 {q} to %Result*))",
                qubit(q)
            ));
        }
        for q in 0..n {
            e.mark("__quantum__rt__result_record_output");
            e.body.push(format!(
                "  call void @__quantum__rt__result_record_output(%Result* inttoptr (i64 {q} to %Result*), i8* null)"
            ));
        }
    }

    let mut s = String::new();
    s.push_str("; QIR emitted by wai-quantum — deterministic, byte-identical on every target.\n");
    s.push_str("source_filename = \"wai_quantum\"\n\n");
    s.push_str("%Qubit = type opaque\n%Result = type opaque\n\n");
    for i in &e.used {
        s.push_str(&declaration(i));
        s.push('\n');
    }
    s.push_str("\ndefine void @main() #0 {\nentry:\n");
    for line in &e.body {
        s.push_str(line);
        s.push('\n');
    }
    s.push_str("  ret void\n}\n\n");
    let results = if measure_all { n } else { 0 };
    s.push_str(&format!(
        "attributes #0 = {{ \"entry_point\" \"output_labeling_schema\" \
         \"qir_profiles\"=\"base_profile\" \"required_num_qubits\"=\"{n}\" \
         \"required_num_results\"=\"{results}\" }}\n\n"
    ));
    s.push_str("!llvm.module.flags = !{!0, !1, !2, !3}\n");
    s.push_str("!0 = !{i32 1, !\"qir_major_version\", i32 1}\n");
    s.push_str("!1 = !{i32 7, !\"qir_minor_version\", i32 0}\n");
    s.push_str("!2 = !{i32 1, !\"dynamic_qubit_management\", i1 false}\n");
    s.push_str("!3 = !{i32 1, !\"dynamic_result_management\", i1 false}\n");
    s
}

// ---------------------------------------------------------------------------
// Reference rewrites, in the crate's own gate set, used to PROVE the emitted
// decompositions are the circuits they claim to be.
// ---------------------------------------------------------------------------

fn push(c: &mut Circuit, base: BaseGate, controls: Vec<u8>, target: u8, param: u16) {
    c.ops.push(Gate { base, controls, target, param });
}

/// The `CY` rewrite as a circuit: `S†; CNOT; S`.
pub fn rewrite_cy(n: u8, c0: u8, t: u8) -> Circuit {
    let mut c = Circuit::new(n);
    push(&mut c, BaseGate::Sdg, vec![], t, 0);
    c.cx(c0, t);
    push(&mut c, BaseGate::S, vec![], t, 0);
    c
}

/// The `CCX` rewrite as a circuit: the standard 6-CNOT Toffoli.
pub fn rewrite_ccx(n: u8, a: u8, b: u8, t: u8) -> Circuit {
    let mut c = Circuit::new(n);
    c.h(t);
    c.cx(b, t);
    push(&mut c, BaseGate::Tdg, vec![], t, 0);
    c.cx(a, t);
    c.t(t);
    c.cx(b, t);
    push(&mut c, BaseGate::Tdg, vec![], t, 0);
    c.cx(a, t);
    c.t(b);
    c.t(t);
    c.h(t);
    c.cx(a, b);
    c.t(a);
    push(&mut c, BaseGate::Tdg, vec![], b, 0);
    c.cx(a, b);
    c
}


// ---------------------------------------------------------------------------
// Ingest
// ---------------------------------------------------------------------------

/// The angle `2π/2^k` for the smallest `k` matching `theta`, if one does.
fn angle_to_param(theta: f64) -> Option<u16> {
    for k in 0u16..=62 {
        let a = p_angle(k);
        if (a - theta).abs() <= 1e-9 * a.max(1.0) {
            return Some(k);
        }
    }
    None
}

/// Every `i64 N` appearing in a call's argument list, in order.
fn arg_indices(line: &str) -> Vec<u8> {
    let mut out = Vec::new();
    let mut rest = line;
    while let Some(i) = rest.find("i64 ") {
        rest = &rest[i + 4..];
        let end = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len());
        if let Ok(v) = rest[..end].parse::<u64>() {
            out.push(v as u8);
        }
        rest = &rest[end..];
    }
    out
}

/// The `double` operand of an `rz` call — hex (`0x…`, the exact bit pattern) or
/// decimal.
fn arg_double(line: &str) -> Option<f64> {
    let i = line.find("double ")? + 7;
    let rest = &line[i..];
    let end = rest.find([',', ')']).unwrap_or(rest.len());
    let tok = rest[..end].trim();
    if let Some(hex) = tok.strip_prefix("0x") {
        u64::from_str_radix(hex, 16).ok().map(f64::from_bits)
    } else {
        tok.parse::<f64>().ok()
    }
}

/// Parse a QIR module into a [`Circuit`].
///
/// Accepts the modules [`to_qir`] emits and, more generally, any QIR whose body
/// is calls to the standard `__quantum__qis__*` intrinsics with constant qubit
/// operands. Measurement calls (`mz`, `result_record_output`) are recognised and
/// skipped — a `Circuit` is unitary, the measurement is the caller's business.
///
/// # Errors
///
/// This crate's gate set represents phases as `2π/2^k`, so an `rz(θ)` whose angle
/// is not such a dyadic fraction — a **negative** angle included — cannot be
/// represented and is reported rather than silently approximated. In practice
/// that means Clifford+T modules ingest cleanly, while a module containing an
/// arbitrary-angle rotation (or the `rz` half of an emitted `CP`) is refused.
/// Being told is better than being lied to.
pub fn from_qir(src: &str) -> Result<Circuit, String> {
    // Parse to a raw op list first, keeping `rz` angles intact. The controlled-
    // phase decomposition this module emits contains a NEGATIVE rz, which the
    // dyadic gate set cannot hold on its own — but the five-gate pattern as a
    // whole is a `CP`, which it can. Folding before conversion is what lets a
    // QFT-shaped module (phase estimation, Shor) come back in.
    enum Raw {
        G(BaseGate, Vec<u8>, u8),
        Rz(f64, u8),
    }
    let mut raw: Vec<Raw> = Vec::new();
    let mut max_q: i32 = -1;

    for line in src.lines() {
        let line = line.trim();
        if !line.starts_with("call void @__quantum__") {
            continue;
        }
        let name = line
            .split('@')
            .nth(1)
            .and_then(|r| r.split('(').next())
            .ok_or_else(|| format!("malformed call: {line}"))?;
        let qs = arg_indices(line);
        for q in &qs {
            max_q = max_q.max(*q as i32);
        }
        let need = |n: usize| -> Result<(), String> {
            if qs.len() < n {
                Err(format!("{name}: expected {n} qubit operands, got {}", qs.len()))
            } else {
                Ok(())
            }
        };
        match name {
            "__quantum__qis__x__body" => { need(1)?; raw.push(Raw::G(BaseGate::X, vec![], qs[0])); }
            "__quantum__qis__y__body" => { need(1)?; raw.push(Raw::G(BaseGate::Y, vec![], qs[0])); }
            "__quantum__qis__z__body" => { need(1)?; raw.push(Raw::G(BaseGate::Z, vec![], qs[0])); }
            "__quantum__qis__h__body" => { need(1)?; raw.push(Raw::G(BaseGate::H, vec![], qs[0])); }
            "__quantum__qis__s__body" => { need(1)?; raw.push(Raw::G(BaseGate::S, vec![], qs[0])); }
            "__quantum__qis__s__adj"  => { need(1)?; raw.push(Raw::G(BaseGate::Sdg, vec![], qs[0])); }
            "__quantum__qis__t__body" => { need(1)?; raw.push(Raw::G(BaseGate::T, vec![], qs[0])); }
            "__quantum__qis__t__adj"  => { need(1)?; raw.push(Raw::G(BaseGate::Tdg, vec![], qs[0])); }
            "__quantum__qis__cnot__body" | "__quantum__qis__cx__body" => {
                need(2)?; raw.push(Raw::G(BaseGate::X, vec![qs[0]], qs[1]));
            }
            "__quantum__qis__cz__body" => { need(2)?; raw.push(Raw::G(BaseGate::Z, vec![qs[0]], qs[1])); }
            "__quantum__qis__rz__body" => {
                need(1)?;
                let theta = arg_double(line).ok_or_else(|| format!("rz: no double operand: {line}"))?;
                raw.push(Raw::Rz(theta, qs[0]));
            }
            "__quantum__qis__mz__body" | "__quantum__qis__m__body"
            | "__quantum__rt__result_record_output" | "__quantum__rt__tuple_record_output"
            | "__quantum__rt__array_record_output" => {}
            other => return Err(format!("unsupported intrinsic: {other}")),
        }
    }

    // Fold `rz(a,c); cnot(c,t); rz(-a,t); cnot(c,t); rz(a,t)` back into CP(2a).
    let close = |x: f64, y: f64| (x - y).abs() <= 1e-9 * x.abs().max(1.0);
    let mut gates: Vec<(BaseGate, Vec<u8>, u8, u16)> = Vec::new();
    let mut i = 0usize;
    while i < raw.len() {
        if i + 4 < raw.len()
            && let (
                Raw::Rz(a0, c0),
                Raw::G(BaseGate::X, cs1, t1),
                Raw::Rz(a2, t2),
                Raw::G(BaseGate::X, cs3, t3),
                Raw::Rz(a4, t4),
            ) = (&raw[i], &raw[i + 1], &raw[i + 2], &raw[i + 3], &raw[i + 4])
            && cs1.len() == 1
            && cs3.len() == 1
            && cs1[0] == *c0
            && cs3[0] == *c0
            && t1 == t2
            && t1 == t3
            && t1 == t4
            && close(*a2, -*a0)
            && close(*a4, *a0)
            && let Some(k) = angle_to_param(2.0 * *a0)
        {
            gates.push((BaseGate::P, vec![*c0], *t1, k));
            i += 5;
            continue;
        }
        match &raw[i] {
            Raw::G(b, cs, t) => gates.push((*b, cs.clone(), *t, 0)),
            Raw::Rz(theta, q) => {
                let k = angle_to_param(*theta).ok_or_else(|| {
                    format!("rz({theta}) is not a representable 2π/2^k phase — this gate set stores dyadic phases only")
                })?;
                gates.push((BaseGate::P, vec![], *q, k));
            }
        }
        i += 1;
    }

    // Prefer the declared width; fall back to the highest operand seen.
    let declared = src
        .find("\"required_num_qubits\"=\"")
        .and_then(|i| src[i + 23..].split('"').next().and_then(|v| v.parse::<u8>().ok()));
    let n = declared.unwrap_or_else(|| (max_q + 1).max(1) as u8);
    if let Some(d) = declared
        && max_q + 1 > d as i32
    {
        return Err(format!("module uses qubit {max_q} but declares required_num_qubits={d}"));
    }

    let mut c = Circuit::new(n);
    for (base, controls, target, param) in gates {
        c.ops.push(Gate { base, controls, target, param });
    }
    c.validate().map_err(|e| format!("parsed an invalid circuit: {e:?}"))?;
    Ok(c)
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::quantum::ONE;
    use crate::quantum_toolchain as qt;

    /// Compare by **fidelity**, not by statevector hash.
    ///
    /// The rewrites below are mathematically exact, but this simulator is
    /// fixed-point: `CCX` is applied directly as a permutation (no rounding),
    /// while its decomposition routes through seven irrational `T`/`H` gates that
    /// each round in the last bits. Demanding hash equality would be demanding
    /// that two different arithmetic paths round identically, which is not what
    /// "exact decomposition" means. `|⟨a|b⟩|² = 1` is the right statement — and it
    /// is also insensitive to global phase, which is precisely the freedom the
    /// `P`/`CP` mappings use.
    fn agrees_on_all_inputs(n: u8, build: &dyn Fn(&mut Circuit), rewrite: &Circuit) -> (bool, i64) {
        let tol = ONE / 100_000; // fixed-point rounding only
        let mut worst = ONE;
        for k in 0..(1usize << n) {
            let mut a = Circuit::new(n);
            let mut b = Circuit::new(n);
            for q in 0..n {
                if k >> q & 1 == 1 {
                    a.x(q);
                    b.x(q);
                }
            }
            build(&mut a);
            for g in &rewrite.ops {
                b.ops.push(g.clone());
            }
            let f = a.simulate().unwrap().fidelity_fx(&b.simulate().unwrap());
            worst = worst.min(f);
            if (ONE - f).abs() > tol {
                return (false, f);
            }
        }
        (true, worst)
    }

    #[test]
    fn cy_rewrite_is_exact() {
        let (ok, f) = agrees_on_all_inputs(
            2,
            &|c: &mut Circuit| {
                c.ops.push(Gate { base: BaseGate::Y, controls: vec![0], target: 1, param: 0 });
            },
            &rewrite_cy(2, 0, 1),
        );
        assert!(ok, "CY rewrite fidelity {f} of {ONE}");
    }

    #[test]
    fn ccx_rewrite_is_exact() {
        let (ok, f) = agrees_on_all_inputs(3, &|c: &mut Circuit| { c.ccx(0, 1, 2); }, &rewrite_ccx(3, 0, 1, 2));
        assert!(ok, "CCX rewrite fidelity {f} of {ONE}");
    }

    #[test]
    fn ccx_rewrite_holds_with_controls_swapped() {
        let (ok, f) = agrees_on_all_inputs(3, &|c: &mut Circuit| { c.ccx(1, 0, 2); }, &rewrite_ccx(3, 1, 0, 2));
        assert!(ok, "CCX(swapped) rewrite fidelity {f} of {ONE}");
    }

    // -- an independent check of the CP mapping, in f64 ----------------------
    // The simulator has no `Rz`, so the emitted controlled-phase decomposition
    // cannot be replayed through it. Verify it directly as a 4x4 complex matrix.

    type C = (f64, f64);
    fn cmul(a: C, b: C) -> C { (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0) }
    fn expi(t: f64) -> C { (t.cos(), t.sin()) }

    /// Apply `rz(phi)` on `q` (0 = high bit) to a 4-vector.
    fn rz_on(v: &mut [C; 4], phi: f64, q: usize) {
        for (i, e) in v.iter_mut().enumerate() {
            let bit = if q == 0 { i >> 1 & 1 } else { i & 1 };
            let sign = if bit == 1 { 1.0 } else { -1.0 };
            *e = cmul(*e, expi(sign * phi / 2.0));
        }
    }
    /// CNOT with control 0, target 1.
    fn cnot(v: &mut [C; 4]) {
        v.swap(0b10, 0b11);
    }

    #[test]
    fn cp_mapping_is_exact_up_to_global_phase() {
        for &k in &[1u16, 2, 3, 5, 8] {
            let theta = p_angle(k);
            let mut global: Option<C> = None;
            for basis in 0..4usize {
                let mut v: [C; 4] = [(0.0, 0.0); 4];
                v[basis] = (1.0, 0.0);
                // the emitted sequence: rz(θ/2) c; cnot; rz(-θ/2) t; cnot; rz(θ/2) t
                rz_on(&mut v, theta / 2.0, 0);
                cnot(&mut v);
                rz_on(&mut v, -theta / 2.0, 1);
                cnot(&mut v);
                rz_on(&mut v, theta / 2.0, 1);
                // reference CP(theta): diag(1,1,1,e^{iθ})
                let want: C = if basis == 3 { expi(theta) } else { (1.0, 0.0) };
                let got = v[basis];
                // the ratio got/want must be one constant global phase for all basis states
                let ratio = cmul(got, (want.0, -want.1)); // want has modulus 1
                match global {
                    None => global = Some(ratio),
                    Some(g) => {
                        assert!((g.0 - ratio.0).abs() < 1e-12 && (g.1 - ratio.1).abs() < 1e-12,
                            "k={k} basis={basis}: phase {ratio:?} != {g:?} — not a GLOBAL phase");
                    }
                }
                // and nothing may leak to other basis states
                for (j, e) in v.iter().enumerate() {
                    if j != basis {
                        assert!(e.0.abs() < 1e-12 && e.1.abs() < 1e-12, "k={k} leaked into {j}");
                    }
                }
            }
            let g = global.unwrap();
            assert!((g.0 * g.0 + g.1 * g.1 - 1.0).abs() < 1e-12, "global phase must be unit");
        }
    }

    #[test]
    fn emits_a_wellformed_module() {
        let c = qt::ghz(3);
        let ir = to_qir(&c, true);
        assert!(ir.contains("%Qubit = type opaque"));
        assert!(ir.contains("declare void @__quantum__qis__h__body(%Qubit*)"));
        assert!(ir.contains("declare void @__quantum__qis__cnot__body(%Qubit*, %Qubit*)"));
        assert!(ir.contains("define void @main() #0 {"));
        assert!(ir.contains("\"required_num_qubits\"=\"3\""));
        assert!(ir.contains("\"required_num_results\"=\"3\""));
        assert!(ir.contains("qir_major_version"));
        assert_eq!(ir.matches("__quantum__qis__cnot__body(%Qubit* inttoptr").count(), 2);
        assert!(!ir.contains("UNMAPPED"));
    }

    #[test]
    fn angles_are_exact_hex_floats() {
        let mut c = Circuit::new(1);
        c.p(3, 0); // 2π/8 = π/4
        let ir = to_qir(&c, false);
        let want = hexf(std::f64::consts::FRAC_PI_4);
        assert!(ir.contains(&format!("double {want}")), "{ir}");
        let bits = u64::from_str_radix(&want[2..], 16).unwrap();
        assert_eq!(f64::from_bits(bits), std::f64::consts::FRAC_PI_4);
    }

    #[test]
    fn every_toolchain_algorithm_maps_completely() {
        for (id, _, _) in qt::catalog() {
            if let Some(c) = qt::build_algorithm(id, 3, 5) {
                let ir = to_qir(&c, true);
                assert!(!ir.contains("UNMAPPED"), "{id} produced an unfaithful module:\n{ir}");
            }
        }
    }

    /// Two `declare`s of one symbol (with different signatures) is invalid LLVM —
    /// it slipped in once when the measurement intrinsic hit the generic fallback.
    #[test]
    fn no_symbol_is_declared_twice() {
        for (id, _, _) in qt::catalog() {
            if let Some(c) = qt::build_algorithm(id, 3, 5) {
                for measure in [true, false] {
                    let ir = to_qir(&c, measure);
                    let mut names: Vec<&str> = ir
                        .lines()
                        .filter(|l| l.starts_with("declare "))
                        .map(|l| l.split('@').nth(1).unwrap().split('(').next().unwrap())
                        .collect();
                    let n = names.len();
                    names.sort_unstable();
                    names.dedup();
                    assert_eq!(n, names.len(), "{id}: duplicate declare in\n{ir}");
                }
            }
        }
    }

    /// QIR round-trip is **semantic**, not structural: `to_qir` decomposes CY /
    /// CCX / CCZ, so what comes back is the decomposed equivalent, not the
    /// original op-log. Equivalence is the property that matters.
    #[test]
    fn round_trips_semantically() {
        let mut checked = 0;
        for (id, _, _) in qt::catalog() {
            let Some(c) = qt::build_algorithm(id, 3, 5) else { continue };
            let ir = to_qir(&c, true);
            match from_qir(&ir) {
                Ok(back) => {
                    assert_eq!(back.n_qubits, c.n_qubits, "{id}: width changed");
                    let f = c.simulate().unwrap().fidelity_fx(&back.simulate().unwrap());
                    assert!(
                        (ONE - f).abs() <= ONE / 100_000,
                        "{id}: round-trip fidelity {f} of {ONE}"
                    );
                    checked += 1;
                }
                Err(e) => {
                    // Only the dyadic-phase limit may cause a refusal, and it must say so.
                    assert!(e.contains("not a representable"), "{id}: unexpected error: {e}");
                }
            }
        }
        assert!(checked >= 5, "expected most algorithms to round-trip, got {checked}");
    }

    /// QFT is the peephole's reason to exist: its controlled-phase ladder emits a
    /// negative `rz`, which the dyadic gate set cannot hold on its own. Folding the
    /// five-gate pattern back into `CP` is what lets phase-estimation-shaped
    /// modules return intact — and intact means the SAME hash, not merely equivalent.
    #[test]
    fn qft_round_trips_to_an_identical_statevector() {
        for n in 2..=4u8 {
            let c = qt::build_algorithm("qft", n, 0).unwrap();
            let back = from_qir(&to_qir(&c, true)).expect("QFT must ingest");
            assert_eq!(
                c.simulate().unwrap().statevector_hash(),
                back.simulate().unwrap().statevector_hash(),
                "qft n={n} did not return identical"
            );
            assert!(
                c.ops.iter().any(|g| matches!(g.base, BaseGate::P) && !g.controls.is_empty()),
                "qft n={n} should contain a controlled phase for this to be meaningful"
            );
        }
    }

    #[test]
    fn refuses_unrepresentable_angles_instead_of_approximating() {
        // 0.1 rad is not 2π/2^k for any k.
        let ir = format!(
            "define void @main() #0 {{\nentry:\n  call void @__quantum__qis__rz__body(double {}, %Qubit* inttoptr (i64 0 to %Qubit*))\n  ret void\n}}\nattributes #0 = {{ \"required_num_qubits\"=\"1\" }}\n",
            hexf(0.1)
        );
        let e = from_qir(&ir).unwrap_err();
        assert!(e.contains("not a representable"), "{e}");
    }

    #[test]
    fn rejects_unknown_intrinsics_and_overwide_modules() {
        let bad = "define void @main() #0 {\nentry:\n  call void @__quantum__qis__toffoli__body(%Qubit* inttoptr (i64 0 to %Qubit*))\n  ret void\n}\n";
        assert!(from_qir(bad).unwrap_err().contains("unsupported intrinsic"));

        let over = "define void @main() #0 {\nentry:\n  call void @__quantum__qis__h__body(%Qubit* inttoptr (i64 5 to %Qubit*))\n  ret void\n}\nattributes #0 = { \"required_num_qubits\"=\"2\" }\n";
        assert!(from_qir(over).unwrap_err().contains("required_num_qubits"));
    }

    #[test]
    fn ingests_a_hand_written_clifford_t_module() {
        // What another toolchain would hand us: no attributes, decimal angle.
        let ir = "\
define void @main() {
entry:
  call void @__quantum__qis__h__body(%Qubit* inttoptr (i64 0 to %Qubit*))
  call void @__quantum__qis__cnot__body(%Qubit* inttoptr (i64 0 to %Qubit*), %Qubit* inttoptr (i64 1 to %Qubit*))
  call void @__quantum__qis__t__body(%Qubit* inttoptr (i64 1 to %Qubit*))
  call void @__quantum__qis__mz__body(%Qubit* inttoptr (i64 0 to %Qubit*), %Result* inttoptr (i64 0 to %Result*))
  ret void
}
";
        let c = from_qir(ir).expect("should ingest");
        assert_eq!(c.n_qubits, 2, "width inferred from operands");
        assert_eq!(c.ops.len(), 3, "measurement is not a gate");
        // same state as building it directly
        let mut want = Circuit::new(2);
        want.h(0);
        want.cx(0, 1);
        want.t(1);
        assert_eq!(
            want.simulate().unwrap().statevector_hash(),
            c.simulate().unwrap().statevector_hash()
        );
    }

    #[test]
    fn deterministic() {
        let c = qt::grover(3, 5);
        assert_eq!(to_qir(&c, true), to_qir(&c, true));
    }
}