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
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
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
//! Typed AST for the DEQ file format, mirroring deqagram's Python dataclasses.
//!
//! Every construct parses from a string via [`FromStr`] and serializes back via
//! [`Display`](std::fmt::Display). Roundtrip fidelity holds at the AST level: parsing a file,
//! displaying it, and re-parsing yields the same AST. Because the format is
//! whitespace- and newline-insensitive, `Display` reformats canonically rather
//! than reproducing the original bytes; comments are not retained.
//!
//! `CHECK`/`DETECTOR` and `READOUT`/`OBSERVABLE_INCLUDE` are spelling aliases
//! rather than distinct constructs, so each pair is conflated into a single node
//! kind ([`CheckStatement`] / [`ReadoutStatement`]); `Display` emits the
//! canonical `CHECK` / `READOUT` spelling.
//!
//! The parser guarantees `count >= 1` for the `Repeat` variant of
//! [`GadgetStatement`], [`ComposeStatement`], and [`ProgramStatement`].

use std::fmt;
use std::str::FromStr;

use pest::Parser;
use pest::iterators::Pair;

use super::{DeqParser, ParseError, Rule, Span, Spanned};
use crate::common::{decode_string, decode_tag, encode_string, encode_tag, write_separated};

// ── Pauli letters ────────────────────────────────────────────────────

/// A Pauli letter. `I` only appears in `PAULI_TERM` positions (`CODE`
/// operators); operator positions (`LX0`, `X1`, ...) are always `X`/`Y`/`Z`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pauli {
    I,
    X,
    Y,
    Z,
}

impl Pauli {
    fn from_char(c: char) -> Self {
        match c {
            'I' => Self::I,
            'X' => Self::X,
            'Y' => Self::Y,
            'Z' => Self::Z,
            _ => unreachable!("grammar guarantees a Pauli letter, got {c:?}"),
        }
    }
}

impl fmt::Display for Pauli {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::I => "I",
            Self::X => "X",
            Self::Y => "Y",
            Self::Z => "Z",
        })
    }
}

// ── Stim-level targets ───────────────────────────────────────────────

/// A target of an embedded Stim instruction, `CHECK`, or `ASSERT_EQ`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
    Qubit { inverted: bool, index: u64 },
    Loss { index: u64 },
    Pauli { inverted: bool, pauli: Pauli, index: u64 },
    MeasurementRecord { offset: u64 },
    PhysicalMeasurement { index: u64 },
    InputVirtual { port: u64, stabilizer: u64 },
    OutputVirtual { port: u64, stabilizer: u64 },
    SweepBit { index: u64 },
    Combiner,
}

impl fmt::Display for Target {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Qubit { inverted, index } => {
                write!(f, "{}{index}", if *inverted { "!" } else { "" })
            }
            Self::Pauli { inverted, pauli, index } => write!(f, "{}{pauli}{index}", if *inverted { "!" } else { "" }),
            Self::Loss { index } => write!(f, "L{index}"),
            Self::MeasurementRecord { offset } => write!(f, "rec[-{offset}]"),
            Self::PhysicalMeasurement { index } => write!(f, "M{index}"),
            Self::InputVirtual { port, stabilizer } => write!(f, "IN{port}.S{stabilizer}"),
            Self::OutputVirtual { port, stabilizer } => write!(f, "OUT{port}.S{stabilizer}"),
            Self::SweepBit { index } => write!(f, "sweep[{index}]"),
            Self::Combiner => f.write_str("*"),
        }
    }
}

/// A logical Pauli operator: `LX0`, or port-scoped `IN0.LX0` / `OUT1.LZ2`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LogicalPauliTarget {
    pub pauli: Pauli,
    pub index: u64,
    pub port: Option<Port>,
}

/// The `IN`/`OUT` side and index of a port-scoped target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Port {
    pub kind: PortKind,
    pub index: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PortKind {
    In,
    Out,
}

impl fmt::Display for PortKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::In => "IN",
            Self::Out => "OUT",
        })
    }
}

impl fmt::Display for LogicalPauliTarget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(port) = self.port {
            write!(f, "{}{}.L{}{}", port.kind, port.index, self.pauli, self.index)
        } else {
            write!(f, "L{}{}", self.pauli, self.index)
        }
    }
}

/// A measurement reference usable in `CONDITIONAL` / `PRESELECT` conditions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MeasurementRef {
    Record { offset: u64 },
    Physical { index: u64 },
    InputVirtual { port: u64, stabilizer: u64 },
    OutputVirtual { port: u64, stabilizer: u64 },
}

impl fmt::Display for MeasurementRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Record { offset } => write!(f, "rec[-{offset}]"),
            Self::Physical { index } => write!(f, "M{index}"),
            Self::InputVirtual { port, stabilizer } => {
                write!(f, "IN{port}.S{stabilizer}")
            }
            Self::OutputVirtual { port, stabilizer } => {
                write!(f, "OUT{port}.S{stabilizer}")
            }
        }
    }
}

// ── Statement-specific target sets ───────────────────────────────────

/// An item of a `READOUT` statement: a Stim target, a logical Pauli, or an
/// INPUT-port destabilizer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReadoutTargetItem {
    Target(Target),
    Logical(LogicalPauliTarget),
    Destabilizer { port: u64, stabilizer: u64 },
}

impl fmt::Display for ReadoutTargetItem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Target(t) => write!(f, "{t}"),
            Self::Logical(l) => write!(f, "{l}"),
            Self::Destabilizer { port, stabilizer } => {
                write!(f, "IN{port}.DS{stabilizer}")
            }
        }
    }
}

/// A target of an `ERROR` statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorTarget {
    Check(u64),
    Readout(u64),
    Logical(LogicalPauliTarget),
}

impl fmt::Display for ErrorTarget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Check(i) => write!(f, "C{i}"),
            Self::Readout(i) => write!(f, "R{i}"),
            Self::Logical(l) => write!(f, "{l}"),
        }
    }
}

/// A term after `FROM` in a `PROPAGATE` statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PropagateTerm {
    Logical(LogicalPauliTarget),
    Destabilizer { port: u64, stabilizer: u64 },
    MeasurementRecord { offset: u64 },
    PhysicalMeasurement { index: u64 },
    Readout { index: u64 },
}

impl fmt::Display for PropagateTerm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Logical(l) => write!(f, "{l}"),
            Self::Destabilizer { port, stabilizer } => {
                write!(f, "IN{port}.DS{stabilizer}")
            }
            Self::MeasurementRecord { offset } => write!(f, "rec[-{offset}]"),
            Self::PhysicalMeasurement { index } => write!(f, "M{index}"),
            Self::Readout { index } => write!(f, "R{index}"),
        }
    }
}

// ── Decorators ───────────────────────────────────────────────────────

/// A decorator value: a string literal (stored without surrounding quotes),
/// an integer, or a float.
#[derive(Debug, Clone, PartialEq)]
pub enum DecoratorValue {
    String(String),
    Int(i64),
    Float(f64),
}

impl fmt::Display for DecoratorValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::String(s) => write!(f, "\"{}\"", encode_string(s)),
            Self::Int(i) => write!(f, "{i}"),
            // Force a decimal point so an integral float (e.g. `1.0`) does not
            // re-parse as a `DecoratorValue::Int`, which would break roundtrip.
            Self::Float(x) => {
                let s = x.to_string();
                if s.bytes().all(|b| b.is_ascii_digit() || b == b'-') {
                    write!(f, "{s}.0")
                } else {
                    f.write_str(&s)
                }
            }
        }
    }
}

