qxide 0.6.0

Qxide: a language and Rust library for classical and quantum computers with C-style syntax, compile-time qubit safety like Rust's ownership, and OpenQASM 3 output
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
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
// Checker and interpreter tests. Assertions use error codes and line:column, never message text.

use super::diag::SourceMap;
use super::*;

const BELL: &str = include_str!("../../examples/qx/bell.qx");
const GHZ: &str = include_str!("../../examples/qx/ghz.qx");
const TELEPORT: &str = include_str!("../../examples/qx/teleport.qx");
const FUNCTIONS: &str = include_str!("../../examples/qx/functions.qx");
const ROTATION: &str = include_str!("../../examples/qx/rotation.qx");
const TELEPORT_FN: &str = include_str!("../../examples/qx/teleport_fn.qx");

fn located(src: &str, errors: &[Diagnostic]) -> Vec<(&'static str, usize, usize)> {
    let map = SourceMap::new("t.qx", src);
    errors
        .iter()
        .map(|d| {
            let (l, c) = map.line_col(d.span.start);
            (d.code.as_str(), l, c)
        })
        .collect()
}

/// Static errors as (code, line, column).
fn errors(src: &str) -> Vec<(&'static str, usize, usize)> {
    match front(src) {
        Ok(_) => Vec::new(),
        Err(e) => located(src, &e),
    }
}

fn codes(src: &str) -> Vec<&'static str> {
    errors(src).into_iter().map(|e| e.0).collect()
}

fn ok(src: &str) {
    assert_eq!(errors(src), Vec::new(), "unexpected errors in:\n{src}");
}

/// Runtime error of a program that passes the checker.
fn runtime_error(src: &str) -> (&'static str, usize, usize) {
    ok(src);
    match build(src) {
        Ok(_) => panic!("expected a runtime error in:\n{src}"),
        Err(e) => located(src, &e)[0],
    }
}

fn run_ok(src: &str, shots: u64) -> String {
    match run("t.qx", src, shots, 0) {
        Ok(s) => s,
        Err(Failure(d)) => panic!("run failed:\n{d}"),
    }
}

fn main_body(body: &str) -> String {
    format!("void main() {{\n{body}\n}}\n")
}

/// Parses a multi-shot table into (bits, count, printed lines) rows.
fn table(out: &str) -> Vec<(String, u64, Vec<String>)> {
    let mut rows: Vec<(String, u64, Vec<String>)> = Vec::new();
    for line in out.lines() {
        if let Some(text) = line.strip_prefix("  ") {
            rows.last_mut()
                .expect("output before a row")
                .2
                .push(text.into());
        } else {
            let (head, count) = line.rsplit_once("  ×").expect("row has a count");
            rows.push((head.into(), count.parse().unwrap(), Vec::new()));
        }
    }
    rows
}

#[test]
fn examples_and_doc_samples_pass_the_checker() {
    for src in [BELL, GHZ, TELEPORT, FUNCTIONS, ROTATION, TELEPORT_FN] {
        ok(src);
    }
    ok("boolean parity(int n) {\n    return n % 2 == 1;\n}\n\nvoid main() {\n    int total = 0;\n    for i in 0..10 {\n        if parity(i) {\n            total = total + i;\n        }\n    }\n    println(\"total={}\", total);\n}\n");
}

// The error samples of docs/design/qx-language.md section 4, with their positions.
#[test]
fn design_doc_error_samples() {
    let use_after =
        "void main() {\n    Qubit q = qubit();\n    Bit m = measure(q);\n    h(q);\n}\n";
    assert_eq!(errors(use_after), vec![("Q0301", 4, 7)]);

    let dup = "void main() {\n    Qubit a = qubit();\n    cx(a, a);\n    discard(a);\n}\n";
    assert_eq!(errors(dup), vec![("Q0303", 3, 11)]);

    let leak = "void main() {\n    Qubit q = qubit();\n    h(q);\n}\n";
    assert_eq!(errors(leak), vec![("Q0302", 2, 11)]);

    let in_loop = "void main() {\n    Qubit q = qubit();\n    for i in 0..3 {\n        Bit m = measure(q);\n    }\n}\n";
    // The loop may also run zero times, so `q` additionally leaks at the end of `main`.
    assert_eq!(errors(in_loop), vec![("Q0302", 2, 11), ("Q0305", 4, 17)]);

    let bit_if = "void main() {\n    Qubit a = qubit();\n    Qubit t = qubit();\n    h(a);\n    Bit m = measure(a);\n    if m {\n        x(t);\n        Bit m2 = measure(t);\n    }\n}\n";
    assert_eq!(errors(bit_if), vec![("Q0308", 8, 18)]);
}

#[test]
fn removed_rust_syntax_points_to_the_new_form() {
    assert_eq!(codes("fn main() {}"), ["Q0110"]);
    assert_eq!(codes(&main_body("let x = 1;")), ["Q0110"]);
    let Err(Failure(d)) = check("t.qx", &main_body("let mut x = 1;")) else {
        panic!("expected an error")
    };
    assert!(
        d.starts_with("error[Q0110]") && d.contains("\nhelp: ") && d.contains("int x = 1;"),
        "{d}"
    );
    // Tail expressions are gone too: functions return with `return`.
    assert_eq!(codes("int f() { 1 }\nvoid main() {}"), ["Q0105"]);
}

#[test]
fn java_style_declarations_and_functions() {
    let src = "int add(int a, int b) {\n    return a + b;\n}\n\ndouble half(double x) {\n    return x / 2;\n}\n\nvoid main() {\n    final int n = 3;\n    double d = n;\n    d = d * 2;\n    boolean big = add(n, 4) > 6;\n    println(\"{} {} {} {} {}\", add(n, 4), half(n), d, big, 7 / 2);\n}\n";
    assert_eq!(run_ok(src, 1), "7 1.5 6.0 true 3\n");
    assert_eq!(codes(&main_body("final int x = 1;\nx = 2;")), ["Q0207"]);
    assert_eq!(codes(&main_body("int x = 1.5;")), ["Q0204"]);
    assert_eq!(codes(&main_body("void x = 1;")), ["Q0204"]);
    assert_eq!(codes("void f(void v) {}\nvoid main() {}"), ["Q0204"]);
    assert_eq!(codes("int main() {\n    return 0;\n}"), ["Q0206"]);
    assert_eq!(codes(&main_body("boolean b = 1 == true;")), ["Q0204"]);
    // Doubles follow IEEE 754: division by zero is not an error.
    assert_eq!(
        run_ok(&main_body("double z = 0.0;\nprintln(\"{}\", 1.0 / z);"), 1),
        "inf\n"
    );
}

