deqagram 0.7.0

A pest-based parser and typed AST for the deq (.deq) quantum error correction file format.
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
use super::*;
use crate::{Span, Spanned};

/// Wraps a node in a `Spanned<T>` with a dummy span. Equality ignores spans, so
/// this compares equal to any parsed `Spanned<T>` carrying the same node.
fn sp<T>(node: T) -> Spanned<T> {
    Spanned::new(node, Span { start: 0, end: 0 })
}

/// Parsing a source, displaying it, and re-parsing must yield the same AST.
fn assert_roundtrip(input: &str) {
    let ast1: DeqFile = input.parse().unwrap_or_else(|e| panic!("parse failed:\n{input}\n{e}"));
    let serialized = ast1.to_string();
    let ast2: DeqFile = serialized
        .parse()
        .unwrap_or_else(|e| panic!("re-parse failed:\n{serialized}\n{e}"));
    assert_eq!(
        ast1, ast2,
        "roundtrip mismatch.\ninput:\n{input}\nserialized:\n{serialized}"
    );
}

#[test]
fn parse_small_example_ast() {
    let ast: DeqFile = "\
CODE RepetitionCode [[3,1,1]] {
    LOGICAL X0*X1*X2 Z0*Z1*Z2
    STABILIZER Z0*Z1 Z1*Z2
}

GADGET PrepareZ {
    R 0 1 2
    X_ERROR(0.03) 0 1 2
    OUTPUT RepetitionCode 0 1 2
}
"
    .parse()
    .unwrap();

    assert_eq!(ast.definitions.len(), 2);
    let Definition::Code(code) = &ast.definitions[0].node else {
        panic!("expected CODE");
    };
    assert_eq!(code.name, "RepetitionCode");
    assert_eq!((code.n, code.k, code.d), (3, 1, Some(1)));
    assert_eq!(code.logicals.len(), 1);
    assert_eq!(code.stabilizers.len(), 2);

    let Definition::Gadget(gadget) = &ast.definitions[1].node else {
        panic!("expected GADGET");
    };
    assert_eq!(gadget.name, "PrepareZ");
    assert_eq!(gadget.body.len(), 3);
}

#[test]
fn code_without_distance() {
    let ast: DeqFile = "CODE C [[96,0]] {\n    STABILIZER X0*X1\n}\n".parse().unwrap();
    let Definition::Code(code) = &ast.definitions[0].node else {
        panic!("expected CODE");
    };
    assert_eq!((code.n, code.k, code.d), (96, 0, None));
}

#[test]
fn imports_are_collected() {
    let ast: DeqFile = "IMPORT \"code.deq\"\nGADGET G {\n    R 0\n}\n".parse().unwrap();
    assert_eq!(ast.imports, vec!["code.deq".to_string()]);
    assert_eq!(ast.definitions.len(), 1);
}

#[test]
fn decorators_attach_to_definition() {
    let ast: DeqFile = "@GTYPE(1)\n@CHECKS(\"syndrome\")\nGADGET G {\n    R 0\n}\n"
        .parse()
        .unwrap();
    let Definition::Gadget(gadget) = &ast.definitions[0].node else {
        panic!("expected GADGET");
    };
    assert_eq!(gadget.decorators.len(), 2);
    assert_eq!(gadget.decorators[0].name, "GTYPE");
    assert_eq!(
        gadget.decorators[0].arguments,
        vec![DecoratorArg::Value(DecoratorValue::Int(1))]
    );
    assert_eq!(
        gadget.decorators[1].arguments,
        vec![DecoratorArg::Value(DecoratorValue::String("syndrome".into()))]
    );
}

#[test]
fn check_and_detector_conflate() {
    let a: DeqFile = "GADGET G {\n    CHECK rec[-1]\n}\n".parse().unwrap();
    let b: DeqFile = "GADGET G {\n    DETECTOR rec[-1]\n}\n".parse().unwrap();
    assert_eq!(a, b);
    let Definition::Gadget(gadget) = &a.definitions[0].node else {
        panic!("expected GADGET");
    };
    assert_eq!(
        gadget.body[0],
        GadgetStatement::Check(CheckStatement {
            targets: vec![sp(Target::MeasurementRecord { offset: 1 })],
            flip: false,
        })
    );
}