/// A decorator argument: either a positional value or a `key=value` pair.
#[derive(Debug, Clone, PartialEq)]
pub enum DecoratorArg {
    Value(DecoratorValue),
    Keyword { key: String, value: DecoratorValue },
}

impl fmt::Display for DecoratorArg {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Value(v) => write!(f, "{v}"),
            Self::Keyword { key, value } => write!(f, "{key}={value}"),
        }
    }
}

/// A decorator like `@GTYPE(1)` or `@CHECKS("syndrome")`. `name` excludes `@`.
#[derive(Debug, Clone, PartialEq)]
pub struct Decorator {
    pub name: String,
    pub arguments: Vec<DecoratorArg>,
}

impl fmt::Display for Decorator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "@{}", self.name)?;
        if !self.arguments.is_empty() {
            write!(f, "(")?;
            write_separated(f, &self.arguments, ", ")?;
            write!(f, ")")?;
        }
        Ok(())
    }
}

// ── Embedded Stim instruction ────────────────────────────────────────

/// An embedded Stim instruction, e.g. `X_ERROR(0.03) 0 1 2` or `MPP X1 * Z2`.
#[derive(Debug, Clone, PartialEq)]
pub struct Instruction {
    pub name: String,
    pub tag: Option<String>,
    pub arguments: Vec<f64>,
    pub targets: Vec<Spanned<Target>>,
}

impl fmt::Display for Instruction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.name, encode_tag(self.tag.as_deref()))?;
        if !self.arguments.is_empty() {
            write!(f, "(")?;
            write_separated(f, &self.arguments, ", ")?;
            write!(f, ")")?;
        }
        for target in &self.targets {
            write!(f, " {target}")?;
        }
        Ok(())
    }
}

// ── Pauli products (CODE) ────────────────────────────────────────────

/// A single Pauli term on a qubit, e.g. `Z0` or `X3`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PauliTerm {
    pub pauli: Pauli,
    pub index: u64,
}

impl fmt::Display for PauliTerm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.pauli, self.index)
    }
}

/// A product of Pauli terms (`Z0*Z1*Z2`) or the identity (`_`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PauliProduct {
    Identity,
    Terms(Vec<PauliTerm>),
}

impl fmt::Display for PauliProduct {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Identity => f.write_str("_"),
            Self::Terms(terms) => write_separated(f, terms, "*"),
        }
    }
}

// ── Ports and gadget application ─────────────────────────────────────

/// An `INPUT`/`OUTPUT CodeName qubit_indices...` port declaration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortDeclaration {
    pub code_name: Spanned<String>,
    pub qubit_indices: Vec<u64>,
}

/// A gadget application with explicit port bindings, e.g. `Idle IN(0 1) OUT(0 1)`
/// or the empty `Name ()`. The shortcut form (`Name integer+`) parses as an
/// [`Instruction`] instead, matching deq.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GadgetApplication {
    pub gadget_name: Spanned<String>,
    pub in_indices: Option<Vec<u64>>,
    pub out_indices: Option<Vec<u64>>,
}

impl fmt::Display for GadgetApplication {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.gadget_name)?;
        if let Some(indices) = &self.in_indices {
            write!(f, " IN(")?;
            write_separated(f, indices, " ")?;
            write!(f, ")")?;
        }
        if let Some(indices) = &self.out_indices {
            write!(f, " OUT(")?;
            write_separated(f, indices, " ")?;
            write!(f, ")")?;
        }
        if self.in_indices.is_none() && self.out_indices.is_none() {
            write!(f, " ()")?;
        }
        Ok(())
    }
}

// ── GADGET-only statements ───────────────────────────────────────────

/// A `READOUT`/`OBSERVABLE_INCLUDE targets... [FLIP]` statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReadoutStatement {
    pub targets: Vec<Spanned<ReadoutTargetItem>>,
    pub flip: bool,
}

impl fmt::Display for ReadoutStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "READOUT ")?;
        write_separated(f, &self.targets, " ")?;
        if self.flip {
            write!(f, " FLIP")?;
        }
        Ok(())
    }
}

/// A `CHECK`/`DETECTOR targets... [FLIP]` statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckStatement {
    pub targets: Vec<Spanned<Target>>,
    pub flip: bool,
}

impl fmt::Display for CheckStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "CHECK ")?;
        write_separated(f, &self.targets, " ")?;
        if self.flip {
            write!(f, " FLIP")?;
        }
        Ok(())
    }
}

/// An `ERROR(p) targets...` statement. The parser guarantees `0 <= p <= 1`.
#[derive(Debug, Clone, PartialEq)]
pub struct ErrorStatement {
    pub probability: f64,
    pub targets: Vec<Spanned<ErrorTarget>>,
}

impl fmt::Display for ErrorStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ERROR({}) ", self.probability)?;
        write_separated(f, &self.targets, " ")
    }
}

/// The condition of a `CONDITIONAL` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Condition {
    Readout(u64),
    Measurement(MeasurementRef),
}

impl fmt::Display for Condition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Readout(i) => write!(f, "R{i}"),
            Self::Measurement(m) => write!(f, "{m}"),
        }
    }
}

/// A `CONDITIONAL condition L<P><i>...` statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConditionalStatement {
    pub condition: Condition,
    pub targets: Vec<Spanned<LogicalPauliTarget>>,
}

impl fmt::Display for ConditionalStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "CONDITIONAL {} ", self.condition)?;
        write_separated(f, &self.targets, " ")
    }
}

/// A `VIRTUAL L<P><i>...` logical-correction statement (inside a GADGET).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VirtualLogicalStatement {
    pub targets: Vec<Spanned<LogicalPauliTarget>>,
}

impl fmt::Display for VirtualLogicalStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "VIRTUAL ")?;
        write_separated(f, &self.targets, " ")
    }
}

/// A `PROPAGATE L<P><i> FROM terms... [FLIP]` statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PropagateStatement {
    pub target: Spanned<LogicalPauliTarget>,
    pub terms: Vec<Spanned<PropagateTerm>>,
    pub flip: bool,
}

impl fmt::Display for PropagateStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "PROPAGATE {} FROM", self.target)?;
        for term in &self.terms {
            write!(f, " {term}")?;
        }
        if self.flip {
            write!(f, " FLIP")?;
        }
        Ok(())
    }
}

/// A `PRESELECT <target>+ [<bit>]` statement. Each target is a concrete
/// physical measurement (`rec[-k]` or `M<i>`); the trailing parity bit is
/// optional, defaults to 0, and must be 0 or 1.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreselectStatement {
    pub conditions: Vec<MeasurementRef>,
    pub expected_value: u64,
}

impl fmt::Display for PreselectStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "PRESELECT")?;
        for condition in &self.conditions {
            write!(f, " {condition}")?;
        }
        write!(f, " {}", self.expected_value)
    }
}

/// A `LOSS(...)` statement mirroring one JIT loss-model entry.
///
/// A *source* loss (`LOSS(p) ...`) carries the declared `LOSS_ERROR`
/// probability, `0 < p <= 1`. An *input* loss (`LOSS(IN<i>.L<j>) ...`) is the
/// continuation of a loss entering on input physical qubit `input_qubit` of
/// input port `input_port`; it carries no probability and no `source_errors`.
/// `source_errors` / `continuation_errors`
/// index the gadget's `ERROR` mechanisms, `child_losses` index the source losses
/// (within-gadget children), `output_qubits` are `(port, qubit)` physical exits,
/// and `measurement_indices` are herald measurements.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct LossStatement {
    pub probability: Option<f64>,
    pub input_port: Option<u64>,
    pub input_qubit: Option<u64>,
    pub source_errors: Vec<u64>,
    pub continuation_errors: Vec<u64>,
    pub child_losses: Vec<u64>,
    pub output_qubits: Vec<(u64, u64)>,
    pub measurement_indices: Vec<u64>,
}