#[test]
fn rotation_gates_take_double_angles() {
    let src =
        main_body("Qubit q = qubit();\nrx(q, 0.5);\nry(q, 1);\nrz(q, -0.25);\nBit m = measure(q);");
    let q = qasm("t.qx", &src).ok().unwrap();
    assert!(
        q.contains("rx(0.5) q[0];\nry(1.0) q[0];\nrz(-0.25) q[0];"),
        "{q}"
    );
    assert_eq!(
        codes(&main_body("Qubit q = qubit();\nrx(q, true);\ndiscard(q);")),
        ["Q0204"]
    );
}

#[test]
fn linear_qubit_rules() {
    // Moving a qubit into another variable consumes the original.
    assert_eq!(
        codes(&main_body(
            "Qubit q = qubit(); Qubit p = q; h(q); discard(p);"
        )),
        ["Q0301"]
    );
    ok(&main_body(
        "Qubit q = qubit(); Qubit p = q; h(p); discard(p);",
    ));
    assert_eq!(
        codes(&main_body(
            "Qubit q = qubit(); Qubit q = qubit(); discard(q);"
        )),
        ["Q0310"]
    );
    // Shadowing in an inner scope does not leak the outer qubit.
    ok(&main_body(
        "Qubit q = qubit(); if true { Qubit q = qubit(); discard(q); } discard(q);",
    ));
    assert_eq!(
        codes(&main_body("Qubit q = qubit(); if true { discard(q); }")),
        ["Q0304"]
    );
    ok(&main_body(
        "Qubit q = qubit(); if true { discard(q); } else { Bit m = measure(q); }",
    ));
    // A branch that returns does not have to agree with the other one.
    ok(&main_body(
        "Qubit q = qubit(); if true { discard(q); return; } discard(q);",
    ));
    assert_eq!(
        codes(&main_body(
            "Qubit q = qubit(); if true { return; } discard(q);"
        )),
        ["Q0302"]
    );
    assert_eq!(
        codes(&main_body(
            "QReg r = qreg(2); Bit m = measure(r[0]); discard(r);"
        )),
        ["Q0306"]
    );
    assert_eq!(
        codes(&main_body("QReg r = qreg(2); Qubit q = r[0]; discard(r);")),
        ["Q0306"]
    );
    assert_eq!(
        codes(&main_body("Qubit q = qubit(); q = qubit(); discard(q);")),
        ["Q0307"]
    );
    assert_eq!(codes(&main_body("h(qubit());")), ["Q0311"]);
    ok(&main_body("Bit m = measure(qubit()); discard(qreg(3));"));
    // Registers: literal indices are checked statically, others at run time.
    assert_eq!(
        codes(&main_body("QReg r = qreg(2); cx(r[0], r[0]); discard(r);")),
        ["Q0303"]
    );
    ok(&main_body(
        "QReg r = qreg(3); ccx(r[0], r[1], r[2]); int i = 1; cx(r[i], r[0]); discard(r);",
    ));
    assert_eq!(
        codes(&main_body(
            "Qubit a = qubit(); Qubit b = qubit(); ccx(a, b, a); discard(a); discard(b);"
        )),
        ["Q0303"]
    );
    // Allocating and consuming inside a loop body is fine.
    ok(&main_body(
        "for i in 0..3 { Qubit q = qubit(); h(q); Bit m = measure(q); println(\"{}\", m); }",
    ));
    assert_eq!(
        codes(&main_body(
            "Qubit q = qubit(); Bit m = measure(q); Bit n = measure(q);"
        )),
        ["Q0301"]
    );
}

#[test]
fn unbound_quantum_temporaries_are_rejected() {
    assert_eq!(codes(&main_body("qubit();")), ["Q0312"]);
    assert_eq!(codes(&main_body("qreg(3);")), ["Q0312"]);
    assert_eq!(codes(&main_body("int n = len(qreg(3));")), ["Q0312"]);
    assert_eq!(codes(&main_body("Bit m = measure(qreg(2)[0]);")), ["Q0312"]);
    assert_eq!(
        codes(&main_body("Qubit q = qreg(2)[1]; discard(q);")),
        ["Q0312"]
    );
    // Reading a register variable is fine.
    ok(&main_body(
        "QReg r = qreg(3); int n = len(r); h(r[n - 1]); discard(r);",
    ));
}

#[test]
fn byte_order_mark_is_ignored() {
    let src = format!("\u{feff}{BELL}");
    assert!(check("t.qx", &src).is_ok());
    let bad = "\u{feff}void main() {\n    Qubit q = qubit();\n}\n";
    let Err(Failure(d)) = check("t.qx", bad) else {
        panic!("expected an error")
    };
    // Columns are counted from after the mark.
    assert!(d.contains("--> t.qx:2:11\n"), "{d}");
}

#[test]
fn huge_stabilizer_runs_are_refused_before_allocating() {
    // About 20 GB of tableau; must become Q0406 instead of aborting on allocation.
    let src = main_body("QReg r = qreg(200000);\nBitReg m = measure(r);\nprintln(\"{}\", m);");
    let Err(Failure(d)) = run("t.qx", &src, 1, 0) else {
        panic!("expected a simulation error")
    };
    assert!(d.contains("error[Q0406]"), "{d}");
    assert!(qasm("t.qx", &src).is_ok());
    // Slots freed by `measure` are reused, so 1000 sequential qubits need a single slot.
    let reuse = main_body(
        "for i in 0..1000 { Qubit q = qubit(); h(q); Bit m = measure(q); if i == 999 { println(\"{}\", m); } }",
    );
    let q = qasm("t.qx", &reuse).ok().unwrap();
    assert!(q.contains("qubit[1] q;"), "{}", &q[..80]);
    let (_, e) = build(&reuse).ok().unwrap();
    assert_eq!(e.slots, 1);
    let out = run_ok(&reuse, 1);
    assert!(out == "0\n" || out == "1\n", "{out}");
}