#[test]
fn readout_and_observable_include_conflate() {
    let a: DeqFile = "GADGET G {\n    READOUT LX0 FLIP\n}\n".parse().unwrap();
    let b: DeqFile = "GADGET G {\n    OBSERVABLE_INCLUDE LX0 FLIP\n}\n".parse().unwrap();
    assert_eq!(a, b);
    let Definition::Gadget(gadget) = &a.definitions[0].node else {
        panic!("expected GADGET");
    };
    assert_eq!(
        gadget.body[0],
        GadgetStatement::Readout(ReadoutStatement {
            targets: vec![sp(ReadoutTargetItem::Logical(LogicalPauliTarget {
                pauli: Pauli::X,
                index: 0,
                port: None,
            }))],
            flip: true,
        })
    );
}

#[test]
fn propagate_targets() {
    let ast: DeqFile = "GADGET G {\n    PROPAGATE LX0 FROM LZ0 IN0.DS3 rec[-2] M4 R1 FLIP\n}\n"
        .parse()
        .unwrap();
    let Definition::Gadget(gadget) = &ast.definitions[0].node else {
        panic!("expected GADGET");
    };
    assert_eq!(
        gadget.body[0],
        GadgetStatement::Propagate(PropagateStatement {
            target: sp(LogicalPauliTarget {
                pauli: Pauli::X,
                index: 0,
                port: None
            }),
            terms: vec![
                sp(PropagateTerm::Logical(LogicalPauliTarget {
                    pauli: Pauli::Z,
                    index: 0,
                    port: None
                })),
                sp(PropagateTerm::Destabilizer { port: 0, stabilizer: 3 }),
                sp(PropagateTerm::MeasurementRecord { offset: 2 }),
                sp(PropagateTerm::PhysicalMeasurement { index: 4 }),
                sp(PropagateTerm::Readout { index: 1 }),
            ],
            flip: true,
        })
    );
}

#[test]
fn readout_with_destabilizer_target() {
    let ast: DeqFile = "GADGET G {\n    READOUT LX0 IN1.DS2\n}\n".parse().unwrap();
    let Definition::Gadget(gadget) = &ast.definitions[0].node else {
        panic!("expected GADGET");
    };
    assert_eq!(
        gadget.body[0],
        GadgetStatement::Readout(ReadoutStatement {
            targets: vec![
                sp(ReadoutTargetItem::Logical(LogicalPauliTarget {
                    pauli: Pauli::X,
                    index: 0,
                    port: None
                })),
                sp(ReadoutTargetItem::Destabilizer { port: 1, stabilizer: 2 }),
            ],
            flip: false,
        })
    );
}

#[test]
fn conditional_correction_in_program_and_compose() {
    let ast: DeqFile = "\
COMPOSE C {
    CONDITIONAL rec[-1] X0*Y1 2
}

PROGRAM P {
    CONDITIONAL rec[-3] Z0 4
}
"
    .parse()
    .unwrap();

    let Definition::Compose(compose) = &ast.definitions[0].node else {
        panic!("expected COMPOSE");
    };
    assert_eq!(
        compose.body[0],
        ComposeStatement::ConditionalCorrection(ConditionalCorrection {
            readout_offset: 1,
            paulis: vec![(Pauli::X, 0), (Pauli::Y, 1)],
            wire: 2,
        })
    );

    let Definition::Program(program) = &ast.definitions[1].node else {
        panic!("expected PROGRAM");
    };
    assert_eq!(
        program.body[0],
        ProgramStatement::ConditionalCorrection(ConditionalCorrection {
            readout_offset: 3,
            paulis: vec![(Pauli::Z, 0)],
            wire: 4,
        })
    );
}

#[test]
fn port_scoped_logical() {
    let ast: DeqFile = "GADGET G {\n    VIRTUAL IN0.LX1 OUT2.LZ3\n}\n".parse().unwrap();
    let Definition::Gadget(gadget) = &ast.definitions[0].node else {
        panic!("expected GADGET");
    };
    assert_eq!(
        gadget.body[0],
        GadgetStatement::VirtualLogical(VirtualLogicalStatement {
            targets: vec![
                sp(LogicalPauliTarget {
                    pauli: Pauli::X,
                    index: 1,
                    port: Some(Port {
                        kind: PortKind::In,
                        index: 0
                    }),
                }),
                sp(LogicalPauliTarget {
                    pauli: Pauli::Z,
                    index: 3,
                    port: Some(Port {
                        kind: PortKind::Out,
                        index: 2
                    }),
                }),
            ],
        })
    );
}