impl fmt::Display for LossStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (self.input_port, self.input_qubit) {
            (Some(port), Some(qubit)) => write!(f, "LOSS(IN{port}.L{qubit})")?,
            _ => write!(f, "LOSS({})", self.probability.unwrap_or(0.0))?,
        }
        for index in &self.source_errors {
            write!(f, " SE{index}")?;
        }
        for index in &self.continuation_errors {
            write!(f, " CE{index}")?;
        }
        for index in &self.child_losses {
            write!(f, " L{index}")?;
        }
        for (port, qubit) in &self.output_qubits {
            write!(f, " OUT{port}.L{qubit}")?;
        }
        for index in &self.measurement_indices {
            write!(f, " M{index}")?;
        }
        Ok(())
    }
}

// ── PROGRAM-only statements ──────────────────────────────────────────

/// An `ASSERT_EQ targets...` statement asserting that the XOR of its values is zero.
///
/// PROGRAM interpretation accepts logical readout records and literal bits.
/// Literal bits use the shared target syntax (`Target::Qubit` with index 0 or 1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssertStatement {
    pub targets: Vec<Spanned<Target>>,
}

impl fmt::Display for AssertStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ASSERT_EQ ")?;
        write_separated(f, &self.targets, " ")
    }
}

/// A `VIRTUAL X0*Y1 wire` Pauli-correction statement (inside a PROGRAM).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VirtualCorrection {
    pub paulis: Vec<(Pauli, u64)>,
    pub wire: u64,
}

impl fmt::Display for VirtualCorrection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "VIRTUAL ")?;
        for (i, (pauli, index)) in self.paulis.iter().enumerate() {
            if i > 0 {
                write!(f, "*")?;
            }
            write!(f, "{pauli}{index}")?;
        }
        write!(f, " {}", self.wire)
    }
}

/// A `CONDITIONAL rec[-k] X0*Y1 wire` conditional Pauli-correction statement.
///
/// Valid inside a COMPOSE or PROGRAM. Applies the logical Pauli product to
/// `wire` conditioned on the `readout_offset`-th most recent logical readout.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConditionalCorrection {
    pub readout_offset: u64,
    pub paulis: Vec<(Pauli, u64)>,
    pub wire: u64,
}

impl fmt::Display for ConditionalCorrection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "CONDITIONAL rec[-{}] ", self.readout_offset)?;
        for (i, (pauli, index)) in self.paulis.iter().enumerate() {
            if i > 0 {
                write!(f, "*")?;
            }
            write!(f, "{pauli}{index}")?;
        }
        write!(f, " {}", self.wire)
    }
}

// ── Body statements (per definition kind) ────────────────────────────

/// A statement inside a `GADGET` body.
#[derive(Debug, Clone, PartialEq)]
pub enum GadgetStatement {
    Instruction(Instruction),
    Repeat { count: u64, body: Vec<Spanned<Self>> },
    InputPort(PortDeclaration),
    OutputPort(PortDeclaration),
    Readout(ReadoutStatement),
    Check(CheckStatement),
    Error(ErrorStatement),
    Conditional(ConditionalStatement),
    VirtualLogical(VirtualLogicalStatement),
    Propagate(PropagateStatement),
    Preselect(PreselectStatement),
    Loss(LossStatement),
    Decorator(Decorator),
}

/// A statement inside a `COMPOSE` body.
#[derive(Debug, Clone, PartialEq)]
pub enum ComposeStatement {
    Instruction(Instruction),
    Repeat { count: u64, body: Vec<Spanned<Self>> },
    InputPort(PortDeclaration),
    OutputPort(PortDeclaration),
    GadgetApplication(GadgetApplication),
    ConditionalCorrection(ConditionalCorrection),
    Decorator(Decorator),
}

/// A statement inside a `PROGRAM` body.
#[derive(Debug, Clone, PartialEq)]
pub enum ProgramStatement {
    Instruction(Instruction),
    Repeat { count: u64, body: Vec<Spanned<Self>> },
    InputPort(PortDeclaration),
    OutputPort(PortDeclaration),
    GadgetApplication(GadgetApplication),
    Assert(AssertStatement),
    VirtualCorrection(VirtualCorrection),
    ConditionalCorrection(ConditionalCorrection),
    Decorator(Decorator),
}

// ── Definitions ──────────────────────────────────────────────────────

/// A pair of X and Z logical operators for one logical qubit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogicalOperator {
    pub x_operator: Spanned<PauliProduct>,
    pub z_operator: Spanned<PauliProduct>,
}

/// A `CODE Name [[n,k,d]] { ... }` definition.
///
/// The parser guarantees `n >= 1`, `k <= n`, `d >= 1` when present, and exactly
/// `k` `LOGICAL` declarations.
#[derive(Debug, Clone, PartialEq)]
pub struct CodeDefinition {
    pub name: String,
    pub n: u64,
    pub k: u64,
    pub d: Option<u64>,
    pub logicals: Vec<LogicalOperator>,
    pub stabilizers: Vec<Spanned<PauliProduct>>,
    pub decorators: Vec<Decorator>,
}

/// A `GADGET Name { ... }` definition.
#[derive(Debug, Clone, PartialEq)]
pub struct GadgetDefinition {
    pub name: String,
    pub body: Vec<Spanned<GadgetStatement>>,
    pub decorators: Vec<Decorator>,
}

/// A `COMPOSE Name { ... }` definition.
#[derive(Debug, Clone, PartialEq)]
pub struct ComposeDefinition {
    pub name: String,
    pub body: Vec<Spanned<ComposeStatement>>,
    pub decorators: Vec<Decorator>,
}

/// A `PROGRAM Name { ... }` definition.
#[derive(Debug, Clone, PartialEq)]
pub struct ProgramDefinition {
    pub name: String,
    pub body: Vec<Spanned<ProgramStatement>>,
    pub decorators: Vec<Decorator>,
}

/// A top-level definition.
#[derive(Debug, Clone, PartialEq)]
pub enum Definition {
    Code(CodeDefinition),
    Gadget(GadgetDefinition),
    Compose(ComposeDefinition),
    Program(ProgramDefinition),
}

/// A complete `.deq` file: imports followed by definitions.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct DeqFile {
    pub imports: Vec<String>,
    pub definitions: Vec<Spanned<Definition>>,
}

// ── Parsing helpers ──────────────────────────────────────────────────

/// Captures a pair's source span as an owned [`Span`].
fn span_of(pair: &Pair<Rule>) -> Span {
    pair.as_span().into()
}

/// Convenience methods over pest [`Pair`]s, cutting boilerplate that recurs
/// across the parser.
trait PairExt<'i> {
    /// The single inner pair. Grammar rules that wrap exactly one child (most of
    /// them) guarantee this; like the `unreachable!` arms, it trusts the grammar.
    fn only(self) -> Pair<'i, Rule>;

    /// Parses `self` with `f`, pairing the result with `self`'s source span.
    fn spanned<T>(self, f: impl FnOnce(Pair<'i, Rule>) -> Result<T, ParseError>) -> Result<Spanned<T>, ParseError>;
}

impl<'i> PairExt<'i> for Pair<'i, Rule> {
    fn only(self) -> Pair<'i, Rule> {
        self.into_inner().next().unwrap()
    }

    fn spanned<T>(self, f: impl FnOnce(Pair<'i, Rule>) -> Result<T, ParseError>) -> Result<Spanned<T>, ParseError> {
        let span = span_of(&self);
        Ok(Spanned::new(f(self)?, span))
    }
}