#[test]
fn bit_if_restrictions() {
    let pre = "Qubit a = qubit(); Qubit t = qubit(); h(a); Bit m = measure(a);";
    let with = |body: &str| main_body(&format!("{pre} {body} discard(t);"));
    ok(&with(
        "if m { x(t); for i in 0..2 { z(t); } int k = 3; if k > 2 { h(t); } } else { reset(t); }",
    ));
    ok(&with(
        "Bit r = measure(qubit()); if m { x(t); } else if r { z(t); }",
    ));
    assert_eq!(codes(&with("if m { println(\"x\"); }")), ["Q0308"]);
    assert_eq!(
        codes(&with("if m { Qubit q = qubit(); discard(q); }")),
        // `qubit()` and `discard`; the declaration is not reported again.
        ["Q0308", "Q0308"]
    );
    assert_eq!(codes(&with("if m { return; }")), ["Q0308"]);
    // Functions that only apply gates may be called inside (section 14 of the design doc).
    ok(&format!("void f() {{}}\n{}", with("if m { f(); }")));
    assert_eq!(codes(&with("int k = 0; if m { k = 1; }")), ["Q0309"]);
    // Locals declared inside the body may be assigned there.
    ok(&with("if m { int k = 0; k = k + 1; }"));
}

#[test]
fn types_and_names() {
    let m = "Bit m = measure(qubit());";
    assert_eq!(codes(&main_body(&format!("{m} int x = m + 1;"))), ["Q0218"]);
    assert_eq!(
        codes(&main_body(&format!("{m} for i in 0..m {{}}"))),
        ["Q0218"]
    );
    assert_eq!(codes(&main_body(&format!("{m} boolean b = m;"))), ["Q0218"]);
    assert_eq!(codes(&main_body("if 1 {}")), ["Q0215"]);
    assert_eq!(codes(&main_body("boolean x = 1;")), ["Q0204"]);
    assert_eq!(codes(&main_body("int x = 1 + true;")), ["Q0204"]);
    assert_eq!(codes(&main_body("int x = y;")), ["Q0201"]);
    assert_eq!(codes(&main_body("foo();")), ["Q0202"]);
    assert_eq!(
        codes(&main_body("Qubit q = qubit(1); discard(q);")),
        ["Q0203"]
    );
    assert_eq!(codes(&main_body("int x = 3; int y = x[0];")), ["Q0209"]);
    assert_eq!(codes(&main_body("println(\"{} {}\", 1);")), ["Q0210"]);
    assert_eq!(codes(&main_body("println(1);")), ["Q0211"]);
    assert_eq!(
        codes(&main_body(
            "Qubit q = qubit(); println(\"{}\", q); discard(q);"
        )),
        ["Q0212"]
    );
    assert_eq!(codes(&main_body("int s = \"hi\";")), ["Q0214"]);
    assert_eq!(codes("void f() {}\nvoid f() {}\nvoid main() {}"), ["Q0205"]);
    assert_eq!(codes("void f(int a, int a) {}\nvoid main() {}"), ["Q0205"]);
    assert_eq!(codes("void helper() {}"), ["Q0206"]);
    assert_eq!(codes("void main(int x) {}"), ["Q0206"]);
    assert_eq!(codes("void h() {}\nvoid main() {}"), ["Q0217"]);
    // Qubit parameters and quantum return types are supported; Q0219 is retired.
    ok("void f(Qubit q) {}\nvoid main() {}");
    ok("Qubit f() {\n    return qubit();\n}\nvoid main() {\n    discard(f());\n}");
    assert_eq!(
        codes("int f() { if true { return 1; } }\nvoid main() {}"),
        ["Q0213"]
    );
    ok("int f() { if true { return 1; } else { return 2; } }\nvoid main() { int x = f(); }");
    assert_eq!(codes("int f() { return true; }\nvoid main() {}"), ["Q0204"]);
    // Every error is reported, not just the first.
    assert_eq!(
        codes(&main_body("int a = y; int b = z; boolean c = 1;")),
        ["Q0201", "Q0201", "Q0204"]
    );
}

#[test]
fn runtime_errors_have_positions() {
    assert_eq!(
        runtime_error(&main_body("int x = 9223372036854775807;\nint y = x + 1;")),
        ("Q0401", 3, 9)
    );
    assert_eq!(
        runtime_error(&main_body("int z = 0;\nint y = 7 % z;")),
        ("Q0402", 3, 9)
    );
    assert_eq!(
        runtime_error(&main_body("QReg r = qreg(2);\nh(r[2]);\ndiscard(r);")).0,
        "Q0403"
    );
    assert_eq!(
        runtime_error(&main_body(
            "QReg r = qreg(2);\nint i = 1;\ncx(r[i], r[1]);\ndiscard(r);"
        )),
        ("Q0303", 4, 1)
    );
    assert_eq!(
        runtime_error(
            "int f(int n) {\n    return f(n + 1);\n}\nvoid main() {\n    int x = f(0);\n}\n"
        )
        .0,
        "Q0405"
    );
    assert_eq!(
        runtime_error(&main_body("int n = 0 - 1;\nQReg r = qreg(n);\ndiscard(r);")).0,
        "Q0408"
    );
    assert_eq!(
        runtime_error(&main_body("QReg r = qreg(2000000);\ndiscard(r);")).0,
        "Q0409"
    );
    assert_eq!(
        runtime_error(&main_body(
            "BitReg m = measure(qreg(65));\nprintln(\"{}\", m.as_int());"
        )),
        ("Q0410", 3, 15)
    );
}