#[test]
fn gadget_application_forms() {
    let ast: DeqFile = "\
COMPOSE C {
    Idle IN(0 1) OUT(2 3)
    Setup ()
    Shortcut 0 1
}
"
    .parse()
    .unwrap();
    let Definition::Compose(compose) = &ast.definitions[0].node else {
        panic!("expected COMPOSE");
    };
    assert_eq!(
        compose.body[0],
        ComposeStatement::GadgetApplication(GadgetApplication {
            gadget_name: sp("Idle".to_string()),
            in_indices: Some(vec![0, 1]),
            out_indices: Some(vec![2, 3]),
        })
    );
    assert_eq!(
        compose.body[1],
        ComposeStatement::GadgetApplication(GadgetApplication {
            gadget_name: sp("Setup".to_string()),
            in_indices: None,
            out_indices: None,
        })
    );
    // Shortcut form parses as a plain instruction.
    assert!(matches!(compose.body[2].node, ComposeStatement::Instruction(_)));
}

#[test]
fn pauli_products_with_combiners_and_identity() {
    let ast: DeqFile = "GADGET G {\n    MPP X1*Z2 !Y3\n}\n".parse().unwrap();
    let Definition::Gadget(gadget) = &ast.definitions[0].node else {
        panic!("expected GADGET");
    };
    let GadgetStatement::Instruction(instr) = &gadget.body[0].node else {
        panic!("expected instruction");
    };
    assert_eq!(instr.name, "MPP");
    assert_eq!(
        instr.targets,
        vec![
            sp(Target::Pauli {
                inverted: false,
                pauli: Pauli::X,
                index: 1
            }),
            sp(Target::Combiner),
            sp(Target::Pauli {
                inverted: false,
                pauli: Pauli::Z,
                index: 2
            }),
            sp(Target::Pauli {
                inverted: true,
                pauli: Pauli::Y,
                index: 3
            }),
        ]
    );
}

#[test]
fn identity_pauli_product() {
    let ast: DeqFile = "CODE C [[1,1]] {\n    LOGICAL _ Z0\n}\n".parse().unwrap();
    let Definition::Code(code) = &ast.definitions[0].node else {
        panic!("expected CODE");
    };
    assert_eq!(code.logicals[0].x_operator, PauliProduct::Identity);
}

// ── Roundtrip tests ──────────────────────────────────────────────────