/// Parses the whole text of `pair` as a `u64`, reporting an out-of-range error
/// anchored at the pair's span.
fn int_u64(pair: &Pair<Rule>) -> Result<u64, ParseError> {
    sub_u64(pair, pair.as_str())
}

/// Parses `text` — a numeric substring of `pair` — as a `u64`. Errors point at
/// the whole `pair` span.
fn sub_u64(pair: &Pair<Rule>, text: &str) -> Result<u64, ParseError> {
    text.parse()
        .map_err(|_| ParseError::at_span(pair.as_span(), format!("integer out of range (0..={})", u64::MAX)))
}

/// Parses `text` — a numeric substring of `pair` — as an `i64`.
fn sub_i64(pair: &Pair<Rule>, text: &str) -> Result<i64, ParseError> {
    text.parse().map_err(|_| {
        ParseError::at_span(
            pair.as_span(),
            format!("integer out of range ({}..={})", i64::MIN, i64::MAX),
        )
    })
}

/// Parses `text` — a numeric substring of `pair` — as a finite `f64`. A literal
/// that overflows to infinity (or parses to NaN) is rejected, since it would not
/// round-trip through `Display`.
fn sub_f64(pair: &Pair<Rule>, text: &str) -> Result<f64, ParseError> {
    let value: f64 = text
        .parse()
        .map_err(|_| ParseError::at_span(pair.as_span(), "invalid floating-point number"))?;
    if value.is_finite() {
        Ok(value)
    } else {
        Err(ParseError::at_span(
            pair.as_span(),
            "floating-point number must be finite",
        ))
    }
}

/// Splits a `<letter><digits>` terminal into its letter and index.
fn letter_index(pair: &Pair<Rule>) -> Result<(char, u64), ParseError> {
    let s = pair.as_str();
    let letter = s.chars().next().unwrap();
    let index = sub_u64(pair, &s[letter.len_utf8()..])?;
    Ok((letter, index))
}

/// Parses the integer between two known delimiters, e.g. `rec[-3]` -> 3.
fn bracketed_int(pair: &Pair<Rule>, prefix: &str, suffix: &str) -> Result<u64, ParseError> {
    let digits = pair
        .as_str()
        .strip_prefix(prefix)
        .and_then(|s| s.strip_suffix(suffix))
        .unwrap();
    sub_u64(pair, digits)
}

/// Parses a `<PORT><p>.<KIND><s>` terminal (e.g. `IN0.S2`, `IN3.DS1`) into its
/// port index and trailing index, given the port and kind prefixes.
fn port_indexed(pair: &Pair<Rule>, port_prefix: &str, kind_prefix: &str) -> Result<(u64, u64), ParseError> {
    let (left, right) = pair.as_str().split_once('.').unwrap();
    let port = sub_u64(pair, left.strip_prefix(port_prefix).unwrap())?;
    let index = sub_u64(pair, right.strip_prefix(kind_prefix).unwrap())?;
    Ok((port, index))
}

fn parse_logical(pair: Pair<Rule>) -> Result<LogicalPauliTarget, ParseError> {
    let terminal = pair.only();
    let s = terminal.as_str();
    match terminal.as_rule() {
        Rule::LOGICAL_PAULI_TARGET => {
            // "L<P><i>"
            let pauli = Pauli::from_char(s.chars().nth(1).unwrap());
            let index = sub_u64(&terminal, &s[2..])?;
            Ok(LogicalPauliTarget {
                pauli,
                index,
                port: None,
            })
        }
        Rule::INPUT_LOGICAL_TARGET | Rule::OUTPUT_LOGICAL_TARGET => {
            // "IN<p>.L<P><i>" / "OUT<p>.L<P><i>"
            let (left, right) = s.split_once('.').unwrap();
            let (kind, port_prefix) = if terminal.as_rule() == Rule::INPUT_LOGICAL_TARGET {
                (PortKind::In, "IN")
            } else {
                (PortKind::Out, "OUT")
            };
            let port_index = sub_u64(&terminal, left.strip_prefix(port_prefix).unwrap())?;
            let pauli = Pauli::from_char(right.chars().nth(1).unwrap());
            let index = sub_u64(&terminal, &right[2..])?;
            Ok(LogicalPauliTarget {
                pauli,
                index,
                port: Some(Port {
                    kind,
                    index: port_index,
                }),
            })
        }
        rule => unreachable!("unexpected logical target rule {rule:?}"),
    }
}

fn parse_measurement_ref(pair: &Pair<Rule>) -> Result<MeasurementRef, ParseError> {
    let s = pair.as_str();
    Ok(match pair.as_rule() {
        Rule::MEASUREMENT_RECORD_TARGET => MeasurementRef::Record {
            offset: bracketed_int(pair, "rec[-", "]")?,
        },
        Rule::PHYS_MEAS_TARGET => MeasurementRef::Physical {
            index: sub_u64(pair, s.strip_prefix('M').unwrap())?,
        },
        Rule::INPUT_VIRTUAL_TARGET => {
            let (port, stabilizer) = port_indexed(pair, "IN", "S")?;
            MeasurementRef::InputVirtual { port, stabilizer }
        }
        Rule::OUTPUT_VIRTUAL_TARGET => {
            let (port, stabilizer) = port_indexed(pair, "OUT", "S")?;
            MeasurementRef::OutputVirtual { port, stabilizer }
        }
        rule => unreachable!("unexpected measurement-ref rule {rule:?}"),
    })
}

fn parse_target(pair: Pair<Rule>) -> Result<Target, ParseError> {
    let inner = pair.only();
    let s = inner.as_str();
    Ok(match inner.as_rule() {
        Rule::MEASUREMENT_RECORD_TARGET => Target::MeasurementRecord {
            offset: bracketed_int(&inner, "rec[-", "]")?,
        },
        Rule::SWEEP_BIT_TARGET => Target::SweepBit {
            index: bracketed_int(&inner, "sweep[", "]")?,
        },
        Rule::INPUT_VIRTUAL_TARGET => {
            let (port, stabilizer) = port_indexed(&inner, "IN", "S")?;
            Target::InputVirtual { port, stabilizer }
        }
        Rule::OUTPUT_VIRTUAL_TARGET => {
            let (port, stabilizer) = port_indexed(&inner, "OUT", "S")?;
            Target::OutputVirtual { port, stabilizer }
        }
        Rule::PHYS_MEAS_TARGET => Target::PhysicalMeasurement {
            index: sub_u64(&inner, s.strip_prefix('M').unwrap())?,
        },
        Rule::loss_qubit_target => Target::Loss {
            index: sub_u64(&inner, s.strip_prefix('L').unwrap())?,
        },
        Rule::pauli_target => {
            let inverted = s.starts_with('!');
            let operator = inner.only();
            let (letter, index) = letter_index(&operator)?;
            Target::Pauli {
                inverted,
                pauli: Pauli::from_char(letter),
                index,
            }
        }
        Rule::qubit_target => {
            let inverted = s.starts_with('!');
            let int = inner.only();
            let index = int_u64(&int)?;
            Target::Qubit { inverted, index }
        }
        Rule::combiner => Target::Combiner,
        rule => unreachable!("unexpected target rule {rule:?}"),
    })
}