// `[0, 1, 1]` lists r[0] first; `0b110` and `as_int() == 6` read r[0] as the least significant bit.
#[test]
fn bit_registers_print_as_array_binary_and_int() {
    let src = main_body(
        "QReg r = qreg(3);\nx(r[1]);\nx(r[2]);\nBitReg m = measure(r);\nprintln(\"{} {} {} {}\", m, m.to_binary(), m.as_int(), m[0]);",
    );
    assert_eq!(run_ok(&src, 1), "[0, 1, 1] 0b110 6 0\n");
    assert_eq!(
        run_ok(&src, 5),
        "[0, 1, 1]  0b110 = 6  ×5\n  [0, 1, 1] 0b110 6 0\n"
    );
    let empty = main_body(
        "BitReg m = measure(qreg(0));\nprintln(\"{} {} {}\", m, m.to_binary(), m.as_int());",
    );
    assert_eq!(run_ok(&empty, 1), "[] 0b0 0\n");
    let m = "BitReg m = measure(qreg(2));";
    assert_eq!(
        codes(&main_body(&format!("{m} int v = m.as_int();"))),
        ["Q0218"]
    );
    assert_eq!(
        codes(&main_body(&format!("{m} println(\"{{}}\", m.foo());"))),
        ["Q0220"]
    );
    assert_eq!(
        codes(&main_body(
            "Qubit q = qubit(); println(\"{}\", q.to_binary()); discard(q);"
        )),
        ["Q0220"]
    );
}

#[test]
fn bell_and_ghz_outcomes_are_correlated() {
    let rows = table(&run_ok(BELL, 200));
    let mut keys: Vec<&str> = rows.iter().map(|r| r.0.as_str()).collect();
    keys.sort_unstable();
    assert_eq!(keys, ["[0, 0]  0b00 = 0", "[1, 1]  0b11 = 3"]);
    assert_eq!(rows.iter().map(|r| r.1).sum::<u64>(), 200);
    for (bits, _, lines) in &rows {
        let want = if bits.starts_with("[0") {
            "a=0 b=0"
        } else {
            "a=1 b=1"
        };
        assert_eq!(lines, &[want]);
    }
    // Rows are sorted by count, largest first.
    assert!(rows[0].1 >= rows[1].1);
    let one = run_ok(GHZ, 1);
    assert!(
        one == "[0, 0, 0, 0, 0]  0b00000 = 0\n" || one == "[1, 1, 1, 1, 1]  0b11111 = 31\n",
        "{one}"
    );
    for (bits, _, _) in table(&run_ok(GHZ, 100)) {
        assert!(
            bits == "[0, 0, 0, 0, 0]  0b00000 = 0" || bits == "[1, 1, 1, 1, 1]  0b11111 = 31",
            "{bits}"
        );
    }
}

#[test]
fn teleport_always_delivers_one() {
    let rows = table(&run_ok(TELEPORT, 64));
    assert_eq!(rows.iter().map(|r| r.1).sum::<u64>(), 64);
    for (bits, _, lines) in rows {
        // c[2] is bob's measurement: always 1.
        assert!(
            bits.starts_with('[') && bits[1..].contains(", 1]"),
            "{bits}"
        );
        assert_eq!(lines, ["bob=1"]);
    }
}

#[test]
fn qasm_matches_the_library_circuit() {
    let mut c = qxide::Circuit::new();
    let mut a = c.qubit();
    let mut b = c.qubit();
    c.h(&mut a);
    c.cx(&mut a, &mut b);
    c.measure(a);
    c.measure(b);
    assert_eq!(qasm("t.qx", BELL).ok().unwrap(), c.to_qasm());

    let tele = qasm("t.qx", TELEPORT).ok().unwrap();
    assert!(tele.contains("if (c[1] == true) {\n  x q[2];\n}"), "{tele}");
    let els = main_body("Qubit a = qubit(); Qubit t = qubit(); h(a); Bit m = measure(a); if m { x(t); } else { z(t); } discard(t);");
    let q = qasm("t.qx", &els).ok().unwrap();
    assert!(
        q.contains("if (c[0] == true) {\n  x q[1];\n}\nif (c[0] == false) {\n  z q[1];\n}"),
        "{q}"
    );
    // A `boolean` condition is decided at build time: only the taken branch is emitted.
    let q = qasm(
        "t.qx",
        &main_body("Qubit q = qubit(); if 1 < 2 { x(q); } else { h(q); } discard(q);"),
    )
    .ok()
    .unwrap();
    assert!(q.contains("x q[0];") && !q.contains("h q[0];"), "{q}");
}

#[test]
fn classical_programs_run_without_simulation() {
    let src = "int fib(int n) {\n    if n < 2 {\n        return n;\n    }\n    return fib(n - 1) + fib(n - 2);\n}\nvoid main() {\n    int s = 0;\n    for i in 0..10 {\n        if i % 2 == 1 && !(i == 5) {\n            s = s + i;\n        }\n    }\n    println(\"fib={} s={} {{ok}}\", fib(15), s);\n}\n";
    assert_eq!(run_ok(src, 1), "fib=610 s=20 {ok}\n");
    // No measurement: the output does not depend on the shot, so it is printed once.
    assert_eq!(run_ok(src, 3), "fib=610 s=20 {ok}\n");
}

#[test]
fn simulation_errors_become_diagnostics() {
    // 30 qubits with a non-Clifford gate need a 16 GiB state vector, over the 1 GiB default.
    let src =
        main_body("QReg r = qreg(30);\nt(r[0]);\nBitReg m = measure(r);\nprintln(\"{}\", m);");
    ok(&src);
    let Err(Failure(d)) = run("t.qx", &src, 1, 0) else {
        panic!("expected a simulation error")
    };
    assert!(d.contains("error[Q0406]"), "{d}");
    // QASM export does not simulate, so it still works.
    assert!(qasm("t.qx", &src).is_ok());
}

#[test]
fn rendering_shows_position_snippet_and_notes() {
    let src =
        "void main() {\r\n    Qubit q = qubit();\r\n    Bit m = measure(q);\r\n    h(q);\r\n}\r\n";
    let Err(Failure(d)) = check("bad.qx", src) else {
        panic!("expected errors")
    };
    assert!(d.starts_with("error[Q0301]: "), "{d}");
    assert!(d.contains("--> bad.qx:4:7\n"), "{d}");
    assert!(d.contains("4 |     h(q);\n  |       ^\n"), "{d}");
    assert!(d.contains("--> bad.qx:3:13\n"), "{d}");
    assert!(
        d.contains("3 |     Bit m = measure(q);\n  |             ^^^^^^^^^^\n"),
        "{d}"
    );
    assert!(!d.contains('\r'), "{d:?}");
}

