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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#![deny(clippy::all, clippy::pedantic)]

//! # QIR compliant backend for quantum simulation.
//! This libary builds on top of the `qir_stdlib` to implement a full backend for simulation of QIR
//! programs. This includes a broad set of quantum intrinsic operations for sparse state simulation,
//! based on the design from
//! <a href="https://arxiv.org/abs/2105.01533">Leveraging state sparsity for more efficient quantum simulations</a>.

pub mod result_bool;

pub mod exp;

use bitvec::prelude::*;
use num_bigint::BigUint;
use num_complex::Complex64;
use quantum_sparse_sim::QuantumSim;
use std::cell::RefCell;
use std::convert::TryInto;
use std::ffi::c_char;
use std::ffi::c_double;
use std::ffi::{c_void, CString};
use std::io::Write;
use std::mem::size_of;

use result_bool::{
    __quantum__rt__result_equal, __quantum__rt__result_get_one, __quantum__rt__result_get_zero,
};

pub use qir_stdlib::{
    arrays::*, bigints::*, callables::*, math::*, output_recording::*, range_support::*,
    strings::*, tuples::*, *,
};

struct SimulatorState {
    pub sim: QuantumSim,
    pub res: BitVec,
    pub max_qubit_id: usize,
}

thread_local! {
    static SIM_STATE: RefCell<SimulatorState> = RefCell::new(SimulatorState {
        sim: QuantumSim::default(),
        res: bitvec![],
        max_qubit_id: 0
    });
}

/// Sets the seed for the pseudo-random number generator used during measurements.
pub fn set_rng_seed(seed: u64) {
    SIM_STATE.with(|sim_state| {
        let state = &mut *sim_state.borrow_mut();
        state.sim.set_rng_seed(seed);
    });
}

/// Initializes the execution environment.
#[no_mangle]
pub extern "C" fn __quantum__rt__initialize(_: *mut c_char) {
    SIM_STATE.with(|sim_state| {
        let state = &mut *sim_state.borrow_mut();
        state.sim = QuantumSim::default();
        state.res = bitvec![];
        state.max_qubit_id = 0;
    });
}

fn ensure_sufficient_qubits(sim: &mut QuantumSim, qubit_id: usize, max: &mut usize) {
    while qubit_id + 1 > *max {
        let _ = sim.allocate();
        *max += 1;
    }
}

/// Maps the given qubits from the given Pauli basis into the computational basis, returning the
/// unwrapped `QirArray`s into a vector of matching Pauli and qubit id tuples.
#[allow(clippy::cast_ptr_alignment)]
unsafe fn map_to_z_basis(
    state: &mut SimulatorState,
    paulis: *const QirArray,
    qubits: *const QirArray,
) -> Vec<(Pauli, usize)> {
    let paulis_size = __quantum__rt__array_get_size_1d(paulis);
    let qubits_size = __quantum__rt__array_get_size_1d(qubits);
    if paulis_size != qubits_size {
        __quantum__rt__fail(__quantum__rt__string_create(
            CString::new("Pauli array and Qubit array must be the same size.")
                .expect("Unable to allocate memory for failure message string.")
                .as_bytes_with_nul()
                .as_ptr() as *mut c_char,
        ));
    }

    let combined_list: Vec<(Pauli, usize)> = (0..paulis_size)
        .filter_map(|index| {
            let p =
                *__quantum__rt__array_get_element_ptr_1d(paulis, index).cast::<Pauli>() as Pauli;
            let q = *__quantum__rt__array_get_element_ptr_1d(qubits, index).cast::<*mut c_void>()
                as usize;
            if let Pauli::I = p {
                None
            } else {
                ensure_sufficient_qubits(&mut state.sim, q, &mut state.max_qubit_id);
                Some((p, q))
            }
        })
        .collect();

    for (pauli, qubit) in &combined_list {
        match pauli {
            Pauli::X => state.sim.h(*qubit),
            Pauli::Y => {
                state.sim.h(*qubit);
                state.sim.s(*qubit);
                state.sim.h(*qubit);
            }
            _ => (),
        }
    }

    combined_list
}

/// Given a vector of Pauli and qubit id pairs, unmaps from the computational basis back into the given
/// Pauli basis. This should be the adjoint of the `map_to_z_basis` operation.
fn unmap_from_z_basis(state: &mut SimulatorState, combined_list: Vec<(Pauli, usize)>) {
    for (pauli, qubit) in combined_list {
        match pauli {
            Pauli::X => state.sim.h(qubit),
            Pauli::Y => {
                state.sim.h(qubit);
                state.sim.sadj(qubit);
                state.sim.h(qubit);
            }
            _ => (),
        }
    }
}

