prism-q 0.35.0

Fast Rust quantum circuit simulator. OpenQASM 3.0, multiple backends, AVX2 SIMD kernels, optional CUDA and MPI, QEC tooling, Python bindings.
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
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
//! Walking a parsed program into instructions.
//!
//! Every name a statement reads is resolved against the scope the evaluator
//! holds, so a `for` body or a `gate` body is parsed once and run against
//! fresh bindings rather than rewritten and reparsed.

use std::collections::HashMap;

use super::*;
use crate::circuit::qasm::ast::{
    self, Argument, AssignOp, Block, CmpOp, Condition, DefParam, ForRange, Index, Operand,
    OperandName, Stmt, StmtKind,
};
use crate::circuit::qasm::expr::{self as syntax_expr, BinaryOp, Duration, Expr, Timed};
use crate::circuit::qasm::{lexer, parser as syntax};

/// Highest `$k` the program names, `None` when it names none.
///
/// Physical qubits declare no register, so the width comes from the tree
/// before any of it runs.
pub(super) fn highest_physical(block: &Block) -> Option<usize> {
    let mut highest: Option<usize> = None;
    let mut note = |operand: &Operand| {
        if let OperandName::Physical(index) = operand.name {
            highest = Some(highest.map_or(index, |seen: usize| seen.max(index)));
        }
    };
    walk_operands(block, &mut note);
    highest
}

fn walk_operands(block: &Block, note: &mut impl FnMut(&Operand)) {
    for stmt in block {
        match &stmt.kind {
            StmtKind::Alias { sources, .. } => sources.iter().for_each(&mut *note),
            StmtKind::Call {
                params, operands, ..
            } => {
                for param in params {
                    if let Argument::Operand(operand) = param {
                        note(operand);
                    }
                }
                operands.iter().for_each(&mut *note);
            }
            StmtKind::Measure(measure) => {
                note(&measure.source);
                note(&measure.target);
            }
            StmtKind::CallAssign(assign) => {
                note(&assign.target);
                for arg in &assign.args {
                    if let Argument::Operand(operand) = arg {
                        note(operand);
                    }
                }
            }
            StmtKind::Return(Some(ast::ReturnValue::Measure(source))) => note(source),
            StmtKind::Reset { targets }
            | StmtKind::Barrier { targets }
            | StmtKind::Delay { targets, .. } => targets.iter().for_each(&mut *note),
            StmtKind::If(conditional) => {
                match &conditional.condition {
                    Condition::Truthy(operand) | Condition::Negated(operand) => note(operand),
                    Condition::Compare { lhs, .. } => note(lhs),
                    Condition::Parity { bits, .. } => bits.iter().for_each(&mut *note),
                    Condition::Expr(_) => {}
                }
                walk_operands(&conditional.then_body, note);
                if let Some(body) = &conditional.else_body {
                    walk_operands(body, note);
                }
            }
            StmtKind::For { body, .. }
            | StmtKind::While { body, .. }
            | StmtKind::Box { body, .. }
            | StmtKind::DefDef { body, .. }
            | StmtKind::GateDef { body, .. } => walk_operands(body, note),
            StmtKind::Switch { operand, arms } => {
                note(operand);
                for arm in arms {
                    walk_operands(&arm.body, note);
                }
            }
            _ => {}
        }
    }
}

/// Fold an expression to a number, where a ratio of two durations counts as
/// one. The duration path runs only once the plain fold has failed, so a
/// program that names no duration never pays for it.
fn number_of(
    expr: &Expr,
    line: usize,
    vars: Option<&HashMap<&str, f64>>,
    durations: &HashMap<&str, Timed>,
    arrays: &HashMap<&str, ClassicalArray>,
) -> Result<f64> {
    let value = syntax_expr::eval(expr, line, vars);
    if value.is_ok() {
        return value;
    }
    if !arrays.is_empty() && expr.reads_element() {
        let resolved = resolve_elements(expr, line, vars, durations, arrays)?;
        return number_of(&resolved, line, vars, durations, arrays);
    }
    if !syntax_expr::is_timed(expr, durations) {
        return value;
    }
    match syntax_expr::eval_timed(expr, line, vars, durations)? {
        Timed::Number(value) => Ok(value),
        Timed::Duration(_) => Err(parse_error(
            line,
            format!("`{expr}` is a duration where a number belongs"),
        )),
        Timed::Stretch => Err(parse_error(
            line,
            format!("`{expr}` is a stretch where a number belongs"),
        )),
    }
}

fn compound(op: AssignOp, current: f64, folded: f64, line: usize) -> Result<f64> {
    Ok(match op {
        AssignOp::Add => current + folded,
        AssignOp::Sub => current - folded,
        AssignOp::Mul => current * folded,
        AssignOp::Div if folded == 0.0 => {
            return Err(parse_error(
                line,
                "division by zero in a compound assignment",
            ));
        }
        AssignOp::Rem if folded == 0.0 => {
            return Err(parse_error(line, "modulo by zero in a compound assignment"));
        }
        AssignOp::Div => current / folded,
        AssignOp::Rem => current % folded,
    })
}

/// Fold a timing expression, resolving the array elements it reads first.
fn timed_of(
    expr: &Expr,
    line: usize,
    vars: Option<&HashMap<&str, f64>>,
    durations: &HashMap<&str, Timed>,
    arrays: &HashMap<&str, ClassicalArray>,
) -> Result<Timed> {
    if arrays.is_empty() || !expr.reads_element() {
        return syntax_expr::eval_timed(expr, line, vars, durations);
    }
    let resolved = resolve_elements(expr, line, vars, durations, arrays)?;
    syntax_expr::eval_timed(&resolved, line, vars, durations)
}

/// `expr` with each array element it reads replaced by that element's value.
fn resolve_elements<'e>(
    expr: &Expr<'e>,
    line: usize,
    vars: Option<&HashMap<&str, f64>>,
    durations: &HashMap<&str, Timed>,
    arrays: &HashMap<&str, ClassicalArray>,
) -> Result<Expr<'e>> {
    let resolve = |inner: &Expr<'e>| resolve_elements(inner, line, vars, durations, arrays);
    Ok(match expr {
        Expr::Element(element) => {
            let array = arrays.get(element.array).ok_or_else(|| {
                parse_error(line, format!("`{}` is not a declared array", element.array))
            })?;
            let at = element_offset(array, element.array, &element.indices, line, |index| {
                number_of(index, line, vars, durations, arrays)
            })?;
            Expr::Number(array.values[at])
        }
        Expr::Negate(inner) => Expr::Negate(Box::new(resolve(inner)?)),
        Expr::Not(inner) => Expr::Not(Box::new(resolve(inner)?)),
        Expr::BitNot(inner) => Expr::BitNot(Box::new(resolve(inner)?)),
        Expr::Binary { op, left, right } => Expr::Binary {
            op: *op,
            left: Box::new(resolve(left)?),
            right: Box::new(resolve(right)?),
        },
        Expr::Call(call) => Expr::Call(Box::new(syntax_expr::Call {
            name: call.name,
            args: call.args.iter().map(resolve).collect::<Result<_>>()?,
        })),
        other => other.clone(),
    })
}

/// Row-major position of `array[indices]`, each index folded by `fold`.
fn element_offset(
    array: &ClassicalArray,
    name: &str,
    indices: &[Expr],
    line: usize,
    fold: impl Fn(&Expr) -> Result<f64>,
) -> Result<usize> {
    if indices.len() != array.dims.len() {
        return Err(parse_error(
            line,
            format!(
                "`{name}` has {} dimension(s) but is indexed with {}",
                array.dims.len(),
                indices.len()
            ),
        ));
    }
    let mut at = 0usize;
    for (index, &size) in indices.iter().zip(&array.dims) {
        let value = fold(index)?;
        if value.fract() != 0.0 || value < 0.0 || value >= size as f64 {
            return Err(parse_error(
                line,
                format!("index {value} is outside `{name}`, whose dimension has size {size}"),
            ));
        }
        at = at * size + value as usize;
    }
    Ok(at)
}

fn is_bit_param(args: &[DefParam], name: &str) -> bool {
    args.iter()
        .any(|arg| matches!(arg, DefParam::Bit { name: param, .. } if *param == name))
}

/// Line of the first `return` in `block`, nested bodies included.
fn return_line(block: &[Stmt]) -> Option<usize> {
    block.iter().find_map(|stmt| match &stmt.kind {
        StmtKind::Return(_) => Some(stmt.line),
        StmtKind::If(conditional) => return_line(&conditional.then_body)
            .or_else(|| conditional.else_body.as_deref().and_then(return_line)),
        StmtKind::For { body, .. } | StmtKind::While { body, .. } | StmtKind::Box { body, .. } => {
            return_line(body)
        }
        StmtKind::Switch { arms, .. } => arms.iter().find_map(|arm| return_line(&arm.body)),
        _ => None,
    })
}

impl<'a> Parser<'a> {
    /// Lex, parse, and run the source.
    pub(super) fn parse_program(
        &mut self,
    ) -> Result<(Circuit, Parameters, Vec<ResultSpec>, Option<NoiseModel>)> {
        let tokens = lexer::tokenize(self.input)?;
        let program = syntax::parse_program(&tokens)?;
        if let Some(highest) = highest_physical(&program) {
            self.physical = true;
            self.total_qubits = highest + 1;
        }
        let instructions = self.execute(&program)?;
        if self.verbatim_pending {
            return Err(parse_error(
                program.last().map_or(1, |stmt| stmt.line),
                "a verbatim pragma must be followed by a `box`",
            ));
        }

        let circuit = Circuit {
            num_qubits: self.total_qubits,
            num_classical_bits: self.total_cbits,
            instructions,
        };
        let params =
            Parameters::from_links(std::mem::take(&mut self.links), self.input_names.len())
                .with_names(std::mem::take(&mut self.input_names))
                .pinned_to(&circuit);
        let noise = self.build_noise_model(&circuit)?;
        Ok((circuit, params, std::mem::take(&mut self.results), noise))
    }