fn rendered(src: &str) -> String {
    match run("t.qx", src, 1, 0) {
        Ok(out) => panic!("expected errors, got output {out:?}"),
        Err(Failure(d)) => d,
    }
}

// Diagnostics are English: no Hangul in any message, note or help (out-of-memory errors are
// re-worded with GiB sizes and a help line).
#[test]
fn diagnostics_are_english_with_help_lines() {
    let hangul = |s: &str| s.chars().any(|c| ('\u{AC00}'..='\u{D7A3}').contains(&c));
    let samples = [
        "void main() { int x = 1 # 2; }".to_string(),
        "void main() { int x = \"\\q\"; }".to_string(),
        "void main() { long x = 1; }".to_string(),
        "void main() { boolean b = 1 < 2 < 3; }".to_string(),
        "fn main() {}".to_string(),
        main_body("Qubit q = qubit();\nh(q);"),
        main_body("Qubit q = qubit();\nBit m = measure(q);\nh(q);"),
        main_body("final int x = 1;\nx = 2;\nint y = z;\nqubit();"),
        main_body("Qubit a = qubit(); Qubit t = qubit(); Bit m = measure(a); if m { println(\"x\"); } discard(t);"),
        main_body("QReg r = qreg(30);\nt(r[0]);\nBitReg m = measure(r);\nprintln(\"{}\", m);"),
        main_body("QReg r = qreg(200000);\nBitReg m = measure(r);\nprintln(\"{}\", m);"),
        main_body("BitReg m = measure(qreg(65));\nprintln(\"{}\", m.as_int());"),
        "int f(int n) {\n    return f(n + 1);\n}\nvoid main() {\n    int x = f(0);\n}\n".to_string(),
        "void f(Qubit q) {\n    discard(q);\n}\nvoid main() {}\n".to_string(),
        "void f(consume int n, var x) {}\nvoid main() {}\n".to_string(),
        main_body("var q = qubit();\nboolean b = (boolean) 1;\ndouble PI = 1.0;"),
        format!("void f(Qubit q) {{\n    Bit m = measure(q);\n}}\n{}", main_body("Qubit a = qubit();\nBit m = measure(a);\nQubit t = qubit();\nif m {\n    f(t);\n}\ndiscard(t);")),
    ];
    for src in &samples {
        let d = rendered(src);
        assert!(d.starts_with("error[Q"), "{d}");
        assert!(!hangul(&d), "non-English diagnostic:\n{d}");
    }
    let d = rendered(&main_body("Qubit q = qubit();\nh(q);"));
    assert!(d.contains("\nhelp: "), "{d}");
    let d = rendered("void main() { boolean b = 1 < 2 < 3; }");
    assert!(d.contains("\nhelp: ") && d.contains("&&"), "{d}");
    let d = rendered(&main_body(
        "QReg r = qreg(30);\nt(r[0]);\nBitReg m = measure(r);\nprintln(\"{}\", m);",
    ));
    assert!(
        d.contains("error[Q0406]") && d.contains("16.0 GiB") && d.contains("\nhelp: "),
        "{d}"
    );
}

const BELL_PAIR: &str = "void bellPair(Qubit a, Qubit b) {\n    h(a);\n    cx(a, b);\n}\n\n";
const SINK: &str = "void sink(consume Qubit q) {\n    discard(q);\n}\n\n";

#[test]
fn qubit_parameters_are_borrowed_by_default() {
    let src = format!("{BELL_PAIR}void main() {{\n    Qubit a = qubit();\n    Qubit b = qubit();\n    bellPair(a, b);\n    Bit ma = measure(a);\n    Bit mb = measure(b);\n    println(\"a={{}} b={{}}\", ma, mb);\n}}\n");
    // A borrowed call lowers to the same circuit as writing the gates inline.
    assert_eq!(
        qasm("t.qx", &src).ok().unwrap(),
        qasm("t.qx", BELL).ok().unwrap()
    );
    let rows = table(&run_ok(&src, 200));
    assert_eq!(rows.len(), 2);
    for (bits, _, lines) in &rows {
        let want = if bits.starts_with("[0, 0]") {
            "a=0 b=0"
        } else {
            "a=1 b=1"
        };
        assert_eq!(lines, &[want.to_string()], "{bits}");
    }
    // Whole registers and register elements can be borrowed, also through nested calls.
    let reg = format!("{BELL_PAIR}void flipAll(QReg r) {{\n    for i in 0..len(r) {{\n        x(r[i]);\n    }}\n}}\n\nvoid twice(QReg r) {{\n    flipAll(r);\n    flipAll(r);\n    x(r[1]);\n}}\n\nvoid main() {{\n    QReg r = qreg(3);\n    twice(r);\n    flipAll(r);\n    BitReg m = measure(r);\n    println(\"{{}}\", m);\n}}\n");
    assert_eq!(run_ok(&reg, 1), "[1, 0, 1]\n");
    // A `return` in a function with borrowed parameters does not leak them.
    ok("void f(Qubit q) {\n    if true {\n        return;\n    }\n    h(q);\n}\nvoid main() {}\n");
}

#[test]
fn borrowed_parameters_cannot_be_consumed() {
    let measured = "void f(Qubit q) {\n    Bit m = measure(q);\n}\nvoid main() {}\n";
    assert_eq!(errors(measured), vec![("Q0313", 2, 21)]);
    let discarded = "void f(QReg r) {\n    discard(r);\n}\nvoid main() {}\n";
    assert_eq!(errors(discarded), vec![("Q0313", 2, 13)]);
    let moved = "void f(Qubit q) {\n    Qubit p = q;\n    discard(p);\n}\nvoid main() {}\n";
    assert_eq!(errors(moved), vec![("Q0313", 2, 15)]);
    // Passing a borrowed qubit on to a `consume` parameter would consume it too.
    let passed = format!("{SINK}void f(Qubit q) {{\n    sink(q);\n}}\nvoid main() {{}}\n");
    assert_eq!(errors(&passed), vec![("Q0313", 6, 10)]);
    let d = rendered(measured);
    assert!(
        d.contains("error[Q0313]") && d.contains("\nnote: ") && d.contains("consume Qubit q"),
        "{d}"
    );
}