macro_rules! single_qubit_gate {
    ($(#[$meta:meta])*
    $qir_name:ident, $gate:expr) => {
        $(#[$meta])*
        #[no_mangle]
        pub extern "C" fn $qir_name(qubit: *mut c_void) {
            SIM_STATE.with(|sim_state| {
                let state = &mut *sim_state.borrow_mut();
                ensure_sufficient_qubits(&mut state.sim, qubit as usize, &mut state.max_qubit_id);

                $gate(&mut state.sim, qubit as usize);
            });
        }
    };
}

single_qubit_gate!(
    /// QIR API for performing the H gate on the given qubit.
    __quantum__qis__h__body,
    QuantumSim::h
);
single_qubit_gate!(
    /// QIR API for performing the S gate on the given qubit.
    __quantum__qis__s__body,
    QuantumSim::s
);
single_qubit_gate!(
    /// QIR API for performing the Adjoint S gate on the given qubit.
    __quantum__qis__s__adj,
    QuantumSim::sadj
);
single_qubit_gate!(
    /// QIR API for performing the T gate on the given qubit.
    __quantum__qis__t__body,
    QuantumSim::t
);
single_qubit_gate!(
    /// QIR API for performing the Adjoint T gate on the given qubit.
    __quantum__qis__t__adj,
    QuantumSim::tadj
);
single_qubit_gate!(
    /// QIR API for performing the X gate on the given qubit.
    __quantum__qis__x__body,
    QuantumSim::x
);
single_qubit_gate!(
    /// QIR API for performing the Y gate on the given qubit.
    __quantum__qis__y__body,
    QuantumSim::y
);
single_qubit_gate!(
    /// QIR API for performing the Z gate on the given qubit.
    __quantum__qis__z__body,
    QuantumSim::z
);

macro_rules! controlled_qubit_gate {
    ($(#[$meta:meta])*
    $qir_name:ident, $gate:expr, 1) => {
        $(#[$meta])*
        #[no_mangle]
        pub extern "C" fn $qir_name(control: *mut c_void, target: *mut c_void) {
            SIM_STATE.with(|sim_state| {
                let state = &mut *sim_state.borrow_mut();
                ensure_sufficient_qubits(&mut state.sim, target as usize, &mut state.max_qubit_id);
                ensure_sufficient_qubits(&mut state.sim, control as usize, &mut state.max_qubit_id);

                $gate(&mut state.sim, &[control as usize], target as usize);
            });
        }
    };

    ($(#[$meta:meta])*
    $qir_name:ident, $gate:expr, 2) => {
        $(#[$meta])*
        #[no_mangle]
        pub extern "C" fn $qir_name(
            control_1: *mut c_void,
            control_2: *mut c_void,
            target: *mut c_void,
        ) {
            SIM_STATE.with(|sim_state| {
                let state = &mut *sim_state.borrow_mut();
                ensure_sufficient_qubits(&mut state.sim, target as usize, &mut state.max_qubit_id);
                ensure_sufficient_qubits(&mut state.sim, control_1 as usize, &mut state.max_qubit_id);
                ensure_sufficient_qubits(&mut state.sim, control_2 as usize, &mut state.max_qubit_id);

                $gate(&mut state.sim, &[control_1 as usize, control_2 as usize], target as usize);
            });
        }
    };
}

controlled_qubit_gate!(
    /// QIR API for performing the CNOT gate with the given qubits.
    __quantum__qis__cnot__body,
    QuantumSim::mcx,
    1
);
controlled_qubit_gate!(
    /// QIR API for performing the CNOT gate with the given qubits.
    __quantum__qis__cx__body,
    QuantumSim::mcx,
    1
);
controlled_qubit_gate!(
    /// QIR API for performing the CCNOT gate with the given qubits.
    __quantum__qis__ccx__body,
    QuantumSim::mcx,
    2
);
controlled_qubit_gate!(
    /// QIR API for performing the CY gate with the given qubits.
    __quantum__qis__cy__body,
    QuantumSim::mcy,
    1
);
controlled_qubit_gate!(
    /// QIR API for performing the CZ gate with the given qubits.
    __quantum__qis__cz__body,
    QuantumSim::mcz,
    1
);

macro_rules! single_qubit_rotation {
    ($(#[$meta:meta])*
    $qir_name:ident, $gate:expr) => {
        $(#[$meta])*
        #[no_mangle]
        pub extern "C" fn $qir_name(theta: c_double, qubit: *mut c_void) {
            SIM_STATE.with(|sim_state| {
                let state = &mut *sim_state.borrow_mut();
                ensure_sufficient_qubits(&mut state.sim, qubit as usize, &mut state.max_qubit_id);

                $gate(&mut state.sim, theta, qubit as usize);
            });
        }
    };
}

single_qubit_rotation!(
    /// QIR API for applying a Pauli-X rotation with the given angle and qubit.
    __quantum__qis__rx__body,
    QuantumSim::rx
);
single_qubit_rotation!(
    /// QIR API for applying a Pauli-Y rotation with the given angle and qubit.
    __quantum__qis__ry__body,
    QuantumSim::ry
);
single_qubit_rotation!(
    /// QIR API for applying a Pauli-Z rotation with the given angle and qubit.
    __quantum__qis__rz__body,
    QuantumSim::rz
);

macro_rules! multicontrolled_qubit_gate {
    ($(#[$meta:meta])*
    $qir_name:ident, $gate:expr) => {
        $(#[$meta])*
        /// # Safety
        ///
        /// This function should only be called with arrays and tuples created by the QIR runtime library.
        #[no_mangle]
        pub unsafe extern "C" fn $qir_name(ctls: *const QirArray, qubit: *mut c_void) {
            SIM_STATE.with(|sim_state| {
                let state = &mut *sim_state.borrow_mut();
                ensure_sufficient_qubits(&mut state.sim, qubit as usize, &mut state.max_qubit_id);
                let ctls_size = __quantum__rt__array_get_size_1d(ctls);
                let ctls_list: Vec<usize> = (0..ctls_size)
                    .map(|index| {
                        let q = *__quantum__rt__array_get_element_ptr_1d(ctls, index)
                            .cast::<*mut c_void>() as usize;
                        ensure_sufficient_qubits(&mut state.sim, q, &mut state.max_qubit_id);
                        q
                    })
                    .collect();

                $gate(&mut state.sim, &ctls_list, qubit as usize);
            });
        }
    };
}

multicontrolled_qubit_gate!(
    /// QIR API for performing the multicontrolled H gate with the given qubits.
    __quantum__qis__h__ctl,
    QuantumSim::mch
);
multicontrolled_qubit_gate!(
    /// QIR API for performing the multicontrolled S gate with the given qubits.
    __quantum__qis__s__ctl,
    QuantumSim::mcs
);
multicontrolled_qubit_gate!(
    /// QIR API for performing the multicontrolled Adjoint S gate with the given qubits.
    __quantum__qis__s__ctladj,
    QuantumSim::mcsadj
);
multicontrolled_qubit_gate!(
    /// QIR API for performing the multicontrolled T gate with the given qubits.
    __quantum__qis__t__ctl,
    QuantumSim::mct
);
multicontrolled_qubit_gate!(
    /// QIR API for performing the multicontrolled Adjoint T gate with the given qubits.
    __quantum__qis__t__ctladj,
    QuantumSim::mctadj
);
multicontrolled_qubit_gate!(
    /// QIR API for performing the multicontrolled X gate with the given qubits.
    __quantum__qis__x__ctl,
    QuantumSim::mcx
);
multicontrolled_qubit_gate!(
    /// QIR API for performing the multicontrolled Y gate with the given qubits.
    __quantum__qis__y__ctl,
    QuantumSim::mcy
);
multicontrolled_qubit_gate!(
    /// QIR API for performing the multicontrolled Z gate with the given qubits.
    __quantum__qis__z__ctl,
    QuantumSim::mcz
);

#[derive(Copy, Clone)]
#[repr(C)]
struct RotationArgs {
    theta: c_double,
    qubit: *mut c_void,
}

macro_rules! multicontrolled_qubit_rotation {
    ($(#[$meta:meta])*
    $qir_name:ident, $gate:expr) => {
        $(#[$meta])*
        /// # Safety
        ///
        /// This function should only be called with arrays and tuples created by the QIR runtime library.
        #[no_mangle]
        pub unsafe extern "C" fn $qir_name(
            ctls: *const QirArray,
            arg_tuple: *mut *const Vec<u8>,
        ) {
            SIM_STATE.with(|sim_state| {
                let state = &mut *sim_state.borrow_mut();

                let args = *arg_tuple.cast::<RotationArgs>();

                ensure_sufficient_qubits(&mut state.sim, args.qubit as usize, &mut state.max_qubit_id);
                let ctls_size = __quantum__rt__array_get_size_1d(ctls);
                let ctls_list: Vec<usize> = (0..ctls_size)
                    .map(|index| {
                        let q = *__quantum__rt__array_get_element_ptr_1d(ctls, index)
                            .cast::<*mut c_void>() as usize;
                        ensure_sufficient_qubits(&mut state.sim, q, &mut state.max_qubit_id);
                        q
                    })
                    .collect();

                $gate(
                    &mut state.sim,
                    &ctls_list,
                    args.theta,
                    args.qubit as usize,
                );
            });
        }
    };
}

multicontrolled_qubit_rotation!(
    /// QIR API for applying a multicontrolled Pauli-X rotation with the given angle and qubit.
    __quantum__qis__rx__ctl,
    QuantumSim::mcrx
);
multicontrolled_qubit_rotation!(
    /// QIR API for applying a multicontrolled Pauli-Y rotation with the given angle and qubit.
    __quantum__qis__ry__ctl,
    QuantumSim::mcry
);
multicontrolled_qubit_rotation!(
    /// QIR API for applying a multicontrolled Pauli-Z rotation with the given angle and qubit.
    __quantum__qis__rz__ctl,
    QuantumSim::mcrz
);

/// QIR API for applying a joint rotation Pauli-Y rotation with the given angle for the two target qubit.
#[no_mangle]
pub extern "C" fn __quantum__qis__rxx__body(
    theta: c_double,
    qubit1: *mut c_void,
    qubit2: *mut c_void,
) {
    __quantum__qis__h__body(qubit1);

    __quantum__qis__h__body(qubit2);

    __quantum__qis__rzz__body(theta, qubit1, qubit2);

    __quantum__qis__h__body(qubit2);

    __quantum__qis__h__body(qubit1);
}

/// QIR API for applying a joint rotation Pauli-Y rotation with the given angle for the two target qubit.
#[no_mangle]
pub extern "C" fn __quantum__qis__ryy__body(
    theta: c_double,
    qubit1: *mut c_void,
    qubit2: *mut c_void,
) {
    __quantum__qis__h__body(qubit1);
    __quantum__qis__s__body(qubit1);
    __quantum__qis__h__body(qubit1);

    __quantum__qis__h__body(qubit2);
    __quantum__qis__s__body(qubit2);
    __quantum__qis__h__body(qubit2);

    __quantum__qis__rzz__body(theta, qubit1, qubit2);

    __quantum__qis__h__body(qubit2);
    __quantum__qis__s__adj(qubit2);
    __quantum__qis__h__body(qubit2);

    __quantum__qis__h__body(qubit1);
    __quantum__qis__s__adj(qubit1);
    __quantum__qis__h__body(qubit1);
}

/// QIR API for applying a joint rotation Pauli-Z rotation with the given angle for the two target qubit.
#[no_mangle]
pub extern "C" fn __quantum__qis__rzz__body(
    theta: c_double,
    qubit1: *mut c_void,
    qubit2: *mut c_void,
) {
    __quantum__qis__cx__body(qubit2, qubit1);
    __quantum__qis__rz__body(theta, qubit1);
    __quantum__qis__cx__body(qubit2, qubit1);
}

/// QIR API for applying a rotation about the given Pauli axis with the given angle and qubit.
#[no_mangle]
pub extern "C" fn __quantum__qis__r__body(pauli: Pauli, theta: c_double, qubit: *mut c_void) {
    match pauli {
        Pauli::I => (),
        Pauli::X => __quantum__qis__rx__body(theta, qubit),
        Pauli::Y => __quantum__qis__ry__body(theta, qubit),
        Pauli::Z => __quantum__qis__rz__body(theta, qubit),
    }
}

/// QIR API for applying an adjoint rotation about the given Pauli axis with the given angle and qubit.
#[no_mangle]
pub extern "C" fn __quantum__qis__r__adj(pauli: Pauli, theta: c_double, qubit: *mut c_void) {
    __quantum__qis__r__body(pauli, -theta, qubit);
}

#[derive(Copy, Clone)]
#[repr(C)]
struct PauliRotationArgs {
    pauli: Pauli,
    theta: c_double,
    qubit: *mut c_void,
}

/// QIR API for applying a controlled rotation about the given Pauli axis with the given angle and qubit.
/// # Safety
///
/// This function should only be called with arrays and tuples created by the QIR runtime library.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn __quantum__qis__r__ctl(
    ctls: *const QirArray,
    arg_tuple: *mut *const Vec<u8>,
) {
    let args = *arg_tuple.cast::<PauliRotationArgs>();
    let rot_args = RotationArgs {
        theta: args.theta,
        qubit: args.qubit,
    };
    let rot_arg_tuple = __quantum__rt__tuple_create(size_of::<RotationArgs>() as u64);
    *rot_arg_tuple.cast::<RotationArgs>() = rot_args;

    match args.pauli {
        Pauli::X => __quantum__qis__rx__ctl(ctls, rot_arg_tuple),
        Pauli::Y => __quantum__qis__ry__ctl(ctls, rot_arg_tuple),
        Pauli::Z => __quantum__qis__rz__ctl(ctls, rot_arg_tuple),
        Pauli::I => {
            if __quantum__rt__array_get_size_1d(ctls) > 0 {
                SIM_STATE.with(|sim_state| {
                    let state = &mut *sim_state.borrow_mut();

                    ensure_sufficient_qubits(
                        &mut state.sim,
                        args.qubit as usize,
                        &mut state.max_qubit_id,
                    );
                    let ctls_size = __quantum__rt__array_get_size_1d(ctls);
                    let ctls_list: Vec<usize> = (0..ctls_size)
                        .map(|index| {
                            let q = *__quantum__rt__array_get_element_ptr_1d(ctls, index)
                                .cast::<*mut c_void>() as usize;
                            ensure_sufficient_qubits(&mut state.sim, q, &mut state.max_qubit_id);
                            q
                        })
                        .collect();

                    if let Some((head, rest)) = ctls_list.split_first() {
                        state.sim.mcphase(
                            rest,
                            Complex64::exp(Complex64::new(0.0, -args.theta / 2.0)),
                            *head,
                        );
                    }
                });
            }
        }
    };

    __quantum__rt__tuple_update_reference_count(rot_arg_tuple, -1);
}

/// QIR API for applying an adjoint controlled rotation about the given Pauli axis with the given angle and qubit.
/// # Safety
///
/// This function should only be called with arrays and tuples created by the QIR runtime library.
#[no_mangle]
pub unsafe extern "C" fn __quantum__qis__r__ctladj(
    ctls: *const QirArray,
    arg_tuple: *mut *const Vec<u8>,
) {
    let args = *arg_tuple.cast::<PauliRotationArgs>();
    let new_args = PauliRotationArgs {
        pauli: args.pauli,
        theta: -args.theta,
        qubit: args.qubit,
    };
    let new_arg_tuple = __quantum__rt__tuple_create(size_of::<PauliRotationArgs>() as u64);
    *new_arg_tuple.cast::<PauliRotationArgs>() = new_args;
    __quantum__qis__r__ctl(ctls, new_arg_tuple);
    __quantum__rt__tuple_update_reference_count(new_arg_tuple, -1);
}

/// QIR API for applying a SWAP gate to the given qubits.
#[no_mangle]
pub extern "C" fn __quantum__qis__swap__body(qubit1: *mut c_void, qubit2: *mut c_void) {
    SIM_STATE.with(|sim_state| {
        let state = &mut *sim_state.borrow_mut();
        ensure_sufficient_qubits(&mut state.sim, qubit1 as usize, &mut state.max_qubit_id);
        ensure_sufficient_qubits(&mut state.sim, qubit2 as usize, &mut state.max_qubit_id);

        state.sim.swap_qubit_ids(qubit1 as usize, qubit2 as usize);
    });
}

/// QIR API for resetting the given qubit in the computational basis.
#[no_mangle]
pub extern "C" fn __quantum__qis__reset__body(qubit: *mut c_void) {
    SIM_STATE.with(|sim_state| {
        let state = &mut *sim_state.borrow_mut();
        ensure_sufficient_qubits(&mut state.sim, qubit as usize, &mut state.max_qubit_id);

        if state.sim.measure(qubit as usize) {
            state.sim.x(qubit as usize);
        }
    });
}

/// QIR API for measuring the given qubit and storing the measured value with the given result identifier,
/// then resetting it in the computational basis.
#[allow(clippy::missing_panics_doc)]
// reason="Panics can only occur if the result that was just collected is not found in the BitVec, which should not happen."
#[no_mangle]
pub extern "C" fn __quantum__qis__mresetz__body(qubit: *mut c_void, result: *mut c_void) {
    SIM_STATE.with(|sim_state| {
        let state = &mut *sim_state.borrow_mut();
        let res_id = result as usize;
        ensure_sufficient_qubits(&mut state.sim, qubit as usize, &mut state.max_qubit_id);

        if state.res.len() < res_id + 1 {
            state.res.resize(res_id + 1, false);
        }

        let res = state.sim.measure(qubit as usize);

        if res {
            state.sim.x(qubit as usize);
        }

        *state
            .res
            .get_mut(res_id)
            .expect("Result with given id missing after expansion.") = res;
    });
}

/// QIR API for measuring the given qubit in the computation basis and storing the measured value with the given result identifier.
#[allow(clippy::missing_panics_doc)]
// reason="Panics can only occur if the result index is not found in the BitVec after resizing, which should not happen."
#[no_mangle]
pub extern "C" fn __quantum__qis__mz__body(qubit: *mut c_void, result: *mut c_void) {
    SIM_STATE.with(|sim_state| {
        let state = &mut *sim_state.borrow_mut();
        let res_id = result as usize;
        ensure_sufficient_qubits(&mut state.sim, qubit as usize, &mut state.max_qubit_id);

        if state.res.len() < res_id + 1 {
            state.res.resize(res_id + 1, false);
        }

        *state
            .res
            .get_mut(res_id)
            .expect("Result with given id missing after expansion.") =
            state.sim.measure(qubit as usize);
    });
}

/// QIR API that reads the Boolean value corresponding to the given result identifier, where true
/// indicates a |1⟩ state and false indicates a |0⟩ state.
#[allow(clippy::missing_panics_doc)]
// reason="Panics can only occur if the result index is not found in the BitVec after resizing, which should not happen."
#[no_mangle]
pub extern "C" fn __quantum__qis__read_result__body(result: *mut c_void) -> bool {
    SIM_STATE.with(|sim_state| {
        let res = &mut sim_state.borrow_mut().res;
        let res_id = result as usize;
        if res.len() < res_id + 1 {
            res.resize(res_id + 1, false);
        }

        let b = *res
            .get(res_id)
            .expect("Result with given id missing after expansion.");
        b
    })
}

/// QIR API that measures a given qubit in the computational basis, returning a runtime managed result value.
#[no_mangle]
pub extern "C" fn __quantum__qis__m__body(qubit: *mut c_void) -> *mut c_void {
    SIM_STATE.with(|sim_state| {
        let state = &mut *sim_state.borrow_mut();
        ensure_sufficient_qubits(&mut state.sim, qubit as usize, &mut state.max_qubit_id);

        if state.sim.measure(qubit as usize) {
            __quantum__rt__result_get_one()
        } else {
            __quantum__rt__result_get_zero()
        }
    })
}

/// QIR API that performs joint measurement of the given qubits in the corresponding Pauli bases, returning the parity as a runtime managed result value.
/// # Safety
///
/// This function should only be called with arrays created by the QIR runtime library.
/// # Panics
///
/// This function will panic if the provided paulis and qubits arrays are not of the same size.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn __quantum__qis__measure__body(
    paulis: *const QirArray,
    qubits: *const QirArray,
) -> *mut c_void {
    SIM_STATE.with(|sim_state| {
        let mut state = sim_state.borrow_mut();

        let combined_list = map_to_z_basis(&mut state, paulis, qubits);

        let res = state.sim.joint_measure(
            &combined_list
                .iter()
                .map(|(_, q)| *q)
                .collect::<Vec<usize>>(),
        );

        unmap_from_z_basis(&mut state, combined_list);

        if res {
            __quantum__rt__result_get_one()
        } else {
            __quantum__rt__result_get_zero()
        }
    })
}

/// Rust API for checking internal simulator state and returning true only if the given qubit is in exactly the |0⟩ state.
pub fn qubit_is_zero(qubit: *mut c_void) -> bool {
    SIM_STATE.with(|sim_state| {
        let state = &mut *sim_state.borrow_mut();
        ensure_sufficient_qubits(&mut state.sim, qubit as usize, &mut state.max_qubit_id);

        state.sim.qubit_is_zero(qubit as usize)
    })
}

/// QIR API for checking internal simulator state and verifying the probability of the given parity measurement result
/// for the given qubits in the given Pauli bases is equal to the expected probability, within the given tolerance.
/// # Safety
///
/// This function should only be called with arrays created by the QIR runtime library.
#[no_mangle]
pub unsafe extern "C" fn __quantum__qis__assertmeasurementprobability__body(
    paulis: *const QirArray,
    qubits: *const QirArray,
    result: *mut c_void,
    prob: c_double,
    msg: *const CString,
    tol: c_double,
) {
    SIM_STATE.with(|sim_state| {
        let mut state = sim_state.borrow_mut();

        let combined_list = map_to_z_basis(&mut state, paulis, qubits);

        let mut actual_prob = state.sim.joint_probability(
            &combined_list
                .iter()
                .map(|(_, q)| *q)
                .collect::<Vec<usize>>(),
        );

        if __quantum__rt__result_equal(result, __quantum__rt__result_get_zero()) {
            actual_prob = 1.0 - actual_prob;
        }

        if (actual_prob - prob).abs() > tol {
            __quantum__rt__fail(msg);
        }

        unmap_from_z_basis(&mut state, combined_list);
    });
}

#[derive(Copy, Clone)]
#[repr(C)]
struct AssertMeasurementProbabilityArgs {
    paulis: *const QirArray,
    qubits: *const QirArray,
    result: *mut c_void,
    prob: c_double,
    msg: *const CString,
    tol: c_double,
}

/// QIR API for checking internal simulator state and verifying the probability of the given parity measurement result
/// for the given qubits in the given Pauli bases is equal to the expected probability, within the given tolerance.
/// Note that control qubits are ignored.
/// # Safety
///
/// This function should only be called with arrays created by the QIR runtime library.
#[no_mangle]
pub unsafe extern "C" fn __quantum__qis__assertmeasurementprobability__ctl(
    _ctls: *const QirArray,
    arg_tuple: *mut *const Vec<u8>,
) {
    let args = *arg_tuple.cast::<AssertMeasurementProbabilityArgs>();
    __quantum__qis__assertmeasurementprobability__body(
        args.paulis,
        args.qubits,
        args.result,
        args.prob,
        args.msg,
        args.tol,
    );
}

pub mod legacy_output {
    use std::ffi::c_void;

    use qir_stdlib::output_recording::record_output_str;

    use crate::{
        result_bool::{__quantum__rt__result_equal, __quantum__rt__result_get_one},
        SIM_STATE,
    };

    #[allow(clippy::missing_panics_doc)]
    // reason="Panics can only occur if the result index is not found in the BitVec after resizing, which should not happen."
    #[allow(non_snake_case)]
    pub extern "C" fn __quantum__rt__result_record_output(result: *mut c_void) {
        SIM_STATE.with(|sim_state| {
            let res = &mut sim_state.borrow_mut().res;
            let res_id = result as usize;
            let b = if res.is_empty() {
                // No static measurements have been used, so default to dynamic handling.
                __quantum__rt__result_equal(result, __quantum__rt__result_get_one())
            } else {
                if res.len() < res_id + 1 {
                    res.resize(res_id + 1, false);
                }
                *res.get(res_id)
                    .expect("Result with given id missing after expansion.")
            };

            record_output_str(&format!("RESULT\t{}", if b { "1" } else { "0" }))
                .expect("Failed to write result output");
        });
    }
}

/// QIR API for recording the given result into the program output.
#[allow(clippy::missing_panics_doc)]
// reason="Panics can only occur if the result index is not found in the BitVec after resizing, which should not happen."
/// # Safety
/// This function will panic if the tag cannot be written to the output buffer.
#[no_mangle]
pub unsafe extern "C" fn __quantum__rt__result_record_output(
    result: *mut c_void,
    tag: *mut c_char,
) {
    SIM_STATE.with(|sim_state| {
        let res = &mut sim_state.borrow_mut().res;
        let res_id = result as usize;
        let b = if res.is_empty() {
            // No static measurements have been used, so default to dynamic handling.
            __quantum__rt__result_equal(result, __quantum__rt__result_get_one())
        } else {
            if res.len() < res_id + 1 {
                res.resize(res_id + 1, false);
            }
            *res.get(res_id)
                .expect("Result with given id missing after expansion.")
        };

        let val: i64 = i64::from(b);
        record_output("RESULT", &val, tag).expect("Failed to write result output");
    });
}

/// QIR API that allocates the next available qubit in the simulation.
#[no_mangle]
pub extern "C" fn __quantum__rt__qubit_allocate() -> *mut c_void {
    SIM_STATE.with(|sim_state| {
        let mut state = sim_state.borrow_mut();
        let qubit_id = state.sim.allocate();

        // Increase the max qubit id global so that `ensure_sufficient_qubits` wont trigger more allocations.
        // NOTE: static allocation and dynamic allocation shouldn't be used together, so this is safe to do.
        state.max_qubit_id = state.max_qubit_id.max(qubit_id + 1);

        qubit_id as *mut c_void
    })
}

/// QIR API for allocating the given number of qubits in the simulation, returning them as a runtime managed array.
/// # Panics
/// This function will panic if the requested array size is too large to be described with the system pointer size.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn __quantum__rt__qubit_allocate_array(size: u64) -> *const QirArray {
    let arr = __quantum__rt__array_create_1d(
        size_of::<usize>()
            .try_into()
            .expect("System pointer size too large to be described with u32."),
        size,
    );
    for index in 0..size {
        unsafe {
            let elem = __quantum__rt__array_get_element_ptr_1d(arr, index).cast::<*mut c_void>();
            *elem = __quantum__rt__qubit_allocate();
        }
    }
    arr
}

/// QIR API for releasing the given runtime managed qubit array.
/// # Safety
///
/// This function should only be called with arrays created by `__quantum__rt__qubit_allocate_array`.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn __quantum__rt__qubit_release_array(arr: *const QirArray) {
    for index in 0..__quantum__rt__array_get_size_1d(arr) {
        let elem = __quantum__rt__array_get_element_ptr_1d(arr, index).cast::<*mut c_void>();
        __quantum__rt__qubit_release(*elem);
    }
    __quantum__rt__array_update_alias_count(arr, -1);
}

/// QIR API for releasing the given qubit from the simulation.
#[no_mangle]
pub extern "C" fn __quantum__rt__qubit_release(qubit: *mut c_void) {
    SIM_STATE.with(|sim_state| {
        let mut state = sim_state.borrow_mut();
        state.sim.release(qubit as usize);
    });
}

/// QIR API for getting the string interpretation of a qubit identifier.
/// # Panics
/// This function will panic if memory cannot be allocated for the underyling string.
#[no_mangle]
pub extern "C" fn __quantum__rt__qubit_to_string(qubit: *mut c_void) -> *const CString {
    unsafe {
        __quantum__rt__string_create(
            CString::new(format!("{}", qubit as usize))
                .expect("Unable to allocate memory for qubit string.")
                .as_bytes_with_nul()
                .as_ptr() as *mut c_char,
        )
    }
}

/// Rust API for getting a snapshot of current quantum state. The state is a sorted copy of
/// the current sparse state represented by a vector of pairs of indices and complex numbers along
/// with the total number of currently allocated qubits to help in interpreting the state.
#[must_use]
pub fn capture_quantum_state() -> (Vec<(BigUint, Complex64)>, usize) {
    SIM_STATE.with(|sim_state| {
        let mut state = sim_state.borrow_mut();
        state.sim.get_state()
    })
}

/// QIR API for dumping full internal simulator state.
/// # Panics
/// This function will panic if the output buffer is not available.
#[no_mangle]
pub extern "C" fn __quantum__qis__dumpmachine__body(location: *mut c_void) {
    if !location.is_null() {
        unimplemented!("Dump to location is not implemented.")
    }
    SIM_STATE.with(|sim_state| {
        let mut state = sim_state.borrow_mut();

        if !state.res.is_empty() {
            OUTPUT.with(|output| {
                let mut output = output.borrow_mut();
                output
                    .write_fmt(format_args!("Global Results: {}", state.res))
                    .expect("Failed to write global results");
                output.write_newline();
            });
        }
        OUTPUT.with(|output| {
            let mut output = output.borrow_mut();
            output
                .write_all(state.sim.dump().as_bytes())
                .expect("Failed to write simulator state");
        });
    });
}

#[cfg(test)]
mod tests {
    use std::{f64::consts::PI, ffi::c_void, ptr::null_mut};

    use crate::{
        __quantum__qis__cnot__body, __quantum__qis__cx__body, __quantum__qis__cz__body,
        __quantum__qis__dumpmachine__body, __quantum__qis__h__body, __quantum__qis__m__body,
        __quantum__qis__mresetz__body, __quantum__qis__mz__body, __quantum__qis__read_result__body,
        __quantum__qis__rx__body, __quantum__qis__rxx__body, __quantum__qis__ry__body,
        __quantum__qis__ryy__body, __quantum__qis__rz__body, __quantum__qis__rzz__body,
        __quantum__qis__s__adj, __quantum__qis__s__body, __quantum__qis__x__body,
        __quantum__rt__qubit_allocate, __quantum__rt__qubit_allocate_array,
        __quantum__rt__qubit_release, __quantum__rt__qubit_release_array,
        __quantum__rt__result_equal, capture_quantum_state, map_to_z_basis, qubit_is_zero,
        result_bool::__quantum__rt__result_get_one, unmap_from_z_basis, SIM_STATE,
    };
    use num_bigint::BigUint;
    use qir_stdlib::{
        arrays::{
            __quantum__rt__array_create_1d, __quantum__rt__array_get_element_ptr_1d,
            __quantum__rt__array_update_reference_count,
        },
        Pauli,
    };

    #[test]
    fn basic_test_static() {
        let q0 = 5 as *mut c_void;
        let r0 = std::ptr::null_mut();
        let r1 = 1 as *mut c_void;
        __quantum__qis__mz__body(q0, r0);
        assert!(!__quantum__qis__read_result__body(r0));
        __quantum__qis__x__body(q0);
        __quantum__qis__mz__body(q0, r1);
        assert!(__quantum__qis__read_result__body(r1));
        __quantum__qis__x__body(q0);
        __quantum__qis__mz__body(q0, r0);
        assert!(!__quantum__qis__read_result__body(r0));
        assert!(!__quantum__qis__read_result__body(3 as *mut c_void));
        __quantum__qis__dumpmachine__body(null_mut());
    }

    #[allow(clippy::cast_ptr_alignment)]
    #[test]
    fn basic_test_dynamic() {
        let q1 = __quantum__rt__qubit_allocate();
        let q2 = __quantum__rt__qubit_allocate();
        __quantum__qis__h__body(q1);
        __quantum__qis__cnot__body(q1, q2);
        let r1 = __quantum__qis__m__body(q1);
        let r2 = __quantum__qis__m__body(q2);
        assert!(__quantum__rt__result_equal(r1, r2));
        __quantum__qis__dumpmachine__body(null_mut());
        __quantum__rt__qubit_release(q2);
        __quantum__rt__qubit_release(q1);
        let qs = __quantum__rt__qubit_allocate_array(4);
        unsafe {
            let q_elem = __quantum__rt__array_get_element_ptr_1d(qs, 3).cast::<*mut c_void>();
            __quantum__qis__x__body(*q_elem);
            __quantum__qis__dumpmachine__body(null_mut());
            let r = __quantum__qis__m__body(*q_elem);
            assert!(__quantum__rt__result_equal(
                r,
                __quantum__rt__result_get_one()
            ));
            __quantum__rt__qubit_release_array(qs);
        }
    }

    #[test]
    fn test_qubit_is_zero() {
        let q0 = __quantum__rt__qubit_allocate();
        assert!(qubit_is_zero(q0));
        __quantum__qis__x__body(q0);
        assert!(!qubit_is_zero(q0));
        __quantum__qis__h__body(q0);
        assert!(!qubit_is_zero(q0));
        let r = __quantum__qis__m__body(q0);
        assert!(
            qubit_is_zero(q0) != __quantum__rt__result_equal(r, __quantum__rt__result_get_one())
        );
    }

    #[allow(clippy::cast_ptr_alignment)]
    #[test]
    fn test_map_unmap_are_adjoint() {
        unsafe fn check_map_unmap(pauli: Pauli) {
            let check_qubit = __quantum__rt__qubit_allocate();
            let qubits = __quantum__rt__qubit_allocate_array(1);
            let q = *__quantum__rt__array_get_element_ptr_1d(qubits, 0).cast::<*mut c_void>();
            let paulis = __quantum__rt__array_create_1d(1, 1);
            *__quantum__rt__array_get_element_ptr_1d(paulis, 0).cast::<Pauli>() = pauli;

            __quantum__qis__h__body(check_qubit);
            __quantum__qis__cnot__body(check_qubit, q);

            SIM_STATE.with(|sim_state| {
                let state = &mut *sim_state.borrow_mut();
                let combined_list = map_to_z_basis(state, paulis, qubits);
                unmap_from_z_basis(state, combined_list);
            });

            __quantum__qis__cnot__body(check_qubit, q);
            __quantum__qis__h__body(check_qubit);

            assert!(qubit_is_zero(q));
            assert!(qubit_is_zero(check_qubit));

            __quantum__rt__array_update_reference_count(paulis, -1);
            __quantum__rt__qubit_release_array(qubits);
            __quantum__rt__qubit_release(check_qubit);
        }

        unsafe {
            check_map_unmap(Pauli::X);
            check_map_unmap(Pauli::Y);
            check_map_unmap(Pauli::Z);
        }
    }

    #[allow(clippy::cast_ptr_alignment)]
    #[test]
    fn test_map_pauli_x() {
        let qubits = __quantum__rt__qubit_allocate_array(1);
        unsafe {
            let q = *__quantum__rt__array_get_element_ptr_1d(qubits, 0).cast::<*mut c_void>();
            let paulis = __quantum__rt__array_create_1d(1, 1);
            *__quantum__rt__array_get_element_ptr_1d(paulis, 0).cast::<Pauli>() = Pauli::X;

            __quantum__qis__h__body(q);

            SIM_STATE.with(|sim_state| {
                let state = &mut *sim_state.borrow_mut();
                let _ = map_to_z_basis(state, paulis, qubits);
            });

            qubit_is_zero(q);

            __quantum__rt__array_update_reference_count(paulis, -1);
            __quantum__rt__qubit_release_array(qubits);
        }
    }

    #[allow(clippy::cast_ptr_alignment)]
    #[test]
    fn test_map_pauli_y() {
        let qubits = __quantum__rt__qubit_allocate_array(1);
        unsafe {
            let q = *__quantum__rt__array_get_element_ptr_1d(qubits, 0).cast::<*mut c_void>();
            let paulis = __quantum__rt__array_create_1d(1, 1);
            *__quantum__rt__array_get_element_ptr_1d(paulis, 0).cast::<Pauli>() = Pauli::Y;

            __quantum__qis__h__body(q);
            __quantum__qis__s__adj(q);
            __quantum__qis__h__body(q);

            SIM_STATE.with(|sim_state| {
                let state = &mut *sim_state.borrow_mut();
                let _ = map_to_z_basis(state, paulis, qubits);
            });

            qubit_is_zero(q);

            __quantum__rt__array_update_reference_count(paulis, -1);
            __quantum__rt__qubit_release_array(qubits);
        }
    }

    #[allow(clippy::cast_ptr_alignment)]
    #[test]
    fn test_map_pauli_z() {
        let qubits = __quantum__rt__qubit_allocate_array(1);
        unsafe {
            let q = *__quantum__rt__array_get_element_ptr_1d(qubits, 0).cast::<*mut c_void>();
            let paulis = __quantum__rt__array_create_1d(1, 1);
            *__quantum__rt__array_get_element_ptr_1d(paulis, 0).cast::<Pauli>() = Pauli::Z;

            SIM_STATE.with(|sim_state| {
                let state = &mut *sim_state.borrow_mut();
                let _ = map_to_z_basis(state, paulis, qubits);
            });

            qubit_is_zero(q);

            __quantum__rt__array_update_reference_count(paulis, -1);
            __quantum__rt__qubit_release_array(qubits);
        }
    }

    #[test]
    fn test_joint_zz() {
        let check_qubit = __quantum__rt__qubit_allocate();
        let q0 = __quantum__rt__qubit_allocate();
        let q1 = __quantum__rt__qubit_allocate();

        __quantum__qis__h__body(check_qubit);
        __quantum__qis__cx__body(check_qubit, q0);
        __quantum__qis__cx__body(check_qubit, q1);

        __quantum__qis__rzz__body(PI / 2.0, q0, q1);
        __quantum__qis__rz__body(-PI / 2.0, q0);
        __quantum__qis__rz__body(-PI / 2.0, q1);

        __quantum__qis__cz__body(q0, q1);

        __quantum__qis__cx__body(check_qubit, q1);
        __quantum__qis__cx__body(check_qubit, q0);
        __quantum__qis__h__body(check_qubit);

        assert!(qubit_is_zero(check_qubit));
        assert!(qubit_is_zero(q0));
        assert!(qubit_is_zero(q1));
    }

    #[test]
    fn test_joint_yy() {
        let check_qubit = __quantum__rt__qubit_allocate();
        let q0 = __quantum__rt__qubit_allocate();
        let q1 = __quantum__rt__qubit_allocate();

        __quantum__qis__h__body(check_qubit);
        __quantum__qis__cx__body(check_qubit, q0);
        __quantum__qis__cx__body(check_qubit, q1);

        __quantum__qis__h__body(q0);
        __quantum__qis__s__adj(q0);
        __quantum__qis__h__body(q0);
        __quantum__qis__h__body(q1);
        __quantum__qis__s__adj(q1);
        __quantum__qis__h__body(q1);

        __quantum__qis__ryy__body(PI / 2.0, q0, q1);
        __quantum__qis__ry__body(-PI / 2.0, q0);
        __quantum__qis__ry__body(-PI / 2.0, q1);

        __quantum__qis__h__body(q1);
        __quantum__qis__s__body(q1);
        __quantum__qis__h__body(q1);
        __quantum__qis__h__body(q0);
        __quantum__qis__s__body(q0);
        __quantum__qis__h__body(q0);

        __quantum__qis__cz__body(q0, q1);

        __quantum__qis__cx__body(check_qubit, q1);
        __quantum__qis__cx__body(check_qubit, q0);
        __quantum__qis__h__body(check_qubit);

        assert!(qubit_is_zero(check_qubit));
        assert!(qubit_is_zero(q0));
        assert!(qubit_is_zero(q1));
    }

    #[test]
    fn test_joint_xx() {
        let check_qubit = __quantum__rt__qubit_allocate();
        let q0 = __quantum__rt__qubit_allocate();
        let q1 = __quantum__rt__qubit_allocate();

        __quantum__qis__h__body(check_qubit);
        __quantum__qis__cx__body(check_qubit, q0);
        __quantum__qis__cx__body(check_qubit, q1);

        __quantum__qis__h__body(q0);
        __quantum__qis__h__body(q1);

        __quantum__qis__rxx__body(PI / 2.0, q0, q1);
        __quantum__qis__rx__body(-PI / 2.0, q0);
        __quantum__qis__rx__body(-PI / 2.0, q1);

        __quantum__qis__h__body(q0);
        __quantum__qis__h__body(q1);

        __quantum__qis__cz__body(q0, q1);

        __quantum__qis__cx__body(check_qubit, q1);
        __quantum__qis__cx__body(check_qubit, q0);
        __quantum__qis__h__body(check_qubit);

        assert!(qubit_is_zero(check_qubit));
        assert!(qubit_is_zero(q0));
        assert!(qubit_is_zero(q1));
    }

    #[test]
    fn test_mresetz() {
        let qubit = __quantum__rt__qubit_allocate();
        let r0 = std::ptr::null_mut();
        let r1 = 1 as *mut c_void;
        assert!(qubit_is_zero(qubit));
        __quantum__qis__mresetz__body(qubit, r0);
        assert!(!__quantum__qis__read_result__body(r0));
        assert!(qubit_is_zero(qubit));
        __quantum__qis__x__body(qubit);
        __quantum__qis__mresetz__body(qubit, r1);
        assert!(__quantum__qis__read_result__body(r1));
        assert!(qubit_is_zero(qubit));
    }

    #[test]
    fn test_capture_quantum_state() {
        let qubit = __quantum__rt__qubit_allocate();
        let (state, qubit_count) = capture_quantum_state();
        assert_eq!(qubit_count, 1);
        assert_eq!(state.len(), 1);
        assert_eq!(state[0].0, BigUint::from(0u32));
        __quantum__qis__x__body(qubit);
        let (state, qubit_count) = capture_quantum_state();
        assert_eq!(qubit_count, 1);
        assert_eq!(state.len(), 1);
        assert_eq!(state[0].0, BigUint::from(1u32));
        __quantum__qis__h__body(qubit);
        let qubit2 = __quantum__rt__qubit_allocate();
        let (state, qubit_count) = capture_quantum_state();
        assert_eq!(qubit_count, 2);
        assert_eq!(state.len(), 2);
        assert_eq!(state[0].1, -state[1].1);
        __quantum__qis__h__body(qubit);
        __quantum__qis__x__body(qubit);
        let (state, qubit_count) = capture_quantum_state();
        assert_eq!(qubit_count, 2);
        assert_eq!(state.len(), 1);
        assert_eq!(state[0].0, BigUint::from(0u32));
        __quantum__rt__qubit_release(qubit);
        __quantum__rt__qubit_release(qubit2);
        let (state, qubit_count) = capture_quantum_state();
        assert_eq!(qubit_count, 0);
        assert_eq!(state.len(), 1);
        assert_eq!(state[0].0, BigUint::from(0u32));
    }
}