fn parse_pauli_product(pair: Pair<Rule>) -> Result<PauliProduct, ParseError> {
    let mut terms = Vec::new();
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::PAULI_IDENTITY => return Ok(PauliProduct::Identity),
            Rule::PAULI_TERM => {
                let (letter, index) = letter_index(&inner)?;
                terms.push(PauliTerm {
                    pauli: Pauli::from_char(letter),
                    index,
                });
            }
            rule => unreachable!("unexpected pauli-product rule {rule:?}"),
        }
    }
    Ok(PauliProduct::Terms(terms))
}

fn parse_decorator_value(pair: Pair<Rule>) -> Result<DecoratorValue, ParseError> {
    let inner = pair.only();
    Ok(match inner.as_rule() {
        Rule::string_literal => DecoratorValue::String(string_literal_content(&inner)),
        Rule::NUMBER => {
            let s = inner.as_str();
            if s.contains('.') || s.contains('e') || s.contains('E') {
                DecoratorValue::Float(sub_f64(&inner, s)?)
            } else {
                DecoratorValue::Int(sub_i64(&inner, s)?)
            }
        }
        rule => unreachable!("unexpected decorator-value rule {rule:?}"),
    })
}

fn parse_decorator(pair: Pair<Rule>) -> Result<Decorator, ParseError> {
    let mut inner = pair.into_inner();
    let name = inner.next().unwrap().as_str().strip_prefix('@').unwrap().to_string();
    let mut arguments = Vec::new();
    if let Some(args) = inner.next() {
        for arg in args.into_inner() {
            match arg.as_rule() {
                Rule::keyword_argument => {
                    let mut kv = arg.into_inner();
                    let key = kv.next().unwrap().as_str().to_string();
                    let value = parse_decorator_value(kv.next().unwrap())?;
                    arguments.push(DecoratorArg::Keyword { key, value });
                }
                Rule::decorator_value => {
                    arguments.push(DecoratorArg::Value(parse_decorator_value(arg)?));
                }
                rule => unreachable!("unexpected decorator-arg rule {rule:?}"),
            }
        }
    }
    Ok(Decorator { name, arguments })
}

/// Returns a string literal's content, without the surrounding quotes.
fn string_literal_content(pair: &Pair<Rule>) -> String {
    let escaped = pair.as_str();
    decode_string(&escaped[1..escaped.len() - 1])
}

fn parse_instruction(pair: Pair<Rule>) -> Result<Instruction, ParseError> {
    let mut name = String::new();
    let mut tag = None;
    let mut arguments = Vec::new();
    let mut targets = Vec::new();
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::IDENT => name = inner.as_str().to_string(),
            Rule::tag => tag = Some(decode_tag(inner.into_inner())),
            Rule::parenthesized_arguments => {
                let accepts_radians = matches!(
                    name.to_ascii_uppercase().as_str(),
                    "R_X" | "R_Y" | "R_Z" | "R_XX" | "R_YY" | "R_ZZ" | "R_PAULI" | "U" | "U3"
                );
                arguments = inner
                    .into_inner()
                    .map(|argument| {
                        if let Some(radians) = argument.as_str().strip_suffix("rad") {
                            if !accepts_radians {
                                return Err(ParseError::at_span(
                                    argument.as_span(),
                                    "radian suffix is only supported for rotation angles",
                                ));
                            }
                            Ok(sub_f64(&argument, radians)? / std::f64::consts::PI)
                        } else {
                            sub_f64(&argument, argument.as_str())
                        }
                    })
                    .collect::<Result<Vec<_>, _>>()?;
            }
            Rule::target => targets.push(inner.spanned(parse_target)?),
            rule => unreachable!("unexpected instruction rule {rule:?}"),
        }
    }
    Ok(Instruction {
        name,
        tag,
        arguments,
        targets,
    })
}

fn parse_port(pair: Pair<Rule>) -> Result<PortDeclaration, ParseError> {
    let mut inner = pair.into_inner();
    let name_pair = inner.next().unwrap();
    let code_name = Spanned::new(name_pair.as_str().to_string(), span_of(&name_pair));
    let qubit_indices = inner.map(|p| int_u64(&p)).collect::<Result<Vec<_>, _>>()?;
    Ok(PortDeclaration {
        code_name,
        qubit_indices,
    })
}

fn parse_gadget_application(pair: Pair<Rule>) -> Result<GadgetApplication, ParseError> {
    let mut inner = pair.into_inner();
    let name_pair = inner.next().unwrap();
    let gadget_name = Spanned::new(name_pair.as_str().to_string(), span_of(&name_pair));
    let mut in_indices = None;
    let mut out_indices = None;
    for binding in inner {
        let rule = binding.as_rule();
        let indices = binding
            .into_inner()
            .map(|p| int_u64(&p))
            .collect::<Result<Vec<_>, _>>()?;
        match rule {
            Rule::port_binding_in => in_indices = Some(indices),
            Rule::port_binding_out => out_indices = Some(indices),
            rule => unreachable!("unexpected gadget-application rule {rule:?}"),
        }
    }
    Ok(GadgetApplication {
        gadget_name,
        in_indices,
        out_indices,
    })
}

fn parse_readout_statement(pair: Pair<Rule>) -> Result<ReadoutStatement, ParseError> {
    let mut targets = Vec::new();
    let mut flip = false;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::target => {
                let span = span_of(&inner);
                targets.push(Spanned::new(ReadoutTargetItem::Target(parse_target(inner)?), span));
            }
            Rule::logical_pauli_target => {
                let span = span_of(&inner);
                targets.push(Spanned::new(ReadoutTargetItem::Logical(parse_logical(inner)?), span));
            }
            Rule::destabilizer_target => {
                let span = span_of(&inner);
                let term = inner.only();
                let (port, stabilizer) = port_indexed(&term, "IN", "DS")?;
                targets.push(Spanned::new(ReadoutTargetItem::Destabilizer { port, stabilizer }, span));
            }
            Rule::flip_flag => flip = true,
            rule => unreachable!("unexpected readout rule {rule:?}"),
        }
    }
    Ok(ReadoutStatement { targets, flip })
}

fn parse_check_statement(pair: Pair<Rule>) -> Result<CheckStatement, ParseError> {
    let mut targets = Vec::new();
    let mut flip = false;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::target => targets.push(inner.spanned(parse_target)?),
            Rule::flip_flag => flip = true,
            rule => unreachable!("unexpected check rule {rule:?}"),
        }
    }
    Ok(CheckStatement { targets, flip })
}

fn parse_error_statement(pair: Pair<Rule>) -> Result<ErrorStatement, ParseError> {
    let mut inner = pair.into_inner();
    let probability_pair = inner.next().unwrap();
    let probability = sub_f64(&probability_pair, probability_pair.as_str())?;
    if !(0.0..=1.0).contains(&probability) {
        return Err(ParseError::at_span(
            probability_pair.as_span(),
            format!("ERROR probability must be in [0, 1], got {probability}"),
        ));
    }
    let targets = inner
        .map(|t| -> Result<Spanned<ErrorTarget>, ParseError> {
            let span = span_of(&t);
            let node = match t.as_rule() {
                Rule::check_target => ErrorTarget::Check(sub_u64(&t, t.as_str().strip_prefix('C').unwrap())?),
                Rule::readout_target => ErrorTarget::Readout(sub_u64(&t, t.as_str().strip_prefix('R').unwrap())?),
                Rule::logical_pauli_target => ErrorTarget::Logical(parse_logical(t)?),
                rule => unreachable!("unexpected error-target rule {rule:?}"),
            };
            Ok(Spanned::new(node, span))
        })
        .collect::<Result<Vec<_>, _>>()?;
    Ok(ErrorStatement { probability, targets })
}