#[test]
fn consume_parameters_transfer_ownership() {
    let src = "void measureAll(consume QReg r) {\n    BitReg m = measure(r);\n    println(\"{}\", m);\n}\n\nvoid main() {\n    QReg r = qreg(2);\n    x(r[0]);\n    measureAll(r);\n}\n";
    assert_eq!(run_ok(src, 1), "[1, 0]\n");
    // A fresh value can be handed over directly.
    ok("void sink(consume QReg r) {\n    discard(r);\n}\nvoid main() {\n    sink(qreg(2));\n}\n");
    // The callee must measure or discard what it consumes, on every path.
    let kept = "void keep(consume Qubit q) {\n    h(q);\n}\nvoid main() {}\n";
    assert_eq!(errors(kept), vec![("Q0302", 1, 25)]);
    let early = "void keep(consume Qubit q) {\n    if true {\n        return;\n    }\n    discard(q);\n}\nvoid main() {}\n";
    assert_eq!(errors(early), vec![("Q0302", 1, 25)]);
    // The caller cannot use it afterwards, nor hand it over inside a loop.
    let after =
        format!("{SINK}void main() {{\n    Qubit q = qubit();\n    sink(q);\n    h(q);\n}}\n");
    assert_eq!(errors(&after), vec![("Q0301", 8, 7)]);
    let looped = format!("{SINK}void main() {{\n    Qubit q = qubit();\n    for i in 0..2 {{\n        sink(q);\n    }}\n}}\n");
    assert_eq!(codes(&looped), ["Q0302", "Q0305"]);
    assert_eq!(codes("void f(consume int n) {}\nvoid main() {}"), ["Q0221"]);
    // Moving one element out of a register is still a partial move.
    let partial = format!(
        "{SINK}void main() {{\n    QReg r = qreg(2);\n    sink(r[0]);\n    discard(r);\n}}\n"
    );
    assert_eq!(codes(&partial), ["Q0306"]);
}

#[test]
fn quantum_arguments_must_not_alias() {
    let main = |body: &str| format!("{BELL_PAIR}void main() {{\n{body}\n}}\n");
    assert_eq!(
        errors(&main("Qubit a = qubit();\nbellPair(a, a);\ndiscard(a);")),
        vec![("Q0303", 8, 13)]
    );
    ok(&main(
        "QReg r = qreg(2);\nbellPair(r[0], r[1]);\ndiscard(r);",
    ));
    assert_eq!(
        codes(&main(
            "QReg r = qreg(2);\nbellPair(r[1], r[1]);\ndiscard(r);"
        )),
        ["Q0303"]
    );
    // A whole register overlaps each of its elements.
    let whole = "void g(QReg r, Qubit q) {}\nvoid main() {\n    QReg r = qreg(2);\n    g(r, r[0]);\n    discard(r);\n}\n";
    assert_eq!(codes(whole), ["Q0303"]);
    // Borrowing and consuming the same qubit in one call is rejected once.
    let mixed = "void g(Qubit a, consume Qubit b) {\n    discard(b);\n}\nvoid main() {\n    Qubit q = qubit();\n    g(q, q);\n}\n";
    assert_eq!(codes(mixed), ["Q0303"]);
    // Run-time indices are checked when the call runs.
    let dynamic = main("QReg r = qreg(2);\nint i = 1;\nbellPair(r[i], r[1]);\ndiscard(r);");
    assert_eq!(runtime_error(&dynamic), ("Q0303", 9, 1));
    // Borrowed arguments must be variables or register elements of the right type.
    assert_eq!(
        codes(&main(
            "Qubit b = qubit();\nbellPair(qubit(), b);\ndiscard(b);"
        )),
        ["Q0311"]
    );
    assert_eq!(
        codes(&main(
            "QReg r = qreg(2);\nQubit b = qubit();\nbellPair(r, b);\ndiscard(r);\ndiscard(b);"
        )),
        ["Q0204"]
    );
}

#[test]
fn var_infers_classical_local_types() {
    let src = main_body("var n = 3;\nvar t = 0.5;\nvar big = n > 2;\nfinal var k = n * 2;\nvar d = 1.0;\nd = 2;\nprintln(\"{} {} {} {} {}\", n, t, big, k, d);");
    assert_eq!(run_ok(&src, 1), "3 0.5 true 6 2.0\n");
    // The inferred type is fixed afterwards.
    assert_eq!(codes(&main_body("var n = 1;\nn = 2.5;")), ["Q0204"]);
    assert_eq!(codes(&main_body("final var k = 1;\nk = 2;")), ["Q0207"]);
    // Quantum values, measurement results and `void` need an explicit type.
    assert_eq!(
        errors(&main_body("var q = qubit();")),
        vec![("Q0222", 2, 1)]
    );
    assert_eq!(
        codes(&main_body("Qubit q = qubit();\nvar m = measure(q);")),
        ["Q0222"]
    );
    assert_eq!(
        codes(&main_body(
            "BitReg m = measure(qreg(2));\nvar v = m.as_int();"
        )),
        ["Q0222"]
    );
    assert_eq!(codes(&main_body("var v = println(\"\");")), ["Q0222"]);
    // `var` is for local variables with an initializer only.
    assert_eq!(codes("void f(var x) {}\nvoid main() {}"), ["Q0111"]);
    assert_eq!(
        codes("var f() {\n    return 1;\n}\nvoid main() {}"),
        ["Q0111"]
    );
    assert_eq!(codes(&main_body("var x;")), ["Q0105"]);
}