#[test]
fn roundtrip_full_program() {
    assert_roundtrip(
        "\
IMPORT \"code.deq\"

CODE RepetitionCode [[3,1,1]] {
    LOGICAL X0*X1*X2 Z0*Z1*Z2
    STABILIZER Z0*Z1 Z1*Z2
}

@GTYPE(1)
@CHECKS(\"syndrome\")
GADGET Idle {
    INPUT RepetitionCode 0 2 4
    X_ERROR(0.03) 0 2 4
    R 1 3
    CX 0 1 2 3
    M(0.03) 1 3
    CHECK rec[-1] rec[-2] FLIP
    READOUT LX0
    ERROR(0.001) C0 R1 LX0
    CONDITIONAL R0 LZ0 LX1
    CONDITIONAL rec[-1] LZ0
    PRESELECT rec[-1] 0
    PROPAGATE LX0 FROM LZ0 IN0.DS3 rec[-2] FLIP
    VIRTUAL LZ0 OUT1.LX2
    OUTPUT RepetitionCode 0 2 4
}

COMPOSE Round {
    INPUT RepetitionCode 0 1 2
    Idle IN(0 1 2) OUT(0 1 2)
    Idle 0
    REPEAT 5 {
        Idle IN(0 1 2) OUT(0 1 2)
    }
    OUTPUT RepetitionCode 0 1 2
}

PROGRAM Simulation {
    PrepareZ 0
    Round IN(0 1 2) OUT(0 1 2)
    VIRTUAL X0*Y1 3
    ASSERT_EQ rec[-1] 0
}
",
    );
}

#[test]
fn roundtrip_tags_and_sweep() {
    assert_roundtrip("GADGET G {\n    TICK[hello\\Cworld\\n]\n    CX sweep[5] 1\n}\n");
}

#[test]
fn assert_eq_preserves_all_targets_and_spans() {
    let source = "PROGRAM P { ASSERT_EQ rec[-3] rec[-2] rec[-1] 1 }";
    let ast: DeqFile = source.parse().unwrap();
    let Definition::Program(program) = &ast.definitions[0].node else {
        panic!("expected PROGRAM");
    };
    let ProgramStatement::Assert(assertion) = &program.body[0].node else {
        panic!("expected ASSERT_EQ");
    };
    assert_eq!(
        assertion.targets,
        vec![
            sp(Target::MeasurementRecord { offset: 3 }),
            sp(Target::MeasurementRecord { offset: 2 }),
            sp(Target::MeasurementRecord { offset: 1 }),
            sp(Target::Qubit {
                inverted: false,
                index: 1,
            }),
        ]
    );
    for target in &assertion.targets {
        assert_eq!(&source[target.span.start..target.span.end], target.to_string());
    }
}

#[test]
fn roundtrip_assert_eq_parities() {
    for terms in [
        "rec[-1] 0",
        "rec[-1] 1",
        "rec[-3] rec[-2] rec[-1] 1",
        "rec[-2] rec[-1]",
        "rec[-1]",
        "1 rec[-2] 0 rec[-1] 1",
        "rec[-1] rec[-1]",
        "0",
        "1 1",
    ] {
        assert_roundtrip(&format!("PROGRAM P {{ ASSERT_EQ {terms} }}"));
    }
    assert!("PROGRAM P { ASSERT_EQ }".parse::<DeqFile>().is_err());
}

#[test]
fn roundtrip_preselect_forms() {
    // Default parity (no trailing bit): Display emits an explicit ` 0`, which
    // must re-parse to the same AST (expected_value == 0).
    assert_roundtrip("GADGET G {\n    M 0\n    PRESELECT rec[-1]\n}\n");
    // Multiple physical targets, default and explicit parity.
    assert_roundtrip("GADGET G {\n    M 0 1\n    PRESELECT rec[-1] rec[-2]\n}\n");
    assert_roundtrip("GADGET G {\n    M 0 1\n    PRESELECT rec[-1] rec[-2] 1\n}\n");
    // Absolute physical measurement form.
    assert_roundtrip("GADGET G {\n    M 0\n    PRESELECT M0 1\n}\n");
}

#[test]
fn roundtrip_correlated_error_chain() {
    assert_roundtrip("GADGET G {\n    CORRELATED_ERROR(0.2) Z17\n    ELSE_CORRELATED_ERROR(0.25) Z158\n}\n");
    assert_roundtrip(
        "GADGET G {\n    CORRELATED_ERROR(0.1) L0\n    ELSE_CORRELATED_ERROR(0.2) L1\n    ELSE_CORRELATED_ERROR(0.3) L0 L1\n    E(0.1) X2 L3\n}\n",
    );
}

#[test]
fn roundtrip_decorator_keyword_args() {
    assert_roundtrip("@TWEAK(level=\"high\", scale=2.5, count=3)\nGADGET G {\n    R 0\n}\n");
}

#[test]
fn decorator_string_escapes_are_decoded() {
    let ast: DeqFile = "@label(\"hello\\nworld\")\nGADGET G {\n    R 0\n}\n".parse().unwrap();
    let Definition::Gadget(gadget) = &ast.definitions[0].node else {
        panic!("expected GADGET");
    };
    assert_eq!(
        gadget.decorators[0].arguments,
        vec![DecoratorArg::Value(DecoratorValue::String("hello\nworld".to_string()))]
    );
    // The decoded newline must re-encode so the value round-trips.
    assert_roundtrip("@label(\"hello\\nworld\")\nGADGET G {\n    R 0\n}\n");
}

#[test]
fn import_string_escapes_are_decoded() {
    let ast: DeqFile = "IMPORT \"a\\tb.deq\"\n".parse().unwrap();
    assert_eq!(ast.imports, vec!["a\tb.deq".to_string()]);
    assert_roundtrip("IMPORT \"a\\tb.deq\"\n");
}

#[test]
fn roundtrip_integral_decorator_float() {
    // `2.0` must not collapse to `2` (which would re-parse as an Int).
    let ast: DeqFile = "@A(2.0)\nGADGET G {\n    R 0\n}\n".parse().unwrap();
    let Definition::Gadget(gadget) = &ast.definitions[0].node else {
        panic!("expected GADGET");
    };
    assert_eq!(
        gadget.decorators[0].arguments,
        vec![DecoratorArg::Value(DecoratorValue::Float(2.0))]
    );
    assert_roundtrip("@A(2.0)\nGADGET G {\n    R 0\n}\n");
}

#[test]
fn roundtrip_code_surgery_constructs() {
    assert_roundtrip(
        "\
GADGET G {
    READOUT LX0 IN0.DS1
    PROPAGATE LZ0 FROM IN0.DS0 R2 rec[-1] FLIP
}

COMPOSE C {
    CONDITIONAL rec[-2] X0*Z1 3
}

PROGRAM P {
    CONDITIONAL rec[-1] Y0 0
}
",
    );
}