fn parse_loss_statement(pair: Pair<Rule>) -> Result<LossStatement, ParseError> {
    let mut statement = LossStatement::default();
    for item in pair.into_inner() {
        match item.as_rule() {
            Rule::NUMBER => {
                let probability = sub_f64(&item, item.as_str())?;
                if probability <= 0.0 || probability > 1.0 {
                    return Err(ParseError::at_span(
                        item.as_span(),
                        format!("LOSS probability must be in (0, 1], got {probability}"),
                    ));
                }
                statement.probability = Some(probability);
            }
            Rule::INPUT_PHYS_QUBIT_TARGET => {
                let (port, qubit) = port_indexed(&item, "IN", "L")?;
                statement.input_port = Some(port);
                statement.input_qubit = Some(qubit);
            }
            Rule::SOURCE_ERROR_TARGET => {
                if statement.input_port.is_some() {
                    return Err(ParseError::at_span(
                        item.as_span(),
                        "input LOSS(IN<i>.L<j>) must not carry source-error (SE) targets",
                    ));
                }
                statement
                    .source_errors
                    .push(sub_u64(&item, item.as_str().strip_prefix("SE").unwrap())?);
            }
            Rule::CONT_ERROR_TARGET => {
                statement
                    .continuation_errors
                    .push(sub_u64(&item, item.as_str().strip_prefix("CE").unwrap())?);
            }
            Rule::CHILD_LOSS_TARGET => {
                statement
                    .child_losses
                    .push(sub_u64(&item, item.as_str().strip_prefix('L').unwrap())?);
            }
            Rule::OUTPUT_PHYS_QUBIT_TARGET => {
                let (port, qubit) = port_indexed(&item, "OUT", "L")?;
                statement.output_qubits.push((port, qubit));
            }
            Rule::PHYS_MEAS_TARGET => {
                statement
                    .measurement_indices
                    .push(sub_u64(&item, item.as_str().strip_prefix('M').unwrap())?);
            }
            rule => unreachable!("unexpected loss-target rule {rule:?}"),
        }
    }
    Ok(statement)
}

fn parse_conditional_statement(pair: Pair<Rule>) -> Result<ConditionalStatement, ParseError> {
    let mut inner = pair.into_inner();
    let first = inner.next().unwrap();
    let condition = match first.as_rule() {
        Rule::readout_target => Condition::Readout(sub_u64(&first, first.as_str().strip_prefix('R').unwrap())?),
        _ => Condition::Measurement(parse_measurement_ref(&first)?),
    };
    let targets = inner
        .map(|p| p.spanned(parse_logical))
        .collect::<Result<Vec<_>, ParseError>>()?;
    Ok(ConditionalStatement { condition, targets })
}

fn parse_propagate_statement(pair: Pair<Rule>) -> Result<PropagateStatement, ParseError> {
    let mut inner = pair.into_inner();
    let target_pair = inner.next().unwrap();
    let target = target_pair.spanned(parse_logical)?;
    let mut terms = Vec::new();
    let mut flip = false;
    for item in inner {
        let span = span_of(&item);
        let node = match item.as_rule() {
            Rule::logical_pauli_target => PropagateTerm::Logical(parse_logical(item)?),
            Rule::destabilizer_target => {
                let term = item.only();
                let (port, stabilizer) = port_indexed(&term, "IN", "DS")?;
                PropagateTerm::Destabilizer { port, stabilizer }
            }
            Rule::MEASUREMENT_RECORD_TARGET => PropagateTerm::MeasurementRecord {
                offset: bracketed_int(&item, "rec[-", "]")?,
            },
            Rule::PHYS_MEAS_TARGET => PropagateTerm::PhysicalMeasurement {
                index: sub_u64(&item, item.as_str().strip_prefix('M').unwrap())?,
            },
            Rule::readout_target => PropagateTerm::Readout {
                index: sub_u64(&item, item.as_str().strip_prefix('R').unwrap())?,
            },
            Rule::flip_flag => {
                flip = true;
                continue;
            }
            rule => unreachable!("unexpected propagate rule {rule:?}"),
        };
        terms.push(Spanned::new(node, span));
    }
    Ok(PropagateStatement { target, terms, flip })
}

fn parse_virtual_correction(pair: Pair<Rule>) -> Result<VirtualCorrection, ParseError> {
    let mut paulis = Vec::new();
    let mut wire = 0;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::PAULI_OPERATOR => {
                let (letter, index) = letter_index(&inner)?;
                paulis.push((Pauli::from_char(letter), index));
            }
            Rule::INT => wire = int_u64(&inner)?,
            rule => unreachable!("unexpected virtual-correction rule {rule:?}"),
        }
    }
    Ok(VirtualCorrection { paulis, wire })
}

fn parse_conditional_correction(pair: Pair<Rule>) -> Result<ConditionalCorrection, ParseError> {
    let mut readout_offset = 0;
    let mut paulis = Vec::new();
    let mut wire = 0;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::MEASUREMENT_RECORD_TARGET => {
                readout_offset = bracketed_int(&inner, "rec[-", "]")?;
            }
            Rule::PAULI_OPERATOR => {
                let (letter, index) = letter_index(&inner)?;
                paulis.push((Pauli::from_char(letter), index));
            }
            Rule::INT => wire = int_u64(&inner)?,
            rule => unreachable!("unexpected conditional-correction rule {rule:?}"),
        }
    }
    Ok(ConditionalCorrection {
        readout_offset,
        paulis,
        wire,
    })
}

fn repeat_count(pair: &Pair<Rule>) -> Result<u64, ParseError> {
    let count = int_u64(pair)?;
    if count == 0 {
        return Err(ParseError::at_span(pair.as_span(), "REPEAT count must be >= 1, got 0"));
    }
    Ok(count)
}

// The three `parse_*_statement` functions below (and the `write_*_body` trio in
// the Display section) share a spine — `Repeat`/`InputPort`/`OutputPort`/
// `Instruction`/`Decorator` are handled identically — but are deliberately kept
// as separate copies rather than folded behind a macro/trait like
// `decorators::BodyStatement`. The set of statement kinds per body context is
// stable, so these dispatch tables change ~never, and three boring functions
// read clearer than one clever abstraction. Keep the shared arms in sync by hand.
fn parse_gadget_statement(pair: Pair<Rule>) -> Result<Spanned<GadgetStatement>, ParseError> {
    let span = span_of(&pair);
    let node = match pair.as_rule() {
        Rule::repeat_block_gadget => {
            let mut inner = pair.into_inner();
            let count = repeat_count(&inner.next().unwrap())?;
            let body = inner.map(parse_gadget_statement).collect::<Result<Vec<_>, _>>()?;
            GadgetStatement::Repeat { count, body }
        }
        Rule::input_port => GadgetStatement::InputPort(parse_port(pair)?),
        Rule::output_port => GadgetStatement::OutputPort(parse_port(pair)?),
        Rule::readout_statement => GadgetStatement::Readout(parse_readout_statement(pair)?),
        Rule::check_statement => GadgetStatement::Check(parse_check_statement(pair)?),
        Rule::error_statement => GadgetStatement::Error(parse_error_statement(pair)?),
        Rule::conditional_statement => GadgetStatement::Conditional(parse_conditional_statement(pair)?),
        Rule::preselect_statement => {
            let mut conditions = Vec::new();
            let mut expected_value = 0;
            for item in pair.into_inner() {
                if item.as_rule() == Rule::INT {
                    expected_value = int_u64(&item)?;
                    if expected_value > 1 {
                        return Err(ParseError::at_span(
                            item.as_span(),
                            format!("PRESELECT expected parity must be 0 or 1, got {expected_value}"),
                        ));
                    }
                } else {
                    conditions.push(parse_measurement_ref(&item)?);
                }
            }
            GadgetStatement::Preselect(PreselectStatement {
                conditions,
                expected_value,
            })
        }
        Rule::virtual_logical_statement => {
            let targets = pair
                .into_inner()
                .map(|p| p.spanned(parse_logical))
                .collect::<Result<Vec<_>, ParseError>>()?;
            GadgetStatement::VirtualLogical(VirtualLogicalStatement { targets })
        }
        Rule::propagate_statement => GadgetStatement::Propagate(parse_propagate_statement(pair)?),
        Rule::loss_statement => GadgetStatement::Loss(parse_loss_statement(pair)?),
        Rule::decorator => GadgetStatement::Decorator(parse_decorator(pair)?),
        Rule::instruction => GadgetStatement::Instruction(parse_instruction(pair)?),
        rule => unreachable!("unexpected gadget statement rule {rule:?}"),
    };
    Ok(Spanned::new(node, span))
}