#[test]
fn casts_between_int_and_double() {
    let src = main_body("double x = 2.9;\nint n = 7;\nprintln(\"{} {} {} {} {} {} {} {}\", (int) x, (int) -x, -(int) x, (double) n / 2, (int) x * 2, (int) (x * 2), (int) 3, (double) 1.5);");
    assert_eq!(run_ok(&src, 1), "2 -2 -2 3.5 4 5 3 1.5\n");
    // Java's rules: NaN becomes 0, out-of-range values saturate (2^63 does too).
    let edge = main_body("double z = 0.0;\nprintln(\"{} {} {} {}\", (int) (z / z), (int) 1e300, (int) -1e300, (int) 9223372036854775807.0);");
    assert_eq!(
        run_ok(&edge, 1),
        format!("0 {} {} {}\n", i64::MAX, i64::MIN, i64::MAX)
    );
    assert_eq!(codes(&main_body("boolean b = (boolean) 1;")), ["Q0223"]);
    assert_eq!(codes(&main_body("int n = (int) true;")), ["Q0223"]);
    assert_eq!(
        codes(&main_body(
            "Qubit q = qubit();\nint n = (int) q;\ndiscard(q);"
        )),
        ["Q0223"]
    );
    assert_eq!(
        codes(&main_body(
            "Qubit q = qubit();\nBit m = measure(q);\nint n = (int) m;"
        )),
        ["Q0218"]
    );
    // Type names cannot name values, so `(int) x` is always a cast.
    assert_eq!(codes(&main_body("int int = 1;")), ["Q0112"]);
    assert_eq!(codes("void f(double double) {}\nvoid main() {}"), ["Q0112"]);
    assert_eq!(
        codes("int Qubit() {\n    return 1;\n}\nvoid main() {}"),
        ["Q0112"]
    );
    assert_eq!(codes(&main_body("for int in 0..3 {}")), ["Q0112"]);
    let deep = main_body(&format!("int x = {}1;", "(int) ".repeat(500)));
    assert_eq!(codes(&deep), ["Q0106"]);
}

#[test]
fn pi_is_a_builtin_double_constant() {
    use std::f64::consts::{FRAC_PI_2, PI};
    assert_eq!(
        run_ok(&main_body("println(\"{} {}\", PI, PI / 2);"), 1),
        format!("{PI:?} {FRAC_PI_2:?}\n")
    );
    let src = main_body("Qubit q = qubit();\nrz(q, PI);\nBit m = measure(q);");
    let q = qasm("t.qx", &src).ok().unwrap();
    assert!(q.contains(&format!("rz({PI:?}) q[0];")), "{q}");
    assert_eq!(codes(&main_body("double PI = 3.0;")), ["Q0217"]);
    assert_eq!(codes("void f(double PI) {}\nvoid main() {}"), ["Q0217"]);
    assert_eq!(
        codes("double PI() {\n    return 3.0;\n}\nvoid main() {}"),
        ["Q0217"]
    );
    assert_eq!(codes(&main_body("for PI in 0..2 {}")), ["Q0217"]);
    assert_eq!(codes(&main_body("PI = 3.0;")), ["Q0207"]);
    let d = rendered(&main_body("double PI = 3.0;"));
    assert!(
        d.contains("\nhelp: ") && d.contains("PI") && !d.contains("function"),
        "{d}"
    );
    // Assigning to `PI` suggests a local variable, not removing `final`.
    let d = rendered(&main_body("PI = 3.0;"));
    assert!(
        d.contains("\nhelp: ") && d.contains("double angle = PI;") && !d.contains("final"),
        "{d}"
    );
}

#[test]
fn new_examples_run() {
    let rows = table(&run_ok(FUNCTIONS, 200));
    let mut heads: Vec<&str> = rows.iter().map(|r| r.0.as_str()).collect();
    heads.sort_unstable();
    assert_eq!(heads, ["[0, 0]  0b00 = 0", "[1, 1]  0b11 = 3"]);
    assert_eq!(run_ok(ROTATION, 1), "ry total 90 degrees (90.0), m=0\n");
    let q = qasm("t.qx", ROTATION).ok().unwrap();
    assert_eq!(q.matches("ry(").count(), 4, "{q}");
}

const CONDITIONAL_FN: &str = include_str!("../../examples/qx/conditional_fn.qx");
const MAKE: &str = "Qubit make() {\n    Qubit q = qubit();\n    h(q);\n    return q;\n}\n\n";

fn same_qasm(a: &str, b: &str) {
    assert_eq!(qasm("t.qx", a).ok().unwrap(), qasm("t.qx", b).ok().unwrap());
}

#[test]
fn functions_return_qubits_to_the_caller() {
    let ghz = "QReg ghz(int n) {\n    QReg r = qreg(n);\n    h(r[0]);\n    for i in 1..n {\n        cx(r[0], r[i]);\n    }\n    return r;\n}\n\nvoid main() {\n    QReg r = ghz(5);\n    BitReg m = measure(r);\n    println(\"{}  {} = {}\", m, m.to_binary(), m.as_int());\n}\n";
    // Building the register in a function gives the same circuit as examples/qx/ghz.qx.
    same_qasm(ghz, GHZ);
    let rows = table(&run_ok(ghz, 200));
    let mut heads: Vec<&str> = rows.iter().map(|r| r.0.as_str()).collect();
    heads.sort_unstable();
    assert_eq!(
        heads,
        [
            "[0, 0, 0, 0, 0]  0b00000 = 0",
            "[1, 1, 1, 1, 1]  0b11111 = 31"
        ]
    );
    // `consume` in, return out: ownership passes through the function.
    ok("Qubit hadamard(consume Qubit q) {\n    h(q);\n    return q;\n}\nvoid main() {\n    Qubit q = hadamard(qubit());\n    Bit m = measure(q);\n}\n");
    ok(&format!(
        "{MAKE}void main() {{\n    Bit m = measure(make());\n}}\n"
    ));
}