#[test]
fn multiline_string_is_rejected() {
    assert!("IMPORT \"a\nb\"\n".parse::<DeqFile>().is_err());
}

// ── Error reporting (numeric out-of-range / non-finite) ──────────────

/// Parses `input`, expecting an `Err` whose rendered message contains `substr`.
/// Crucially, this must be a returned error — never a panic.
fn assert_error_contains(input: &str, substr: &str) {
    let err = input.parse::<DeqFile>().expect_err("expected a parse error");
    let rendered = err.to_string();
    assert!(
        rendered.contains(substr),
        "error did not mention {substr:?}:\n{rendered}"
    );
}

#[test]
fn oversized_qubit_index_errors_not_panics() {
    assert_error_contains("GADGET G {\n    R 99999999999999999999\n}\n", "integer out of range");
}

#[test]
fn oversized_decorator_int_errors() {
    assert_error_contains(
        "@A(99999999999999999999999)\nGADGET G {\n    R 0\n}\n",
        "integer out of range",
    );
}

#[test]
fn non_finite_instruction_argument_errors() {
    assert_error_contains("GADGET G {\n    X_ERROR(1e999) 0\n}\n", "finite");
}

#[test]
fn out_of_domain_values_error() {
    for (source, substr) in [
        ("CODE C [[0,0]] {\n}\n", "parameter n must be >= 1"),
        ("CODE C [[2,3]] {\n}\n", "parameter k (3) must be <= n (2)"),
        ("CODE C [[1,0,0]] {\n}\n", "parameter d must be >= 1"),
        ("CODE C [[1,1]] {\n}\n", "has 0 LOGICAL declaration(s); expected 1"),
        (
            "GADGET G {\n    ERROR(1.5) C0\n}\n",
            "ERROR probability must be in [0, 1]",
        ),
        ("GADGET G {\n    LOSS(0) M0\n}\n", "LOSS probability must be in (0, 1]"),
        ("GADGET G {\n    LOSS(IN0.L0) SE0\n}\n", "must not carry source-error"),
        (
            "GADGET G {\n    PRESELECT rec[-1] 2\n}\n",
            "expected parity must be 0 or 1",
        ),
        ("GADGET G {\n    REPEAT 0 {\n    }\n}\n", "REPEAT count must be >= 1"),
        ("COMPOSE C {\n    REPEAT 0 {\n    }\n}\n", "REPEAT count must be >= 1"),
        ("PROGRAM P {\n    REPEAT 0 {\n    }\n}\n", "REPEAT count must be >= 1"),
    ] {
        assert_error_contains(source, substr);
    }
}

#[test]
fn error_message_carries_line_and_column() {
    // The span-anchored pest formatting includes a `line:col` locator.
    assert_error_contains("GADGET G {\n    R 99999999999999999999\n}\n", "2:7");
}

// ── Source spans (G2) ────────────────────────────────────────────────

#[test]
fn spans_point_at_the_right_bytes() {
    let src = "GADGET G {\n    R 3 5\n}\n";
    let ast: DeqFile = src.parse().unwrap();

    // The gadget definition spans from `GADGET` to its closing brace.
    let def = &ast.definitions[0];
    assert_eq!(&src[def.span.start..def.span.end], src.trim_end());

    let Definition::Gadget(gadget) = &def.node else {
        panic!("expected GADGET");
    };
    // The `R 3 5` instruction statement.
    let stmt = &gadget.body[0];
    assert_eq!(&src[stmt.span.start..stmt.span.end], "R 3 5");

    let GadgetStatement::Instruction(instr) = &stmt.node else {
        panic!("expected instruction");
    };
    // Each target carries its own span.
    assert_eq!(&src[instr.targets[0].span.start..instr.targets[0].span.end], "3");
    assert_eq!(&src[instr.targets[1].span.start..instr.targets[1].span.end], "5");
    // line/col resolves against the source.
    assert_eq!(instr.targets[1].span.line_col(src), Some((2, 9)));
}

#[test]
fn spans_ignored_by_equality() {
    // Two sources that differ only in whitespace produce equal ASTs despite
    // carrying different byte offsets.
    let a: DeqFile = "GADGET G {\n    R 0\n}\n".parse().unwrap();
    let b: DeqFile = "GADGET G {  R 0  }\n".parse().unwrap();
    assert_eq!(a, b);
}