fn parse_compose_statement(pair: Pair<Rule>) -> Result<Spanned<ComposeStatement>, ParseError> {
    let span = span_of(&pair);
    let node = match pair.as_rule() {
        Rule::repeat_block_compose => {
            let mut inner = pair.into_inner();
            let count = repeat_count(&inner.next().unwrap())?;
            let body = inner.map(parse_compose_statement).collect::<Result<Vec<_>, _>>()?;
            ComposeStatement::Repeat { count, body }
        }
        Rule::input_port => ComposeStatement::InputPort(parse_port(pair)?),
        Rule::output_port => ComposeStatement::OutputPort(parse_port(pair)?),
        Rule::gadget_application => ComposeStatement::GadgetApplication(parse_gadget_application(pair)?),
        Rule::conditional_correction => ComposeStatement::ConditionalCorrection(parse_conditional_correction(pair)?),
        Rule::decorator => ComposeStatement::Decorator(parse_decorator(pair)?),
        Rule::instruction => ComposeStatement::Instruction(parse_instruction(pair)?),
        rule => unreachable!("unexpected compose statement rule {rule:?}"),
    };
    Ok(Spanned::new(node, span))
}

fn parse_program_statement(pair: Pair<Rule>) -> Result<Spanned<ProgramStatement>, ParseError> {
    let span = span_of(&pair);
    let node = match pair.as_rule() {
        Rule::repeat_block_program => {
            let mut inner = pair.into_inner();
            let count = repeat_count(&inner.next().unwrap())?;
            let body = inner.map(parse_program_statement).collect::<Result<Vec<_>, _>>()?;
            ProgramStatement::Repeat { count, body }
        }
        Rule::input_port => ProgramStatement::InputPort(parse_port(pair)?),
        Rule::output_port => ProgramStatement::OutputPort(parse_port(pair)?),
        Rule::gadget_application => ProgramStatement::GadgetApplication(parse_gadget_application(pair)?),
        Rule::assert_statement => {
            let targets = pair
                .into_inner()
                .map(|target| target.spanned(parse_target))
                .collect::<Result<Vec<_>, _>>()?;
            ProgramStatement::Assert(AssertStatement { targets })
        }
        Rule::virtual_correction => ProgramStatement::VirtualCorrection(parse_virtual_correction(pair)?),
        Rule::conditional_correction => ProgramStatement::ConditionalCorrection(parse_conditional_correction(pair)?),
        Rule::decorator => ProgramStatement::Decorator(parse_decorator(pair)?),
        Rule::instruction => ProgramStatement::Instruction(parse_instruction(pair)?),
        rule => unreachable!("unexpected program statement rule {rule:?}"),
    };
    Ok(Spanned::new(node, span))
}

fn parse_code_definition(pair: Pair<Rule>, decorators: Vec<Decorator>) -> Result<CodeDefinition, ParseError> {
    let mut inner = pair.into_inner();
    let name = inner.next().unwrap().as_str().to_string();
    let params_pair = inner.next().unwrap();
    let params_span = params_pair.as_span();
    let mut params = params_pair.into_inner();
    let n_pair = params.next().unwrap();
    let n = int_u64(&n_pair)?;
    if n == 0 {
        return Err(ParseError::at_span(
            n_pair.as_span(),
            "CODE parameter n must be >= 1, got 0",
        ));
    }
    let k_pair = params.next().unwrap();
    let k = int_u64(&k_pair)?;
    if k > n {
        return Err(ParseError::at_span(
            k_pair.as_span(),
            format!("CODE parameter k ({k}) must be <= n ({n})"),
        ));
    }
    let d_pair = params.next();
    let d = d_pair.as_ref().map(int_u64).transpose()?;
    if let (Some(pair), Some(0)) = (&d_pair, d) {
        return Err(ParseError::at_span(
            pair.as_span(),
            "CODE parameter d must be >= 1, got 0",
        ));
    }

    let mut logicals = Vec::new();
    let mut stabilizers = Vec::new();
    for item in inner {
        match item.as_rule() {
            Rule::logical_declaration => {
                let mut products = item.into_inner();
                let x_operator = products.next().unwrap().spanned(parse_pauli_product)?;
                let z_operator = products.next().unwrap().spanned(parse_pauli_product)?;
                logicals.push(LogicalOperator { x_operator, z_operator });
            }
            Rule::stabilizer_declaration => {
                for product in item.into_inner() {
                    stabilizers.push(product.spanned(parse_pauli_product)?);
                }
            }
            rule => unreachable!("unexpected code-body rule {rule:?}"),
        }
    }
    if logicals.len() as u64 != k {
        return Err(ParseError::at_span(
            params_span,
            format!(
                "CODE '{name}' declares [[{n},{k}]] but has {} LOGICAL declaration(s); expected {k}",
                logicals.len()
            ),
        ));
    }
    Ok(CodeDefinition {
        name,
        n,
        k,
        d,
        logicals,
        stabilizers,
        decorators,
    })
}

fn parse_definition(pair: Pair<Rule>, decorators: Vec<Decorator>) -> Result<Definition, ParseError> {
    Ok(match pair.as_rule() {
        Rule::code_definition => Definition::Code(parse_code_definition(pair, decorators)?),
        Rule::gadget_definition => {
            let mut inner = pair.into_inner();
            let name = inner.next().unwrap().as_str().to_string();
            let body = inner.map(parse_gadget_statement).collect::<Result<Vec<_>, _>>()?;
            Definition::Gadget(GadgetDefinition { name, body, decorators })
        }
        Rule::compose_definition => {
            let mut inner = pair.into_inner();
            let name = inner.next().unwrap().as_str().to_string();
            let body = inner.map(parse_compose_statement).collect::<Result<Vec<_>, _>>()?;
            Definition::Compose(ComposeDefinition { name, body, decorators })
        }
        Rule::program_definition => {
            let mut inner = pair.into_inner();
            let name = inner.next().unwrap().as_str().to_string();
            let body = inner.map(parse_program_statement).collect::<Result<Vec<_>, _>>()?;
            Definition::Program(ProgramDefinition { name, body, decorators })
        }
        rule => unreachable!("unexpected definition rule {rule:?}"),
    })
}

// ── FromStr ──────────────────────────────────────────────────────────