#[test]
fn returned_qubits_follow_the_linear_rules() {
    let main = |body: &str| format!("{MAKE}void main() {{\n{body}\n}}\n");
    // The caller must consume the result, exactly once.
    assert_eq!(errors(&main("Qubit q = make();")), vec![("Q0302", 8, 7)]);
    assert_eq!(errors(&main("make();")), vec![("Q0312", 8, 1)]);
    assert_eq!(
        errors(&main(
            "Qubit q = make();\nBit a = measure(q);\nBit b = measure(q);"
        )),
        vec![("Q0301", 10, 17)]
    );
    assert_eq!(codes(&main("QReg r = make();\ndiscard(r);")), ["Q0204"]);
    assert_eq!(codes(&main("h(make());")), ["Q0311"]);
    // Qubits the function keeps instead of returning are still leaks.
    let kept = "Qubit f() {\n    Qubit a = qubit();\n    Qubit b = qubit();\n    return a;\n}\nvoid main() {}\n";
    assert_eq!(errors(kept), vec![("Q0302", 3, 11)]);
    // Borrowed parameters and single register elements cannot be returned.
    assert_eq!(
        errors("Qubit f(Qubit q) {\n    return q;\n}\nvoid main() {}\n"),
        vec![("Q0313", 2, 12)]
    );
    assert_eq!(
        codes("Qubit f() {\n    QReg r = qreg(2);\n    return r[0];\n}\nvoid main() {}\n"),
        ["Q0302", "Q0306"]
    );
    assert_eq!(
        codes("Qubit f() {\n    return 1;\n}\nvoid main() {}\n"),
        ["Q0204"]
    );
    assert_eq!(
        codes("Qubit f() {\n    Qubit q = qubit();\n    discard(q);\n}\nvoid main() {}\n"),
        ["Q0213"]
    );
}

#[test]
fn gate_only_functions_run_inside_bit_conditions() {
    // The function version lowers to the same conditional blocks as the inline teleport.
    same_qasm(TELEPORT_FN, TELEPORT);
    for (_, _, lines) in table(&run_ok(TELEPORT_FN, 200)) {
        assert_eq!(lines, ["bob=1"]);
    }
    // `else`, loops with rotations, a nested `if` on a `Bit` parameter and a classical helper.
    let inline = "void main() {\n    Qubit coin = qubit();\n    h(coin);\n    Bit m = measure(coin);\n    Qubit other = qubit();\n    h(other);\n    Bit f = measure(other);\n    QReg r = qreg(2);\n    if m {\n        for i in 0..len(r) {\n            rz(r[i], PI / 4);\n        }\n        if f {\n            x(r[0]);\n        }\n    } else {\n        for i in 0..2 {\n            x(r[1]);\n        }\n    }\n    BitReg out = measure(r);\n    println(\"m={} f={} r={}\", m, f, out);\n}\n";
    same_qasm(CONDITIONAL_FN, inline);
    let q = qasm("t.qx", CONDITIONAL_FN).ok().unwrap();
    assert!(q.contains("if (c[0] == false) {"), "{q}");
    assert!(q.contains("  if (c[1] == true) {\n    x q[0];\n  }"), "{q}");
    for (_, _, lines) in table(&run_ok(CONDITIONAL_FN, 300)) {
        // r[0] is flipped only when both coins are 1; the two `x(r[1])` cancel out.
        assert!(
            matches!(
                lines[0].as_str(),
                "m=1 f=1 r=[1, 0]" | "m=1 f=0 r=[0, 0]" | "m=0 f=1 r=[0, 0]" | "m=0 f=0 r=[0, 0]"
            ),
            "{lines:?}"
        );
    }
    // Recursion is fine as long as every reachable body only applies gates.
    let rec = "void flipN(Qubit q, int n) {\n    if n > 0 {\n        x(q);\n        flipN(q, n - 1);\n    }\n}\nvoid main() {\n    Qubit a = qubit();\n    h(a);\n    Bit m = measure(a);\n    Qubit t = qubit();\n    if m {\n        flipN(t, 3);\n    }\n    Bit out = measure(t);\n}\n";
    let q = qasm("t.qx", rec).ok().unwrap();
    assert!(
        q.contains("if (c[0] == true) {\n  x q[0];\n  x q[0];\n  x q[0];\n}"),
        "{q}"
    );
}

#[test]
fn conditional_calls_reject_what_blocks_cannot_hold() {
    let pre =
        "void main() {\n    Qubit a = qubit();\n    Bit m = measure(a);\n    Qubit t = qubit();\n";
    // `f` calls `g`, which prints; the note points at the call inside `f`.
    let transitive = format!("void g() {{\n    println(\"x\");\n}}\nvoid f(Qubit q) {{\n    h(q);\n    g();\n}}\n{pre}    if m {{\n        f(t);\n    }}\n    discard(t);\n}}\n");
    assert_eq!(errors(&transitive), vec![("Q0314", 13, 9)]);
    let d = rendered(&transitive);
    assert!(
        d.contains("--> t.qx:6:5") && d.contains("`g`") && d.contains("\nhelp: "),
        "{d}"
    );
    // A `consume` parameter would consume the qubit on only some shots; reported once, no leak.
    let consume = format!("void eat(consume Qubit q) {{\n    discard(q);\n}}\n{pre}    if m {{\n        eat(t);\n    }}\n}}\n");
    assert_eq!(errors(&consume), vec![("Q0314", 9, 9)]);
    assert!(rendered(&consume).contains("--> t.qx:1:24"));
    // A function returning a qubit would allocate inside the block; reported once.
    let make =
        format!("{MAKE}{pre}    if m {{\n        Qubit p = make();\n    }}\n    discard(t);\n}}\n");
    assert_eq!(errors(&make), vec![("Q0314", 12, 19)]);
    // Measuring inside the callee, also through recursion.
    let measured = format!("void probe() {{\n    Bit b = measure(qubit());\n}}\n{pre}    if m {{\n        probe();\n    }}\n    discard(t);\n}}\n");
    assert_eq!(codes(&measured), ["Q0314"]);
    let rec = format!("void bad(int n) {{\n    if n > 0 {{\n        bad(n - 1);\n    }} else {{\n        println(\"done\");\n    }}\n}}\n{pre}    if m {{\n        bad(2);\n    }}\n    discard(t);\n}}\n");
    assert_eq!(codes(&rec), ["Q0314"]);
    // Outside the `if` the same calls are fine.
    ok(&format!("void g() {{\n    println(\"x\");\n}}\nvoid f(Qubit q) {{\n    h(q);\n    g();\n}}\n{pre}    f(t);\n    discard(t);\n}}\n"));
}