    /// Run a block, threading the parameter link and noise event each statement
    /// may leave behind onto the instruction index they belong to.
    pub(super) fn execute(&mut self, block: &Block<'a>) -> Result<Vec<Instruction>> {
        let mut instructions = Vec::with_capacity(block.len());
        for stmt in block {
            let base = instructions.len();
            self.pending_input_slot = None;
            self.exec_stmt(stmt, &mut instructions)?;
            if let Some(slot) = self.pending_input_slot.take() {
                for offset in 0..instructions.len() - base {
                    self.links.push(ParamLink {
                        instruction: base + offset,
                        slot,
                    });
                }
            }
            if let Some(spec) = self.pending_noise.take() {
                // A channel acts at the point the pragma stands, which is after
                // everything emitted so far.
                if base == 0 {
                    return Err(parse_error(
                        stmt.line,
                        "a noise pragma needs a preceding instruction to follow",
                    ));
                }
                self.noise_specs.push((base - 1, spec));
            }
            if self.streaming() {
                let produced = std::mem::take(&mut instructions);
                self.flush(produced);
            }
        }
        Ok(instructions)
    }

    fn exec_stmt(&mut self, stmt: &Stmt<'a>, out: &mut Vec<Instruction>) -> Result<()> {
        let line = stmt.line;
        match &stmt.kind {
            StmtKind::Empty | StmtKind::Include => Ok(()),
            StmtKind::Version(version) => {
                Self::check_version_number(version, line)?;
                Ok(())
            }
            StmtKind::RegisterDecl { kind, name, size } => {
                if let Some(result) = self.def_result.as_ref().filter(|result| {
                    *kind == ast::RegisterKind::Classical && result.local == Some(*name)
                }) {
                    // The returned bit is the caller's target, bound before the
                    // body ran, so its declaration allocates nothing.
                    let width = match size {
                        Some(size) => self.integer_of(size, line)?,
                        None => 1,
                    };
                    if width != result.bits.len() as i64 {
                        return Err(parse_error(
                            line,
                            format!(
                                "`{name}` declares {width} bit(s) where the def returns {}",
                                result.bits.len()
                            ),
                        ));
                    }
                    return Ok(());
                }
                if self.in_while() {
                    return Err(PrismError::UnsupportedConstruct {
                        construct: format!(
                            "register `{name}` declared inside a `while` loop; declare it \
                             before the loop"
                        ),
                        line,
                    });
                }
                self.declare_register(*kind, name, size.as_ref(), line)?;
                Ok(())
            }
            StmtKind::InputDecl { ty, name } => {
                if self.dynamic.is_some() {
                    return Err(PrismError::UnsupportedConstruct {
                        construct: format!("input `{name}` in a dynamic program"),
                        line,
                    });
                }
                self.declare_input(ty, name, line)?;
                Ok(())
            }
            StmtKind::OutputDecl { ty, name, size } => {
                if *ty != "bit" {
                    return Err(PrismError::UnsupportedConstruct {
                        construct: format!("`output {ty}` (only bit outputs are reported)"),
                        line,
                    });
                }
                self.declare_register(ast::RegisterKind::Classical, name, size.as_ref(), line)?;
                Ok(())
            }
            StmtKind::ClassicalDecl {
                constant,
                ty,
                width,
                name,
                value,
            } => {
                if self.is_runtime_decl(stmt) {
                    return self.declare_runtime(
                        *constant,
                        ty,
                        width.as_ref(),
                        name,
                        value.as_ref(),
                        line,
                    );
                }
                self.declare_classical(*constant, ty, name, value.as_ref(), line)?;
                Ok(())
            }
            StmtKind::Assign { target, op, value } => {
                self.assign_classical(target, *op, value, line)?;
                Ok(())
            }
            StmtKind::Alias { name, sources } => {
                self.declare_alias(name, sources, line)?;
                Ok(())
            }
            StmtKind::Call {
                modifiers,
                name,
                params,
                operands,
            } => self.exec_call(modifiers, name, params, operands, line, out),
            StmtKind::Measure(measure) => {
                if let Some(name) = measure
                    .target
                    .register()
                    .filter(|name| self.dynamic.is_some() && self.classical.contains_key(name))
                {
                    return Err(PrismError::UnsupportedConstruct {
                        construct: format!(
                            "a measurement into variable `{name}`; measure into a bit and \
                             assign the bit"
                        ),
                        line,
                    });
                }
                let qubits = self.qubits_of(&measure.source)?;
                let bits = self.bits_of(&measure.target)?;
                out.extend(Self::build_measurements(qubits, bits, line)?);
                Ok(())
            }
            StmtKind::Reset { targets } => {
                for target in targets {
                    out.extend(
                        self.qubits_of(target)?
                            .into_iter()
                            .map(|qubit| Instruction::Reset { qubit }),
                    );
                }
                Ok(())
            }
            StmtKind::Barrier { targets } => {
                let mut qubits = SmallVec::<[usize; 4]>::new();
                if targets.is_empty() {
                    qubits.extend(0..self.total_qubits);
                } else {
                    for target in targets {
                        qubits.extend(self.qubits_of(target)?);
                    }
                }
                out.push(Instruction::Barrier { qubits });
                Ok(())
            }
            // An ideal simulation has no clock, so a delay is the identity on
            // its qubits. It emits nothing, which also leaves fusion free to
            // merge across it.
            StmtKind::Delay { duration, targets } => {
                self.span_of(duration, "delay", line)?;
                for target in targets {
                    self.qubits_of(target)?;
                }
                Ok(())
            }
            StmtKind::If(conditional) if self.dynamic.is_some() => {
                self.exec_if_dynamic(stmt, conditional, line, out)
            }
            StmtKind::If(conditional) => {
                out.extend(self.exec_if(conditional, line)?);
                Ok(())
            }
            StmtKind::For {
                variable,
                range,
                body,
            } => {
                out.extend(self.exec_for(variable, range, body, line)?);
                Ok(())
            }
            StmtKind::Switch { operand, arms } if self.switch_needs_graph(stmt, operand) => {
                self.exec_switch_branches(operand, arms, line)
            }
            StmtKind::Switch { operand, arms } => {
                out.extend(self.exec_switch(operand, arms, line)?);
                Ok(())
            }
            StmtKind::While { condition, body } if self.dynamic.is_some() => {
                self.exec_while(condition, body, line)
            }
            StmtKind::Break | StmtKind::Continue if self.dynamic.is_some() => {
                self.exec_loop_exit(matches!(stmt.kind, StmtKind::Break), line)
            }
            StmtKind::While { .. } | StmtKind::Break | StmtKind::Continue => {
                let construct = match stmt.kind {
                    StmtKind::While { .. } => "while",
                    StmtKind::Break => "break",
                    _ => "continue",
                };
                Err(PrismError::UnsupportedConstruct {
                    construct: construct.to_string(),
                    line,
                })
            }
            StmtKind::GateDef {
                name,
                params,
                qubits,
                body,
            } => {
                if body.is_empty() {
                    return Err(parse_error(
                        line,
                        format!("gate '{name}' has an empty body"),
                    ));
                }
                self.gate_defs.insert(
                    *name,
                    GateDefinition {
                        params: params.clone(),
                        qubits: qubits.clone(),
                        body: body.clone(),
                    },
                );
                Ok(())
            }
            StmtKind::DefDef {
                name,
                args,
                result,
                body,
            } => {
                self.declare_def(name, args, result.as_ref(), body, line)?;
                Ok(())
            }
            StmtKind::Return(value) => {
                let Some(result) = &self.def_result else {
                    return Err(PrismError::UnsupportedConstruct {
                        construct: "`return` outside a def".to_string(),
                        line,
                    });
                };
                if let Some(ast::ReturnValue::Measure(source)) = value {
                    let qubits = self.qubits_of(source)?;
                    out.extend(Self::build_measurements(qubits, result.bits.clone(), line)?);
                }
                Ok(())
            }
            StmtKind::CallAssign(assign) => self.exec_call_assign(assign, line, out),
            StmtKind::ArrayDecl(decl) if self.is_runtime_decl(stmt) => {
                Err(PrismError::UnsupportedConstruct {
                    construct: format!(
                        "array `{}`, written where a loop or a measurement decides the value",
                        decl.name
                    ),
                    line,
                })
            }
            StmtKind::ArrayDecl(decl) => self.declare_array(decl, line),
            StmtKind::ElementAssign(assign) => self.assign_element(assign, line),
            StmtKind::Box { duration, body } => {
                // A box and Braket's verbatim pragma both direct a scheduler or
                // a device compiler, which a simulator has nothing to honour.
                self.verbatim_pending = false;
                if let Some(duration) = duration {
                    self.span_of(duration, "box", line)?;
                }
                out.extend(self.exec_box(body)?);
                Ok(())
            }
            StmtKind::Pragma(text) => {
                out.extend(self.exec_pragma(text, line)?);
                Ok(())
            }
        }
    }

    // ---------------------------------------------------------- declarations

    fn declare_register(
        &mut self,
        kind: ast::RegisterKind,
        name: &'a str,
        size: Option<&Expr<'a>>,
        line: usize,
    ) -> Result<()> {
        let width = match size {
            None => 1usize,
            Some(expr) => {
                let value = self.integer_of(expr, line)?;
                if value <= 0 {
                    return Err(parse_error(
                        line,
                        format!("{} count must be > 0", kind.name()),
                    ));
                }
                value as usize
            }
        };
        self.reject_redeclaration(name, line)?;
        match kind {
            ast::RegisterKind::Qubit => {
                self.reject_mixed_addressing(line)?;
                let offset = self.total_qubits;
                self.total_qubits += width;
                self.qregs.insert(
                    name,
                    Register {
                        offset,
                        size: width,
                    },
                );
            }
            ast::RegisterKind::Classical => {
                let offset = self.total_cbits;
                self.total_cbits += width;
                self.cregs.insert(
                    name,
                    Register {
                        offset,
                        size: width,
                    },
                );
            }
        }
        Ok(())
    }

    fn declare_input(&mut self, ty: &str, name: &'a str, line: usize) -> Result<()> {
        if !matches!(ty, "float" | "angle") {
            return Err(PrismError::UnsupportedConstruct {
                construct: format!("`input {ty}` (only float and angle inputs bind to an angle)"),
                line,
            });
        }
        if self.inputs.contains_key(name) {
            return Err(parse_error(line, format!("input `{name}` declared twice")));
        }
        self.inputs.insert(name, self.input_names.len());
        self.input_names.push(name.to_string());
        Ok(())
    }

    fn declare_classical(
        &mut self,
        constant: bool,
        ty: &str,
        name: &'a str,
        value: Option<&Expr<'a>>,
        line: usize,
    ) -> Result<()> {
        let kind = match ty {
            "int" | "uint" => ClassicalType::Int,
            "bool" => ClassicalType::Bool,
            "float" | "angle" => ClassicalType::Float,
            "duration" => ClassicalType::Duration,
            "stretch" => ClassicalType::Stretch,
            other => {
                return Err(PrismError::UnsupportedConstruct {
                    construct: format!("`{other}` declarations"),
                    line,
                });
            }
        };
        self.reject_redeclaration(name, line)?;
        let Some(value) = value else {
            if constant {
                return Err(parse_error(
                    line,
                    format!("`const {ty} {name}` needs a value"),
                ));
            }
            if matches!(kind, ClassicalType::Duration | ClassicalType::Stretch) {
                let zero = Timed::Duration(Duration::default());
                self.bind_duration(name, kind, zero, constant);
            } else {
                self.bind_classical(name, kind, 0.0, constant);
            }
            return Ok(());
        };
        if matches!(kind, ClassicalType::Duration | ClassicalType::Stretch) {
            let folded = self.duration_of(value, line)?;
            self.bind_duration(name, kind, folded, constant);
            return Ok(());
        }
        let folded = self.fold_typed(kind, value, line)?;
        self.bind_classical(name, kind, folded, constant);
        Ok(())
    }

    /// Bind a `duration` or `stretch`. A stretch keeps no value: a scheduler
    /// sizes it, so whatever it was initialised with is only a lower bound.
    fn bind_duration(&mut self, name: &'a str, ty: ClassicalType, value: Timed, constant: bool) {
        let value = if ty == ClassicalType::Stretch {
            Timed::Stretch
        } else {
            value
        };
        self.classical.insert(name, ClassicalDecl { ty, constant });
        self.durations.insert(name, value);
    }

    /// Fold an expression that has to be a duration or a stretch.
    fn duration_of(&self, expr: &Expr, line: usize) -> Result<Timed> {
        let vars = self.param_vars.as_ref();
        match timed_of(expr, line, vars, &self.durations, &self.arrays)? {
            Timed::Number(value) => Err(parse_error(
                line,
                format!("`{expr}` is the number {value} where a duration belongs; give it a unit"),
            )),
            timed => Ok(timed),
        }
    }

    /// Check the length a `delay` or `box` names, which has no further effect.
    fn span_of(&self, expr: &Expr, what: &str, line: usize) -> Result<()> {
        if let Timed::Duration(duration) = self.duration_of(expr, line)?
            && duration.is_negative()
        {
            return Err(parse_error(
                line,
                format!("`{what}` needs a non-negative duration, got `{expr}`"),
            ));
        }
        Ok(())
    }

    fn assign_classical(
        &mut self,
        target: &'a str,
        op: Option<AssignOp>,
        value: &Expr<'a>,
        line: usize,
    ) -> Result<()> {
        if let Some(var) = self.runtime_var(target) {
            return self.assign_runtime(var, op, value, line);
        }
        let Some(decl) = self.classical.get(target) else {
            return Err(parse_error(
                line,
                format!("`{target}` is not a declared classical variable"),
            ));
        };
        let (kind, constant) = (decl.ty, decl.constant);
        if constant {
            return Err(parse_error(
                line,
                format!("`{target}` is `const` and cannot be assigned"),
            ));
        }
        self.reject_guarded_write(target, line)?;
        if matches!(kind, ClassicalType::Duration | ClassicalType::Stretch) {
            return self.assign_duration(target, kind, op, value, line);
        }
        let folded = self.fold_typed(kind, value, line)?;
        let updated = match op {
            None => folded,
            Some(op) => {
                let current = self.fold_typed(kind, &Expr::Ident(target), line)?;
                compound(op, current, folded, line)?
            }
        };
        self.bind_classical(target, kind, updated, false);
        Ok(())
    }

    fn declare_array(&mut self, decl: &ast::ArrayDecl<'a>, line: usize) -> Result<()> {
        let kind = match decl.ty {
            "int" | "uint" => ClassicalType::Int,
            "bool" => ClassicalType::Bool,
            "float" | "angle" => ClassicalType::Float,
            other => {
                return Err(PrismError::UnsupportedConstruct {
                    construct: format!(
                        "`array[{other}, ...]`; an array holds `int`, `uint`, `float`, \
                         `angle` or `bool`, and bits belong in a `bit[n]` register"
                    ),
                    line,
                });
            }
        };
        self.reject_redeclaration(decl.name, line)?;
        let mut dims = Vec::with_capacity(decl.dims.len());
        let mut total = 1usize;
        for dim in &decl.dims {
            let size = self.integer_of(dim, line)?;
            let size = usize::try_from(size)
                .ok()
                .filter(|&size| size > 0)
                .ok_or_else(|| parse_error(line, format!("array size must be > 0, got {size}")))?;
            total = total
                .checked_mul(size)
                .filter(|&total| total <= MAX_ARRAY_ELEMENTS)
                .ok_or_else(|| {
                    parse_error(
                        line,
                        format!(
                            "array `{}` holds more than {MAX_ARRAY_ELEMENTS} elements",
                            decl.name
                        ),
                    )
                })?;
            dims.push(size);
        }
        if decl.constant && decl.init.is_none() {
            return Err(parse_error(
                line,
                format!("`const array {}` needs a value", decl.name),
            ));
        }
        let mut values = Vec::with_capacity(total);
        match &decl.init {
            None => values.resize(total, 0.0),
            Some(init) => self.fold_initializer(kind, init, &dims, decl.name, line, &mut values)?,
        }
        self.arrays.insert(
            decl.name,
            ClassicalArray {
                ty: kind,
                constant: decl.constant,
                dims,
                values,
            },
        );
        Ok(())
    }

    /// Fold an initializer into `values` in row-major order, checking that each
    /// braced list has one entry per index of the dimension it stands at.
    fn fold_initializer(
        &self,
        kind: ClassicalType,
        init: &ast::ArrayInit,
        dims: &[usize],
        name: &str,
        line: usize,
        values: &mut Vec<f64>,
    ) -> Result<()> {
        match (init, dims.split_first()) {
            (ast::ArrayInit::Value(expr), None) => {
                values.push(self.fold_typed(kind, expr, line)?);
                Ok(())
            }
            (ast::ArrayInit::List(entries), Some((&size, inner))) if entries.len() == size => {
                for entry in entries {
                    self.fold_initializer(kind, entry, inner, name, line, values)?;
                }
                Ok(())
            }
            (ast::ArrayInit::List(entries), Some((&size, _))) => Err(parse_error(
                line,
                format!(
                    "initializer for `{name}` lists {} entries where a dimension of size \
                     {size} stands",
                    entries.len()
                ),
            )),
            _ => Err(parse_error(
                line,
                format!("initializer for `{name}` does not match its dimensions"),
            )),
        }
    }

    fn assign_element(&mut self, assign: &ast::ElementAssign<'a>, line: usize) -> Result<()> {
        let Some(array) = self.arrays.get(assign.array) else {
            return Err(parse_error(
                line,
                format!(
                    "`{}` is not a name an assignment can write",
                    Expr::Element(Box::new(syntax_expr::Element {
                        array: assign.array,
                        indices: assign.indices.clone(),
                    }))
                ),
            ));
        };
        if array.constant {
            return Err(parse_error(
                line,
                format!("`{}` is `const` and cannot be assigned", assign.array),
            ));
        }
        self.reject_guarded_write(assign.array, line)?;
        let at = element_offset(array, assign.array, &assign.indices, line, |index| {
            self.value_of(index, line)
        })?;
        let kind = array.ty;
        let current = array.values[at];
        let folded = self.fold_typed(kind, &assign.value, line)?;
        let updated = match assign.op {
            None => folded,
            Some(op) => compound(op, current, folded, line)?,
        };
        if let Some(array) = self.arrays.get_mut(assign.array) {
            array.values[at] = updated;
        }
        Ok(())
    }

    fn assign_duration(
        &mut self,
        target: &'a str,
        kind: ClassicalType,
        op: Option<AssignOp>,
        value: &Expr<'a>,
        line: usize,
    ) -> Result<()> {
        if kind == ClassicalType::Stretch {
            return Err(parse_error(
                line,
                format!(
                    "`{target}` is a stretch, which a scheduler sizes and a program cannot assign"
                ),
            ));
        }
        let value = timed_of(
            value,
            line,
            self.param_vars.as_ref(),
            &self.durations,
            &self.arrays,
        )?;
        let updated = match op {
            None => value,
            Some(op) => {
                let op = match op {
                    AssignOp::Add => BinaryOp::Add,
                    AssignOp::Sub => BinaryOp::Sub,
                    AssignOp::Mul => BinaryOp::Mul,
                    AssignOp::Div => BinaryOp::Div,
                    AssignOp::Rem => BinaryOp::Rem,
                };
                let current = self
                    .durations
                    .get(target)
                    .copied()
                    .unwrap_or(Timed::Stretch);
                syntax_expr::combine_timed(op, current, value, line)?
            }
        };
        if let Timed::Number(number) = updated {
            return Err(parse_error(
                line,
                format!("assignment leaves duration `{target}` holding the number {number}"),
            ));
        }
        self.bind_duration(target, kind, updated, false);
        Ok(())
    }

    /// Fold an initializer to the value its declared type holds, naming an
    /// `input` rather than leaving it to read as an unknown identifier.
    fn fold_typed(&self, kind: ClassicalType, value: &Expr, line: usize) -> Result<f64> {
        if let Some(name) = self.input_names.iter().find(|name| value.mentions(name)) {
            return Err(PrismError::UnsupportedConstruct {
                construct: format!(
                    "input `{name}` in a classical declaration; an input binds an angle whole"
                ),
                line,
            });
        }
        match kind {
            ClassicalType::Float | ClassicalType::Duration | ClassicalType::Stretch => {
                self.value_of(value, line)
            }
            ClassicalType::Int => Ok(self.integer_of(value, line)? as f64),
            ClassicalType::Bool => Ok(f64::from(self.integer_of(value, line)? != 0)),
        }
    }

    fn declare_alias(&mut self, name: &'a str, sources: &[Operand<'a>], line: usize) -> Result<()> {
        self.reject_redeclaration(name, line)?;
        let mut kind: Option<ast::RegisterKind> = None;
        let mut indices: Vec<usize> = Vec::new();
        for source in sources {
            let (source_kind, resolved) = self.alias_source(source, line)?;
            match kind {
                Some(seen) if seen != source_kind => {
                    return Err(parse_error(
                        line,
                        format!("alias `{name}` joins qubits and classical bits"),
                    ));
                }
                _ => kind = Some(source_kind),
            }
            indices.extend(resolved);
        }
        let kind =
            kind.ok_or_else(|| parse_error(line, format!("alias `{name}` names nothing")))?;
        self.aliases.insert(name, Alias { kind, indices });
        Ok(())
    }

    /// One operand of an alias, resolved on the side of the register wall the
    /// name it opens with sits on.
    fn alias_source(
        &self,
        source: &Operand,
        line: usize,
    ) -> Result<(ast::RegisterKind, SmallVec<[usize; 4]>)> {
        let Some(name) = source.register() else {
            return Ok((ast::RegisterKind::Qubit, self.qubits_of(source)?));
        };
        let alias_kind = self.aliases.get(name).map(|alias| alias.kind);
        if self.qregs.contains_key(name) || alias_kind == Some(ast::RegisterKind::Qubit) {
            return Ok((ast::RegisterKind::Qubit, self.qubits_of(source)?));
        }
        if self.cregs.contains_key(name) || alias_kind == Some(ast::RegisterKind::Classical) {
            return Ok((ast::RegisterKind::Classical, self.bits_of(source)?));
        }
        Err(PrismError::UndefinedRegister {
            name: name.to_string(),
            line,
        })
    }

    fn declare_def(
        &mut self,
        name: &'a str,
        args: &[DefParam<'a>],
        result: Option<&ast::BitResult<'a>>,
        body: &Block<'a>,
        line: usize,
    ) -> Result<()> {
        let Some((last, rest)) = body.split_last() else {
            return Err(parse_error(line, format!("def `{name}` has an empty body")));
        };
        // A `return` anywhere but last decides at run time whether the rest of
        // the body runs, which no guarded region can say.
        let early = return_line(rest).or_else(|| match last.kind {
            StmtKind::Return(_) => None,
            _ => return_line(std::slice::from_ref(last)),
        });
        if let Some(at) = early {
            return Err(PrismError::UnsupportedConstruct {
                construct: format!(
                    "`return` before the end of def `{name}`, which needs control flow \
                     beyond a guarded region"
                ),
                line: at,
            });
        }
        let local = Self::def_result_local(name, args, result.is_some(), last, rest)?;
        Self::check_def_writes(name, args, local, body, true)?;
        self.def_defs.insert(
            name,
            DefDefinition {
                args: args.to_vec(),
                result: result.cloned(),
                local,
                body: body.clone(),
            },
        );
        Ok(())
    }

    /// The bit a `def` body declares and returns by name, after checking that
    /// its final statement returns what the signature promises.
    fn def_result_local(
        name: &str,
        args: &[DefParam<'a>],
        has_result: bool,
        last: &Stmt<'a>,
        rest: &[Stmt<'a>],
    ) -> Result<Option<&'a str>> {
        let value = match &last.kind {
            StmtKind::Return(value) => value.as_ref(),
            _ if has_result => None,
            _ => return Ok(None),
        };
        let Some(value) = value else {
            if has_result {
                return Err(parse_error(
                    last.line,
                    format!(
                        "def `{name}` declares a `bit` result but does not end by returning one"
                    ),
                ));
            }
            return Ok(None);
        };
        if !has_result {
            return Err(parse_error(
                last.line,
                format!("def `{name}` returns a value but declares no `-> bit` result"),
            ));
        }
        let ast::ReturnValue::Value(expr) = value else {
            return Ok(None);
        };
        let declared = |local: &str| {
            rest.iter().any(|stmt| {
                matches!(
                    &stmt.kind,
                    StmtKind::RegisterDecl {
                        kind: ast::RegisterKind::Classical,
                        name,
                        ..
                    } if *name == local
                )
            })
        };
        match expr.as_ident() {
            Some(local) if is_bit_param(args, local) => Err(PrismError::UnsupportedConstruct {
                construct: format!(
                    "def `{name}` returning its bit parameter `{local}`, a copy the \
                     instruction list has no classical move for"
                ),
                line: last.line,
            }),
            Some(local) if declared(local) => Ok(Some(local)),
            _ => Err(PrismError::UnsupportedConstruct {
                construct: format!(
                    "return of `{expr}` from def `{name}`; a def returns a measurement or a \
                     bit it declares"
                ),
                line: last.line,
            }),
        }
    }

    /// Check that a `def` body writes classical bits only through its result.
    ///
    /// A bit parameter is a copy, and any other bit would need a classical
    /// register the program never declared, so neither can be written here.
    fn check_def_writes(
        name: &str,
        args: &[DefParam<'a>],
        local: Option<&str>,
        block: &Block<'a>,
        top: bool,
    ) -> Result<()> {
        for stmt in block {
            match &stmt.kind {
                StmtKind::RegisterDecl {
                    kind: ast::RegisterKind::Classical,
                    name: declared,
                    ..
                } if !(top && local == Some(*declared)) => {
                    return Err(PrismError::UnsupportedConstruct {
                        construct: format!(
                            "`bit {declared}` inside def `{name}`, which does not return it; \
                             holding it would need a classical bit the program never declared"
                        ),
                        line: stmt.line,
                    });
                }
                StmtKind::Measure(measure) => {
                    let target = measure.target.register();
                    if target.is_some() && target == local {
                        continue;
                    }
                    let construct = match target {
                        Some(param) if is_bit_param(args, param) => format!(
                            "measure into bit parameter `{param}` of def `{name}`, which is \
                             passed by value"
                        ),
                        _ => format!(
                            "measure into `{}` inside def `{name}`, which writes classical \
                             bits only through its result",
                            measure.target.describe()
                        ),
                    };
                    return Err(PrismError::UnsupportedConstruct {
                        construct,
                        line: stmt.line,
                    });
                }
                StmtKind::If(conditional) => {
                    Self::check_def_writes(name, args, local, &conditional.then_body, false)?;
                    if let Some(body) = &conditional.else_body {
                        Self::check_def_writes(name, args, local, body, false)?;
                    }
                }
                StmtKind::For { body, .. } | StmtKind::Box { body, .. } => {
                    Self::check_def_writes(name, args, local, body, false)?;
                }
                StmtKind::Switch { arms, .. } => {
                    for arm in arms {
                        Self::check_def_writes(name, args, local, &arm.body, false)?;
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }

    // ------------------------------------------------------------- operands

    /// Qubits an operand names: a physical index, a whole register, one
    /// element, a slice, or an alias of any of those.
    pub(super) fn qubits_of(&self, operand: &Operand) -> Result<SmallVec<[usize; 4]>> {
        let name = match &operand.name {
            OperandName::Physical(index) => return Ok(smallvec![*index]),
            OperandName::Register(name) => name,
        };
        if let Some(indices) = self.alias_indices(ast::RegisterKind::Qubit, name, operand)? {
            return Ok(indices);
        }
        self.register_indices(&self.qregs, ast::RegisterKind::Qubit, name, operand)
    }

    fn bits_of(&self, operand: &Operand) -> Result<SmallVec<[usize; 4]>> {
        let Some(name) = operand.register() else {
            return Err(parse_error(
                operand.line,
                format!(
                    "`{}` is a qubit where a classical bit belongs",
                    operand.describe()
                ),
            ));
        };
        if let Some(indices) = self.alias_indices(ast::RegisterKind::Classical, name, operand)? {
            return Ok(indices);
        }
        self.register_indices(&self.cregs, ast::RegisterKind::Classical, name, operand)
    }

    pub(super) fn bit_of(&self, operand: &Operand) -> Result<usize> {
        match self.bits_of(operand)?.as_slice() {
            [single] => Ok(*single),
            other => Err(parse_error(
                operand.line,
                format!(
                    "`{}` names {} bits where one belongs",
                    operand.describe(),
                    other.len()
                ),
            )),
        }
    }

    fn alias_indices(
        &self,
        kind: ast::RegisterKind,
        name: &str,
        operand: &Operand,
    ) -> Result<Option<SmallVec<[usize; 4]>>> {
        let Some(alias) = self.aliases.get(name) else {
            return Ok(None);
        };
        if alias.kind != kind {
            return Err(parse_error(
                operand.line,
                format!("alias `{name}` names {}s", alias.kind.name()),
            ));
        }
        let Some(index) = &operand.index else {
            return Ok(Some(alias.indices.iter().copied().collect()));
        };
        let picks = self.pick_indices(alias.indices.len(), index, kind, operand)?;
        Ok(Some(picks.iter().map(|at| alias.indices[*at]).collect()))
    }

    fn register_indices(
        &self,
        registers: &HashMap<&'a str, Register>,
        kind: ast::RegisterKind,
        name: &str,
        operand: &Operand,
    ) -> Result<SmallVec<[usize; 4]>> {
        let register = registers
            .get(name)
            .ok_or_else(|| PrismError::UndefinedRegister {
                name: name.to_string(),
                line: operand.line,
            })?;
        let Some(index) = &operand.index else {
            return Ok((0..register.size).map(|at| register.offset + at).collect());
        };
        let picks = self.pick_indices(register.size, index, kind, operand)?;
        Ok(picks.iter().map(|at| register.offset + at).collect())
    }

    /// Positions a subscript names on a run of `size`.
    fn pick_indices(
        &self,
        size: usize,
        index: &Index,
        kind: ast::RegisterKind,
        operand: &Operand,
    ) -> Result<SmallVec<[usize; 4]>> {
        let line = operand.line;
        let bound = |value: i64| -> Result<usize> {
            let at = usize::try_from(value).map_err(|_| {
                parse_error(line, format!("negative index in `{}`", operand.describe()))
            })?;
            if at >= size {
                return Err(invalid_index(kind, at, size));
            }
            Ok(at)
        };
        match index {
            Index::Single(expr) => Ok(smallvec![bound(self.integer_of(expr, line)?)?]),
            Index::Set(entries) => {
                let mut out = SmallVec::new();
                for entry in entries {
                    out.push(bound(self.integer_of(entry, line)?)?);
                }
                Ok(out)
            }
            Index::Range(range) => {
                let at = |bound: &Option<Expr>, fallback: i64| -> Result<i64> {
                    match bound {
                        None => Ok(fallback),
                        Some(expr) => self.integer_of(expr, line),
                    }
                };
                let first = at(&range.start, 0)?;
                let last = at(&range.stop, size as i64 - 1)?;
                let stride = at(&range.step, 1)?;
                if stride == 0 {
                    return Err(parse_error(
                        line,
                        format!("range step in `{}` must be non-zero", operand.describe()),
                    ));
                }
                let mut out = SmallVec::new();
                let mut at = first;
                while (stride > 0 && at <= last) || (stride < 0 && at >= last) {
                    out.push(bound(at)?);
                    at += stride;
                }
                if out.is_empty() {
                    return Err(parse_error(
                        line,
                        format!("`{}` names no index", operand.describe()),
                    ));
                }
                Ok(out)
            }
        }
    }

    // ------------------------------------------------------------ expressions

    pub(super) fn value_of(&self, expr: &Expr, line: usize) -> Result<f64> {
        self.reject_runtime(expr, line)?;
        number_of(
            expr,
            line,
            self.param_vars.as_ref(),
            &self.durations,
            &self.arrays,
        )
    }

    pub(super) fn integer_of(&self, expr: &Expr, line: usize) -> Result<i64> {
        let value = self.value_of(expr, line)?;
        if !value.is_finite() || value.fract() != 0.0 {
            return Err(parse_error(
                line,
                format!("expected an integer, got {value}"),
            ));
        }
        if value > i64::MAX as f64 || value < i64::MIN as f64 {
            return Err(parse_error(line, "integer expression out of range"));
        }
        Ok(value as i64)
    }

    // ------------------------------------------------------------------ calls

    fn exec_call(
        &mut self,
        modifiers: &[ast::Modifier],
        name: &str,
        params: &[Argument],
        operands: &[Operand],
        line: usize,
        out: &mut Vec<Instruction>,
    ) -> Result<()> {
        if self.dynamic.is_some() && params.iter().any(|param| self.argument_is_runtime(param)) {
            return self.exec_runtime_rotation(modifiers, name, params, operands, line, out);
        }
        let modifiers = self.fold_modifiers(modifiers, line)?;

        if self.def_defs.contains_key(name) {
            let instrs = self.expand_def(name, params, None, line)?;
            out.extend(Self::modify_expansion(instrs, &modifiers, name, line)?);
            return Ok(());
        }

        let (values, input_slot) = self.fold_params(params, line)?;
        if name == "gphase" {
            let qubits = operands
                .iter()
                .map(|operand| match self.qubits_of(operand)?.as_slice() {
                    [single] => Ok(*single),
                    _ => Err(parse_error(
                        line,
                        format!(
                            "`{}` names a register where one qubit belongs",
                            operand.describe()
                        ),
                    )),
                })
                .collect::<Result<Vec<_>>>()?;
            out.extend(self.resolve_global_phase(&values, &modifiers, &qubits, line)?);
            return Ok(());
        }
        if input_slot.is_some() && !modifiers.is_empty() {
            return Err(PrismError::UnsupportedConstruct {
                construct: format!("modifier on `{name}` reading an `input`"),
                line,
            });
        }

        let resolved: SmallVec<[SmallVec<[usize; 4]>; 4]> = operands
            .iter()
            .map(|operand| self.qubits_of(operand))
            .collect::<Result<_>>()?;
        let width = self.broadcast_length(&resolved, name, line)?;

        let base = out.len();
        for at in 0..width {
            let qubits: SmallVec<[usize; 4]> = resolved
                .iter()
                .map(|entry| {
                    if entry.len() == 1 {
                        entry[0]
                    } else {
                        entry[at]
                    }
                })
                .collect();
            self.resolve_gate_application_once(
                name,
                &values,
                &modifiers,
                &qubits,
                input_slot.is_some(),
                line,
                out,
            )?;
        }
        if input_slot.is_some() {
            Self::check_every_instruction_is_bindable(&out[base..], name, line)?;
        }
        self.pending_input_slot = input_slot;
        Ok(())
    }

    fn fold_modifiers(
        &self,
        modifiers: &[ast::Modifier],
        line: usize,
    ) -> Result<Vec<super::Modifier>> {
        modifiers
            .iter()
            .map(|modifier| {
                Ok(match modifier {
                    ast::Modifier::Inv => super::Modifier::Inv,
                    ast::Modifier::Ctrl { negated } => super::Modifier::Ctrl { negated: *negated },
                    ast::Modifier::Pow(expr) => {
                        let exponent = self.value_of(expr, line)?;
                        if exponent.fract() == 0.0 && exponent.abs() > MAX_POW_REPEATS as f64 {
                            return Err(parse_error(
                                line,
                                format!(
                                    "pow({exponent}) repeats a gate more than \
                                     {MAX_POW_REPEATS} times"
                                ),
                            ));
                        }
                        super::Modifier::Pow(exponent)
                    }
                })
            })
            .collect()
    }

    /// Evaluate a call's angle arguments, reporting the one `input` slot they
    /// read. Two inputs on one gate are rejected: a slot is written onto the
    /// single angle a bindable gate carries.
    fn fold_params(&self, params: &[Argument], line: usize) -> Result<(Vec<f64>, Option<usize>)> {
        let mut values = Vec::with_capacity(params.len());
        let mut input_slot = None;
        for param in params {
            let element = self.element_argument(param);
            let expr = match (param, &element) {
                (_, Some(element)) => element,
                (Argument::Value(expr), None) => expr,
                (Argument::Operand(_), None) => {
                    return Err(parse_error(
                        line,
                        "a gate angle cannot be a qubit reference",
                    ));
                }
            };
            let (value, slot) = self.fold_angle(expr, line)?;
            if slot.is_some() && input_slot.is_some() {
                return Err(PrismError::UnsupportedConstruct {
                    construct: "two `input` parameters on one gate".to_string(),
                    line,
                });
            }
            input_slot = input_slot.or(slot);
            values.push(value);
        }
        Ok((values, input_slot))
    }

    /// An argument written `a[i]` parses as a qubit or bit reference; read it
    /// as an array element when `a` names an array.
    fn element_argument<'e>(&self, argument: &Argument<'e>) -> Option<Expr<'e>> {
        let Argument::Operand(operand) = argument else {
            return None;
        };
        let array = operand
            .register()
            .filter(|name| self.arrays.contains_key(name))?;
        let Some(Index::Single(index)) = &operand.index else {
            return None;
        };
        Some(Expr::Element(Box::new(syntax_expr::Element {
            array,
            indices: vec![index.clone()],
        })))
    }

    /// One angle argument, reporting the slot when it is exactly an `input`.
    fn fold_angle(&self, expr: &Expr, line: usize) -> Result<(f64, Option<usize>)> {
        if let Some((name, &slot)) = expr
            .as_ident()
            .and_then(|name| self.inputs.get(name).map(|slot| (name, slot)))
        {
            if self.nested {
                return Err(PrismError::UnsupportedConstruct {
                    construct: format!("input `{name}` inside a block body"),
                    line,
                });
            }
            return Ok((0.0, Some(slot)));
        }
        if let Some(name) = self.input_names.iter().find(|name| expr.mentions(name)) {
            return Err(PrismError::UnsupportedConstruct {
                construct: format!(
                    "an expression over input `{name}`; an input binds an angle whole"
                ),
                line,
            });
        }
        Ok((self.value_of(expr, line)?, None))
    }

    /// Expand a user `gate` by binding its qubit names to the call's qubits and
    /// its parameters to the call's values, then running the body.
    pub(super) fn expand_user_gate(
        &self,
        name: &str,
        call_params: &[f64],
        call_qubits: &SmallVec<[usize; 4]>,
        line: usize,
    ) -> Result<Option<Vec<Instruction>>> {
        if self.gate_expansion_depth >= MAX_GATE_EXPANSION_DEPTH {
            return Err(parse_error(
                line,
                format!(
                    "gate expansion depth exceeds maximum ({MAX_GATE_EXPANSION_DEPTH}); \
                     possible recursive gate definition for `{name}`"
                ),
            ));
        }
        let Some(def) = self.gate_defs.get(name) else {
            return Ok(None);
        };
        if call_params.len() != def.params.len() {
            return Err(parse_error(
                line,
                format!(
                    "gate `{name}` expects {} parameters, got {}",
                    def.params.len(),
                    call_params.len()
                ),
            ));
        }
        if call_qubits.len() != def.qubits.len() {
            return Err(PrismError::GateArity {
                gate: name.to_string(),
                expected: def.qubits.len(),
                got: call_qubits.len(),
            });
        }

        // A gate body sees its own parameters and nothing else, which is what
        // the language scopes it to.
        let bindings: HashMap<&'a str, f64> = def
            .params
            .iter()
            .copied()
            .zip(call_params.iter().copied())
            .collect();
        let mut sub = self.expansion_parser(bindings);
        for (&qubit_name, qubit) in def.qubits.iter().zip(call_qubits) {
            sub.aliases.insert(
                qubit_name,
                Alias {
                    kind: ast::RegisterKind::Qubit,
                    indices: vec![*qubit],
                },
            );
        }
        Ok(Some(sub.execute(&def.body)?))
    }

    /// `target = f(...);`: a `def` call whose `bit` result lands on `target`,
    /// or a builtin on the right of a classical assignment.
    fn exec_call_assign(
        &mut self,
        assign: &ast::CallAssign<'a>,
        line: usize,
        out: &mut Vec<Instruction>,
    ) -> Result<()> {
        if self.def_defs.contains_key(assign.name) {
            let bits = self.bits_of(&assign.target)?;
            out.extend(self.expand_def(assign.name, &assign.args, Some(&bits), line)?);
            return Ok(());
        }
        let Some(target) = assign
            .target
            .register()
            .filter(|_| assign.target.index.is_none())
        else {
            return Err(parse_error(
                line,
                format!(
                    "`{}` is not a name an assignment can write",
                    assign.target.describe()
                ),
            ));
        };
        let args = assign
            .args
            .iter()
            .map(|arg| match arg {
                Argument::Value(expr) => Ok(expr.clone()),
                Argument::Operand(operand) => Err(parse_error(
                    line,
                    format!(
                        "`{}` is a qubit or bit where a value belongs",
                        operand.describe()
                    ),
                )),
            })
            .collect::<Result<Vec<_>>>()?;
        let value = Expr::Call(Box::new(syntax_expr::Call {
            name: assign.name,
            args,
        }));
        self.assign_classical(target, None, &value, line)
    }

    /// Inline a `def` call, binding each argument by the kind its declaration
    /// gave it and the result, when there is one, to `result`.
    fn expand_def(
        &self,
        name: &str,
        args: &[Argument],
        result: Option<&[usize]>,
        line: usize,
    ) -> Result<Vec<Instruction>> {
        if self.gate_expansion_depth >= MAX_GATE_EXPANSION_DEPTH {
            return Err(parse_error(
                line,
                format!(
                    "def expansion depth exceeds maximum ({MAX_GATE_EXPANSION_DEPTH}); \
                     possible recursive call to `{name}`"
                ),
            ));
        }
        let def = self.def_defs.get(name).expect("checked by the caller");
        if args.len() != def.args.len() {
            return Err(PrismError::GateArity {
                gate: name.to_string(),
                expected: def.args.len(),
                got: args.len(),
            });
        }

        let mut bindings: HashMap<&'a str, f64> = self.param_vars.clone().unwrap_or_default();
        let mut durations = self.durations.clone();
        let mut qubit_bindings: Vec<(&'a str, usize)> = Vec::new();
        let mut bit_bindings: Vec<(&'a str, SmallVec<[usize; 4]>)> = Vec::new();
        for (slot, argument) in def.args.iter().zip(args) {
            match slot {
                DefParam::Qubit(param_name) => {
                    let param_name = *param_name;
                    let operand = match argument {
                        Argument::Operand(operand) => operand.clone(),
                        Argument::Value(expr) => {
                            let Some(register) = expr.as_ident() else {
                                return Err(parse_error(
                                    line,
                                    format!(
                                        "def `{name}` qubit parameter `{param_name}` needs a \
                                         qubit, not an expression"
                                    ),
                                ));
                            };
                            Operand {
                                name: OperandName::Register(register),
                                index: None,
                                line,
                            }
                        }
                    };
                    match self.qubits_of(&operand)?.as_slice() {
                        [single] => qubit_bindings.push((param_name, *single)),
                        _ => {
                            return Err(parse_error(
                                line,
                                format!(
                                    "def `{name}` qubit parameter `{param_name}` requires a \
                                     single qubit, got register `{}`",
                                    operand.describe()
                                ),
                            ));
                        }
                    }
                }
                DefParam::Value {
                    name: param_name,
                    integral,
                } => {
                    let param_name = *param_name;
                    let element = self.element_argument(argument);
                    let expr = match (argument, &element) {
                        (_, Some(element)) => element,
                        (Argument::Value(expr), None) => expr,
                        (Argument::Operand(_), None) => {
                            return Err(parse_error(
                                line,
                                format!("def `{name}` parameter `{param_name}` takes a value"),
                            ));
                        }
                    };
                    // The body reads the argument's value, so an input bound
                    // later would never reach it.
                    if let Some(input) = self.input_names.iter().find(|input| expr.mentions(input))
                    {
                        return Err(PrismError::UnsupportedConstruct {
                            construct: format!("input `{input}` as an argument to `def {name}`"),
                            line,
                        });
                    }
                    let value = number_of(expr, line, Some(&bindings), &durations, &self.arrays)?;
                    let value = if *integral {
                        let rounded = value.round();
                        if (value - rounded).abs() > 0.0 {
                            return Err(parse_error(
                                line,
                                format!("def `{name}` parameter `{param_name}` takes an integer"),
                            ));
                        }
                        rounded
                    } else {
                        value
                    };
                    bindings.insert(param_name, value);
                }
                DefParam::Duration(param_name) => {
                    let Argument::Value(expr) = argument else {
                        return Err(parse_error(
                            line,
                            format!("def `{name}` parameter `{param_name}` takes a duration"),
                        ));
                    };
                    let value = timed_of(expr, line, Some(&bindings), &durations, &self.arrays)?;
                    if let Timed::Number(number) = value {
                        return Err(parse_error(
                            line,
                            format!(
                                "def `{name}` parameter `{param_name}` takes a duration, got {number}"
                            ),
                        ));
                    }
                    durations.insert(param_name, value);
                }
                DefParam::Bit {
                    name: param_name,
                    width,
                } => {
                    let operand = match argument {
                        Argument::Operand(operand) => operand.clone(),
                        Argument::Value(expr) => match expr.as_ident() {
                            Some(register) => Operand {
                                name: OperandName::Register(register),
                                index: None,
                                line,
                            },
                            None => {
                                return Err(parse_error(
                                    line,
                                    format!(
                                        "def `{name}` bit parameter `{param_name}` needs a bit, \
                                         not an expression"
                                    ),
                                ));
                            }
                        },
                    };
                    let bits = self.bits_of(&operand)?;
                    let wanted = match width {
                        Some(width) => self.integer_of(width, line)?,
                        None => 1,
                    };
                    if bits.len() as i64 != wanted {
                        return Err(parse_error(
                            line,
                            format!(
                                "def `{name}` bit parameter `{param_name}` takes {wanted} bit(s), \
                                 got {}",
                                bits.len()
                            ),
                        ));
                    }
                    bit_bindings.push((param_name, bits));
                }
            }
        }

        let frame = match (&def.result, result) {
            (None, None) => DefResult {
                bits: SmallVec::new(),
                local: None,
            },
            (None, Some(_)) => {
                return Err(parse_error(
                    line,
                    format!("def `{name}` declares no result to assign"),
                ));
            }
            (Some(_), None) => {
                return Err(PrismError::UnsupportedConstruct {
                    construct: format!(
                        "a call to def `{name}` that drops its `bit` result, which would need \
                         a classical bit the program never declared"
                    ),
                    line,
                });
            }
            (Some(declared), Some(bits)) => {
                let wanted = match &declared.width {
                    Some(width) => self.integer_of(width, line)?,
                    None => 1,
                };
                if bits.len() as i64 != wanted {
                    return Err(parse_error(
                        line,
                        format!(
                            "def `{name}` returns {wanted} bit(s) where its target names {}",
                            bits.len()
                        ),
                    ));
                }
                // The named result is written in place, so a parameter reading
                // the same bit would see the new value rather than its copy.
                let aliased = def.local.is_some()
                    && bit_bindings
                        .iter()
                        .any(|(_, param)| param.iter().any(|bit| bits.contains(bit)));
                if aliased {
                    return Err(PrismError::UnsupportedConstruct {
                        construct: format!(
                            "a call to def `{name}` passing a bit it also assigns, which the \
                             body would read after writing its result"
                        ),
                        line,
                    });
                }
                DefResult {
                    bits: bits.iter().copied().collect(),
                    local: def.local,
                }
            }
        };

        let mut sub = self.expansion_parser(bindings);
        // The body runs in a parser of its own, so a write it made to an outer
        // variable would be dropped on return; only the constants it may read
        // stay declared, and a write to anything else is rejected.
        sub.classical.retain(|_, decl| decl.constant);
        sub.durations = durations;
        // A def sees the global constants and nothing else it does not take as
        // an argument, so only a `const` array reaches its body.
        sub.arrays = self
            .arrays
            .iter()
            .filter(|(_, array)| array.constant)
            .map(|(name, array)| (*name, array.clone()))
            .collect();
        for (param_name, qubit) in qubit_bindings {
            sub.aliases.insert(
                param_name,
                Alias {
                    kind: ast::RegisterKind::Qubit,
                    indices: vec![qubit],
                },
            );
        }
        for (param_name, bits) in bit_bindings {
            sub.bind_bits(param_name, bits);
        }
        if let Some(local) = frame.local {
            sub.bind_bits(local, frame.bits.clone());
        }
        sub.def_result = Some(frame);
        sub.execute(&def.body)
    }

    /// Name `bits` inside an expanded body: as a register when they run
    /// contiguously, which a register comparison needs, and as an alias
    /// otherwise.
    fn bind_bits(&mut self, name: &'a str, bits: SmallVec<[usize; 4]>) {
        let contiguous = bits.windows(2).all(|pair| pair[1] == pair[0] + 1);
        match bits.first() {
            Some(&offset) if contiguous => {
                self.aliases.remove(name);
                self.cregs.insert(
                    name,
                    Register {
                        offset,
                        size: bits.len(),
                    },
                );
            }
            _ => {
                self.aliases.insert(
                    name,
                    Alias {
                        kind: ast::RegisterKind::Classical,
                        indices: bits.to_vec(),
                    },
                );
            }
        }
    }

    /// A parser for an expanded body: the enclosing registers and definitions,
    /// one level deeper, with its own bindings.
    fn expansion_parser(&self, bindings: HashMap<&'a str, f64>) -> Parser<'a> {
        let mut sub = Parser {
            dialect: self.dialect,
            input: "",
            qregs: HashMap::new(),
            cregs: HashMap::new(),
            gate_defs: HashMap::new(),
            def_defs: HashMap::new(),
            total_qubits: self.total_qubits,
            total_cbits: self.total_cbits,
            gate_expansion_depth: self.gate_expansion_depth + 1,
            region_depth: self.region_depth,
            param_vars: Some(bindings),
            inputs: HashMap::new(),
            input_names: Vec::new(),
            links: Vec::new(),
            pending_input_slot: None,
            nested: true,
            results: Vec::new(),
            noise_specs: Vec::new(),
            pending_noise: None,
            verbatim_pending: false,
            physical: self.physical,
            aliases: HashMap::new(),
            classical: self.classical_copy(),
            durations: HashMap::new(),
            arrays: HashMap::new(),
            def_result: None,
            guard: None,
            dynamic: None,
        };
        for (name, register) in &self.qregs {
            sub.qregs.insert(
                *name,
                Register {
                    offset: register.offset,
                    size: register.size,
                },
            );
        }
        for (name, register) in &self.cregs {
            sub.cregs.insert(
                *name,
                Register {
                    offset: register.offset,
                    size: register.size,
                },
            );
        }
        for (name, alias) in &self.aliases {
            sub.aliases.insert(
                *name,
                Alias {
                    kind: alias.kind,
                    indices: alias.indices.clone(),
                },
            );
        }
        for (name, def) in &self.gate_defs {
            sub.gate_defs.insert(
                *name,
                GateDefinition {
                    params: def.params.clone(),
                    qubits: def.qubits.clone(),
                    body: def.body.clone(),
                },
            );
        }
        for (name, def) in &self.def_defs {
            sub.def_defs.insert(
                *name,
                DefDefinition {
                    args: def.args.clone(),
                    result: def.result.clone(),
                    local: def.local,
                    body: def.body.clone(),
                },
            );
        }
        sub
    }

    // ------------------------------------------------------------ control flow

    fn exec_if(
        &mut self,
        conditional: &ast::Conditional<'a>,
        line: usize,
    ) -> Result<Vec<Instruction>> {
        let condition = self.condition_of(&conditional.condition, line)?;
        let then_instrs = self.region(&conditional.then_body)?;
        let Some(else_body) = &conditional.else_body else {
            return Ok(guarded(condition, then_instrs).into_iter().collect());
        };
        // The negated region re-reads the classical bits after the `then` body
        // has run, so a body that measures into its own guard bits could take
        // both arms.
        if crate::circuit::body_writes_condition_bits(&then_instrs, &condition) {
            return Err(parse_error(
                line,
                "`else` needs a condition the `if` body does not overwrite; \
                          this body measures into a bit the condition reads",
            ));
        }
        let else_instrs = self.region(else_body)?;
        let mut out = Vec::new();
        out.extend(guarded(condition.clone(), then_instrs));
        out.extend(guarded(condition.negate(), else_instrs));
        Ok(out)
    }

    /// Run a `box` body in place, with no guard and no barrier at either edge.
    ///
    /// A box only fixes timing, which an ideal simulation does not model, so
    /// fusion may merge across its boundary as freely as across a `delay`. The
    /// names its body declares go out of scope with it.
    pub(super) fn exec_box(&mut self, body: &Block<'a>) -> Result<Vec<Instruction>> {
        let scope = self.open_scope();
        let was_nested = std::mem::replace(&mut self.nested, true);
        let result = self.execute(body);
        self.nested = was_nested;
        self.close_scope(&scope);
        result
    }

    /// The classical and array names in scope, for [`Parser::close_scope`].
    pub(super) fn open_scope(&self) -> Scope<'a> {
        (
            self.classical.keys().copied().collect(),
            self.arrays.keys().copied().collect(),
        )
    }

    /// Drop the names declared since `scope` was opened. Names declared before
    /// it keep whatever the body wrote to them.
    pub(super) fn close_scope(&mut self, scope: &Scope<'a>) {
        let (classical, arrays) = scope;
        let declared: Vec<&'a str> = self
            .classical
            .keys()
            .copied()
            .filter(|name| !classical.contains(name))
            .collect();
        for name in declared {
            self.forget_runtime(name);
            self.classical.remove(name);
            self.durations.remove(name);
            if let Some(values) = self.param_vars.as_mut() {
                values.remove(name);
            }
        }
        self.arrays.retain(|name, _| arrays.contains(name));
    }

    /// Run a guarded block one nesting level down, in a scope of its own.
    ///
    /// Whether the block runs is decided by a measurement, while a classical
    /// variable is folded here at parse time, so the block may not write any
    /// variable declared outside it.
    pub(super) fn region(&mut self, block: &Block<'a>) -> Result<Vec<Instruction>> {
        self.enter_region_depth(block)?;
        let scope = self.open_scope();
        let outer_guard = self.guard.replace(scope.clone());
        let was_nested = std::mem::replace(&mut self.nested, true);
        self.enter_collecting();
        let body = self.execute(block);
        self.leave_collecting();
        self.nested = was_nested;
        self.guard = outer_guard;
        self.close_scope(&scope);
        self.region_depth -= 1;
        body
    }

    fn reject_guarded_write(&self, name: &str, line: usize) -> Result<()> {
        let Some((classical, arrays)) = &self.guard else {
            return Ok(());
        };
        if classical.contains(&name) || arrays.contains(&name) {
            return Err(PrismError::UnsupportedConstruct {
                construct: format!(
                    "a write to `{name}` under a runtime `if` or `switch`; the variable is \
                     folded at parse time and cannot depend on a measurement, so parse the \
                     program with `openqasm::parse_dynamic` to evaluate it at runtime"
                ),
                line,
            });
        }
        Ok(())
    }

    fn enter_region_depth(&mut self, block: &Block<'a>) -> Result<()> {
        if self.region_depth >= MAX_REGION_DEPTH {
            return Err(parse_error(
                block.first().map_or(1, |stmt| stmt.line),
                format!("`if` blocks nest deeper than {MAX_REGION_DEPTH}"),
            ));
        }
        self.region_depth += 1;
        Ok(())
    }

    fn exec_for(
        &mut self,
        variable: &'a str,
        range: &ForRange<'a>,
        body: &Block<'a>,
        line: usize,
    ) -> Result<Vec<Instruction>> {
        let values = self.for_values(range, line)?;
        if values.len() as i64 > MAX_FOR_ITERATIONS {
            return Err(parse_error(
                line,
                format!(
                    "for loop iterates {} times (max {MAX_FOR_ITERATIONS})",
                    values.len()
                ),
            ));
        }
        let mut out = Vec::new();
        // The loop variable may shadow an outer name, whose value comes back
        // once the loop ends.
        let shadowed = self
            .param_vars
            .as_ref()
            .and_then(|vars| vars.get(variable).copied());
        let scope = self.open_scope();
        let mut result = Ok(());
        self.enter_static_loop();
        for value in values {
            // Each pass drops what the body declared, so a declaration binds
            // for one pass, while a write to an outer name carries on.
            self.param_vars
                .get_or_insert_with(HashMap::new)
                .insert(variable, value as f64);
            let was_nested = std::mem::replace(&mut self.nested, true);
            let produced = self.execute(body);
            self.nested = was_nested;
            self.close_scope(&scope);
            match produced {
                Ok(produced) => out.extend(produced),
                Err(error) => {
                    result = Err(error);
                    break;
                }
            }
        }
        self.leave_static_loop();
        if let Some(vars) = self.param_vars.as_mut() {
            match shadowed {
                Some(value) => vars.insert(variable, value),
                None => vars.remove(variable),
            };
        }
        result.map(|()| out)
    }

    fn for_values(&self, range: &ForRange, line: usize) -> Result<Vec<i64>> {
        match range {
            ForRange::Set(entries) => entries
                .iter()
                .map(|entry| self.integer_of(entry, line))
                .collect(),
            ForRange::Range { start, step, stop } => {
                let first = self.integer_of(start, line)?;
                let last = self.integer_of(stop, line)?;
                let stride = match step {
                    None => 1,
                    Some(expr) => self.integer_of(expr, line)?,
                };
                if stride == 0 {
                    return Err(parse_error(line, "for loop range step must be non-zero"));
                }
                let mut values = Vec::new();
                let mut at = first;
                while (stride > 0 && at <= last) || (stride < 0 && at >= last) {
                    values.push(at);
                    if values.len() as i64 > MAX_FOR_ITERATIONS {
                        return Err(parse_error(
                            line,
                            format!("for loop iterates more than {MAX_FOR_ITERATIONS} times"),
                        ));
                    }
                    at += stride;
                }
                Ok(values)
            }
        }
    }

    fn exec_switch(
        &mut self,
        operand: &Operand<'a>,
        arms: &[ast::SwitchArm<'a>],
        line: usize,
    ) -> Result<Vec<Instruction>> {
        let (offset, size) = self.switch_operand(operand)?;
        let mut labels: Vec<u64> = Vec::new();
        let mut cases: Vec<(Vec<u64>, Vec<Instruction>)> = Vec::new();
        let mut default: Option<Vec<Instruction>> = None;
        for arm in arms {
            let body = self.region(&arm.body)?;
            let Some(arm_labels) = &arm.labels else {
                if default.replace(body).is_some() {
                    return Err(parse_error(
                        arm.line,
                        "`switch` has more than one `default` arm",
                    ));
                }
                continue;
            };
            let mut values = Vec::new();
            for label in arm_labels {
                let value = self.integer_of(label, arm.line)?;
                let value = u64::try_from(value).map_err(|_| {
                    parse_error(
                        arm.line,
                        format!("`switch` case label must be non-negative, got `{value}`"),
                    )
                })?;
                if labels.contains(&value) {
                    return Err(parse_error(
                        arm.line,
                        format!("`switch` case label {value} appears twice"),
                    ));
                }
                labels.push(value);
                values.push(value);
            }
            cases.push((values, body));
        }

        // The chain is exclusive only because no arm writes the switched
        // register, which is checked rather than assumed.
        let probe = ClassicalCondition::RegisterEquals {
            offset,
            size,
            value: 0,
        };
        let writes_operand = cases
            .iter()
            .map(|(_, body)| body)
            .chain(default.iter())
            .any(|body| crate::circuit::body_writes_condition_bits(body, &probe));
        if writes_operand {
            return Err(parse_error(
                line,
                "`switch` needs an operand no arm overwrites; \
                          an arm here measures into the switched register",
            ));
        }

        let mut out = Vec::new();
        for (values, body) in &cases {
            for &value in values {
                let condition = ClassicalCondition::RegisterEquals {
                    offset,
                    size,
                    value,
                };
                out.extend(guarded(condition, body.clone()));
            }
        }
        if let Some(body) = default {
            out.extend(nest_default_arm(
                offset,
                size,
                &labels,
                body,
                self.region_depth,
                line,
            )?);
        }
        Ok(out)
    }

    /// The `(offset, size)` of the classical range a `switch` reads. A bit
    /// reference is a range of one.
    fn switch_operand(&self, operand: &Operand) -> Result<(usize, usize)> {
        if operand.index.is_some() {
            return Ok((self.bit_of(operand)?, 1));
        }
        let name = operand
            .register()
            .ok_or_else(|| PrismError::UndefinedRegister {
                name: operand.describe(),
                line: operand.line,
            })?;
        if let Some(alias) = self.aliases.get(name) {
            return match alias.indices.as_slice() {
                [single] => Ok((*single, 1)),
                _ => Err(parse_error(
                    operand.line,
                    format!("`switch` on alias `{name}`, which is not one contiguous register"),
                )),
            };
        }
        let register = self
            .cregs
            .get(name)
            .ok_or_else(|| PrismError::UndefinedRegister {
                name: name.to_string(),
                line: operand.line,
            })?;
        Ok((register.offset, register.size))
    }

    /// The bit an unsubscripted name stands for when it names exactly one,
    /// as `bit b;` or a `def`'s `bit` parameter does.
    fn single_bit(&self, operand: &Operand) -> Option<usize> {
        if operand.index.is_some() {
            return None;
        }
        match self.bits_of(operand).ok()?.as_slice() {
            [bit] => Some(*bit),
            _ => None,
        }
    }

    pub(super) fn condition_of(
        &self,
        condition: &Condition,
        line: usize,
    ) -> Result<ClassicalCondition> {
        match condition {
            Condition::Truthy(operand) => {
                if let Some(bit) = self.single_bit(operand) {
                    return Ok(ClassicalCondition::BitIsOne(bit));
                }
                if operand.index.is_none() {
                    return Err(parse_error(
                        line,
                        format!(
                            "expected `{0}==value`, `{0}!=value`, `{0}[i]`, `!{0}[i]` or \
                             `{0}[i]==0/1` in `if` condition, got `{0}`",
                            operand.describe()
                        ),
                    ));
                }
                Ok(ClassicalCondition::BitIsOne(self.bit_of(operand)?))
            }
            Condition::Negated(operand) => {
                if let Some(bit) = self.single_bit(operand) {
                    return Ok(ClassicalCondition::BitIsZero(bit));
                }
                if operand.index.is_none() {
                    return Err(parse_error(
                        line,
                        format!(
                            "expected `!c[i]` form in `if` condition, got `!{}`",
                            operand.describe()
                        ),
                    ));
                }
                Ok(ClassicalCondition::BitIsZero(self.bit_of(operand)?))
            }
            Condition::Parity { bits, compare } => {
                let expected = match compare {
                    None => true,
                    Some((op, rhs)) => {
                        let negate = *op == CmpOp::NotEqual;
                        match self.integer_of(rhs, line)? {
                            0 => negate,
                            1 => !negate,
                            other => {
                                return Err(parse_error(
                                    line,
                                    format!("a parity compares against 0 or 1, got `{other}`"),
                                ));
                            }
                        }
                    }
                };
                let mut resolved: Vec<usize> = Vec::with_capacity(bits.len());
                for bit in bits {
                    if bit.index.is_none() {
                        return Err(parse_error(
                            line,
                            format!("`{}` is a register where a bit belongs", bit.describe()),
                        ));
                    }
                    resolved.push(self.bit_of(bit)?);
                }
                Ok(ClassicalCondition::Parity {
                    bits: resolved.into_boxed_slice(),
                    expected,
                })
            }
            Condition::Expr(expr) => Err(parse_error(
                line,
                format!("`{expr}` has no form a guard on classical bits can take"),
            )),
            Condition::Compare { lhs, op, rhs } => {
                let negate = *op == CmpOp::NotEqual;
                let value = self.integer_of(rhs, line)?;
                if value < 0 {
                    return Err(parse_error(
                        line,
                        format!("negative integer in `if` condition is not supported: `{value}`"),
                    ));
                }
                let value = value as u64;
                if lhs.index.is_some() {
                    let bit = self.bit_of(lhs)?;
                    return Ok(match (value, negate) {
                        (0, false) | (1, true) => ClassicalCondition::BitIsZero(bit),
                        (1, false) | (0, true) => ClassicalCondition::BitIsOne(bit),
                        (other, _) => {
                            return Err(parse_error(
                                line,
                                format!("bit comparison must be against 0 or 1, got `{other}`"),
                            ));
                        }
                    });
                }
                let name = lhs
                    .register()
                    .ok_or_else(|| PrismError::UndefinedRegister {
                        name: lhs.describe(),
                        line,
                    })?;
                let register =
                    self.cregs
                        .get(name)
                        .ok_or_else(|| PrismError::UndefinedRegister {
                            name: name.to_string(),
                            line,
                        })?;
                Ok(if negate {
                    ClassicalCondition::RegisterNotEquals {
                        offset: register.offset,
                        size: register.size,
                        value,
                    }
                } else {
                    ClassicalCondition::RegisterEquals {
                        offset: register.offset,
                        size: register.size,
                        value,
                    }
                })
            }
        }
    }

    // --------------------------------------------------------------- pragmas

    /// Dispatch a `#pragma braket ...` line.
    ///
    /// Only the Braket dialect reads these. Under any other the pragma is
    /// rejected rather than dropped, so a lost result request cannot pass
    /// unnoticed.
    fn exec_pragma(&mut self, text: &str, line: usize) -> Result<Vec<Instruction>> {
        let body = text.trim_start_matches("#pragma").trim();
        let Some(braket_body) = body.strip_prefix("braket") else {
            return Err(PrismError::UnsupportedConstruct {
                construct: format!("pragma `{body}`"),
                line,
            });
        };
        if self.dialect != Dialect::Braket {
            return Err(PrismError::UnsupportedConstruct {
                construct: "`#pragma braket`, which needs `Dialect::Braket`".to_string(),
                line,
            });
        }
        if self.nested {
            return Err(PrismError::UnsupportedConstruct {
                construct: "`#pragma braket` inside a block body".to_string(),
                line,
            });
        }
        let braket_body = braket_body.trim();
        let (kind, rest) = match braket_body.split_once(char::is_whitespace) {
            Some((kind, rest)) => (kind, rest.trim()),
            None => (braket_body, ""),
        };
        match kind {
            "result" => {
                let total = self.total_qubits;
                let spec = braket::parse_result_pragma(rest, line, total, &|token| {
                    self.qubits_of_text(token, line)
                        .map(|targets| targets.to_vec())
                })?;
                self.results.push(spec);
                Ok(Vec::new())
            }
            "noise" => {
                let spec = braket::parse_noise_pragma(rest, line, &|token| {
                    self.qubits_of_text(token, line)
                        .map(|targets| targets.to_vec())
                })?;
                self.pending_noise = Some(spec);
                Ok(Vec::new())
            }
            "verbatim" => {
                self.verbatim_pending = true;
                Ok(Vec::new())
            }
            _ if braket_body.starts_with("unitary") => self.exec_unitary_pragma(braket_body, line),
            other => Err(PrismError::UnsupportedConstruct {
                construct: format!("`#pragma braket {other}`"),
                line,
            }),
        }
    }

    /// `#pragma braket unitary([[...]]) q[0]`, an inline gate matrix.
    fn exec_unitary_pragma(&mut self, body: &str, line: usize) -> Result<Vec<Instruction>> {
        let rest = body.trim_start_matches("unitary").trim();
        if !rest.starts_with('(') {
            return Err(parse_error(
                line,
                "`unitary` takes its matrix in parentheses",
            ));
        }
        let (matrix_text, targets_text) = braket::split_paren_body(rest, line)?;
        let matrix = braket::parse_matrix(matrix_text, line)?;
        let targets = self.qubits_of_text(targets_text, line)?;
        braket::unitary_instructions(&matrix, &targets, line)
    }

    /// Resolve a qubit reference written inside a pragma, whose body is its own
    /// grammar rather than part of the statement stream.
    pub(super) fn qubits_of_text(&self, token: &str, line: usize) -> Result<SmallVec<[usize; 4]>> {
        let mut out = SmallVec::new();
        for operand in syntax::parse_operands(&lexer::tokenize(token)?)? {
            out.extend(self.qubits_of(&Operand { line, ..operand })?);
        }
        Ok(out)
    }
}