impl FromStr for DeqFile {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let file = DeqParser::parse(Rule::deq_file, s)?.next().unwrap();
        let mut imports = Vec::new();
        let mut definitions = Vec::new();
        for item in file.into_inner() {
            match item.as_rule() {
                Rule::import_statement => {
                    let literal = item.only();
                    imports.push(string_literal_content(&literal));
                }
                Rule::decorated_definition => {
                    let mut decorators = Vec::new();
                    let mut definition = None;
                    for inner in item.into_inner() {
                        if inner.as_rule() == Rule::decorator {
                            decorators.push(parse_decorator(inner)?);
                        } else {
                            definition = Some(inner);
                        }
                    }
                    // Span the definition itself (from its `CODE`/`GADGET`/… keyword),
                    // not any leading decorators — the decorators are captured
                    // separately, and a definition-anchored span gives cleaner
                    // diagnostics.
                    let definition = definition.unwrap();
                    let span = span_of(&definition);
                    definitions.push(Spanned::new(parse_definition(definition, decorators)?, span));
                }
                Rule::EOI => {}
                rule => unreachable!("unexpected top-level rule {rule:?}"),
            }
        }
        Ok(Self { imports, definitions })
    }
}

// ── Display ──────────────────────────────────────────────────────────

const INDENT: &str = "    ";

fn write_decorators(f: &mut fmt::Formatter<'_>, decorators: &[Decorator]) -> fmt::Result {
    for decorator in decorators {
        writeln!(f, "{decorator}")?;
    }
    Ok(())
}

fn write_indent(f: &mut fmt::Formatter<'_>, level: usize) -> fmt::Result {
    for _ in 0..level {
        f.write_str(INDENT)?;
    }
    Ok(())
}

fn write_port(f: &mut fmt::Formatter<'_>, level: usize, keyword: &str, port: &PortDeclaration) -> fmt::Result {
    write_indent(f, level)?;
    write!(f, "{keyword} {}", port.code_name)?;
    for index in &port.qubit_indices {
        write!(f, " {index}")?;
    }
    writeln!(f)
}

fn write_line<T: fmt::Display>(f: &mut fmt::Formatter<'_>, level: usize, value: &T) -> fmt::Result {
    write_indent(f, level)?;
    writeln!(f, "{value}")
}

// Deliberate copy of the `parse_*_statement` shape; see the note there.
fn write_gadget_body(f: &mut fmt::Formatter<'_>, body: &[Spanned<GadgetStatement>], level: usize) -> fmt::Result {
    for statement in body {
        match &statement.node {
            GadgetStatement::Repeat { count, body } => {
                write_indent(f, level)?;
                writeln!(f, "REPEAT {count} {{")?;
                write_gadget_body(f, body, level + 1)?;
                write_indent(f, level)?;
                writeln!(f, "}}")?;
            }
            GadgetStatement::InputPort(port) => write_port(f, level, "INPUT", port)?,
            GadgetStatement::OutputPort(port) => write_port(f, level, "OUTPUT", port)?,
            GadgetStatement::Instruction(v) => write_line(f, level, v)?,
            GadgetStatement::Readout(v) => write_line(f, level, v)?,
            GadgetStatement::Check(v) => write_line(f, level, v)?,
            GadgetStatement::Error(v) => write_line(f, level, v)?,
            GadgetStatement::Conditional(v) => write_line(f, level, v)?,
            GadgetStatement::VirtualLogical(v) => write_line(f, level, v)?,
            GadgetStatement::Propagate(v) => write_line(f, level, v)?,
            GadgetStatement::Preselect(v) => write_line(f, level, v)?,
            GadgetStatement::Loss(v) => write_line(f, level, v)?,
            GadgetStatement::Decorator(v) => write_line(f, level, v)?,
        }
    }
    Ok(())
}

fn write_compose_body(f: &mut fmt::Formatter<'_>, body: &[Spanned<ComposeStatement>], level: usize) -> fmt::Result {
    for statement in body {
        match &statement.node {
            ComposeStatement::Repeat { count, body } => {
                write_indent(f, level)?;
                writeln!(f, "REPEAT {count} {{")?;
                write_compose_body(f, body, level + 1)?;
                write_indent(f, level)?;
                writeln!(f, "}}")?;
            }
            ComposeStatement::InputPort(port) => write_port(f, level, "INPUT", port)?,
            ComposeStatement::OutputPort(port) => write_port(f, level, "OUTPUT", port)?,
            ComposeStatement::GadgetApplication(v) => write_line(f, level, v)?,
            ComposeStatement::ConditionalCorrection(v) => write_line(f, level, v)?,
            ComposeStatement::Instruction(v) => write_line(f, level, v)?,
            ComposeStatement::Decorator(v) => write_line(f, level, v)?,
        }
    }
    Ok(())
}

fn write_program_body(f: &mut fmt::Formatter<'_>, body: &[Spanned<ProgramStatement>], level: usize) -> fmt::Result {
    for statement in body {
        match &statement.node {
            ProgramStatement::Repeat { count, body } => {
                write_indent(f, level)?;
                writeln!(f, "REPEAT {count} {{")?;
                write_program_body(f, body, level + 1)?;
                write_indent(f, level)?;
                writeln!(f, "}}")?;
            }
            ProgramStatement::InputPort(port) => write_port(f, level, "INPUT", port)?,
            ProgramStatement::OutputPort(port) => write_port(f, level, "OUTPUT", port)?,
            ProgramStatement::GadgetApplication(v) => write_line(f, level, v)?,
            ProgramStatement::Assert(v) => write_line(f, level, v)?,
            ProgramStatement::VirtualCorrection(v) => write_line(f, level, v)?,
            ProgramStatement::ConditionalCorrection(v) => write_line(f, level, v)?,
            ProgramStatement::Instruction(v) => write_line(f, level, v)?,
            ProgramStatement::Decorator(v) => write_line(f, level, v)?,
        }
    }
    Ok(())
}

impl fmt::Display for CodeDefinition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_decorators(f, &self.decorators)?;
        match self.d {
            Some(d) => writeln!(f, "CODE {} [[{},{},{}]] {{", self.name, self.n, self.k, d)?,
            None => writeln!(f, "CODE {} [[{},{}]] {{", self.name, self.n, self.k)?,
        }
        for logical in &self.logicals {
            writeln!(f, "{INDENT}LOGICAL {} {}", logical.x_operator, logical.z_operator)?;
        }
        for stabilizer in &self.stabilizers {
            writeln!(f, "{INDENT}STABILIZER {stabilizer}")?;
        }
        writeln!(f, "}}")
    }
}

impl fmt::Display for GadgetDefinition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_decorators(f, &self.decorators)?;
        writeln!(f, "GADGET {} {{", self.name)?;
        write_gadget_body(f, &self.body, 1)?;
        writeln!(f, "}}")
    }
}

impl fmt::Display for ComposeDefinition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_decorators(f, &self.decorators)?;
        writeln!(f, "COMPOSE {} {{", self.name)?;
        write_compose_body(f, &self.body, 1)?;
        writeln!(f, "}}")
    }
}

impl fmt::Display for ProgramDefinition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_decorators(f, &self.decorators)?;
        writeln!(f, "PROGRAM {} {{", self.name)?;
        write_program_body(f, &self.body, 1)?;
        writeln!(f, "}}")
    }
}

impl fmt::Display for Definition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Code(d) => write!(f, "{d}"),
            Self::Gadget(d) => write!(f, "{d}"),
            Self::Compose(d) => write!(f, "{d}"),
            Self::Program(d) => write!(f, "{d}"),
        }
    }
}

impl fmt::Display for DeqFile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for import in &self.imports {
            writeln!(f, "IMPORT \"{}\"", encode_string(import))?;
        }
        for (i, definition) in self.definitions.iter().enumerate() {
            if i > 0 || !self.imports.is_empty() {
                writeln!(f)?;
            }
            write!(f, "{definition}")?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests;