dive-core 0.1.0

The dive execution core for TLA+: value store, plan compiler, interpreter and successor generation
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
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
//! The plan compiler: `dive_ir` plus the binder
//! handoff to a [`Plan`].
//!
//! Passes, in one walk:
//!
//! 1. **Static resolution.** Configuration redirects (`Op <- D`), startup
//!    values of constant definitions and constants become pool constants.
//! 2. **Operator inlining.** Every non-recursive user operator is inlined.
//!    Each argument is substituted directly when it is a literal, a constant,
//!    a bound variable or a state read (pure and unable to fail); otherwise it
//!    becomes a thunk slot, forced at most once per activation; an argument
//!    that reads primed variables is re-evaluated by name, as TLC's cache
//!    check would see a different successor buffer. Zero-arity `LET`
//!    definitions are thunks, re-enumerated by name in action position
//!    (TLC binds no `LET` in the generator). Recursive operators are
//!    compiled once into their own frame.
//! 3. **Slot resolution.** Locals become offsets in one flat frame per role.
//! 4. **Specialization.** Arithmetic, comparisons, `x' = e`, `x' \in S`,
//!    `UNCHANGED` of variable tuples, record fields by constant name, and
//!    membership in symbolic sets get their own node kinds.
//! 5. **Constant folding.** A closed subexpression (no state read, no free
//!    slot) is evaluated once at compile time; if it fails it is left alone,
//!    so the error surfaces where TLC raises it.
//! 6. **Read sets and memo sites.** Every node records the variables and
//!    free slots it reads; invariant and constraint conjuncts and action
//!    guards become memo sites keyed on them.
//!
//! Anything else is refused, naming the construct.

use std::collections::HashMap;
use std::sync::Arc;

use dive_ir::{
    Arg, Bound, BuiltinOp, DefId, DefScope, Expr, ExprId, Ir, JunctionKind, Level, LocalRef, OpRef,
    QuantKind, Slot, StdOp,
};
use dive_value::Value;

use crate::Error;
use crate::eval::Machine;
use crate::handle::Handle;
use crate::memo::{MAX_KEY, Memo};
use crate::node::Kind;
use crate::opts::Opts;
use crate::plan::{
    Action, Arith, Bind, Check, Cmp, Code, CompileStats, Conjunct, Fun, G, GNode, LibArg, MemoSite,
    Node, P, Plan, Quant, SetOp, StdFn, Update,
};
use crate::store::Store;

#[path = "compile_gen.rs"]
mod generator;

#[path = "compile_composition.rs"]
mod composition;

/// The largest plan the compiler builds (inlining blow-up guard).
const MAX_NODES: usize = 4_000_000;

/// The most loop iterations one constant fold may spend. A larger
/// closed expression, such as `CoffeeCan`'s initial filter over 1,002,001
/// records (over 10,201 already at 100 beans), is left to run time, where
/// the generator streams it instead of building it in the compile arena.
/// Type sets of a few hundred records, such as `MCNano`'s
/// `SignedBlock \cup {NoBlock}` (593 records, about 5,000 iterations), fit
/// and are folded once instead of being rebuilt in every state.
pub const FOLD_FUEL: u64 = 1 << 16;

/// The most loop iterations all constant folds of one compile may spend
/// together: the compile-time budget. Once it is spent, nothing more
/// is folded.
pub const FOLD_BUDGET: u64 = 1 << 22;

/// The most loop iterations the start-up evaluation of one closed
/// zero-arity definition whose fold ran out of [`FOLD_FUEL`] may spend
/// (`Compiler::settle`). `LeastCircularSubstring`'s
/// `Corpus == ZSeq(CharacterSet)` (9,841 sequences in the Medium model,
/// about 217,000 iterations) fits, and is built once instead of in every
/// state that tests membership in it.
pub const SETTLE_FUEL: u64 = 1 << 22;

/// The most loop iterations all such start-up evaluations of one compile
/// may spend together.
pub const SETTLE_BUDGET: u64 = 1 << 24;

/// A role as `dive-model`'s binder split it: an expression evaluated in a
/// definition's frame, with some of that frame's slots bound to values.
#[derive(Clone, Debug)]
pub struct Role {
    /// The name TLC reports.
    pub name: String,
    /// The expression.
    pub expr: ExprId,
    /// The definition whose frame it is evaluated in.
    pub def: DefId,
    /// Slots of that frame bound by splitting (`\E` variables and inlined
    /// parameters), with their values.
    pub slots: Vec<(Slot, Value)>,
    /// The `INSTANCE` substitutions active where splitting found the role
    /// (it found it inside an instantiated definition).
    pub substs: Vec<RoleSubst>,
}

/// An `INSTANCE` substitution active at a split role.
#[derive(Clone, Debug)]
pub enum RoleSubst {
    /// An operator bound to an uncaptured top-level definition.
    Operator {
        /// The substituted declaration.
        decl: dive_ir::DeclId,
        /// The actual definition, with no retained lexical/dynamic closure.
        def: DefId,
    },
    /// `decl <- expr`, with `expr` evaluated in the frame of `def` with
    /// `slots` bound, outside any substitution.
    Expr {
        /// The substituted declaration.
        decl: dive_ir::DeclId,
        /// The expression.
        expr: ExprId,
        /// The definition whose frame it is evaluated in.
        def: DefId,
        /// That frame's bound slots.
        slots: Vec<(Slot, Value)>,
    },
    /// `decl` bound to a value.
    Value {
        /// The substituted declaration.
        decl: dive_ir::DeclId,
        /// The value.
        value: Value,
    },
}

/// A configured constant.
#[derive(Clone, Debug)]
pub enum ConstBinding {
    /// `C = v`.
    Value(Value),
    /// `C <- D`.
    Def(DefId),
}

/// The binder's start-up evaluation of a constant definition it left to
/// the core ([`Handoff::deferred`]).
///
/// ```
/// #[derive(Debug)]
/// struct Never;
/// impl dive_core::compile::StartupEvaluator for Never {
///     fn evaluate(&self, _def: dive_ir::DefId) -> Option<dive_value::Value> {
///         None
///     }
/// }
/// ```
pub trait StartupEvaluator: std::fmt::Debug {
    /// The definition's start-up value, or `None` when its evaluation fails
    /// or leaves no value: the core then evaluates its body where it is
    /// used.
    fn evaluate(&self, def: DefId) -> Option<Value>;
}

/// The most transient memory, in bytes, the core's evaluation of one
/// deferred start-up definition may hold; past it, the definition goes to
/// the binder's evaluation ([`Handoff::startup_evaluator`]).
pub const STARTUP_TRANSIENT_BYTES: usize = 256 << 20;

/// What `dive-model`'s binder hands to the core.
#[derive(Clone, Debug)]
pub struct Handoff<'a> {
    /// The lowered specification.
    pub ir: &'a Ir,
    /// The value semantics the startup values were built under.
    pub ctx: dive_value::Ctx,
    /// Whether the existing TLA+ action-composition mode is enabled.
    pub action_composition: bool,
    /// Constants, by `ConstId`.
    pub constants: Vec<Option<ConstBinding>>,
    /// `Op <- D` redirects, resolved to their final target.
    pub redirects: HashMap<DefId, DefId>,
    /// Redirects of Java-overridden operators (`Nat <- NatOverride`).
    pub std_redirects: HashMap<StdOp, DefId>,
    /// Startup values of constant definitions.
    pub precomputed: HashMap<DefId, Value>,
    /// The definitions among `precomputed` whose value is a configuration
    /// override (`Op <- value`): their body is not their value.
    pub overrides: std::collections::HashSet<DefId>,
    /// Pure constant-level definitions the binder did not evaluate at
    /// startup (`dive_model::bind_deferring_constants`): the compiler
    /// evaluates each once, before the roles, and uses its value as a
    /// startup value. One the core cannot evaluate within its startup
    /// bounds goes to [`Self::startup_evaluator`], the binder's evaluation;
    /// one that fails there too keeps its body, which is then evaluated
    /// where it is used, as TLC does after a failed startup evaluation.
    pub deferred: std::collections::BTreeSet<DefId>,
    /// The binder's evaluation of a deferred definition, for the ones the
    /// core does not evaluate itself. Without one, such a definition keeps
    /// its body.
    pub startup_evaluator: Option<Arc<dyn StartupEvaluator>>,
    /// Pure `ASSUME`s of the root module (`dive_model::Model::deferred_assumptions`):
    /// the compiler evaluates them in order, after the deferred definitions,
    /// as it evaluates those, stopping at the first that is not `TRUE`, and
    /// lists the ones it finds `TRUE` in [`Plan::startup_assumptions`]. The caller checks the others with the
    /// dive-eval evaluator, which reports a false or failing one as TLC does.
    pub assumptions: Vec<DefId>,
    /// Initial predicates.
    pub init: Vec<Role>,
    /// Next-state actions, split, in TLC's order.
    pub next: Vec<Role>,
    /// `INVARIANT`s.
    pub invariants: Vec<Role>,
    /// `CONSTRAINT`s.
    pub constraints: Vec<Role>,
    /// `ACTION_CONSTRAINT`s, evaluated on a step: unprimed variables read
    /// the parent, primed ones the successor.
    pub action_constraints: Vec<Role>,
    /// Implied initial predicates: the state-level parts of `PROPERTY`s,
    /// checked on the initial states.
    pub implied_inits: Vec<Role>,
    /// Implied actions: the `[A]_v` of `[][A]_v` in `PROPERTY`s, evaluated
    /// on every step as `ACTION_CONSTRAINT`s are.
    pub implied_actions: Vec<Role>,
    /// Whether deadlock is checked.
    pub check_deadlock: bool,
    /// `SYMMETRY`: the closure's nonidentity maps, each as its moved
    /// model values `(from, to)` by name; empty without one.
    pub symmetry: Vec<Vec<(String, String)>>,
    /// `VIEW`: states are keyed by its value.
    pub view: Option<Role>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Mode {
    Plain,
    Primed,
}

/// Recursive compilation identity: definition, mode, Init, owner and substitutions.
type RecKey = (DefId, Mode, bool, Option<usize>, Option<u32>);

/// What a thunk of `Compiler::def_cache` stands for: a zero-arity
/// definition, or a substitution used by name, in a mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Cached {
    // The last substitution's unique id identifies the whole active prefix:
    // entries are immutable, appended fresh, and only truncated/restored.
    // A shared source definition can compile differently in two instances.
    Def(DefId, Mode, Option<u32>),
    Subst(u32, Mode),
}

#[derive(Clone, Copy, Debug)]
enum ArgHow {
    Alias(P),
    Thunk(u32, P),
    ByName,
}

#[derive(Clone, Debug)]
enum Sb {
    Unset,
    Flat(u32),
    Arg {
        expr: ExprId,
        env: usize,
        how: ArgHow,
    },
    LetVal {
        def: DefId,
        env: usize,
        thunk: Option<(u32, P)>,
        owner: usize,
    },
    /// The function name inside a recursive function definition.
    RecSelf(DefId, u32, Mode),
    /// A slot of the owning frame viewed by a LET-bound recursive function.
    /// The value is captured lazily; caller flat slot numbers never enter the
    /// function's runtime frame.
    Enclosing {
        env: usize,
        slot: usize,
    },
    /// An operator parameter bound to an operator argument: the operator,
    /// resolved in the caller's environment `env`.
    OpArg {
        op: OpRef,
        env: usize,
    },
}

/// A function being compiled from a definition nested in others (a
/// recursive `LET` operator or function): its references to enclosing
/// locals become captures, passed by every call (lambda lifting).
#[derive(Debug)]
struct Lift {
    /// The first environment of the function: lower ones enclose it.
    floor: usize,
    /// The definition's lexical parent environment.
    parent: Option<usize>,
    /// The function.
    fun: u32,
    /// Captures: frames out from `parent`, slot there, capture slot.
    caps: Vec<(u32, usize, u32)>,
    /// Recursive calls inside the body, completed with the captures.
    self_calls: Vec<P>,
    /// The mode the body is compiled in. A next-state variant reads every
    /// capture primed, and its callers compute the captures primed.
    mode: Mode,
}

/// One active `INSTANCE` substitution `decl <- value` (`Expr::Subst`), in
/// the dynamic context TLC binds it in (`Expr::SubstRef`).
#[derive(Clone, Debug)]
struct SubstEntry {
    /// Unique among the compiler's substitution entries (`Cached::Subst`).
    id: u32,
    decl: dive_ir::DeclId,
    /// The value: an argument, or a constant (`RoleSubst::Value`).
    value: Result<Arg, P>,
    /// The environment outside the substitution.
    env: usize,
    /// How an expression value is passed (as an operator argument is).
    how: ArgHow,
    /// The dynamic context outside the substitution: the stack below its
    /// group.
    depth: usize,
}

/// Saved slot bindings: environment, slot, old binding.
type Saved = Vec<(usize, usize, Sb)>;

#[derive(Clone, Debug)]
struct EnvFrame {
    def: DefId,
    slots: Vec<Sb>,
    parent: Option<usize>,
}

/// Pushes every value operand of `n` (not the bodies of called functions
/// or the generators of `ENABLED` and composition queries).
fn push_operands(n: &Node, out: &mut Vec<P>) {
    match n {
        Node::Const(_)
        | Node::Slot(_)
        | Node::Var(_)
        | Node::Primed(_)
        | Node::Enabled { .. }
        | Node::Composition { .. } => {}
        Node::Lazy { body, .. }
        | Node::Scope { body, .. }
        | Node::Memo { body, .. }
        | Node::SameVars { eq: body, .. }
        | Node::Spec(body)
        | Node::Not(body)
        | Node::Neg(body)
        | Node::Powerset(body)
        | Node::BigUnion(body)
        | Node::Domain(body)
        | Node::Select(body, _) => out.push(*body),
        Node::And(xs)
        | Node::Or(xs)
        | Node::SetEnum(xs)
        | Node::Product(xs)
        | Node::Tuple(xs)
        | Node::Std(_, xs)
        | Node::Lib { args: xs, .. }
        | Node::Call { args: xs, .. } => out.extend(xs.iter().copied()),
        Node::Implies(a, b)
        | Node::Equiv(a, b)
        | Node::Eq(a, b)
        | Node::Neq(a, b)
        | Node::In(a, b)
        | Node::NotIn(a, b)
        | Node::Subseteq(a, b)
        | Node::Arith(_, a, b)
        | Node::Cmp(_, a, b)
        | Node::Range(a, b)
        | Node::SetBin(_, a, b)
        | Node::FcnSet(a, b)
        | Node::Apply(a, b)
        | Node::InLazy {
            elem: a, set: b, ..
        }
        | Node::DomCheck {
            domain: a, body: b, ..
        } => out.extend([*a, *b]),
        Node::If(a, b, c)
        | Node::Beta {
            chain: a,
            fc: b,
            arg: c,
        } => out.extend([*a, *b, *c]),
        Node::Case(arms, other) => {
            for &(g, v) in arms {
                out.extend([g, v]);
            }
            out.extend(*other);
        }
        Node::RecSet(fs) | Node::Record(fs) => out.extend(fs.iter().map(|&(_, x)| x)),
        Node::Filter { bind, pred, subset } => {
            out.extend([bind.domain, *pred]);
            out.extend(*subset);
        }
        Node::Map { binds, body }
        | Node::FcnCons { binds, body }
        | Node::Quant { binds, body, .. } => {
            out.extend(binds.iter().map(|b| b.domain));
            out.push(*body);
        }
        Node::Except { base, updates } => {
            out.push(*base);
            for u in updates {
                out.extend(u.path.iter().copied());
                out.push(u.value);
            }
        }
        Node::LibHo(_, args) => out.extend(args.iter().map(|a| match a {
            LibArg::Value(p) => *p,
            LibArg::Op { body, .. } => *body,
        })),
    }
}

#[derive(Clone, Debug, Default)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "independent read, effect and budget eligibility facts"
)]
struct Info {
    vars: u64,
    primed: u64,
    free: Vec<u32>,
    calls: bool,
    /// Reaches a nested `ENABLED` or composition query: an instance query's
    /// identity-substitution proof does not cover its own cutoff.
    nested_query: bool,
    /// Contains a fold that ran out of fuel: enclosing folds would too.
    heavy: bool,
    /// Reaches an operator with an effect (`Print`, `PrintT`): TLC performs
    /// it on every evaluation, so the node is never folded, memoized,
    /// cached or skipped.
    effect: bool,
    /// Whether TLC's value of a set expression is `Reducible`,
    /// so that TLC builds a filter, function
    /// or set operation over it eagerly.
    red: Red,
}

/// Whether TLC's value of a set expression is `Reducible`: a set
/// enumeration or an interval (as `dive-eval`'s `is_reducible` decides). TLC builds `{x \in S : P}`, `[x \in S |-> e]` and
/// `S \cup T` eagerly over reducible operands and keeps them lazy
/// otherwise.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum Red {
    /// Always reducible.
    Yes,
    /// Never reducible.
    No,
    /// Not known statically.
    #[default]
    Maybe,
}

/// The most nodes of a constant [`Compiler::holds_lazy_set`] looks at.
const LAZY_SCAN: usize = 4096;

/// Whether Core applies the built-in `op` when it is passed as an
/// operator argument and applied to values: the set, equality,
/// membership, Boolean and `DOMAIN`/`SUBSET`/`UNION` operators. TLC
/// applies these exactly as the operator written in place, including the
/// short-circuit evaluation of `/\`, `\/` and `=>`. The state, temporal
/// and action operators (`'`, `UNCHANGED`, `ENABLED`, `\cdot`, `[]`, ...)
/// stay refused, and `\X` cannot be passed (`DIVE-S0032`).
const fn builtin_value_arg(op: BuiltinOp) -> bool {
    use BuiltinOp as B;
    matches!(
        op,
        B::Eq
            | B::Neq
            | B::In
            | B::NotIn
            | B::Subseteq
            | B::Cup
            | B::Cap
            | B::SetMinus
            | B::PowerSet
            | B::BigUnion
            | B::Domain
            | B::Not
            | B::And
            | B::Or
            | B::Implies
            | B::Equiv
    )
}

/// The arity of a built-in [`builtin_value_arg`] admits.
const fn builtin_arity(op: BuiltinOp) -> Option<usize> {
    use BuiltinOp as B;
    match op {
        B::PowerSet | B::BigUnion | B::Domain | B::Not => Some(1),
        B::Eq
        | B::Neq
        | B::In
        | B::NotIn
        | B::Subseteq
        | B::Cup
        | B::Cap
        | B::SetMinus
        | B::And
        | B::Or
        | B::Implies
        | B::Equiv => Some(2),
        _ => None,
    }
}

fn union(a: &mut Vec<u32>, b: &[u32]) {
    if b.is_empty() {
        return;
    }
    a.extend_from_slice(b);
    a.sort_unstable();
    a.dedup();
}

fn minus(a: &mut Vec<u32>, b: &[u32]) {
    a.retain(|x| !b.contains(x));
}

/// The plan's `SYMMETRY`: the maps over the store's string ids, and under
/// TLC's order TLC's canonicalization.
fn symmetry(h: &Handoff<'_>, m: &Machine) -> Result<Option<crate::symmetry::Symmetry>, Error> {
    if h.symmetry.is_empty() {
        return Ok(None);
    }
    let strings = m.heap.store().strings();
    let mut maps = Vec::with_capacity(h.symmetry.len());
    for perm in &h.symmetry {
        let mut pairs = Vec::with_capacity(perm.len());
        for (a, b) in perm {
            pairs.push((strings.intern(a)?, strings.intern(b)?));
        }
        maps.push(pairs);
    }
    let sym = crate::symmetry::Symmetry::new(maps);
    // TLC's order (`--compat=tlc`): TLC's comparison, in TLC's variable
    // order, as `TLCStateMut` canonicalizes.
    Ok(Some(if h.ctx.order == dive_value::ValueOrder::Tlc {
        sym.tlc(h.ir.tlc_var_order().iter().map(|v| v.index()).collect())
    } else {
        sym
    }))
}

/// A source-bound optional atom wrapper. The role and subscript share one scope.
#[derive(Clone, Copy, Debug)]
pub enum BoundTest {
    /// Ordinary predicate evaluation.
    Predicate,
    /// Successor existence, optionally requiring a subscript change.
    Enabled(Option<ExprId>),
    /// Check subscript change before evaluating the action.
    Nonstuttering(ExprId),
}

/// Compiles one optional source-bound atom using existing evaluation/generation.
///
/// The plan uses the same value nodes as safety checking. Callers separately
/// check its effects, compiled constants and actual input handles, and run it
/// on a machine with [`crate::Machine::set_refuse_unrecorded_warnings`], so a
/// reference warning that Core does not record declines instead.
///
/// ```no_run
/// # fn example(h: &dive_core::Handoff<'_>, store: std::sync::Arc<dive_core::Store>) -> Result<(), dive_core::Error> {
/// let plan = dive_core::compile::compile_bound_test(
///     h, store, dive_core::Opts::default(), dive_core::compile::BoundTest::Enabled(None))?;
/// # let _ = plan;
/// # Ok(()) }
/// ```
///
/// # Errors
/// The existing compiler refusal or an unproved wrapper/update shape.
pub fn compile_bound_test(
    h: &Handoff<'_>,
    store: Arc<Store>,
    opts: Opts,
    test: BoundTest,
) -> Result<Plan, Error> {
    if h.implied_actions.len() != 1
        || !h.init.is_empty()
        || !h.next.is_empty()
        || !h.invariants.is_empty()
        || !h.constraints.is_empty()
        || !h.action_constraints.is_empty()
        || !h.implied_inits.is_empty()
        || h.view.is_some()
    {
        return Err(Error::unsupported("one bound optional atom is required"));
    }
    let opts = Opts {
        memo: false,
        step_memo: false,
        primed_memo: false,
        fold: false,
        ..opts
    };
    compile_inner(h, store, opts, Some(test), false)
}

/// Compiles the handoff into a plan.
///
/// # Errors
/// [`crate::ErrorKind::Unsupported`] naming the first construct Core does
/// not implement.
pub fn compile(h: &Handoff<'_>, store: Arc<Store>, opts: Opts) -> Result<Plan, Error> {
    compile_inner(h, store, opts, None, false)
}

/// Compiles actual value/generator instruction maps for an explicitly observed run.
/// Ordinary compilation retains its allocation-free disabled mapping route.
///
/// # Errors
/// The existing compiler refusal or a bounded source-map capacity refusal.
pub fn compile_debug(h: &Handoff<'_>, store: Arc<Store>, opts: Opts) -> Result<Plan, Error> {
    if h.ir
        .files()
        .iter()
        .map(|file| file.source.len())
        .sum::<usize>()
        > 16 << 20
    {
        return Err(Error::unsupported("compiled debugger source capacity"));
    }
    compile_inner(h, store, opts, None, true)
}

#[allow(
    clippy::too_many_lines,
    reason = "ordered role compilation and optional source map finalization"
)]
fn compile_inner(
    h: &Handoff<'_>,
    store: Arc<Store>,
    opts: Opts,
    test: Option<BoundTest>,
    mapped: bool,
) -> Result<Plan, Error> {
    let nvars = h.ir.vars().len();
    if nvars > 64 {
        return Err(Error::unsupported("more than 64 state variables (M0 core)"));
    }
    let mut c = Compiler {
        h,
        effects: crate::plan::Effects::default(),
        ir: h.ir,
        code: Code {
            source_map: mapped.then(|| crate::debug::SourceMap {
                files: h.ir.files().to_vec(),
                variables: h
                    .ir
                    .vars()
                    .iter()
                    .map(|id| h.ir.decl(*id).name.clone())
                    .collect(),
                ..crate::debug::SourceMap::default()
            }),
            ..Code::default()
        },
        debug_current: None,
        debug_bytes: 0,
        info: Vec::new(),
        envs: Vec::new(),
        m: Machine::new(store, nvars, opts, Memo::default()),
        consts: HashMap::new(),
        pre: HashMap::new(),
        settled: HashMap::new(),
        settle_fuel: 0,
        fallback: HashMap::new(),
        startup_assumptions: Vec::new(),
        startup_assumption_false: None,
        next_slot: 0,
        reset_stack: Vec::new(),
        at_stack: Vec::new(),
        init_mode: false,
        funs: HashMap::new(),
        recfuns: HashMap::new(),
        primed_funs: std::collections::HashSet::new(),
        next_funs: std::collections::HashSet::new(),
        open_funs: std::collections::HashSet::new(),
        reentered_funs: std::collections::HashSet::new(),
        fun_reads: HashMap::new(),
        recursive_action_predicate: false,
        instance_query_calls: false,
        composition: composition::State::Absent,
        frame: 0,
        frames: 0,
        lazies: Vec::new(),
        compositions: Vec::new(),
        def_slots: std::collections::HashSet::new(),
        lifts: Vec::new(),
        substs: Vec::new(),
        fun_caps: HashMap::new(),
        def_cache: HashMap::new(),
        step: false,
        subst_ids: 0,
        effect_thunks: HashMap::new(),
        leaf: 0,
        opts,
        stats: CompileStats::default(),
        site_names: Vec::new(),
        role_name: String::new(),
        bound_preset: test.map(|_| Vec::new()),
    };
    c.startup_values();
    // The initial predicates are conjoined, as TLC's (and the reference
    // engine's `init_states`): one action.
    let init = if h.init.is_empty() {
        Vec::new()
    } else {
        vec![c.init_action(&h.init)?]
    };
    let mut next = Vec::new();
    for r in &h.next {
        next.push(c.action(r, false)?);
    }
    let mut invariants = Vec::new();
    for r in &h.invariants {
        invariants.push(c.check(r)?);
    }
    let view = h.view.as_ref().map(|r| c.view(r)).transpose()?;
    let mut constraints = Vec::new();
    for r in &h.constraints {
        constraints.push(c.check(r)?);
    }
    let mut action_constraints = Vec::new();
    for r in &h.action_constraints {
        action_constraints.push(c.step_check(r)?);
    }
    let mut implied_inits = Vec::new();
    for r in &h.implied_inits {
        implied_inits.push(c.check(r)?);
    }
    let mut implied_actions = Vec::new();
    for r in &h.implied_actions {
        implied_actions.push(if let Some(test) = test {
            c.bound_test(r, test)?
        } else {
            c.step_check(r)?
        });
    }
    // Check the complete compiled plan: Info::effect deliberately does not
    // follow Node::Call bodies, whereas every compiled effect sets effects.any.
    // Conservatively refuse mixed-effect plans and unknown call targets rather
    // than changing witness-dependent effects or inventing a purity analysis.
    if c.recursive_action_predicate
        && (c.effects.any
            || c.code.nodes.iter().any(|node| {
                matches!(node, Node::Call { fun, .. } if c.code.funs.get(*fun as usize).is_none())
            }))
    {
        return Err(Error::unsupported(
            "recursive Boolean action predicates in a compiled plan with effects or unproved calls",
        ));
    }
    // An instance ENABLED query may read compiled calls only when no call
    // body can reach an effect or a nested query, proved conservatively over
    // the whole plan once every function body is compiled.
    if c.instance_query_calls
        && (c.effects.any
            || c.code.nodes.iter().any(|node| {
                matches!(node, Node::Call { fun, .. } if c.code.funs.get(*fun as usize).is_none())
            })
            || c.code.funs.iter().any(|fun| {
                c.info
                    .get(fun.body as usize)
                    .is_none_or(|info| info.effect || info.nested_query)
            }))
    {
        return Err(Error::unsupported(
            "ENABLED in an INSTANCE with effects or recursive/nested calls (M1 core)",
        ));
    }
    c.reset_composition_thunks();
    c.stats.nodes = c.code.nodes.len();
    c.stats.gnodes = c.code.gnodes.len();
    let vars =
        h.ir.vars()
            .iter()
            .map(|&d| h.ir.decl(d).name.clone())
            .collect();
    if c.m.heap.poisoned() {
        return Err(Error::internal("a stale handle was read while compiling"));
    }
    let symmetry = symmetry(h, &c.m)?;
    if let Some(map) = &mut c.code.source_map {
        for check in invariants
            .iter()
            .chain(&implied_inits)
            .chain(&implied_actions)
        {
            map.obligations.extend(
                check
                    .conjuncts
                    .iter()
                    .map(|part| (part.p, check.name.clone())),
            );
        }
    }
    let mut plan = Plan {
        code: c.code,
        vars,
        init,
        next,
        invariants,
        constraints,
        action_constraints,
        implied_inits,
        implied_actions,
        check_deadlock: h.check_deadlock,
        symmetry,
        effects: c.effects,
        view,
        stats: c.stats,
        bound_preset: c.bound_preset.unwrap_or_default(),
        startup_assumptions: c.startup_assumptions,
        startup_assumption_false: c.startup_assumption_false,
    };
    if mapped {
        let executable = crate::debug::reachable(&plan);
        if let Some(map) = &mut plan.code.source_map {
            map.executable = executable;
        }
    }
    Ok(plan)
}

#[allow(
    clippy::struct_excessive_bools,
    reason = "independent compile modes and whole-plan proof obligations"
)]
struct Compiler<'a> {
    h: &'a Handoff<'a>,
    /// The effects compiled nodes reach (`Info::effect`).
    effects: crate::plan::Effects,
    ir: &'a Ir,
    code: Code,
    debug_current: Option<usize>,
    debug_bytes: usize,
    info: Vec<Info>,
    envs: Vec<EnvFrame>,
    m: Machine,
    consts: HashMap<usize, Handle>,
    pre: HashMap<DefId, Handle>,
    /// Closed zero-arity definitions whose fold ran out of fuel, evaluated
    /// once at their first use (`Self::settle`): the value, or `None` when
    /// the evaluation failed and the body is evaluated where it is used.
    settled: HashMap<DefId, Option<Handle>>,
    /// Loop iterations spent by [`Self::settle`], against [`SETTLE_BUDGET`].
    settle_fuel: u64,
    /// Start-up values of deferred definitions the binder's evaluation
    /// supplied ([`Handoff::startup_evaluator`]), used as `h.precomputed`.
    fallback: HashMap<DefId, Value>,
    /// The pure `ASSUME`s the compiler found `TRUE` ([`Handoff::assumptions`]).
    startup_assumptions: Vec<DefId>,
    /// The first pure `ASSUME` the compiler found `FALSE`, if it stopped there.
    startup_assumption_false: Option<DefId>,
    next_slot: u32,
    reset_stack: Vec<Vec<u32>>,
    at_stack: Vec<u32>,
    init_mode: bool,
    /// Recursive operators use the same context identity as function definitions.
    funs: HashMap<RecKey, u32>,
    /// Recursive function definitions `f[x \in S] == e` compiled as
    /// functions of their argument.
    recfuns: HashMap<RecKey, u32>,
    /// The functions compiled as a next-state variant (`Mode::Primed`): the
    /// whole body, and every capture, is read in the next state, so a call
    /// of one reads primed variables.
    primed_funs: std::collections::HashSet<u32>,
    /// The functions a call of which reads primed variables: the next-state
    /// variants, the plain variants of action-level definitions (SANY's
    /// level, the maximum over a recursive section, known before the body
    /// is compiled), and plain variants whose compiled body reads primed
    /// variables. A call of one is never passed as a thunk.
    next_funs: std::collections::HashSet<u32>,
    /// The functions whose body is being compiled.
    open_funs: std::collections::HashSet<u32>,
    /// The open functions called from inside their own compilation, before
    /// their body's reads were known.
    reentered_funs: std::collections::HashSet<u32>,
    /// The unprimed variables a call of a completed function reads through
    /// its body ([`Self::fun_summary`]), beyond those its arguments read.
    /// A function without an entry is assumed to read every variable.
    fun_reads: HashMap<u32, u64>,
    /// Whether an applied recursive function became a Boolean action guard.
    recursive_action_predicate: bool,
    /// Whether an `ENABLED` query in an instance reads a compiled call
    /// (`Node::Call`), whose body facts `Info` does not follow.
    instance_query_calls: bool,
    /// Whether source-changing composition is present or being compiled.
    composition: composition::State,
    /// The runtime frame being compiled: a role's frame, a compiled
    /// function body or a start-up evaluation. Slots index this frame only.
    frame: u32,
    /// Frames numbered so far.
    frames: u32,
    /// Every pushed thunk, with its frame (`Node::Lazy`).
    lazies: Vec<(u32, P)>,
    /// Every compiled composition site, with its frame.
    compositions: Vec<(u32, composition::Site)>,
    /// The thunk slots of `def_cache`.
    def_slots: std::collections::HashSet<u32>,
    /// The nested functions being compiled, innermost last.
    lifts: Vec<Lift>,
    /// The active `INSTANCE` substitutions, innermost last.
    substs: Vec<SubstEntry>,
    /// Each lifted function's captures: frames out from the definition's
    /// lexical parent, and slot there.
    fun_caps: HashMap<u32, Vec<(u32, usize)>>,
    /// Zero-arity top-level definitions of state level, and in a step
    /// predicate any zero-arity definition or substitution used by name,
    /// cached once per frame activation: their thunk slot and body.
    def_cache: HashMap<Cached, (u32, P)>,
    /// Whether the role being compiled is a step predicate (an implied
    /// action or an action constraint), evaluated on a complete pair: its
    /// primed variables, like its unprimed ones, are fixed while it is
    /// evaluated.
    step: bool,
    /// The next `SubstEntry::id`.
    subst_ids: u32,
    /// The generator expression of the first use of each thunk whose body
    /// has an effect (`Compiler::effect_thunk_use`).
    effect_thunks: HashMap<u32, u32>,
    /// The generator expression being compiled (`Compiler::g`).
    leaf: u32,
    opts: Opts,
    stats: CompileStats,
    site_names: Vec<String>,
    role_name: String,
    /// `Some` while compiling one bound optional atom: the frame slots its
    /// role binds, with their values, which the caller installs.
    bound_preset: Option<Vec<(u32, Handle)>>,
}

impl Compiler<'_> {
    fn debug_context(&mut self, expression: ExprId, env: usize) -> Result<Option<usize>, Error> {
        let Some(map) = &self.code.source_map else {
            return Ok(None);
        };
        if map.locations.len() >= 65_536 {
            return Err(Error::unsupported(
                "compiled debugger instruction context capacity",
            ));
        }
        let frame = self
            .envs
            .get(env)
            .ok_or_else(|| Error::internal("debugger compile environment"))?;
        let definition = self.ir.def(frame.def);
        let context_bytes = self
            .substs
            .iter()
            .try_fold(definition.name.len() + 128, |bytes, entry| {
                bytes.checked_add(self.ir.decl(entry.decl).name.len() + 96)
            })
            .ok_or_else(|| Error::unsupported("compiled debugger substitution capacity"))?;
        let bytes = definition
            .frame
            .iter()
            .try_fold(context_bytes, |bytes, slot| {
                bytes.checked_add(slot.name.len() + 64)
            })
            .and_then(|bytes| self.debug_bytes.checked_add(bytes))
            .filter(|bytes| *bytes <= 8 << 20)
            .ok_or_else(|| Error::unsupported("compiled debugger source/local byte capacity"))?;
        self.debug_bytes = bytes;
        let locals = definition
            .frame
            .iter()
            .zip(&frame.slots)
            .map(|(name, slot)| {
                let binding = match slot {
                    Sb::Flat(slot)
                    | Sb::Arg {
                        how: ArgHow::Thunk(slot, _),
                        ..
                    }
                    | Sb::LetVal {
                        thunk: Some((slot, _)),
                        ..
                    } => crate::debug::Binding::Slot(*slot),
                    Sb::Arg {
                        how: ArgHow::Alias(node),
                        ..
                    } => crate::debug::Binding::Alias(*node),
                    _ => crate::debug::Binding::Unavailable,
                };
                crate::debug::Local {
                    name: name.name.clone(),
                    binding,
                }
            })
            .collect();
        let location = crate::debug::Location {
            origin: self.ir.node(expression).origin,
            definition: definition.name.clone(),
            definition_id: frame.def.index(),
            environment_id: env,
            locals,
            caller: self.debug_current,
            substitutions: self
                .substs
                .iter()
                .map(|entry| crate::debug::Substitution {
                    declaration: self.ir.decl(entry.decl).name.clone(),
                    actual: match &entry.value {
                        Ok(Arg::Expr { expr, .. }) => Some(self.ir.node(*expr).origin),
                        _ => None,
                    },
                    identity: entry.id,
                })
                .collect(),
        };
        let Some(map) = &mut self.code.source_map else {
            return Ok(None);
        };
        let index = map.locations.len();
        map.locations.push(location);
        Ok(Some(index))
    }

    /// Starts a new runtime frame, returning the enclosing one.
    fn new_frame(&mut self) -> u32 {
        self.frames += 1;
        std::mem::replace(&mut self.frame, self.frames)
    }

    fn alloc(&mut self) -> u32 {
        let s = self.next_slot;
        self.next_slot += 1;
        s
    }

    fn redirect(&self, d: DefId) -> DefId {
        let mut d = d;
        for _ in 0..64 {
            match self.h.redirects.get(&d) {
                Some(&t) if t != d => d = t,
                _ => break,
            }
        }
        d
    }

    fn convert(&mut self, v: &Value) -> Result<Handle, Error> {
        crate::convert::from_value(&mut self.m.heap, v, self.h.ctx)
    }

    /// Whether `d` has a startup value: the binder's, or one the compiler
    /// evaluated ([`Self::startup_values`]).
    fn has_startup_value(&self, d: DefId) -> bool {
        self.h.precomputed.contains_key(&d)
            || self.pre.contains_key(&d)
            || self.fallback.contains_key(&d)
    }

    fn precomputed(&mut self, d: DefId) -> Result<Option<Handle>, Error> {
        if let Some(&h) = self.pre.get(&d) {
            return Ok(Some(h));
        }
        let v = match self.h.precomputed.get(&d) {
            Some(v) => v.clone(),
            None => match self.fallback.get(&d) {
                Some(v) => v.clone(),
                None => return Ok(None),
            },
        };
        // TLC's startup value of a constant definition may be lazy (a
        // filter or function over `Nat`, a recursive function): the core
        // then compiles the definition's body, which has the same value.
        let h = match self.convert(&v) {
            Ok(h) => h,
            Err(e)
                if e.kind() == crate::ErrorKind::Unsupported && !self.h.overrides.contains(&d) =>
            {
                return Ok(None);
            }
            Err(e) => return Err(e),
        };
        self.pre.insert(d, h);
        Ok(Some(h))
    }

    fn new_env(&mut self, def: DefId, parent: Option<usize>) -> usize {
        let n = self.ir.def(def).frame.len();
        self.envs.push(EnvFrame {
            def,
            slots: vec![Sb::Unset; n],
            parent,
        });
        self.envs.len() - 1
    }

    /// The environment of the enclosing activation of `def`, from `env`
    /// outwards.
    fn find_env(&self, env: usize, def: DefId) -> Option<usize> {
        let mut e = Some(env);
        while let Some(i) = e {
            if self.envs[i].def == def {
                return Some(i);
            }
            e = self.envs[i].parent;
        }
        None
    }

    fn lexical_parent(&self, d: DefId, env: usize) -> Result<Option<usize>, Error> {
        match self.ir.def(d).scope {
            DefScope::TopLevel => Ok(None),
            DefScope::Local { parent } | DefScope::Inline { parent } => self
                .find_env(env, parent)
                .map(Some)
                .ok_or_else(|| Error::unsupported("a LET operator used outside its LET (M0 core)")),
            DefScope::LetValue { .. } => Err(Error::internal("a LET value used as an operator")),
        }
    }

    // ------------------------------------------------------------------
    // Nodes, read sets and folding
    // ------------------------------------------------------------------

    #[allow(
        clippy::too_many_lines,
        clippy::many_single_char_names,
        reason = "one arm per node kind"
    )]
    fn info_of(&self, n: &Node) -> Info {
        let mut i = Info::default();
        let mut add = |p: P, i: &mut Info| {
            if let Some(c) = self.info.get(p as usize) {
                i.vars |= c.vars;
                i.primed |= c.primed;
                i.calls |= c.calls;
                i.nested_query |= c.nested_query;
                i.heavy |= c.heavy;
                i.effect |= c.effect;
                union(&mut i.free, &c.free);
            }
        };
        let binders =
            |binds: &[Bind], body: &[P], i: &mut Info, add: &mut dyn FnMut(P, &mut Info)| {
                let mut inner = Info::default();
                for &b in body {
                    add(b, &mut inner);
                }
                let bound: Vec<u32> = binds.iter().flat_map(|b| b.slots.iter().copied()).collect();
                minus(&mut inner.free, &bound);
                i.vars |= inner.vars;
                i.primed |= inner.primed;
                i.calls |= inner.calls;
                i.nested_query |= inner.nested_query;
                i.heavy |= inner.heavy;
                i.effect |= inner.effect;
                union(&mut i.free, &inner.free);
                for b in binds {
                    add(b.domain, i);
                }
            };
        match n {
            Node::Const(_) => {}
            Node::Slot(s) => i.free.push(*s),
            Node::Lazy { body, .. }
            | Node::Scope { body, .. }
            | Node::Memo { body, .. }
            | Node::SameVars { eq: body, .. }
            | Node::Spec(body) => {
                add(*body, &mut i);
            }
            Node::InLazy { elem, set, .. } => {
                add(*elem, &mut i);
                add(*set, &mut i);
            }
            Node::Beta { chain, arg, .. } => {
                add(*chain, &mut i);
                add(*arg, &mut i);
            }
            Node::DomCheck { slot, domain, body } => {
                add(*domain, &mut i);
                add(*body, &mut i);
                minus(&mut i.free, &[*slot]);
            }
            Node::Var(v) => i.vars |= 1u64 << v,
            Node::Primed(v) => i.primed |= 1u64 << v,
            Node::Not(a)
            | Node::Neg(a)
            | Node::Powerset(a)
            | Node::BigUnion(a)
            | Node::Domain(a)
            | Node::Select(a, _) => {
                add(*a, &mut i);
            }
            Node::And(xs)
            | Node::Or(xs)
            | Node::SetEnum(xs)
            | Node::Product(xs)
            | Node::Tuple(xs)
            | Node::Std(_, xs) => {
                for &x in xs {
                    add(x, &mut i);
                }
            }
            Node::Lib { op, args: xs, .. } => {
                for &x in xs {
                    add(x, &mut i);
                }
                i.effect |= crate::stdlib::effectful(*op);
            }
            Node::Implies(a, b)
            | Node::Equiv(a, b)
            | Node::Eq(a, b)
            | Node::Neq(a, b)
            | Node::In(a, b)
            | Node::NotIn(a, b)
            | Node::Subseteq(a, b)
            | Node::Arith(_, a, b)
            | Node::Cmp(_, a, b)
            | Node::Range(a, b)
            | Node::SetBin(_, a, b)
            | Node::FcnSet(a, b)
            | Node::Apply(a, b) => {
                add(*a, &mut i);
                add(*b, &mut i);
            }
            Node::If(a, b, c) => {
                add(*a, &mut i);
                add(*b, &mut i);
                add(*c, &mut i);
            }
            Node::Case(arms, other) => {
                for &(g, v) in arms {
                    add(g, &mut i);
                    add(v, &mut i);
                }
                if let Some(o) = other {
                    add(*o, &mut i);
                }
            }
            Node::RecSet(fs) | Node::Record(fs) => {
                for &(_, x) in fs {
                    add(x, &mut i);
                }
            }
            Node::Filter { bind, pred, .. } => {
                binders(std::slice::from_ref(bind), &[*pred], &mut i, &mut add);
            }
            Node::Map { binds, body }
            | Node::FcnCons { binds, body }
            | Node::Quant { binds, body, .. } => {
                binders(binds, &[*body], &mut i, &mut add);
            }
            Node::Except { base, updates } => {
                add(*base, &mut i);
                for u in updates {
                    for &p in &u.path {
                        add(p, &mut i);
                    }
                    let mut inner = Info::default();
                    add(u.value, &mut inner);
                    minus(&mut inner.free, &[u.at]);
                    i.vars |= inner.vars;
                    i.primed |= inner.primed;
                    i.calls |= inner.calls;
                    i.nested_query |= inner.nested_query;
                    i.heavy |= inner.heavy;
                    i.effect |= inner.effect;
                    union(&mut i.free, &inner.free);
                }
            }
            Node::LibHo(_, args) => {
                for a in args {
                    match a {
                        LibArg::Value(p) => add(*p, &mut i),
                        LibArg::Op { params, body } => {
                            let mut inner = Info::default();
                            add(*body, &mut inner);
                            minus(&mut inner.free, params);
                            i.vars |= inner.vars;
                            i.primed |= inner.primed;
                            i.calls |= inner.calls;
                            i.nested_query |= inner.nested_query;
                            i.heavy |= inner.heavy;
                            i.effect |= inner.effect;
                            union(&mut i.free, &inner.free);
                        }
                    }
                }
            }
            Node::Call { fun, args } => {
                for &a in args {
                    add(a, &mut i);
                }
                i.calls = true;
                // A completed function's body reads only its own frame (the
                // arguments and captures passed here) and the variables of
                // its summary. An open one's reads are not known yet.
                match self.fun_reads.get(fun) {
                    Some(&vars) if !self.open_funs.contains(fun) => i.vars |= vars,
                    _ => i.vars = u64::MAX,
                }
                if self.next_funs.contains(fun) {
                    i.primed = u64::MAX;
                }
            }
            // The action's reads are not tracked variable by variable: it
            // reads every variable, so it is never folded or skipped.
            Node::Enabled { free, .. } => {
                union(&mut i.free, free);
                i.calls = true;
                i.nested_query = true;
                i.vars = u64::MAX;
            }
            Node::Composition { free, .. } => {
                union(&mut i.free, free);
                i.calls = true;
                i.nested_query = true;
                i.vars = u64::MAX;
                i.primed = u64::MAX;
            }
        }
        i.red = self.red_of(n);
        i
    }

    fn red(&self, p: P) -> Red {
        self.info.get(p as usize).map_or(Red::Maybe, |i| i.red)
    }

    /// TLC's reducibility of a node's value (`Info::red`).
    fn red_of(&self, n: &Node) -> Red {
        match n {
            Node::Const(h) => {
                if !h.is_compound() {
                    return Red::Yes;
                }
                match self.m.heap.view(*h).kind {
                    Kind::Product
                    | Kind::FcnSet
                    | Kind::RecSet
                    | Kind::Subset
                    | Kind::Nat
                    | Kind::Int
                    | Kind::SeqSet => Red::No,
                    _ => Red::Yes,
                }
            }
            Node::SetEnum(..) | Node::Range(..) | Node::Map { .. } => Red::Yes,
            Node::Product(_)
            | Node::FcnSet(..)
            | Node::RecSet(_)
            | Node::Powerset(_)
            | Node::Std(StdFn::Seq, _) => Red::No,
            Node::Filter { bind, .. } => match self.red(bind.domain) {
                Red::Yes => Red::Yes,
                Red::No => Red::No,
                Red::Maybe => Red::Maybe,
            },
            // `S \ T` is reducible as `S` is; `S \cup T` and `S \cap T` are
            // reducible when both are, and lazy when neither is.
            Node::SetBin(SetOp::Minus, a, _) => self.red(*a),
            Node::SetBin(_, a, b) => match (self.red(*a), self.red(*b)) {
                (Red::Yes, Red::Yes) => Red::Yes,
                (Red::No, Red::No) => Red::No,
                _ => Red::Maybe,
            },
            Node::Spec(b)
            | Node::Lazy { body: b, .. }
            | Node::Scope { body: b, .. }
            | Node::Memo { body: b, .. } => self.red(*b),
            _ => Red::Maybe,
        }
    }

    /// The rewrite of `{E \in SUBSET T : \A e \in E : Q}` as `SUBSET F`,
    /// `F = {e \in T : Q}`, when its side conditions hold: one plain
    /// bound `E` over `SUBSET T` (or its folded constant), a predicate that
    /// is exactly a single-variable `\A` over `E` itself, and a body `Q`
    /// that does not read `E`, reads no primed variable, makes no call
    /// (recursive operator, `ENABLED`, composition) and has no effect.
    /// Then `Q` is a function of `e` alone during the filter, so
    /// `\A e \in E : Q` holds exactly when `E \subseteq F`. Returns the
    /// node of `F`, which enumeration uses in place of the filter
    /// (`Node::Filter::subset`).
    fn subset_rewrite(&mut self, bind: &Bind, pred: P) -> Result<Option<P>, Error> {
        let [outer] = *bind.slots else {
            return Ok(None);
        };
        if bind.tuple {
            return Ok(None);
        }
        let base = match self.code.nodes.get(bind.domain as usize) {
            Some(Node::Powerset(t)) => *t,
            Some(Node::Const(h)) if h.is_compound() => {
                let v = self.m.heap.view(*h);
                match (v.kind, v.data) {
                    (Kind::Subset, &[t]) => self.push(Node::Const(t))?,
                    _ => return Ok(None),
                }
            }
            _ => return Ok(None),
        };
        let Some(Node::Quant {
            kind: Quant::Forall,
            binds,
            body,
        }) = self.code.nodes.get(pred as usize)
        else {
            return Ok(None);
        };
        let [inner] = binds.as_ref() else {
            return Ok(None);
        };
        if inner.tuple
            || inner.slots.len() != 1
            || !matches!(
                self.code.nodes.get(inner.domain as usize),
                Some(Node::Slot(s)) if *s == outer
            )
        {
            return Ok(None);
        }
        let (inner, body) = (inner.clone(), *body);
        let Some(info) = self.info.get(body as usize) else {
            return Ok(None);
        };
        if info.free.contains(&outer) || info.primed != 0 || info.calls || info.effect {
            return Ok(None);
        }
        let set = self.push(Node::Filter {
            bind: Bind {
                slots: inner.slots,
                tuple: false,
                domain: base,
            },
            pred: body,
            subset: None,
        })?;
        Ok(Some(set))
    }

    /// Pushes a filter, function constructor or set operation, wrapped in
    /// `Node::Spec` when TLC would build it lazily: the core builds it
    /// eagerly, so an evaluation error inside it may be one TLC never
    /// raises.
    fn push_lazy(&mut self, n: Node) -> Result<P, Error> {
        let eager = match &n {
            Node::Filter { bind, .. } => self.red(bind.domain) == Red::Yes,
            Node::FcnCons { binds, .. } => binds.iter().all(|b| self.red(b.domain) == Red::Yes),
            Node::SetBin(SetOp::Minus, a, _) => self.red(*a) == Red::Yes,
            Node::SetBin(_, a, b) => self.red(*a) == Red::Yes && self.red(*b) == Red::Yes,
            _ => true,
        };
        let p = self.push(n)?;
        if eager {
            Ok(p)
        } else {
            self.stats.speculative += 1;
            self.push(Node::Spec(p))
        }
    }

    /// Whether a set node is one TLC certainly keeps lazy, a filter or a
    /// set operation over non-reducible sets: membership in it is decided
    /// structurally (`Node::InLazy`), as TLC decides it.
    fn lazy_set(&self, p: P) -> bool {
        let p = self.unspec(p);
        match self.code.nodes.get(p as usize) {
            Some(Node::Filter { .. } | Node::SetBin(..)) => self.red(p) == Red::No,
            Some(Node::Lazy { body, .. } | Node::Scope { body, .. }) => self.lazy_set(*body),
            // A primed definition's site is transparent to membership: the
            // test is decided on the body, never on a materialized value
            // (`Machine::member_lazy`).
            Some(Node::Memo { site, body })
                if self
                    .code
                    .sites
                    .get(*site as usize)
                    .is_some_and(|s| s.candidate) =>
            {
                self.lazy_set(*body)
            }
            _ => false,
        }
    }

    /// The function constructor a function expression leads to through
    /// thunks, scopes and speculation wrappers, if any.
    fn lambda(&self, mut p: P) -> Option<P> {
        loop {
            match self.code.nodes.get(p as usize)? {
                Node::Spec(b) | Node::Lazy { body: b, .. } | Node::Scope { body: b, .. } => p = *b,
                Node::FcnCons { .. } => return Some(p),
                _ => return None,
            }
        }
    }

    /// `f[a]`. TLC evaluates `f` with `KEEP_LAZY`, so a function
    /// constructor reached directly, or through a definition, stays lazy,
    /// and so does one over a non-reducible domain. One reached through a
    /// `LET` value or an operator argument (a `LazyValue`) over reducible
    /// domains is built eagerly (fixture `LzApplyDef`). A lazy one whose
    /// bound variables have no tuple pattern is applied without being built
    /// (`Node::Beta`); a lazy one with a tuple pattern is built
    /// speculatively.
    fn apply_value(&mut self, f: P, a: P) -> Result<P, Error> {
        let Some(fc) = self.lambda(f) else {
            return self.push(Node::Apply(f, a));
        };
        let Some(Node::FcnCons { binds, .. }) = self.code.nodes.get(fc as usize) else {
            return self.push(Node::Apply(f, a));
        };
        // Bound variables without tuple patterns: TLC's `FcnLambdaValue.apply`
        // binds each from its argument (several from a tuple) and evaluates
        // the body for that argument alone.
        let plain = binds.iter().all(|b| !b.tuple && !b.slots.is_empty());
        let non_reducible = binds.iter().any(|b| self.red(b.domain) == Red::No);
        let mut thunk = false;
        let mut p = f;
        while let Some(
            n @ (Node::Spec(b) | Node::Lazy { body: b, .. } | Node::Scope { body: b, .. }),
        ) = self.code.nodes.get(p as usize)
        {
            if let Node::Lazy { slot, .. } = n {
                thunk |= !self.def_slots.contains(slot);
            }
            p = *b;
        }
        if !non_reducible && thunk {
            // Built eagerly, as TLC builds it (speculatively already when
            // its domains may not be reducible: `push_lazy`).
            return self.push(Node::Apply(f, a));
        }
        if plain {
            self.stats.beta += 1;
            return self.push(Node::Beta {
                chain: f,
                fc,
                arg: a,
            });
        }
        let f = if matches!(self.code.nodes.get(f as usize), Some(Node::Spec(_))) {
            f
        } else {
            self.stats.speculative += 1;
            self.push(Node::Spec(f))?
        };
        self.push(Node::Apply(f, a))
    }

    /// `DOMAIN f` of a function constructor TLC certainly keeps lazy (over
    /// a non-reducible domain): its domain, without building it
    /// (`FcnLambdaValue.getDomain`). `None` otherwise.
    fn lambda_domain(&mut self, f: P) -> Result<Option<P>, Error> {
        let Some(fc) = self.lambda(f) else {
            return Ok(None);
        };
        let Some(Node::FcnCons { binds, .. }) = self.code.nodes.get(fc as usize) else {
            return Ok(None);
        };
        if !binds.iter().any(|b| self.red(b.domain) == Red::No) {
            return Ok(None);
        }
        if binds.len() == 1 && (binds[0].tuple || binds[0].slots.len() == 1) {
            return Ok(Some(binds[0].domain));
        }
        let mut ds = Vec::new();
        for b in binds {
            if b.tuple {
                ds.push(b.domain);
            } else {
                ds.extend(std::iter::repeat_n(b.domain, b.slots.len()));
            }
        }
        Ok(Some(self.push(Node::Product(ds.into()))?))
    }

    /// The recursive function a function expression names, if it is the
    /// name of `f[x \in S] == e` (outside or inside its body), compiled as
    /// a function of its argument.
    fn rec_target(
        &mut self,
        fcn: ExprId,
        env: usize,
        mode: Mode,
    ) -> Result<Option<(DefId, u32)>, Error> {
        let (d, call_env) = match &self.ir.node(fcn).expr {
            Expr::Local(r) => {
                let fe = self.frame_env(env, r.up)?;
                match self.envs[fe].slots.get(r.slot.index()).cloned() {
                    Some(Sb::RecSelf(d, f, defined_mode)) => {
                        if self.lifts.last().is_some_and(|l| fe < l.floor) {
                            return Err(Error::unsupported(
                                "a recursive function used inside a nested recursive definition (M1 core)",
                            ));
                        }
                        if mode != defined_mode {
                            return Err(Error::unsupported(
                                "a recursive function with mixed plain and primed self applications (M1 core)",
                            ));
                        }
                        return Ok(Some((d, f)));
                    }
                    Some(Sb::LetVal { def, env, .. }) => (def, env),
                    _ => return Ok(None),
                }
            }
            Expr::Def(d) => (*d, env),
            Expr::Apply {
                callee: OpRef::Def(d),
                args,
            } if args.is_empty() => (*d, env),
            _ => return Ok(None),
        };
        let d = self.redirect(d);
        if self.precomputed(d)?.is_some() {
            return Ok(None);
        }
        let def = self.ir.def(d);
        if !def.params.is_empty() || def.std.is_some() {
            return Ok(None);
        }
        let Expr::RecFcn { .. } = &self.ir.node(def.body).expr else {
            return Ok(None);
        };
        self.recfun(d, call_env, mode).map(|f| Some((d, f)))
    }

    /// Compiles `f[x \in S] == e` as a function of its argument, in slot 0:
    /// `DomCheck { 0, S, e }`, with `f[...]` inside `e` a recursive call.
    fn recfun(&mut self, d: DefId, call_env: usize, mode: Mode) -> Result<u32, Error> {
        let owner = match self.ir.def(d).scope {
            DefScope::LetValue { parent, .. } => {
                Some(self.find_env(call_env, parent).ok_or_else(|| {
                    Error::unsupported(
                        "a recursive LET function outside its lexical activation (M1 core)",
                    )
                })?)
            }
            _ => self.lexical_parent(d, call_env)?,
        };
        let key = (
            d,
            mode,
            self.init_mode,
            owner,
            self.substs.last().map(|s| s.id),
        );
        if let Some(&f) = self.recfuns.get(&key) {
            return Ok(self.reenter(f));
        }
        let def = self.ir.def(d);
        let Expr::RecFcn { name, bounds, body } = &self.ir.node(def.body).expr else {
            return Err(Error::internal("not a recursive function definition"));
        };
        let (name, body) = (*name, *body);
        let [b] = &bounds[..] else {
            return Err(Error::unsupported(
                "a recursive function of several bound groups (M1 core)",
            ));
        };
        let ([x], false, Some(domain)) = (&b.vars[..], b.tuple, b.domain) else {
            return Err(Error::unsupported(
                "a recursive function of several arguments or a tuple pattern (M1 core)",
            ));
        };
        let x = *x;
        #[allow(clippy::cast_possible_truncation, reason = "bounded")]
        let id = self.code.funs.len() as u32;
        self.code.funs.push(Fun {
            name: def.name.clone(),
            params: 1,
            frame: 1,
            body: 0,
            caps: Box::new([]),
        });
        self.recfuns.insert(key, id);
        self.open_fun(id, mode, def.level);
        let saved_slot = self.next_slot;
        let saved_resets = std::mem::take(&mut self.reset_stack);
        let saved_cache = std::mem::take(&mut self.def_cache);
        let saved_at = std::mem::take(&mut self.at_stack);
        self.next_slot = 1;
        let saved_frame = self.new_frame();
        let (env, lifted) = match self.begin_recfun(d, id, call_env, owner, mode) {
            Ok(x) => x,
            Err(e) => {
                self.frame = saved_frame;
                self.next_slot = saved_slot;
                self.reset_stack = saved_resets;
                self.def_cache = saved_cache;
                self.at_stack = saved_at;
                return Err(e);
            }
        };
        if let Some(s) = self.envs[env].slots.get_mut(name.index()) {
            *s = Sb::RecSelf(d, id, mode);
        }
        if let Some(s) = self.envs[env].slots.get_mut(x.index()) {
            *s = Sb::Flat(0);
        }
        let r = self
            .p(domain, env, mode)
            .and_then(|dom| Ok((dom, self.p(body, env, mode)?)));
        let ended = self.end_fun(id, lifted);
        self.frame = saved_frame;
        let frame = self.next_slot;
        self.next_slot = saved_slot;
        self.reset_stack = saved_resets;
        self.def_cache = saved_cache;
        self.at_stack = saved_at;
        self.open_funs.remove(&id);
        let (dom, b) = r?;
        ended?;
        self.note_next_reads(id, &[dom, b])?;
        if mode == Mode::Primed && (self.info[dom as usize].effect || self.info[b as usize].effect)
        {
            return Err(Error::unsupported(
                "an effectful recursive function under a prime (M1 core)",
            ));
        }
        let checked = self.push(Node::DomCheck {
            slot: 0,
            domain: dom,
            body: b,
        })?;
        self.complete_fun(id, checked, frame);
        Ok(id)
    }

    /// The node under any `Node::Spec` wrappers.
    fn unspec(&self, mut p: P) -> P {
        while let Some(Node::Spec(b)) = self.code.nodes.get(p as usize) {
            p = *b;
        }
        p
    }

    /// Refuses an effect inside an expression whose evaluation order or
    /// count is TLC's representation choice rather than the expression's:
    /// a function constructor, filter or set map (TLC may build it eagerly,
    /// lazily or once per application), a speculative evaluation, and an
    /// operator argument of a library operator (applied in TLC's internal
    /// order).
    fn effect_allowed(&self, n: &Node) -> Result<(), Error> {
        let inside = |p: P| self.info.get(p as usize).is_some_and(|i| i.effect);
        let lazy = match n {
            Node::FcnCons { body, .. } | Node::Map { body, .. } => inside(*body),
            Node::Filter { pred, .. } => inside(*pred),
            Node::Spec(b) => inside(*b),
            Node::LibHo(_, args) => args
                .iter()
                .any(|a| matches!(a, LibArg::Op { body, .. } if inside(*body))),
            _ => false,
        };
        if lazy {
            return Err(Error::unsupported(
                "Print, PrintT, RandomElement, TLCSet or TLCGet inside a function constructor, set filter, set map or operator argument, which TLC may evaluate lazily or in its own order (M1 core)",
            ));
        }
        Ok(())
    }

    /// Records a use of the thunk `slot`. A `LET`-bound definition or an
    /// operator argument whose body has an effect is TLC's `LazyValue`.
    /// Within one expression TLC forces it once, as the core does; across
    /// the conjuncts of `Init` or an action it evaluates the body again
    /// (fixture `RndLetRedraw`), where the core's thunk is forced once. So
    /// a use in a second generator expression is refused.
    fn effect_thunk_use(&mut self, slot: u32, body: P) -> Result<(), Error> {
        if !self.info.get(body as usize).is_some_and(|i| i.effect) {
            return Ok(());
        }
        let leaf = self.leaf;
        if *self.effect_thunks.entry(slot).or_insert(leaf) != leaf {
            return Err(Error::unsupported(
                "a LET-bound definition or operator argument with an effect (Print, PrintT, RandomElement) used in more than one conjunct, which TLC evaluates again in each (M1 core)",
            ));
        }
        Ok(())
    }

    /// Whether a node may build a value TLC keeps as an interval or a lazy
    /// set, which printing must know (`Store::note_lazy_sets`).
    fn builds_lazy_set(&self, n: &Node) -> bool {
        match n {
            Node::Range(..)
            | Node::Domain(_)
            | Node::Powerset(_)
            | Node::FcnSet(..)
            | Node::RecSet(_)
            | Node::Product(_) => true,
            Node::Const(h) => self.holds_lazy_set(*h, &mut 0),
            _ => false,
        }
    }

    /// Whether a constant holds an interval or a lazy set, looking at most
    /// at [`LAZY_SCAN`] nodes (beyond, it is assumed to).
    fn holds_lazy_set(&self, h: Handle, seen: &mut usize) -> bool {
        if !h.is_compound() {
            return false;
        }
        *seen += 1;
        if *seen > LAZY_SCAN {
            return true;
        }
        let v = self.m.heap.view(h);
        if matches!(
            v.kind,
            Kind::Interval | Kind::Subset | Kind::FcnSet | Kind::RecSet | Kind::Product
        ) {
            return true;
        }
        let data = v.data.to_vec();
        data.into_iter().any(|d| self.holds_lazy_set(d, seen))
    }

    fn push(&mut self, n: Node) -> Result<P, Error> {
        if self.code.nodes.len() >= MAX_NODES {
            return Err(Error::unsupported(
                "a plan larger than the M0 core's inlining limit",
            ));
        }
        let info = self.info_of(&n);
        if !self.m.heap.store().lazy_sets() && self.builds_lazy_set(&n) {
            self.m.heap.store().note_lazy_sets();
        }
        if info.effect {
            self.effect_allowed(&n)?;
            self.effects.any = true;
        }
        if let Node::Lib { op, .. } = &n {
            match op {
                StdOp::TlcPrint | StdOp::TlcPrintT => self.effects.prints = true,
                StdOp::TlcRandomElement => self.effects.draws = true,
                StdOp::TlcTLCSet => self.effects.registers = true,
                _ => {}
            }
        }
        let foldable = !matches!(
            n,
            Node::Const(_) | Node::Slot(_) | Node::Var(_) | Node::Primed(_) | Node::Memo { .. }
        );
        #[allow(clippy::cast_possible_truncation, reason = "bounded by MAX_NODES")]
        let id = self.code.nodes.len() as P;
        if let Some(map) = &mut self.code.source_map {
            let source = self.debug_current.or_else(|| match &n {
                Node::Memo { body, .. } | Node::Scope { body, .. } => {
                    map.values.get(*body as usize).copied().flatten()
                }
                _ => None,
            });
            map.values.push(source);
        }
        if matches!(n, Node::Lazy { .. }) {
            self.lazies.push((self.frame, id));
        }
        self.code.nodes.push(n);
        let closed = info.vars == 0
            && info.primed == 0
            && info.free.is_empty()
            && !info.calls
            && !info.heavy
            && !info.effect;
        self.info.push(info);
        if self.opts.fold && foldable && closed {
            self.fold(id);
        }
        Ok(id)
    }

    /// Folds a closed node to a constant, within [`FOLD_FUEL`] and what is
    /// left of [`FOLD_BUDGET`]. A fold that fails or runs out of fuel leaves
    /// the node alone: its error, if any, surfaces where TLC raises it.
    fn fold(&mut self, id: P) {
        let left = FOLD_BUDGET.saturating_sub(self.stats.fold_fuel);
        if left == 0 {
            self.stats.fold_skipped += 1;
            return;
        }
        let fuel = FOLD_FUEL.min(left);
        let started = std::time::Instant::now();
        self.m.set_fuel(fuel);
        let old = self.m.enter(self.next_slot + 1);
        let r = self.m.eval(&self.code, id);
        self.m.leave(old);
        let spent = fuel - self.m.fuel;
        let exhausted = self.m.fuel == 0;
        self.m.set_fuel(u64::MAX);
        let r = r.and_then(|h| self.m.heap.intern_const(h));
        self.m.heap.reset();
        self.stats.fold_fuel += spent;
        self.stats.fold_nanos += u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX);
        match r {
            Ok(h) if !exhausted && !h.is_empty() => {
                self.code.nodes[id as usize] = Node::Const(h);
                // The folded node keeps TLC's reducibility of the expression.
                let red = self.info[id as usize].red;
                self.info[id as usize] = Info {
                    red,
                    ..Info::default()
                };
                self.stats.folded += 1;
            }
            _ if exhausted => {
                self.info[id as usize].heavy = true;
                self.stats.fold_abandoned += 1;
            }
            _ => {}
        }
    }

    /// Evaluates the constant definitions the binder left to the core
    /// ([`Handoff::deferred`]), in definition order, before any role is
    /// compiled. Each body is compiled in a fresh top-level frame and
    /// evaluated without a fuel bound, as TLC evaluates it at startup, with
    /// the results of calls kept for the evaluation ([`crate::eval`]'s
    /// `CallCache`), and within [`STARTUP_TRANSIENT_BYTES`] of transient
    /// memory. A definition the core does not evaluate to a value (its body
    /// does not compile, is not closed, fails, or needs more memory) goes to
    /// the binder's evaluation ([`Handoff::startup_evaluator`]). One that fails
    /// there too is left alone: its uses compile it in place, and an error
    /// surfaces where it is used, as TLC reports it after swallowing the
    /// startup failure.
    fn startup_values(&mut self) {
        if self.h.deferred.is_empty() && self.h.assumptions.is_empty() {
            return;
        }
        let deferred: Vec<DefId> = self.h.deferred.iter().copied().collect();
        for d in deferred {
            if self.redirect(d) != d || self.h.precomputed.contains_key(&d) {
                continue;
            }
            let def = self.ir.def(d);
            let started = std::time::Instant::now();
            let skip = !def.params.is_empty()
                || def.std.is_some()
                || def.recursive
                || def.scope != DefScope::TopLevel
                || matches!(self.ir.node(def.body).expr, Expr::RecFcn { .. });
            let value = if skip { None } else { self.startup_value(d) };
            if let Some(h) = value {
                self.pre.insert(d, h);
                self.stats.startup_values += 1;
            } else if let Some(v) = self
                .h
                .startup_evaluator
                .as_ref()
                .and_then(|e| e.evaluate(d))
            {
                self.fallback.insert(d, v);
                self.stats.startup_fallbacks += 1;
            }
            self.stats.startup_nanos +=
                u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX);
        }
        // The pure `ASSUME`s, in order, under the same bounds, stopping at
        // the first that is not `TRUE`, as TLC's `Tool.checkAssumptions`
        // does: an earlier `ASSUME` may guard a later one. `FALSE` is
        // reported ([`Plan::startup_assumption_false`]); anything else (an
        // error, a refusal or the memory bound) is left to the reference
        // evaluator, whose report TLC's matches.
        for a in self.h.assumptions.clone() {
            let def = self.ir.def(a);
            if !def.params.is_empty() || def.std.is_some() || def.scope != DefScope::TopLevel {
                break;
            }
            let started = std::time::Instant::now();
            let value = self.startup_value(a);
            self.stats.startup_nanos +=
                u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX);
            if value == Some(Handle::TRUE) {
                self.startup_assumptions.push(a);
            } else {
                if value == Some(Handle::FALSE) {
                    self.startup_assumption_false = Some(a);
                }
                break;
            }
        }
        // A bounded evaluation may still have grown the arena: give that
        // memory back before the search.
        self.m.heap.reset();
        self.m.heap.arena.release();
    }

    fn startup_value(&mut self, d: DefId) -> Option<Handle> {
        let body = self.ir.def(d).body;
        let saved_slot = self.next_slot;
        let saved_resets = std::mem::take(&mut self.reset_stack);
        let saved_cache = std::mem::take(&mut self.def_cache);
        let saved_at = std::mem::take(&mut self.at_stack);
        let saved_lifts = self.lifts.len();
        let saved_substs = self.substs.len();
        let init = std::mem::replace(&mut self.init_mode, false);
        let step = std::mem::replace(&mut self.step, false);
        // What compiling the body records about frame slots and compiled
        // functions belongs to this evaluation only: the roles compile
        // their own, in their own contexts.
        let saved_def_slots = std::mem::take(&mut self.def_slots);
        let saved_thunks = std::mem::take(&mut self.effect_thunks);
        let saved_funs = std::mem::take(&mut self.funs);
        let saved_recfuns = std::mem::take(&mut self.recfuns);
        self.next_slot = 0;
        let saved_frame = self.new_frame();
        let env = self.new_env(d, None);
        let compiled = self.p(body, env, Mode::Plain);
        self.frame = saved_frame;
        let frame = self.next_slot;
        self.def_slots = saved_def_slots;
        self.effect_thunks = saved_thunks;
        self.funs = saved_funs;
        self.recfuns = saved_recfuns;
        self.next_slot = saved_slot;
        self.reset_stack = saved_resets;
        self.def_cache = saved_cache;
        self.at_stack = saved_at;
        self.lifts.truncate(saved_lifts);
        self.substs.truncate(saved_substs);
        self.init_mode = init;
        self.step = step;
        let p = compiled.ok()?;
        let info = self.info.get(p as usize)?;
        // A call is assumed to read every variable; the compiler's machine
        // has no state, so a read raises an error, and the body is left
        // alone.
        if (info.vars != 0 && !info.calls)
            || info.primed != 0
            || !info.free.is_empty()
            || info.effect
        {
            return None;
        }
        self.m.set_fuel(u64::MAX);
        self.m.calls = Some(crate::eval::CallCache::default());
        self.m.set_transient_bound(STARTUP_TRANSIENT_BYTES);
        let old = self.m.enter(frame + 1);
        let r = self.m.eval(&self.code, p);
        self.m.leave(old);
        self.m.set_transient_bound(usize::MAX);
        if let Some(calls) = self.m.calls.take() {
            self.stats.startup_call_hits += calls.hits;
        }
        let r = r.and_then(|h| self.m.heap.intern_const(h));
        self.m.heap.reset();
        r.ok().filter(|h| !h.is_empty())
    }

    /// `ENABLED A`: `A` compiled as an action
    /// in the current frame, searched for one successor at run time.
    ///
    /// An instance environment is supported when its variable substitutions
    /// resolve to the same root variables by name. TLC's branch cutoff then
    /// leaves every primed lookup unchanged, and no hidden candidate state
    /// requires the B2/B4 lazy-cache machinery. Other variable substitutions
    /// remain refused.
    fn enabled(
        &mut self,
        a: Option<ExprId>,
        sub: Option<ExprId>,
        env: usize,
        mode: Mode,
    ) -> Result<P, Error> {
        let a = a.ok_or_else(|| Error::internal("ENABLED without operand"))?;
        if mode == Mode::Primed {
            return Err(Error::unsupported("a primed ENABLED (M1 core)"));
        }
        if self.init_mode && !self.substs.is_empty() {
            return Err(Error::unsupported(
                "ENABLED in an INSTANCE inside an initial predicate (M1 core)",
            ));
        }
        let instance = !self.substs.is_empty();
        let first_slot = self.next_slot;
        // ENABLED evaluates its action on successors of its own, so its body
        // must not reuse a step predicate's primed thunks or memo sites.
        let init = std::mem::replace(&mut self.init_mode, false);
        let step = std::mem::replace(&mut self.step, false);
        let cache = std::mem::take(&mut self.def_cache);
        let g = (|| {
            self.enabled_substs()?;
            let action = self.g(a, env)?;
            if let Some(sub) = sub {
                let same = self.changed_test(sub, env)?;
                Ok(self.gpush(GNode::StepAngle { action, same }))
            } else {
                Ok(action)
            }
        })();
        self.init_mode = init;
        self.step = step;
        self.def_cache = cache;
        let g = g?;
        let mut free = Vec::new();
        self.instance_query_calls |= self.g_free(g, &mut free, 0, instance)?;
        free.retain(|&s| s < first_slot);
        self.push(Node::Enabled {
            g,
            free: free.into(),
        })
    }

    /// Proves that hiding outer variable substitutions at an ENABLED branch
    /// changes no variable lookup. Constants are not hidden by TLC's cutoff.
    fn enabled_substs(&mut self) -> Result<(), Error> {
        if self.substs.is_empty() {
            return Ok(());
        }
        // Configuration operator overrides bypass SANY's level constraint
        // on source INSTANCE constant/operator parameters. Their captured
        // state and cutoff behavior needs a separate proof before admission.
        let stateful_config = self.h.constants.iter().flatten().any(|binding| {
            matches!(binding, ConstBinding::Def(d) if self.ir.def(self.redirect(*d)).level != Level::Constant)
        }) || self.h.redirects.values().any(|&d| self.ir.def(d).level != Level::Constant);
        if stateful_config {
            return Err(Error::unsupported(
                "ENABLED in an INSTANCE with a state-dependent configured operator (M1 core)",
            ));
        }
        for subst in self.substs.clone() {
            let decl = self.ir.decl(subst.decl);
            if !decl.variable {
                // Source constant/operator actuals are level zero, including
                // formal forwarding. Configuration bypasses were refused above.
                // Query effects and unknown calls are checked after generation.
                continue;
            }
            let root = self
                .ir
                .vars()
                .iter()
                .position(|&root| self.ir.decl(root).name == decl.name);
            let Some(root) = root else {
                return Err(Error::unsupported(
                    "ENABLED with a hidden INSTANCE variable (B2, B3, B4; M1 core)",
                ));
            };
            let target = match subst.value {
                Ok(Arg::Expr { expr, .. }) => {
                    self.outside(subst.depth, |c| c.target(expr, subst.env, true))?
                }
                Ok(Arg::Op { .. }) | Err(_) => None,
            };
            if target.map(usize::from) != Some(root) {
                return Err(Error::unsupported(
                    "ENABLED with a nonidentity INSTANCE variable substitution (B3; M1 core)",
                ));
            }
        }
        Ok(())
    }

    /// The free slots of the value nodes a generator node reads, its own
    /// binders included (the caller drops the slots the action allocated).
    /// In an instance query, refuses value nodes with effects or nested
    /// queries and returns whether any reads a compiled call, whose body the
    /// caller checks once the whole plan is compiled.
    #[allow(clippy::too_many_lines, reason = "one arm per generator rule")]
    fn g_free(&self, g: G, out: &mut Vec<u32>, depth: u32, instance: bool) -> Result<bool, Error> {
        if depth > 10_000 {
            return Err(Error::unsupported("an action nested too deeply (M1 core)"));
        }
        let mut unproved = false;
        let mut calls = false;
        let mut inner = false;
        let mut p = |p: P, out: &mut Vec<u32>| {
            if let Some(i) = self.info.get(p as usize) {
                union(out, &i.free);
                unproved |= instance && (i.effect || i.nested_query);
                calls |= instance && i.calls;
            }
        };
        let unch = |items: &[crate::plan::Unch],
                    out: &mut Vec<u32>,
                    p: &mut dyn FnMut(P, &mut Vec<u32>)| {
            for u in items {
                if let crate::plan::Unch::Verify(x) = u {
                    p(*x, out);
                }
            }
        };
        let Some(node) = self.code.gnodes.get(g as usize) else {
            return Err(Error::internal("generator node out of range"));
        };
        match node {
            GNode::Composition { first, then, .. } => {
                inner |= self.g_free(*first, out, depth + 1, instance)?;
                inner |= self.g_free(*then, out, depth + 1, instance)?;
            }
            GNode::Conj(items) => {
                for &(g, x) in items {
                    p(x, out);
                    inner |= self.g_free(g, out, depth + 1, instance)?;
                }
            }
            GNode::Disj(gs) => {
                for &g in gs {
                    inner |= self.g_free(g, out, depth + 1, instance)?;
                }
            }
            GNode::Exists {
                binds,
                body,
                body_p,
            }
            | GNode::Forall {
                binds,
                body,
                body_p,
            } => {
                for b in binds {
                    p(b.domain, out);
                }
                p(*body_p, out);
                inner |= self.g_free(*body, out, depth + 1, instance)?;
            }
            GNode::If { cond, then, other } => {
                p(*cond, out);
                inner |= self.g_free(*then, out, depth + 1, instance)?;
                inner |= self.g_free(*other, out, depth + 1, instance)?;
            }
            GNode::Case { arms, other } => {
                for &(c, g) in arms {
                    p(c, out);
                    inner |= self.g_free(g, out, depth + 1, instance)?;
                }
                if let Some(o) = other {
                    inner |= self.g_free(*o, out, depth + 1, instance)?;
                }
            }
            GNode::Implies { lhs, rhs } => {
                p(*lhs, out);
                inner |= self.g_free(*rhs, out, depth + 1, instance)?;
            }
            GNode::Assign { rhs, .. } => p(*rhs, out),
            GNode::AssignIn { set, .. } | GNode::AssignInRaw { set, .. } => p(*set, out),
            GNode::Unchanged(items) => unch(items, out, &mut p),
            GNode::StepBox { action, vars } => {
                unch(vars, out, &mut p);
                inner |= self.g_free(*action, out, depth + 1, instance)?;
            }
            GNode::StepAngle { action, same } => {
                p(*same, out);
                inner |= self.g_free(*action, out, depth + 1, instance)?;
            }
            GNode::FcnAction { binds, arg, body } => {
                for b in binds {
                    p(b.domain, out);
                }
                p(*arg, out);
                inner |= self.g_free(*body, out, depth + 1, instance)?;
            }
            GNode::Scope { reset, body } => {
                union(out, reset);
                inner |= self.g_free(*body, out, depth + 1, instance)?;
            }
            GNode::Guard(x) => p(*x, out),
        }
        if unproved {
            return Err(Error::unsupported(
                "ENABLED in an INSTANCE with effects or recursive/nested calls (M1 core)",
            ));
        }
        Ok(calls || inner)
    }

    fn konst(&mut self, h: Handle) -> Result<P, Error> {
        self.push(Node::Const(h))
    }

    fn gpush(&mut self, g: GNode) -> G {
        #[allow(clippy::cast_possible_truncation, reason = "bounded by MAX_NODES")]
        let id = self.code.gnodes.len() as G;
        if let Some(map) = &mut self.code.source_map {
            map.generators.push(self.debug_current);
        }
        self.code.gnodes.push(g);
        id
    }

    fn string(&mut self, s: &str) -> Result<Handle, Error> {
        self.m.heap.string(s)
    }

    fn is_trivial(&self, p: P) -> bool {
        matches!(
            self.code.nodes.get(p as usize),
            Some(Node::Const(_) | Node::Slot(_) | Node::Var(_) | Node::Primed(_))
        )
    }

    /// A memo site for a body, if it is eligible.
    fn site(&mut self, name: String, p: P) -> Result<Option<P>, Error> {
        if !self.opts.memo || self.init_mode {
            return Ok(None);
        }
        let Some(info) = self.info.get(p as usize) else {
            return Ok(None);
        };
        if info.primed != 0
            || info.effect
            || matches!(self.code.nodes.get(p as usize), Some(Node::Const(_)))
        {
            return Ok(None);
        }
        #[allow(clippy::cast_possible_truncation, reason = "at most 64 variables")]
        let vars: Vec<u16> = (0..64u16)
            .filter(|&v| info.vars & (1u64 << v) != 0)
            .take(MAX_KEY + 1)
            .collect();
        let slots = info.free.clone();
        if vars.len() + slots.len() > MAX_KEY || (vars.is_empty() && slots.is_empty()) {
            return Ok(None);
        }
        #[allow(clippy::cast_possible_truncation, reason = "bounded")]
        let site = self.code.sites.len() as u32;
        self.code.sites.push(MemoSite {
            name: name.clone(),
            vars: vars.into(),
            slots: slots.into(),
            primed: Box::new([]),
            step: false,
            candidate: false,
        });
        self.site_names.push(name);
        Ok(Some(self.push(Node::Memo { site, body: p })?))
    }

    // ------------------------------------------------------------------
    // Roles
    // ------------------------------------------------------------------

    /// Binds the `LET` values of a role's frame that splitting left unbound
    /// (the role sits inside their `LET`): lazy values, as TLC's
    /// `getActions` binds them, forced at most once per evaluation of the
    /// action (its frame starts empty).
    fn bind_role_lets(&mut self, env: usize, def: DefId) {
        let owner = self.reset_stack.len().saturating_sub(1);
        for (i, info) in self.ir.def(def).frame.iter().enumerate() {
            let dive_ir::SlotKind::LetValue(d) = info.kind else {
                continue;
            };
            if let Some(s @ Sb::Unset) = self.envs[env].slots.get_mut(i) {
                *s = Sb::LetVal {
                    def: d,
                    env,
                    thunk: None,
                    owner,
                };
            }
        }
    }

    fn role_env(&mut self, r: &Role) -> Result<(usize, Vec<(u32, Handle)>), Error> {
        self.next_slot = 0;
        self.new_frame();
        self.role_env_after(r)
    }

    /// [`Self::role_env`] for a role compiled into the same frame as the
    /// previous one: its slots follow the previous role's.
    fn role_env_after(&mut self, r: &Role) -> Result<(usize, Vec<(u32, Handle)>), Error> {
        self.reset_stack.clear();
        self.def_cache.clear();
        self.at_stack.clear();
        self.role_name.clone_from(&r.name);
        let def = self.ir.def(r.def);
        if def.depth != 0 {
            return Err(Error::unsupported(
                "a role inside a LET or LAMBDA (M0 core)",
            ));
        }
        let env = self.new_env(r.def, None);
        let mut preset = Vec::new();
        for (slot, v) in &r.slots {
            let flat = self.alloc();
            let h = self.convert(v)?;
            if let Some(s) = self.envs[env].slots.get_mut(slot.index()) {
                *s = Sb::Flat(flat);
            }
            preset.push((flat, h));
        }
        self.reset_stack.push(Vec::new());
        self.bind_role_lets(env, r.def);
        // Substitutions around the role: values are evaluated by name in
        // their own frame, outside any substitution (TLC's generator binds
        // them uncached: B5).
        self.substs.clear();
        for rs in &r.substs {
            let entry = match rs {
                RoleSubst::Operator { decl, def } => SubstEntry {
                    id: self.subst_id(),
                    decl: *decl,
                    value: Ok(Arg::Op {
                        op: OpRef::Def(*def),
                        level: self.ir.def(*def).level,
                    }),
                    env,
                    how: ArgHow::ByName,
                    depth: 0,
                },
                RoleSubst::Value { decl, value } => {
                    let h = self.convert(value)?;
                    let p = self.konst(h)?;
                    SubstEntry {
                        id: self.subst_id(),
                        decl: *decl,
                        value: Err(p),
                        env,
                        how: ArgHow::Alias(p),
                        depth: 0,
                    }
                }
                RoleSubst::Expr {
                    decl,
                    expr,
                    def,
                    slots,
                } => {
                    if self.ir.def(*def).depth != 0 {
                        return Err(Error::unsupported(
                            "an INSTANCE substitution inside a LET or LAMBDA (M1 core)",
                        ));
                    }
                    let senv = self.new_env(*def, None);
                    for (slot, v) in slots {
                        let flat = self.alloc();
                        let h = self.convert(v)?;
                        if let Some(s) = self.envs[senv].slots.get_mut(slot.index()) {
                            *s = Sb::Flat(flat);
                        }
                        preset.push((flat, h));
                    }
                    self.bind_role_lets(senv, *def);
                    SubstEntry {
                        id: self.subst_id(),
                        decl: *decl,
                        value: Ok(Arg::Expr {
                            expr: *expr,
                            pass: dive_ir::Pass::Lazy,
                        }),
                        env: senv,
                        how: ArgHow::ByName,
                        depth: 0,
                    }
                }
            };
            self.substs.push(entry);
        }
        Ok((env, preset))
    }

    fn action(&mut self, r: &Role, init: bool) -> Result<Action, Error> {
        self.init_mode = init;
        let (env, preset) = self.role_env(r)?;
        let g = self.g(r.expr, env)?;
        Ok(Action {
            name: r.name.clone(),
            g,
            frame: self.next_slot,
            preset,
        })
    }

    /// The initial predicates, conjoined left to right into one action
    /// named after the first.
    fn init_action(&mut self, roles: &[Role]) -> Result<Action, Error> {
        let [first, rest @ ..] = roles else {
            return Err(Error::internal("no initial predicate"));
        };
        if rest.is_empty() {
            return self.action(first, true);
        }
        self.init_mode = true;
        let mut items = Vec::with_capacity(roles.len());
        let mut presets = Vec::new();
        for (i, r) in roles.iter().enumerate() {
            let (env, preset) = if i == 0 {
                self.role_env(r)?
            } else {
                self.role_env_after(r)?
            };
            presets.extend(preset);
            let g = self.g(r.expr, env)?;
            let p = self.p(r.expr, env, Mode::Plain)?;
            items.push((g, p));
        }
        let g = self.gpush(GNode::Conj(items.into()));
        Ok(Action {
            name: first.name.clone(),
            g,
            frame: self.next_slot,
            preset: presets,
        })
    }

    fn check(&mut self, r: &Role) -> Result<Check, Error> {
        self.init_mode = false;
        let (env, preset) = self.role_env(r)?;
        if let Some(bound) = &mut self.bound_preset {
            bound.extend(preset);
        } else if !preset.is_empty() {
            return Err(Error::unsupported(
                "an invariant with bound parameters (M0 core)",
            ));
        }
        let mut parts = Vec::new();
        self.conjuncts(r.expr, env, &mut parts)?;
        let mut conjuncts = Vec::new();
        for (k, (e, env)) in parts.into_iter().enumerate() {
            let p = self.p(e, env, Mode::Plain)?;
            let info = self.info[p as usize].clone();
            let skippable = info.free.is_empty() && info.primed == 0 && !info.effect;
            let reads = info.vars;
            let (p, site) = match self.site(format!("{}#{k}", r.name), p)? {
                Some(m) => {
                    let site = match self.code.nodes.get(m as usize) {
                        Some(Node::Memo { site, .. }) => Some(*site),
                        _ => None,
                    };
                    (m, site)
                }
                None => (p, None),
            };
            conjuncts.push(Conjunct {
                p,
                reads,
                skippable,
                site,
            });
        }
        Ok(Check {
            name: r.name.clone(),
            conjuncts,
            frame: self.next_slot,
        })
    }

    fn bound_test(&mut self, r: &Role, test: BoundTest) -> Result<Check, Error> {
        if matches!(test, BoundTest::Predicate) {
            return self.step_check(r);
        }
        self.init_mode = false;
        let (env, preset) = self.role_env(r)?;
        if let Some(bound) = &mut self.bound_preset {
            bound.extend(preset);
        } else if !preset.is_empty() {
            return Err(Error::internal(
                "a bound atom outside bound-test compilation",
            ));
        }
        let p = match test {
            BoundTest::Enabled(sub) => self.enabled(Some(r.expr), sub, env, Mode::Plain)?,
            BoundTest::Nonstuttering(sub) => {
                // Unlike ENABLED, the reference Nonstuttering wrapper evaluates
                // two ordinary scoped state values and then the action. It
                // creates no branch cutoff; retain actual substitutions in
                // both modes rather than applying ENABLED's identity proof.
                self.step = true;
                let same = self.changed_test(sub, env)?;
                let changed = self.push(Node::Not(same))?;
                let action = self.p(r.expr, env, Mode::Plain)?;
                self.step = false;
                self.push(Node::And([changed, action].into()))?
            }
            BoundTest::Predicate => return Err(Error::internal("ordinary bound test dispatch")),
        };
        Ok(Check {
            name: r.name.clone(),
            conjuncts: vec![Conjunct {
                p,
                reads: u64::MAX,
                skippable: false,
                site: None,
            }],
            frame: self.next_slot,
        })
    }

    /// A step predicate: a check whose conjuncts are never skipped, since
    /// the parent-delta skip compares a state with its parent and a step
    /// predicate has no such parent.
    fn step_check(&mut self, r: &Role) -> Result<Check, Error> {
        self.step = true;
        let k = self.check(r);
        self.step = false;
        let mut k = k?;
        k.conjuncts.iter_mut().for_each(|j| j.skippable = false);
        Ok(k)
    }

    /// `VIEW`: one value-valued conjunct, the whole expression.
    fn view(&mut self, r: &Role) -> Result<Check, Error> {
        self.init_mode = false;
        let (env, preset) = self.role_env(r)?;
        if !preset.is_empty() {
            return Err(Error::unsupported("a VIEW with bound parameters (core)"));
        }
        let p = self.p(r.expr, env, Mode::Plain)?;
        let reads = self.info[p as usize].vars;
        Ok(Check {
            name: r.name.clone(),
            conjuncts: vec![Conjunct {
                p,
                reads,
                skippable: false,
                site: None,
            }],
            frame: self.next_slot,
        })
    }

    /// Flattens a conjunction, through zero-arity definitions, into its
    /// conjuncts in order.
    fn conjuncts(
        &mut self,
        e: ExprId,
        env: usize,
        out: &mut Vec<(ExprId, usize)>,
    ) -> Result<(), Error> {
        match &self.ir.node(e).expr {
            Expr::Junction {
                kind: JunctionKind::And,
                items,
                ..
            } => {
                for &i in items {
                    self.conjuncts(i, env, out)?;
                }
                Ok(())
            }
            Expr::Label { body, .. } | Expr::Selected(body) => self.conjuncts(*body, env, out),
            Expr::Def(d) => {
                let d = self.redirect(*d);
                let def = self.ir.def(d);
                if self.has_startup_value(d)
                    || def.std.is_some()
                    || def.recursive
                    || !def.params.is_empty()
                    || matches!(def.scope, DefScope::LetValue { .. })
                {
                    out.push((e, env));
                    return Ok(());
                }
                let parent = self.lexical_parent(d, env)?;
                let inner = self.new_env(d, parent);
                self.conjuncts(def.body, inner, out)
            }
            _ => {
                out.push((e, env));
                Ok(())
            }
        }
    }

    // ------------------------------------------------------------------
    // Value compilation
    // ------------------------------------------------------------------

    fn p(&mut self, e: ExprId, env: usize, mode: Mode) -> Result<P, Error> {
        if self.code.source_map.is_none() {
            return self.p_inner(e, env, mode);
        }
        let previous = self.debug_current;
        self.debug_current = self.debug_context(e, env)?;
        let result = self.p_inner(e, env, mode);
        self.debug_current = previous;
        result
    }

    #[allow(clippy::too_many_lines, reason = "one arm per expression kind")]
    fn p_inner(&mut self, e: ExprId, env: usize, mode: Mode) -> Result<P, Error> {
        let expr = &self.ir.node(e).expr;
        match expr {
            Expr::Bool(b) => self.konst(Handle::bool(*b)),
            Expr::Num(s) => {
                if self.m.heap.int_mode() == crate::int::IntMode::Tlc && s.parse::<i32>().is_err() {
                    // TLC rejects the numeral before checking starts.
                    return Err(Error::unsupported(format!(
                        "the numeral {s}, outside TLC's 32-bit integers (--compat=tlc)"
                    )));
                }
                let v = if let Some(h) = s.parse::<i64>().ok().and_then(Handle::int) {
                    h
                } else {
                    // Outside the inline range: a big integer constant.
                    let b = s
                        .parse::<num_bigint::BigInt>()
                        .map_err(|_| Error::unsupported(format!("the numeral {s}")))?;
                    let h = self.m.heap.int_from_big(&b);
                    let h = self.m.heap.intern_const(h);
                    self.m.heap.reset();
                    h?
                };
                self.konst(v)
            }
            Expr::Decimal { .. } => Err(Error::unsupported("decimal numbers")),
            Expr::Str(s) => {
                let h = self.string(s)?;
                self.konst(h)
            }
            Expr::Var { var, primed } => {
                #[allow(clippy::cast_possible_truncation, reason = "at most 64 variables")]
                let i = var.index() as u16;
                if self.init_mode {
                    if *primed || mode == Mode::Primed {
                        return Err(Error::unsupported(
                            "a primed variable in an initial predicate",
                        ));
                    }
                    return self.push(Node::Primed(i));
                }
                match (*primed, mode) {
                    (false, Mode::Plain) => self.push(Node::Var(i)),
                    (true, Mode::Plain) | (false, Mode::Primed) => self.push(Node::Primed(i)),
                    (true, Mode::Primed) => Err(Error::unsupported("a doubly primed variable")),
                }
            }
            Expr::Const(c) => self.const_expr(*c, env, mode),
            Expr::Local(r) => self.local(*r, env, mode),
            Expr::Def(d) => self.def_use(*d, env, mode),
            Expr::Apply { callee, args } => self.apply(callee, args, env, mode),
            Expr::Builtin { op, args } => self.builtin(*op, args, env, mode),
            Expr::Junction { kind, items, .. } => {
                let mut ps = Vec::with_capacity(items.len());
                for &i in items {
                    ps.push(self.p(i, env, mode)?);
                }
                match kind {
                    JunctionKind::And => self.push(Node::And(ps.clone().into())),
                    JunctionKind::Or => self.push(Node::Or(ps.clone().into())),
                }
            }
            Expr::Not(a) => {
                let a = self.p(*a, env, mode)?;
                self.push(Node::Not(a))
            }
            Expr::Implies(a, b) => {
                let a = self.p(*a, env, mode)?;
                let b = self.p(*b, env, mode)?;
                self.push(Node::Implies(a, b))
            }
            Expr::Equiv(a, b) => {
                let a = self.p(*a, env, mode)?;
                let b = self.p(*b, env, mode)?;
                self.push(Node::Equiv(a, b))
            }
            Expr::If { cond, then, other } => {
                let c = self.p(*cond, env, mode)?;
                let t = self.p(*then, env, mode)?;
                let o = self.p(*other, env, mode)?;
                self.push(Node::If(c, t, o))
            }
            Expr::Case { arms, other } => {
                let mut out = Vec::with_capacity(arms.len());
                for a in arms {
                    let g = self.p(a.guard, env, mode)?;
                    let v = self.p(a.value, env, mode)?;
                    out.push((g, v));
                }
                let o = match other {
                    Some(o) => Some(self.p(*o, env, mode)?),
                    None => None,
                };
                self.push(Node::Case(out.into(), o))
            }
            Expr::Quant { kind, bounds, body } => {
                let (binds, saved) = self.binds(bounds, env, mode)?;
                let b = self.p(*body, env, mode);
                self.unbind(saved);
                let b = b?;
                let kind = match kind {
                    QuantKind::Exists => Quant::Exists,
                    QuantKind::Forall => Quant::Forall,
                    QuantKind::Choose => Quant::Choose,
                };
                self.push(Node::Quant {
                    kind,
                    binds: binds.into(),
                    body: b,
                })
            }
            Expr::SetFilter { bound, pred } => {
                let (mut binds, saved) = self.binds(std::slice::from_ref(bound), env, mode)?;
                let b = self.p(*pred, env, mode);
                self.unbind(saved);
                let b = b?;
                let bind = binds
                    .pop()
                    .ok_or_else(|| Error::internal("filter without a bound"))?;
                let subset = self.subset_rewrite(&bind, b)?;
                self.push_lazy(Node::Filter {
                    bind,
                    pred: b,
                    subset,
                })
            }
            Expr::SetMap { expr, bounds } => {
                let (binds, saved) = self.binds(bounds, env, mode)?;
                let b = self.p(*expr, env, mode);
                self.unbind(saved);
                let b = b?;
                self.push(Node::Map {
                    binds: binds.into(),
                    body: b,
                })
            }
            Expr::FcnCons { bounds, body } => {
                let (binds, saved) = self.binds(bounds, env, mode)?;
                let b = self.p(*body, env, mode);
                self.unbind(saved);
                let b = b?;
                self.push_lazy(Node::FcnCons {
                    binds: binds.into(),
                    body: b,
                })
            }
            Expr::RecFcn { .. } => Err(Error::unsupported(
                "a recursive function used other than applied (M1 core)",
            )),
            Expr::SetEnum(items) => {
                let ps = self.ps(items, env, mode)?;
                self.push(Node::SetEnum(ps.into()))
            }
            Expr::Tuple(items) => {
                let ps = self.ps(items, env, mode)?;
                self.push(Node::Tuple(ps.into()))
            }
            Expr::Cartesian(items) => {
                let ps = self.ps(items, env, mode)?;
                self.push(Node::Product(ps.clone().into()))
            }
            Expr::Record(fields) | Expr::RecordSet(fields) => {
                let is_set = matches!(expr, Expr::RecordSet(_));
                let mut out = Vec::with_capacity(fields.len());
                for f in fields {
                    let name = self.string(&f.name)?;
                    let v = self.p(f.value, env, mode)?;
                    out.push((name, v));
                }
                out.sort_by(|a, b| self.m.heap.cmp(a.0, b.0));
                if out.windows(2).any(|w| w[0].0 == w[1].0) {
                    return Err(Error::unsupported("a record with a repeated field"));
                }
                if is_set {
                    self.push(Node::RecSet(out.into()))
                } else {
                    self.push(Node::Record(out.into()))
                }
            }
            Expr::FcnSet { domain, range } => {
                let d = self.p(*domain, env, mode)?;
                let r = self.p(*range, env, mode)?;
                self.push(Node::FcnSet(d, r))
            }
            Expr::FcnApply { fcn, arg } => {
                let (fcn, arg) = (*fcn, *arg);
                if let Some((d, fun)) = self.rec_target(fcn, env, mode)? {
                    let a = self.p(arg, env, mode)?;
                    return self.fun_call(d, fun, vec![a], env);
                }
                let f = self.p(fcn, env, mode)?;
                let a = self.p(arg, env, mode)?;
                self.apply_value(f, a)
            }
            Expr::RecordSelect { record, field } => {
                let r = self.p(*record, env, mode)?;
                let f = self.string(field)?;
                self.push(Node::Select(r, f))
            }
            Expr::Except { base, updates } => {
                let b = self.p(*base, env, mode)?;
                let mut out = Vec::with_capacity(updates.len());
                for u in updates {
                    let path = self.ps(&u.path, env, mode)?;
                    let at = self.alloc();
                    self.at_stack.push(at);
                    let v = self.p(u.value, env, mode);
                    self.at_stack.pop();
                    out.push(Update {
                        path: path.into(),
                        at,
                        value: v?,
                    });
                }
                self.push(Node::Except {
                    base: b,
                    updates: out.into(),
                })
            }
            Expr::ExceptAt => match self.at_stack.last() {
                Some(&at) => self.push(Node::Slot(at)),
                None => Err(Error::unsupported("@ outside EXCEPT")),
            },
            Expr::Let { defs, body } => {
                let body = *body;
                let defs = defs.clone();
                let (b, reset) = self.let_scope(&defs, env, |c| c.p(body, env, mode))?;
                if reset.is_empty() {
                    Ok(b)
                } else {
                    self.push(Node::Scope {
                        reset: reset.into(),
                        body: b,
                    })
                }
            }
            Expr::Selected(a) | Expr::Label { body: a, .. } => self.p(*a, env, mode),
            Expr::Prime(a) => {
                if mode == Mode::Primed {
                    return Err(Error::unsupported("a doubly primed expression"));
                }
                if self.init_mode {
                    return Err(Error::unsupported(
                        "a primed expression in an initial predicate",
                    ));
                }
                self.p(*a, env, Mode::Primed)
            }
            Expr::Unchanged(a) => self.unchanged_value(*a, env, mode),
            Expr::Subst { bindings, body } => {
                let (bindings, body) = (bindings.clone(), *body);
                let (b, reset) =
                    self.subst_scope(&bindings, env, mode, |c| c.p(body, env, mode))?;
                if reset.is_empty() {
                    Ok(b)
                } else {
                    self.push(Node::Scope {
                        reset: reset.into(),
                        body: b,
                    })
                }
            }
            Expr::SubstRef { decl, primed } => {
                let (decl, primed) = (*decl, *primed);
                if primed && mode == Mode::Primed {
                    return Err(Error::unsupported("a doubly primed expression"));
                }
                let mode = if primed { Mode::Primed } else { mode };
                self.subst_ref(decl, env, mode)
            }
            // `[A]_v` is `A \/ UNCHANGED v`; `<<A>>_v` is `A /\ v' # v`
            // (TLC's `OPCODE_sa`, `OPCODE_aa` in `eval`).
            Expr::StepBox { action, sub } | Expr::StepAngle { action, sub } => {
                if mode == Mode::Primed || self.init_mode {
                    return Err(Error::unsupported(
                        "[A]_v under a prime or in an initial predicate (M1 core)",
                    ));
                }
                let boxed = matches!(expr, Expr::StepBox { .. });
                let (action, sub) = (*action, *sub);
                let a = self.p(action, env, mode)?;
                let x = self.p(sub, env, Mode::Plain)?;
                let y = self.p(sub, env, Mode::Primed)?;
                let same = self.push(Node::Eq(x, y))?;
                if boxed {
                    self.push(Node::Or([a, same].into()))
                } else {
                    let changed = self.push(Node::Not(same))?;
                    self.push(Node::And([a, changed].into()))
                }
            }
            Expr::Enabled(a) => self.enabled(Some(*a), None, env, mode),
            Expr::Cdot(a, b) => self.composition_value(*a, *b, env, mode),
            Expr::Always(_)
            | Expr::Eventually(_)
            | Expr::LeadsTo(..)
            | Expr::WhilePlus(..)
            | Expr::Wf { .. }
            | Expr::Sf { .. }
            | Expr::TemporalQuant { .. } => Err(Error::unsupported(
                "a temporal formula in a state or action role",
            )),
            Expr::Unbound(n) => Err(Error::unsupported(format!("the unbound name {n}"))),
            Expr::Unevaluable(_) => Err(Error::unsupported("an unevaluable expression")),
        }
    }

    /// A configured constant, including an imported declaration in an INSTANCE.
    fn const_expr(&mut self, c: dive_ir::ConstId, env: usize, mode: Mode) -> Result<P, Error> {
        match self.h.constants.get(c.index()).cloned().flatten() {
            Some(ConstBinding::Value(v)) => {
                let h = if let Some(&h) = self.consts.get(&c.index()) {
                    h
                } else {
                    let h = self.convert(&v)?;
                    self.consts.insert(c.index(), h);
                    h
                };
                self.konst(h)
            }
            Some(ConstBinding::Def(d)) => {
                let d = self.redirect(d);
                let body = if self.h.overrides.contains(&d) {
                    self.def_use(d, env, mode)?
                } else {
                    // A configured constant names the target's body, not the
                    // startup value of that target. Ordinary helpers retain
                    // their own legitimate startup values.
                    self.def_body(d, env, mode)?
                };
                self.configured_result(body)
            }
            None => Err(Error::unsupported("an unbound constant")),
        }
    }

    /// Unknown calls cannot establish a configured target's runtime effects.
    fn configured_result(&self, body: P) -> Result<P, Error> {
        if self.info[body as usize].calls {
            return Err(Error::unsupported(
                "a configured constant target with unresolved recursive or ENABLED calls (core)",
            ));
        }
        Ok(body)
    }

    fn ps(&mut self, items: &[ExprId], env: usize, mode: Mode) -> Result<Vec<P>, Error> {
        let mut out = Vec::with_capacity(items.len());
        for &i in items {
            out.push(self.p(i, env, mode)?);
        }
        Ok(out)
    }

    fn unchanged_value(&mut self, a: ExprId, env: usize, mode: Mode) -> Result<P, Error> {
        if mode == Mode::Primed || self.init_mode {
            return Err(Error::unsupported(
                "UNCHANGED under a prime or in an initial predicate",
            ));
        }
        let x = self.p(a, env, Mode::Plain)?;
        let y = self.p(a, env, Mode::Primed)?;
        self.push(Node::Eq(x, y))
    }

    /// Compiles bound groups: the domains first, then each variable gets a
    /// fresh slot. Returns the saved bindings to restore.
    fn binds(
        &mut self,
        bounds: &[Bound],
        env: usize,
        mode: Mode,
    ) -> Result<(Vec<Bind>, Saved), Error> {
        let mut domains = Vec::with_capacity(bounds.len());
        for b in bounds {
            let Some(d) = b.domain else {
                return Err(Error::unsupported("an unbounded quantifier or CHOOSE"));
            };
            domains.push(self.p(d, env, mode)?);
        }
        let mut saved = Vec::new();
        let mut binds = Vec::with_capacity(bounds.len());
        for (b, domain) in bounds.iter().zip(domains) {
            let mut slots = Vec::with_capacity(b.vars.len());
            for v in &b.vars {
                let flat = self.alloc();
                let old = self.envs[env]
                    .slots
                    .get(v.index())
                    .cloned()
                    .unwrap_or(Sb::Unset);
                saved.push((env, v.index(), old));
                if let Some(s) = self.envs[env].slots.get_mut(v.index()) {
                    *s = Sb::Flat(flat);
                }
                slots.push(flat);
            }
            binds.push(Bind {
                slots: slots.into(),
                tuple: b.tuple,
                domain,
            });
        }
        Ok((binds, saved))
    }

    fn unbind(&mut self, saved: Saved) {
        for (env, slot, old) in saved.into_iter().rev() {
            if let Some(s) = self.envs[env].slots.get_mut(slot) {
                *s = old;
            }
        }
    }

    /// Binds a `LET`'s zero-arity definitions as lazy values in `env`, runs
    /// `f`, and returns its result with the thunk slots to reset on entry.
    fn let_scope<T>(
        &mut self,
        defs: &[DefId],
        env: usize,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<(T, Vec<u32>), Error> {
        let owner = self.reset_stack.len();
        self.reset_stack.push(Vec::new());
        let mut saved = Vec::new();
        for &d in defs {
            if let DefScope::LetValue { parent, slot, .. } = self.ir.def(d).scope {
                let target = self.find_env(env, parent).unwrap_or(env);
                let old = self.envs[target]
                    .slots
                    .get(slot.index())
                    .cloned()
                    .unwrap_or(Sb::Unset);
                saved.push((target, slot.index(), old));
                if let Some(s) = self.envs[target].slots.get_mut(slot.index()) {
                    *s = Sb::LetVal {
                        def: d,
                        env: target,
                        thunk: None,
                        owner,
                    };
                }
            }
        }
        let r = f(self);
        self.unbind(saved);
        let reset = self.reset_stack.pop().unwrap_or_default();
        Ok((r?, reset))
    }

    fn frame_env(&self, env: usize, up: u32) -> Result<usize, Error> {
        let mut e = env;
        for _ in 0..up {
            e = self.envs[e]
                .parent
                .ok_or_else(|| Error::internal("a local reference beyond the outermost frame"))?;
        }
        Ok(e)
    }

    fn local(&mut self, r: LocalRef, env: usize, mode: Mode) -> Result<P, Error> {
        let fe = self.frame_env(env, r.up)?;
        if self.lifts.last().is_some_and(|l| fe < l.floor) {
            return self.capture(fe, r.slot.index(), mode);
        }
        let sb = self.envs[fe]
            .slots
            .get(r.slot.index())
            .cloned()
            .unwrap_or(Sb::Unset);
        match sb {
            Sb::Flat(f) => self.push(Node::Slot(f)),
            Sb::Arg {
                expr,
                env: aenv,
                how,
            } => match (how, mode) {
                (ArgHow::Alias(p), Mode::Plain) => Ok(p),
                (ArgHow::Alias(p), Mode::Primed) => match self.code.nodes.get(p as usize) {
                    Some(Node::Var(i)) => {
                        let i = *i;
                        self.push(Node::Primed(i))
                    }
                    Some(Node::Const(_) | Node::Slot(_)) => Ok(p),
                    _ => {
                        self.stats.by_name += 1;
                        self.p(expr, aenv, Mode::Primed)
                    }
                },
                (ArgHow::Thunk(slot, body), Mode::Plain) => {
                    self.effect_thunk_use(slot, body)?;
                    self.push(Node::Lazy { slot, body })
                }
                (ArgHow::Thunk(..), Mode::Primed) | (ArgHow::ByName, _) => {
                    self.stats.by_name += 1;
                    self.p(expr, aenv, mode)
                }
            },
            Sb::LetVal {
                def,
                env: lenv,
                thunk,
                owner,
            } => {
                let d = self.ir.def(def);
                if mode == Mode::Primed || d.level >= Level::Action {
                    return self.p(d.body, lenv, mode);
                }
                let (slot, body) = if let Some(t) = thunk {
                    t
                } else {
                    let body = self.p(d.body, lenv, Mode::Plain)?;
                    let slot = self.alloc();
                    if let Some(Sb::LetVal { thunk, .. }) =
                        self.envs[fe].slots.get_mut(r.slot.index())
                    {
                        *thunk = Some((slot, body));
                    }
                    if let Some(list) = self.reset_stack.get_mut(owner) {
                        list.push(slot);
                    }
                    (slot, body)
                };
                if self.is_trivial(body) {
                    return Ok(body);
                }
                self.effect_thunk_use(slot, body)?;
                self.push(Node::Lazy { slot, body })
            }
            Sb::RecSelf(..) => Err(Error::unsupported(
                "a recursive function used other than applied (M1 core)",
            )),
            Sb::Enclosing { env, slot } => self.capture(env, slot, mode),
            Sb::OpArg { .. } => Err(Error::internal("an operator parameter used as a value")),
            Sb::Unset => Err(Error::internal(format!(
                "unbound local {} in {}",
                self.ir
                    .def(self.envs[fe].def)
                    .frame
                    .get(r.slot.index())
                    .map_or("?", |s| s.name.as_str()),
                self.ir.def(self.envs[fe].def).name
            ))),
        }
    }

    /// A reference, inside a lifted function, to a local of an enclosing
    /// definition: a capture slot of the function.
    fn capture(&mut self, fe: usize, slot: usize, mode: Mode) -> Result<P, Error> {
        // A function's captures are computed once per call, in its mode: a
        // read in the other mode would need a second value of the capture.
        match (self.lifts.last().map(|l| l.mode), mode) {
            (None | Some(Mode::Plain), Mode::Primed) => {
                return Err(Error::unsupported(
                    "a recursive LET definition reading an enclosing local under a prime (M1 core)",
                ));
            }
            (Some(Mode::Primed), Mode::Plain) => {
                return Err(Error::unsupported(
                    "a recursive LET definition under a prime reading an enclosing local unprimed (M1 core)",
                ));
            }
            _ => {}
        }
        if matches!(self.envs[fe].slots.get(slot), Some(Sb::RecSelf(..))) {
            return Err(Error::unsupported(
                "a recursive function used inside a nested recursive definition (M1 core)",
            ));
        }
        let Some(l) = self.lifts.last() else {
            return Err(Error::internal("a capture outside a lifted function"));
        };
        let mut k = 0u32;
        let mut e = l.parent;
        loop {
            match e {
                Some(x) if x == fe => break,
                Some(x) => {
                    e = self.envs[x].parent;
                    k += 1;
                }
                None => {
                    return Err(Error::unsupported(
                        "a recursive function with a dynamic INSTANCE capture outside its lexical activation (M1 core)",
                    ));
                }
            }
        }
        if let Some(&(_, _, c)) = l.caps.iter().find(|c| c.0 == k && c.1 == slot) {
            return self.push(Node::Slot(c));
        }
        let c = self.alloc();
        if let Some(l) = self.lifts.last_mut() {
            l.caps.push((k, slot, c));
        }
        self.push(Node::Slot(c))
    }

    /// A call of a compiled function: the arguments, then the captures
    /// (compiled at the call site), or, inside the function itself, its own
    /// capture slots (filled in when its body is complete).
    fn fun_call(&mut self, d: DefId, fun: u32, mut ps: Vec<P>, env: usize) -> Result<P, Error> {
        if let Some(i) = self.lifts.iter().position(|l| l.fun == fun) {
            // Top-level functions still need the substitution frame boundary,
            // but have no lexical captures to pass along a mutual back-edge.
            if i + 1 != self.lifts.len() && self.lifts[i].parent.is_some() {
                return Err(Error::unsupported(
                    "mutually recursive nested definitions (M1 core)",
                ));
            }
            let call = self.push(Node::Call {
                fun,
                args: ps.into(),
            })?;
            if let Some(l) = self.lifts.get_mut(i) {
                l.self_calls.push(call);
            }
            return Ok(call);
        }
        let caps = self.fun_caps.get(&fun).cloned().unwrap_or_default();
        if !caps.is_empty() {
            let mode = if self.primed_funs.contains(&fun) {
                Mode::Primed
            } else {
                Mode::Plain
            };
            let parent = match self.ir.def(d).scope {
                DefScope::LetValue { parent, .. } => self.find_env(env, parent),
                _ => self.lexical_parent(d, env)?,
            };
            let Some(parent) = parent else {
                return Err(Error::internal("captures of a top-level definition"));
            };
            for (k, slot) in caps {
                #[allow(clippy::cast_possible_truncation, reason = "frame slots are u32")]
                let r = LocalRef {
                    up: k,
                    slot: dive_ir::Slot(slot as u32),
                };
                let v = self.local(r, parent, mode)?;
                if self.info[v as usize].calls {
                    return Err(Error::unsupported(
                        "a recursive definition capturing a value with unproved recursive calls (M1 core)",
                    ));
                }
                let v = if self.is_trivial(v) {
                    v
                } else {
                    self.stats.speculative += 1;
                    self.push(Node::Spec(v))?
                };
                ps.push(v);
            }
        }
        self.push(Node::Call {
            fun,
            args: ps.into(),
        })
    }

    /// Starts a fresh runtime frame for `d`, including top-level definitions.
    /// Its boundary prevents caller substitutions from reusing frame slots;
    /// a nested definition's lexical parent supplies its captures.
    fn begin_fun(
        &mut self,
        d: DefId,
        fun: u32,
        env: usize,
        mode: Mode,
    ) -> Result<(usize, bool), Error> {
        let parent = self.lexical_parent(d, env)?;
        let inner = self.new_env(d, parent);
        self.lifts.push(Lift {
            floor: inner,
            parent,
            fun,
            caps: Vec::new(),
            self_calls: Vec::new(),
            mode,
        });
        Ok((inner, true))
    }

    /// LET values use their owner's frame layout, rather than owning a frame.
    fn begin_recfun(
        &mut self,
        d: DefId,
        fun: u32,
        env: usize,
        owner: Option<usize>,
        mode: Mode,
    ) -> Result<(usize, bool), Error> {
        if !matches!(self.ir.def(d).scope, DefScope::LetValue { .. }) {
            return self.begin_fun(d, fun, env, mode);
        }
        let owner = owner.ok_or_else(|| Error::internal("recursive LET function owner"))?;
        let inner = self.new_env(self.envs[owner].def, self.envs[owner].parent);
        for (slot, binding) in self.envs[inner].slots.iter_mut().enumerate() {
            *binding = Sb::Enclosing { env: owner, slot };
        }
        self.lifts.push(Lift {
            floor: inner,
            parent: Some(owner),
            fun,
            caps: Vec::new(),
            self_calls: Vec::new(),
            mode,
        });
        Ok((inner, true))
    }

    /// Ends `begin_fun`: records the captures and completes the recursive
    /// calls with them.
    fn end_fun(&mut self, fun: u32, lifted: bool) -> Result<(), Error> {
        if !lifted {
            return Ok(());
        }
        let Some(l) = self.lifts.pop() else {
            return Err(Error::internal("unbalanced lifted function"));
        };
        let slots: Vec<u32> = l.caps.iter().map(|c| c.2).collect();
        for &call in &l.self_calls {
            let mut extra = Vec::with_capacity(slots.len());
            for &c in &slots {
                extra.push(self.push(Node::Slot(c))?);
            }
            if let Some(Node::Call { args, .. }) = self.code.nodes.get_mut(call as usize) {
                let mut v = args.to_vec();
                v.extend(extra);
                *args = v.into();
            }
        }
        if let Some(f) = self.code.funs.get_mut(fun as usize) {
            f.caps = slots.clone().into();
        }
        self.fun_caps
            .insert(fun, l.caps.iter().map(|c| (c.0, c.1)).collect());
        Ok(())
    }

    /// Binds an instance's substitutions for `f`, as operator arguments are
    /// bound (`inline`): each expression value is compiled outside the
    /// substitution, then aliased, made a thunk, or passed by name. Returns
    /// `f`'s result with the thunk slots to reset on entry.
    fn subst_scope<T>(
        &mut self,
        bindings: &[dive_ir::SubstBinding],
        env: usize,
        mode: Mode,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<(T, Vec<u32>), Error> {
        let depth = self.substs.len();
        let mut reset = Vec::new();
        let mut entries = Vec::with_capacity(bindings.len());
        for b in bindings {
            let how = match &b.value {
                Arg::Expr { expr, .. } => {
                    let cp = self.p(*expr, env, mode)?;
                    if self.opts.eager && self.is_trivial(cp) {
                        self.stats.aliased += 1;
                        ArgHow::Alias(cp)
                    } else if self.info[cp as usize].primed == 0 {
                        self.stats.thunks += 1;
                        let slot = self.alloc();
                        reset.push(slot);
                        ArgHow::Thunk(slot, cp)
                    } else {
                        ArgHow::ByName
                    }
                }
                Arg::Op { .. } => ArgHow::ByName,
            };
            let id = self.subst_id();
            entries.push(SubstEntry {
                id,
                decl: b.decl,
                value: Ok(b.value.clone()),
                env,
                how,
                depth,
            });
        }
        self.stats.substituted += entries.len();
        self.substs.extend(entries);
        let r = f(self);
        self.substs.truncate(depth);
        Ok((r?, reset))
    }

    /// Runs `f` in the dynamic context of depth `depth` (outside the
    /// substitutions above it).
    fn outside<T>(&mut self, depth: usize, f: impl FnOnce(&mut Self) -> T) -> T {
        let inner = self.substs.split_off(depth.min(self.substs.len()));
        let r = f(self);
        self.substs.extend(inner);
        r
    }

    /// The operator an operator declaration stands for: the innermost
    /// active substitution, followed through substitutions by declarations
    /// of enclosing instances (`INSTANCE M WITH F <- F`, nested), each
    /// looked up in the context outside its own substitution.
    fn subst_op(&self, decl: dive_ir::DeclId) -> Result<OpRef, Error> {
        let mut decl = decl;
        let mut limit = self.substs.len();
        loop {
            let Some(i) = self.substs[..limit].iter().rposition(|s| s.decl == decl) else {
                return match self.ir.decl(decl).constant {
                    Some(c) => Ok(OpRef::Const(c)),
                    None => Err(Error::unsupported(
                        "an unsubstituted operator declaration (M1 core)",
                    )),
                };
            };
            let s = &self.substs[i];
            match &s.value {
                Ok(Arg::Op {
                    op: OpRef::Subst(d2),
                    ..
                }) => {
                    decl = *d2;
                    limit = s.depth.min(i);
                }
                Ok(Arg::Op {
                    op: op @ (OpRef::Def(_) | OpRef::Std(_) | OpRef::Const(_)),
                    ..
                }) if !matches!(op, OpRef::Def(d) if self.ir.def(self.redirect(*d)).scope != DefScope::TopLevel) =>
                {
                    return Ok(op.clone());
                }
                _ => {
                    return Err(Error::unsupported(
                        "an INSTANCE substitution of an operator by a non-top-level operator (M1 core)",
                    ));
                }
            }
        }
    }

    /// A reference to a substituted declaration: the innermost active
    /// substitution, or else the declaration itself (a root variable or a
    /// constant).
    fn subst_ref(&mut self, decl: dive_ir::DeclId, env: usize, mode: Mode) -> Result<P, Error> {
        let Some(i) = self.substs.iter().rposition(|s| s.decl == decl) else {
            let d = self.ir.decl(decl);
            #[allow(clippy::cast_possible_truncation, reason = "at most 64 variables")]
            return match (d.var, d.constant) {
                (Some(v), _) if self.init_mode => {
                    if mode == Mode::Primed {
                        return Err(Error::unsupported(
                            "a primed variable in an initial predicate",
                        ));
                    }
                    self.push(Node::Primed(v.index() as u16))
                }
                (Some(v), _) => match mode {
                    Mode::Plain => self.push(Node::Var(v.index() as u16)),
                    Mode::Primed => self.push(Node::Primed(v.index() as u16)),
                },
                (None, Some(c)) => self.const_expr(c, env, mode),
                (None, None) => Err(Error::unsupported(format!(
                    "the unsubstituted variable {} of an instantiated module (M1 core)",
                    d.name
                ))),
            };
        };
        let SubstEntry {
            id,
            value,
            env,
            how,
            depth,
            ..
        } = self.substs[i].clone();
        let expr = match value {
            Ok(Arg::Expr { expr, .. }) => expr,
            Err(p) => return Ok(p),
            Ok(Arg::Op { .. }) => {
                return Err(Error::unsupported(
                    "an operator substitution used as a value (M1 core)",
                ));
            }
        };
        if self.lifts.last().is_some_and(|lift| env < lift.floor) {
            // Caller aliases and thunk slots belong to another runtime frame.
            // Constants are frame-independent; otherwise compile fresh nodes
            // here. Existing capture resolution refuses non-lexical locals.
            if let ArgHow::Alias(mut p) | ArgHow::Thunk(_, mut p) = how {
                // Disabling eager aliases can wrap the same constant in
                // caller thunks. Reuse only the constant, never their slots.
                while let Some(Node::Lazy { body, .. }) = self.code.nodes.get(p as usize) {
                    p = *body;
                }
                if matches!(self.code.nodes.get(p as usize), Some(Node::Const(_))) {
                    return Ok(p);
                }
            }
            let body = self.outside(depth, |c| c.p(expr, env, mode))?;
            if self.info[body as usize].effect || self.info[body as usize].calls {
                return Err(Error::unsupported(
                    "an effectful or recursive INSTANCE substitution inside a recursive function (M1 core)",
                ));
            }
            return Ok(body);
        }
        match (how, mode) {
            (ArgHow::Alias(p), Mode::Plain) => Ok(p),
            (ArgHow::Alias(p), Mode::Primed) => match self.code.nodes.get(p as usize) {
                Some(Node::Var(v)) => {
                    let v = *v;
                    self.push(Node::Primed(v))
                }
                Some(Node::Const(_) | Node::Slot(_)) => Ok(p),
                _ => {
                    self.stats.by_name += 1;
                    self.outside(depth, |c| c.p(expr, env, Mode::Primed))
                }
            },
            (ArgHow::Thunk(slot, body), Mode::Plain) => {
                self.effect_thunk_use(slot, body)?;
                self.push(Node::Lazy { slot, body })
            }
            (ArgHow::Thunk(..), Mode::Primed) | (ArgHow::ByName, _) => {
                self.stats.by_name += 1;
                if self.step {
                    return self.step_cached(Cached::Subst(id, mode), |c| {
                        c.outside(depth, |c| c.p(expr, env, mode))
                    });
                }
                self.outside(depth, |c| c.p(expr, env, mode))
            }
        }
    }

    /// A fresh `SubstEntry::id`.
    fn subst_id(&mut self) -> u32 {
        self.subst_ids += 1;
        self.subst_ids
    }

    /// In a step predicate, a body evaluated at most once per frame
    /// activation: the pair does not change within one, so a pure body
    /// with no bound variable has one value. TLC evaluates it by name at
    /// each use; the result, or the first error, is the same. The thunk
    /// counts as by-name for the function-application rule
    /// (`def_slots`).
    fn step_cached(
        &mut self,
        key: Cached,
        compile: impl FnOnce(&mut Self) -> Result<P, Error>,
    ) -> Result<P, Error> {
        if let Some(&(slot, body)) = self.def_cache.get(&key) {
            return self.push(Node::Lazy { slot, body });
        }
        let body = compile(self)?;
        let info = &self.info[body as usize];
        if !info.free.is_empty() || info.effect || info.calls || self.is_trivial(body) {
            return Ok(body);
        }
        let body = self.step_site(key, body)?;
        let slot = self.alloc();
        self.def_cache.insert(key, (slot, body));
        self.def_slots.insert(slot);
        self.stats.cached_defs += 1;
        self.push(Node::Lazy { slot, body })
    }

    /// Whether a body is already cached (a thunk or a memo site), or only
    /// assembles a tuple, record or set from leaves and thunks (such as a
    /// `vars` tuple): rebuilding it is cheaper than keeping an interned
    /// copy of each.
    fn assembles(&self, mut body: P) -> bool {
        while let Some(Node::Scope { body: b, .. } | Node::Spec(b)) =
            self.code.nodes.get(body as usize)
        {
            body = *b;
        }
        let leaf = |p: &P| {
            matches!(
                self.code.nodes.get(*p as usize),
                Some(
                    Node::Const(_)
                        | Node::Slot(_)
                        | Node::Var(_)
                        | Node::Primed(_)
                        | Node::Lazy { .. }
                        | Node::Memo { .. }
                )
            )
        };
        match self.code.nodes.get(body as usize) {
            Some(Node::Lazy { .. } | Node::Memo { .. }) => true,
            Some(Node::Tuple(items) | Node::SetEnum(items)) => items.iter().all(leaf),
            Some(Node::Record(fields)) => fields.iter().all(|(_, p)| leaf(p)),
            _ => false,
        }
    }

    /// A step predicate's cached body as a memo site keyed on the
    /// variables it reads, primed and unprimed (`Opts::step_memo`): its
    /// value is a function of them, the same for every pair that agrees
    /// on them, such as the successors of one state.
    fn step_site(&mut self, key: Cached, body: P) -> Result<P, Error> {
        if !self.opts.step_memo || self.assembles(body) {
            return Ok(body);
        }
        let info = &self.info[body as usize];
        let bits = |m: u64| -> Vec<u16> {
            #[allow(clippy::cast_possible_truncation, reason = "at most 64 variables")]
            (0..64u16).filter(|&v| m & (1u64 << v) != 0).collect()
        };
        let (vars, primed) = (bits(info.vars), bits(info.primed));
        if vars.len() + primed.len() > MAX_KEY || (vars.is_empty() && primed.is_empty()) {
            return Ok(body);
        }
        let name = match key {
            Cached::Def(d, mode, _) => format!("{} ({mode:?}, step)", self.ir.def(d).name),
            Cached::Subst(id, mode) => format!("substitution {id} ({mode:?}, step)"),
        };
        #[allow(clippy::cast_possible_truncation, reason = "bounded")]
        let site = self.code.sites.len() as u32;
        self.code.sites.push(MemoSite {
            name: name.clone(),
            vars: vars.into(),
            slots: Box::new([]),
            primed: primed.into(),
            step: true,
            candidate: false,
        });
        self.site_names.push(name);
        self.push(Node::Memo { site, body })
    }

    /// Whether the innermost substitution of a declaration is a value
    /// (`RoleSubst::Value`).
    fn subst_is_value(&self, decl: dive_ir::DeclId) -> bool {
        self.substs
            .iter()
            .rev()
            .find(|s| s.decl == decl)
            .is_some_and(|s| s.value.is_err())
    }

    /// The substitution for a declaration, if one is active: its expression,
    /// environment and dynamic depth.
    fn subst_expr(&self, decl: dive_ir::DeclId) -> Option<Result<(ExprId, usize, usize), Error>> {
        let i = self.substs.iter().rposition(|s| s.decl == decl)?;
        let s = &self.substs[i];
        Some(match &s.value {
            Ok(Arg::Expr { expr, .. }) => Ok((*expr, s.env, s.depth)),
            Ok(Arg::Op { .. }) => Err(Error::unsupported(
                "an operator substitution used as a value (M1 core)",
            )),
            Err(_) => Err(Error::unsupported(
                "a substitution by a value used as an action or a variable (M1 core)",
            )),
        })
    }

    /// A use of a zero-arity definition.
    fn def_use(&mut self, d: DefId, env: usize, mode: Mode) -> Result<P, Error> {
        let r = self.redirect(d);
        if r != d
            && !self.h.overrides.contains(&r)
            && self.ir.def(r).effects.intersects(dive_ir::Effects::IMPURE)
        {
            // `Op <- D`: `Op`'s tool object is `D`'s node, whose body TLC
            // evaluates at every use, not `D`'s own startup value. A pure
            // body's startup value is the same, so only an impure one
            // (`RandomElement`, ...) is compiled again.
            return self.def_body(r, env, mode);
        }
        let d = r;
        if let Some(h) = self.precomputed(d)? {
            return self.konst(h);
        }
        if self.substs.is_empty()
            && let Some(&Some(h)) = self.settled.get(&d)
        {
            return self.konst(h);
        }
        self.def_body(d, env, mode)
    }

    /// Evaluates the compiled body of a closed zero-arity top-level
    /// definition once, when its constant fold ran out of [`FOLD_FUEL`]
    /// (`Info::heavy`): within [`SETTLE_FUEL`], what is left of
    /// [`SETTLE_BUDGET`] and [`STARTUP_TRANSIENT_BYTES`], into the permanent
    /// store, as TLC evaluates a constant definition at start-up
    /// (`SpecProcessor.processConstantDefns`). Its uses then read the value
    /// instead of rebuilding it in every state. The body is the same
    /// node a fold would replace, with the same reducibility, so its uses
    /// behave as they do for a folded one.
    ///
    /// An evaluation that fails, refuses, or runs out of fuel or memory
    /// changes nothing: the body is evaluated where it is used, as before,
    /// so an error surfaces only where TLC raises it. Only a definition
    /// outside any `INSTANCE` substitution is evaluated, so that its value
    /// depends on the definition alone and is kept for all its uses.
    fn settle(&mut self, d: DefId, body: P) -> P {
        // A deferred definition was evaluated without a fuel bound already
        // (`Self::startup_values`): one that is still compiled failed there.
        if !self.opts.fold
            || !self.substs.is_empty()
            || self.h.deferred.contains(&d)
            || self.settled.contains_key(&d)
        {
            return body;
        }
        let Some(info) = self.info.get(body as usize) else {
            return body;
        };
        let closed = info.vars == 0
            && info.primed == 0
            && info.free.is_empty()
            && !info.calls
            && !info.effect;
        if !closed || !info.heavy || self.is_trivial(body) {
            return body;
        }
        let fuel = SETTLE_FUEL.min(SETTLE_BUDGET.saturating_sub(self.settle_fuel));
        if fuel == 0 {
            return body;
        }
        let started = std::time::Instant::now();
        self.m.set_fuel(fuel);
        let bound = std::mem::replace(&mut self.m.transient_bound, STARTUP_TRANSIENT_BYTES);
        let old = self.m.enter(self.next_slot + 1);
        let r = self.m.eval(&self.code, body);
        self.m.leave(old);
        self.m.transient_bound = bound;
        let spent = fuel - self.m.fuel;
        let exhausted = self.m.fuel == 0;
        self.m.set_fuel(u64::MAX);
        let r = r.and_then(|h| self.m.heap.intern_const(h));
        self.m.heap.reset();
        self.settle_fuel += spent;
        self.stats.startup_nanos += u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX);
        match r {
            Ok(h) if !exhausted && !h.is_empty() => {
                self.code.nodes[body as usize] = Node::Const(h);
                let red = self.info[body as usize].red;
                self.info[body as usize] = Info {
                    red,
                    ..Info::default()
                };
                self.settled.insert(d, Some(h));
                self.stats.startup_values += 1;
            }
            _ => {
                self.settled.insert(d, None);
            }
        }
        body
    }

    /// Compiles a definition's body without replacing it by its startup value.
    fn def_body(&mut self, d: DefId, env: usize, mode: Mode) -> Result<P, Error> {
        let def = self.ir.def(d);
        if let Some(op) = def.std {
            return self.std_apply(op, &[], env, mode);
        }
        if !def.params.is_empty() {
            return Err(Error::unsupported(format!(
                "the operator {} used as a value",
                def.name
            )));
        }
        if def.recursive {
            return self.call(d, &[], env, mode);
        }
        let key = Cached::Def(d, mode, self.substs.last().map(|s| s.id));
        if self.step && !self.init_mode && def.scope == DefScope::TopLevel {
            let parent = self.lexical_parent(d, env)?;
            return self.step_cached(key, |c| {
                let inner = c.new_env(d, parent);
                let body = c.p(def.body, inner, mode)?;
                Ok(c.settle(d, body))
            });
        }
        let cacheable = mode == Mode::Plain && !self.init_mode && def.scope == DefScope::TopLevel;
        if cacheable && let Some(&(slot, body)) = self.def_cache.get(&key) {
            return self.push(Node::Lazy { slot, body });
        }
        let parent = self.lexical_parent(d, env)?;
        let inner = self.new_env(d, parent);
        let body = self.p(def.body, inner, mode)?;
        let body = self.settle(d, body);
        // A state-level definition is a pure function of the current state:
        // evaluate it at most once per frame activation (the state does not
        // change within one). TLC re-evaluates it; the result is the same.
        let info = &self.info[body as usize];
        if cacheable
            && info.free.is_empty()
            && info.primed == 0
            && !info.effect
            && !info.calls
            && !self.is_trivial(body)
        {
            let slot = self.alloc();
            self.def_cache.insert(key, (slot, body));
            self.def_slots.insert(slot);
            self.stats.cached_defs += 1;
            return self.push(Node::Lazy { slot, body });
        }
        if def.scope == DefScope::TopLevel && !self.init_mode {
            return self.primed_site(d, mode, body);
        }
        Ok(body)
    }

    /// A zero-arity top-level definition that a next-state action reads
    /// primed, such as `totalOpOrder'` in `InnerSerial`, as a memo site
    /// keyed on the variables it reads, primed and unprimed
    /// (`Opts::primed_memo`).
    ///
    /// The body is pure (no effect), makes no call and reads no bound
    /// variable, so its value is a function of the key alone. At run time
    /// the site is used only once every primed variable of its key is
    /// assigned (`Machine::memo_eval` bypasses an unassigned one, and the
    /// body then raises the error it raises), so a body that does not read
    /// the variable an enumeration `x' \in S` assigns is evaluated once
    /// per distinct key, not once per candidate. Errors are never cached.
    fn primed_site(&mut self, d: DefId, mode: Mode, body: P) -> Result<P, Error> {
        if !self.opts.primed_memo
            || self.assembles(body)
            || self.is_trivial(body)
            || self.structural(body)
        {
            return Ok(body);
        }
        let info = &self.info[body as usize];
        if info.primed == 0 || !info.free.is_empty() || info.effect || info.calls {
            return Ok(body);
        }
        let bits = |m: u64| -> Vec<u16> {
            #[allow(clippy::cast_possible_truncation, reason = "at most 64 variables")]
            (0..64u16).filter(|&v| m & (1u64 << v) != 0).collect()
        };
        let (vars, primed) = (bits(info.vars), bits(info.primed));
        if vars.len() + primed.len() > MAX_KEY {
            return Ok(body);
        }
        let name = format!("{} ({mode:?}, action)", self.ir.def(d).name);
        #[allow(clippy::cast_possible_truncation, reason = "bounded")]
        let site = self.code.sites.len() as u32;
        self.code.sites.push(MemoSite {
            name: name.clone(),
            vars: vars.into(),
            slots: Box::new([]),
            primed: primed.into(),
            step: true,
            candidate: true,
        });
        self.site_names.push(name);
        self.push(Node::Memo { site, body })
    }

    /// Whether a primed definition's body is a value its consumers may
    /// use without building it, so that a memo site, which builds it,
    /// would change what is evaluated: a function constructor (applied
    /// through `Node::Beta`, or its `DOMAIN` taken, without being built)
    /// or a symbolic set constructor (`SUBSET`, `\X`, `[S -> T]`, a
    /// record set, `Seq`), whose value is a description and which a
    /// filter over it may rewrite (`Compiler::subset_rewrite`). A filter
    /// or set operation stays eligible: membership in it is decided on the
    /// body through the site (`Compiler::lazy_set`), and an enumeration
    /// streams a filter's body (`Machine::assign_in`); every other
    /// consumer builds it.
    fn structural(&self, body: P) -> bool {
        if self.lambda(body).is_some() {
            return true;
        }
        let mut p = body;
        while let Some(Node::Scope { body: b, .. } | Node::Spec(b)) =
            self.code.nodes.get(p as usize)
        {
            p = *b;
        }
        matches!(
            self.code.nodes.get(p as usize),
            Some(
                Node::Powerset(_)
                    | Node::Product(_)
                    | Node::FcnSet(..)
                    | Node::RecSet(_)
                    | Node::Std(StdFn::Seq, _)
            )
        )
    }

    fn apply(&mut self, callee: &OpRef, args: &[Arg], env: usize, mode: Mode) -> Result<P, Error> {
        match callee {
            OpRef::Def(d) => {
                let d = self.redirect(*d);
                let def = self.ir.def(d);
                if let Some(op) = def.std {
                    return self.std_apply(op, args, env, mode);
                }
                if args.is_empty() {
                    return self.def_use(d, env, mode);
                }
                if def.recursive {
                    return self.call(d, args, env, mode);
                }
                self.inline_apply(d, args, env, env, mode)
            }
            OpRef::Std(op) => {
                if let Some(&t) = self.h.std_redirects.get(op) {
                    return self.apply(&OpRef::Def(t), args, env, mode);
                }
                self.std_apply(*op, args, env, mode)
            }
            OpRef::Param(r) => self.apply_param(*r, args, env, env, mode),
            OpRef::Builtin(op) => self.builtin_apply(*op, args, env, mode),
            // `CONSTANT F(_)` with `F <- D` in the configuration.
            OpRef::Const(c) => match self.h.constants.get(c.index()).cloned().flatten() {
                Some(ConstBinding::Def(_)) if args.is_empty() => self.const_expr(*c, env, mode),
                Some(ConstBinding::Def(d)) => {
                    let body = self.apply(&OpRef::Def(d), args, env, mode)?;
                    self.configured_result(body)
                }
                _ => Err(Error::unsupported(
                    "a constant operator the configuration does not bind to a definition (M1 core)",
                )),
            },
            // The operator is resolved outside the substitution; the
            // arguments are compiled here, and TLC applies the operator in
            // the current (dynamic) context.
            OpRef::Subst(decl) => {
                let op = self.subst_op(*decl)?;
                self.apply(&op, args, env, mode)
            }
            OpRef::Unbound(n) => Err(Error::unsupported(format!("the unbound operator {n}"))),
        }
    }

    /// Applies a built-in operator passed as an operator argument (for
    /// example `ReduceSet(\intersect, S, b)` applying `op(x, y)`) to
    /// expression arguments compiled in `env`, as the built-in written
    /// in place would be. Only the value operators of
    /// [`builtin_value_arg`] are applied; the others stay refused.
    fn builtin_apply(
        &mut self,
        op: BuiltinOp,
        args: &[Arg],
        env: usize,
        mode: Mode,
    ) -> Result<P, Error> {
        if !builtin_value_arg(op) {
            return Err(Error::unsupported(format!(
                "the built-in {} as an operator argument (M0 core)",
                op.sany_name()
            )));
        }
        let mut exprs = Vec::with_capacity(args.len());
        for a in args {
            let Arg::Expr { expr, .. } = a else {
                return Err(Error::unsupported(format!(
                    "the built-in {} applied to an operator argument",
                    op.sany_name()
                )));
            };
            exprs.push(*expr);
        }
        if builtin_arity(op) != Some(exprs.len()) {
            return Err(Error::internal(format!(
                "the built-in {} applied to {} arguments",
                op.sany_name(),
                exprs.len()
            )));
        }
        self.builtin(op, &exprs, env, mode)
    }

    /// Inlines a non-recursive operator applied to `args`, which are
    /// compiled in `env`; the operator's lexical parent is found from
    /// `def_env` (the caller's, or where an operator argument was passed).
    fn inline_apply(
        &mut self,
        d: DefId,
        args: &[Arg],
        env: usize,
        def_env: usize,
        mode: Mode,
    ) -> Result<P, Error> {
        let body = self.ir.def(d).body;
        let (inner, reset) = self.inline(d, args, env, def_env, mode)?;
        let b = self.p(body, inner, mode)?;
        if reset.is_empty() {
            Ok(b)
        } else {
            self.push(Node::Scope {
                reset: reset.into(),
                body: b,
            })
        }
    }

    /// Inlines a non-recursive operator applied as an action (see
    /// [`Self::inline_apply`]).
    fn g_inline(&mut self, d: DefId, args: &[Arg], env: usize, def_env: usize) -> Result<G, Error> {
        let body = self.ir.def(d).body;
        let (inner, reset) = self.inline(d, args, env, def_env, Mode::Plain)?;
        let g = self.g(body, inner)?;
        if reset.is_empty() {
            Ok(g)
        } else {
            Ok(self.gpush(GNode::Scope {
                reset: reset.into(),
                body: g,
            }))
        }
    }

    /// Applies, as an action, an operator resolved from a constant, a
    /// substitution or a parameter; `aenv` is where it was resolved.
    fn g_apply_op(
        &mut self,
        op: &OpRef,
        args: &[Arg],
        e: ExprId,
        env: usize,
        aenv: usize,
    ) -> Result<G, Error> {
        let d = match *op {
            OpRef::Def(d) => d,
            OpRef::Const(c) => match self.h.constants.get(c.index()).cloned().flatten() {
                Some(ConstBinding::Def(d)) => d,
                _ => return self.guard_expr(e, env),
            },
            // TLC's action splitting of a passed built-in (`Op(\/)`,
            // `Op(=)` with a primed operand) is not reproduced.
            OpRef::Builtin(b) => {
                return Err(Error::unsupported(format!(
                    "the built-in {} passed as an operator argument and applied as an action (M1 core)",
                    b.sany_name()
                )));
            }
            _ => return self.guard_expr(e, env),
        };
        let d = self.redirect(d);
        let def = self.ir.def(d);
        if def.std.is_some() || def.recursive || args.is_empty() {
            return self.guard_expr(e, env);
        }
        let def_env = if def.scope == DefScope::TopLevel {
            env
        } else {
            aenv
        };
        self.g_inline(d, args, env, def_env)
    }

    /// An operator argument as a function of `arity` fresh frame slots, for
    /// the standard modules' higher-order operators (`SelectSeq`, the
    /// Folds, ...): the slots, and its body compiled with its parameters
    /// bound to them. The caller sets the slots and evaluates the body for
    /// each element. The body's free slots include the parameter slots,
    /// which the caller's node must treat as bound, as a binder's are.
    ///
    /// The operator is resolved as an application of it would be:
    /// - through operator parameters passed on;
    /// - through constant operators bound in the configuration
    ///   (`F <- D`);
    /// - through `INSTANCE` substitutions.
    ///
    /// A `LAMBDA` or `LET` operator's body is compiled in the environment
    /// where it was written, so it reads the caller's locals.
    ///
    /// # Errors
    /// Unsupported for a std or built-in operator passed as the argument
    /// (`FoldSet(+, 0, S)`), a recursive operator, or an expression
    /// argument; internal for an arity mismatch.
    pub(crate) fn op_fn(
        &mut self,
        a: &Arg,
        env: usize,
        arity: usize,
    ) -> Result<(Box<[u32]>, P), Error> {
        let Arg::Op { op, .. } = a else {
            return Err(Error::unsupported(
                "an expression where an operator argument is expected (M1 core)",
            ));
        };
        let (op, aenv, enclosing) = match op {
            OpRef::Param(r) => self.resolve_param(*r, env)?,
            OpRef::Subst(decl) => (self.subst_op(*decl)?, env, false),
            op => (op.clone(), env, false),
        };
        let d = match op {
            OpRef::Def(d) => d,
            OpRef::Std(s) => match self.h.std_redirects.get(&s) {
                Some(&t) => t,
                None => return self.std_op_fn(s, arity),
            },
            OpRef::Const(c) => match self.h.constants.get(c.index()).cloned().flatten() {
                Some(ConstBinding::Def(d)) => d,
                _ => {
                    return Err(Error::unsupported(
                        "a constant operator the configuration does not bind to a definition (M1 core)",
                    ));
                }
            },
            _ => {
                return Err(Error::unsupported(
                    "a built-in operator passed to a higher-order operator (M1 core)",
                ));
            }
        };
        let mut d = self.redirect(d);
        if let Some(s) = self.ir.def(d).std {
            match self.h.std_redirects.get(&s) {
                Some(&t) if t != d => d = self.redirect(t),
                _ => {
                    if self.ir.def(d).params.len() != arity {
                        return Err(Error::internal(format!(
                            "{} passed where an operator of {arity} arguments is expected",
                            self.ir.def(d).name
                        )));
                    }
                    return self.std_op_fn(s, arity);
                }
            }
        }
        let def = self.ir.def(d);
        if def.std.is_some() || def.recursive {
            return Err(Error::unsupported(
                "a std or recursive operator passed to a higher-order operator (M1 core)",
            ));
        }
        if def.params.len() != arity {
            return Err(Error::internal(format!(
                "{} passed where an operator of {arity} arguments is expected",
                def.name
            )));
        }
        let body = def.body;
        let def_env = if def.scope == DefScope::TopLevel {
            env
        } else {
            aenv
        };
        let parent = self.lexical_parent(d, def_env)?;
        let inner = self.new_env(d, parent);
        let mut slots = Vec::with_capacity(arity);
        for i in 0..arity {
            let slot = self.alloc();
            if let Some(s) = self.envs[inner].slots.get_mut(i) {
                *s = Sb::Flat(slot);
            }
            slots.push(slot);
        }
        let b = self.p(body, inner, Mode::Plain)?;
        self.enclosing_op_body(b, enclosing)?;
        Ok((slots.into(), b))
    }

    /// A value-only standard operator (`+`, `\\o`, ...) passed as an
    /// operator argument, as the `LAMBDA` of its arity that applies it: TLC
    /// passes its `MethodValue`, which the override applies to values.
    /// TLC wraps an error the operator raises there in the override's
    /// `TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE` report, which the core does
    /// not reproduce: the body is a `Node::Spec`, so any such error is
    /// reported as `unsupported`.
    ///
    /// # Errors
    /// Unsupported for an operator with operator arguments, an effectful
    /// or nullary one, one of another arity, or one the core does not
    /// apply to values.
    fn std_op_fn(&mut self, op: StdOp, arity: usize) -> Result<(Box<[u32]>, P), Error> {
        if crate::stdlib::higher_order(op) || op.impure() || arity == 0 {
            return Err(Error::unsupported(format!(
                "{} passed to a higher-order operator (M1 core)",
                op.qualified_name()
            )));
        }
        if usize::try_from(op.java_arity()).ok() != Some(arity) {
            return Err(Error::unsupported(format!(
                "{} passed where an operator of {arity} arguments is expected",
                op.qualified_name()
            )));
        }
        let mut slots = Vec::with_capacity(arity);
        let mut ps = Vec::with_capacity(arity);
        for _ in 0..arity {
            let slot = self.alloc();
            slots.push(slot);
            ps.push(self.push(Node::Slot(slot))?);
        }
        let body = self.std_node(op, ps, None)?;
        let body = self.push(Node::Spec(body))?;
        Ok((slots.into(), body))
    }

    /// The operator argument an operator parameter is bound to, following
    /// parameters passed on and recursive LET-function views. The original
    /// argument environment is retained; the boolean records a function view.
    fn resolve_param(&self, r: LocalRef, look_env: usize) -> Result<(OpRef, usize, bool), Error> {
        let mut r = r;
        let mut look = look_env;
        let mut enclosing = false;
        loop {
            let fe = self.frame_env(look, r.up)?;
            if !enclosing && self.lifts.last().is_some_and(|l| fe < l.floor) {
                return Err(Error::unsupported(
                    "an enclosing operator parameter inside a recursive LET definition (M1 core)",
                ));
            }
            let mut binding = self.envs[fe].slots.get(r.slot.index());
            while let Some(Sb::Enclosing { env, slot }) = binding {
                // This is compile-time operator metadata, not a captured
                // runtime value. The inlined body still resolves every value
                // through `local`/`capture` in its original environment.
                enclosing = true;
                binding = self.envs[*env].slots.get(*slot);
            }
            let Some(Sb::OpArg { op, env }) = binding.cloned() else {
                return Err(Error::unsupported(
                    "an operator parameter of a recursive operator (M1 core)",
                ));
            };
            match op {
                OpRef::Param(r2) => {
                    r = r2;
                    look = env;
                }
                op => return Ok((op, env, enclosing)),
            }
        }
    }

    /// A newly admitted enclosing callback cannot hide effects or unknown
    /// calls behind a recursive function's call node.
    fn enclosing_op_body(&self, body: P, enclosing: bool) -> Result<(), Error> {
        if enclosing && (self.info[body as usize].effect || self.info[body as usize].calls) {
            return Err(Error::unsupported(
                "an enclosing operator argument with effects or recursive calls inside a recursive function (M1 core)",
            ));
        }
        Ok(())
    }

    /// Applies an operator parameter: the operator argument bound to it.
    /// The arguments are compiled in `env`; the parameter is looked up from
    /// `look_env`. TLC applies the argument as a closure over the caller's
    /// context, which inlining it there reproduces.
    fn apply_param(
        &mut self,
        r: LocalRef,
        args: &[Arg],
        env: usize,
        look_env: usize,
        mode: Mode,
    ) -> Result<P, Error> {
        let (op, aenv, enclosing) = self.resolve_param(r, look_env)?;
        let body = match op {
            OpRef::Param(_) => Err(Error::internal("an unresolved operator parameter")),
            OpRef::Def(d) => {
                let d = self.redirect(d);
                let def = self.ir.def(d);
                if def.std.is_some() || def.scope == DefScope::TopLevel {
                    self.apply(&OpRef::Def(d), args, env, mode)
                } else if def.recursive {
                    Err(Error::unsupported(
                        "a recursive LET operator passed as an operator argument (M1 core)",
                    ))
                } else {
                    self.inline_apply(d, args, env, aenv, mode)
                }
            }
            OpRef::Subst(_) => Err(Error::unsupported(
                "an INSTANCE-substituted operator passed as an operator argument (M1 core)",
            )),
            // A built-in has no body of its own: its application is the
            // built-in written in place, over arguments compiled in `env`,
            // so any recursive call or effect in it is the caller's own and
            // nothing is hidden behind an enclosing callback.
            OpRef::Builtin(b) => return self.builtin_apply(b, args, env, mode),
            op @ (OpRef::Std(_) | OpRef::Const(_) | OpRef::Unbound(_)) => {
                self.apply(&op, args, env, mode)
            }
        }?;
        self.enclosing_op_body(body, enclosing)?;
        Ok(body)
    }

    /// Binds an inlined operator's parameters: returns its environment and
    /// the thunk slots to reset on entry.
    fn inline(
        &mut self,
        d: DefId,
        args: &[Arg],
        env: usize,
        def_env: usize,
        mode: Mode,
    ) -> Result<(usize, Vec<u32>), Error> {
        let def = self.ir.def(d);
        if def.params.len() != args.len() {
            return Err(Error::internal(format!(
                "{} applied to {} arguments",
                def.name,
                args.len()
            )));
        }
        let parent = self.lexical_parent(d, def_env)?;
        let inner = self.new_env(d, parent);
        let mut reset = Vec::new();
        self.stats.inlined += 1;
        for (i, a) in args.iter().enumerate() {
            let expr = match a {
                Arg::Expr { expr, .. } => expr,
                Arg::Op { op, .. } => {
                    if let Some(s) = self.envs[inner].slots.get_mut(i) {
                        *s = Sb::OpArg {
                            op: op.clone(),
                            env,
                        };
                    }
                    continue;
                }
            };
            let cp = self.p(*expr, env, mode)?;
            let how = if self.opts.eager && self.is_trivial(cp) {
                self.stats.aliased += 1;
                ArgHow::Alias(cp)
            } else if self.info[cp as usize].primed == 0 {
                self.stats.thunks += 1;
                let slot = self.alloc();
                reset.push(slot);
                ArgHow::Thunk(slot, cp)
            } else {
                ArgHow::ByName
            };
            if let Some(s) = self.envs[inner].slots.get_mut(i) {
                *s = Sb::Arg {
                    expr: *expr,
                    env,
                    how,
                };
            }
        }
        Ok((inner, reset))
    }

    /// A recursive operator call. Under a prime, `op(a)'` is `op` applied to
    /// `a'` and evaluated in the next state: the call is of `op`'s
    /// next-state variant, whose body is compiled primed. A prime or
    /// `ENABLED` inside that body stays refused (a doubly primed expression,
    /// a primed `ENABLED`).
    fn call(&mut self, d: DefId, args: &[Arg], env: usize, mode: Mode) -> Result<P, Error> {
        let fun = self.fun(d, env, mode)?;
        let mut ps = Vec::with_capacity(args.len());
        for a in args {
            let Arg::Expr { expr, .. } = a else {
                return Err(Error::unsupported("operator arguments (M0 core)"));
            };
            // TLC passes a recursive operator's arguments lazily; the core
            // evaluates them at the call, speculatively.
            let a = self.p(*expr, env, mode)?;
            let a = if self.is_trivial(a) {
                a
            } else {
                self.stats.speculative += 1;
                self.push(Node::Spec(a))?
            };
            ps.push(a);
        }
        self.fun_call(d, fun, ps, env)
    }

    fn fun(&mut self, d: DefId, call_env: usize, mode: Mode) -> Result<u32, Error> {
        let key = (
            d,
            mode,
            self.init_mode,
            self.lexical_parent(d, call_env)?,
            self.substs.last().map(|s| s.id),
        );
        if let Some(&f) = self.funs.get(&key) {
            return Ok(self.reenter(f));
        }
        let def = self.ir.def(d);
        #[allow(clippy::cast_possible_truncation, reason = "bounded")]
        let id = self.code.funs.len() as u32;
        #[allow(
            clippy::cast_possible_truncation,
            reason = "parameter counts are small"
        )]
        let params = def.params.len() as u32;
        self.code.funs.push(Fun {
            name: def.name.clone(),
            params,
            frame: params,
            body: 0,
            caps: Box::new([]),
        });
        self.funs.insert(key, id);
        self.open_fun(id, mode, def.level);
        let saved_slot = self.next_slot;
        let saved_resets = std::mem::take(&mut self.reset_stack);
        let saved_cache = std::mem::take(&mut self.def_cache);
        let saved_at = std::mem::take(&mut self.at_stack);
        self.next_slot = params;
        let saved_frame = self.new_frame();
        let (env, lifted) = match self.begin_fun(d, id, call_env, mode) {
            Ok(x) => x,
            Err(e) => {
                self.frame = saved_frame;
                self.next_slot = saved_slot;
                self.reset_stack = saved_resets;
                self.def_cache = saved_cache;
                self.at_stack = saved_at;
                return Err(e);
            }
        };
        for i in 0..def.params.len() {
            #[allow(
                clippy::cast_possible_truncation,
                reason = "parameter counts are small"
            )]
            let s = Sb::Flat(i as u32);
            if let Some(x) = self.envs[env].slots.get_mut(i) {
                *x = s;
            }
        }
        let body = self.p(def.body, env, mode);
        let ended = self.end_fun(id, lifted);
        self.frame = saved_frame;
        let frame = self.next_slot;
        self.next_slot = saved_slot;
        self.reset_stack = saved_resets;
        self.def_cache = saved_cache;
        self.at_stack = saved_at;
        self.open_funs.remove(&id);
        let body = body?;
        ended?;
        self.note_next_reads(id, &[body])?;
        if mode == Mode::Primed && self.info[body as usize].effect {
            return Err(Error::unsupported(
                "an effectful recursive operator under a prime (M1 core)",
            ));
        }
        self.complete_fun(id, body, frame);
        Ok(id)
    }

    /// Records the completed body and frame size of `fun`, and its
    /// [`Self::fun_summary`].
    fn complete_fun(&mut self, fun: u32, body: P, frame: u32) {
        if let Some(f) = self.code.funs.get_mut(fun as usize) {
            f.body = body;
            f.frame = frame;
        }
        if let Some(vars) = self.fun_summary(fun, body) {
            self.fun_reads.insert(fun, vars);
        }
    }

    /// The unprimed variables that evaluating `body`, the completed body of
    /// `fun`, can read, when that is provably a function of the call's
    /// frame and those variables alone; `None` otherwise.
    ///
    /// A node without calls contributes its own read set. A recursive call
    /// of `fun` itself contributes only its arguments: the reads of `fun`
    /// are the least set closed under its body, and a self-call adds
    /// nothing beyond that set. A call of another completed function
    /// contributes that function's summary. Anything else (an effect, a
    /// nested `ENABLED` or composition query, a call of an open or
    /// unsummarized function) gives `None`, and calls of `fun` keep reading
    /// every variable.
    fn fun_summary(&self, fun: u32, body: P) -> Option<u64> {
        let mut vars = 0u64;
        let mut seen = std::collections::HashSet::new();
        let mut stack = vec![body];
        while let Some(p) = stack.pop() {
            if !seen.insert(p) {
                continue;
            }
            let info = self.info.get(p as usize)?;
            if info.effect || info.nested_query {
                return None;
            }
            if !info.calls {
                vars |= info.vars;
                continue;
            }
            let node = self.code.nodes.get(p as usize)?;
            match node {
                Node::Call { fun: g, .. } if *g != fun => {
                    if self.open_funs.contains(g) {
                        return None;
                    }
                    vars |= *self.fun_reads.get(g)?;
                }
                Node::Enabled { .. } | Node::Composition { .. } => return None,
                _ => {}
            }
            push_operands(node, &mut stack);
        }
        Some(vars)
    }

    /// A call of `fun` found compiled: notes a call from inside its own
    /// compilation.
    fn reenter(&mut self, fun: u32) -> u32 {
        if self.open_funs.contains(&fun) {
            self.reentered_funs.insert(fun);
        }
        fun
    }

    /// Starts compiling `fun`, a `mode` variant of a definition at `level`.
    fn open_fun(&mut self, fun: u32, mode: Mode, level: Level) {
        if mode == Mode::Primed {
            self.primed_funs.insert(fun);
        }
        if mode == Mode::Primed || self.reads_next(level) {
            self.next_funs.insert(fun);
        }
        self.open_funs.insert(fun);
    }

    /// Whether a plain-mode function of a definition at `level`, in the
    /// active substitutions, may read primed variables: an action-level
    /// definition, or a state-level one while compiling an initial
    /// predicate (which reads the state being built as primed), or any
    /// definition under a substitution whose value is at that level.
    fn reads_next(&self, level: Level) -> bool {
        let at = if self.init_mode {
            Level::State
        } else {
            Level::Action
        };
        level >= at
            || self.substs.iter().any(|s| match &s.value {
                Ok(Arg::Expr { expr, .. }) => self.ir.node(*expr).level >= at,
                Ok(Arg::Op { level, .. }) => *level >= at,
                Err(p) => self.info.get(*p as usize).is_none_or(|i| i.primed != 0),
            })
    }

    /// Records that a call of `fun` reads primed variables when its compiled
    /// `parts` do, although [`Self::reads_next`] did not predict it. Calls
    /// compiled while `fun` was open assumed it did not, so then the
    /// function is refused.
    fn note_next_reads(&mut self, fun: u32, parts: &[P]) -> Result<(), Error> {
        let reentered = self.reentered_funs.remove(&fun);
        if self.next_funs.contains(&fun) || parts.iter().all(|&p| self.info[p as usize].primed == 0)
        {
            return Ok(());
        }
        if reentered {
            return Err(Error::unsupported(
                "a recursive definition below action level whose body reads the next state (M1 core)",
            ));
        }
        self.next_funs.insert(fun);
        Ok(())
    }

    /// A [`crate::stdlib`] operator with operator arguments
    /// (`Node::LibHo`): each operator argument is compiled with
    /// [`Self::op_fn`] at the arity the library expects.
    fn lib_ho(&mut self, op: StdOp, args: &[Arg], env: usize, mode: Mode) -> Result<P, Error> {
        if mode == Mode::Primed && op != StdOp::SequencesSelectSeq {
            return Err(Error::unsupported(format!(
                "{} under a prime (M1 core)",
                op.qualified_name()
            )));
        }
        let mut out = Vec::with_capacity(args.len());
        for (i, a) in args.iter().enumerate() {
            match (crate::stdlib::op_arity(op, i), a) {
                (Some(arity), _) => {
                    let (params, body) = self.op_fn(a, env, arity)?;
                    if mode == Mode::Primed {
                        // `op_fn` compiles the callback in Plain mode. That is
                        // unchanged by the surrounding prime only when its
                        // sole inputs are its element parameters. In
                        // particular, neither a state read hidden behind an
                        // INSTANCE/configured operator nor a lexical capture
                        // may retain the source-state context here.
                        let info = &self.info[body as usize];
                        if info.vars != 0
                            || info.primed != 0
                            || info.effect
                            || info.calls
                            || info.free.iter().any(|s| !params.contains(s))
                        {
                            return Err(Error::unsupported(
                                "Sequences!SelectSeq under a prime with a state-dependent, captured or effectful predicate (M1 core)",
                            ));
                        }
                    }
                    if crate::stdlib::takes_op_value(op)
                        && matches!(self.code.nodes.get(body as usize), Some(Node::Const(_)))
                    {
                        return Err(Error::unsupported(format!(
                            "{} with an operator whose body is constant: TLC may fail to apply it",
                            op.qualified_name()
                        )));
                    }
                    out.push(LibArg::Op { params, body });
                }
                (None, Arg::Expr { expr, .. }) => {
                    out.push(LibArg::Value(self.p(*expr, env, mode)?));
                }
                (None, Arg::Op { .. }) => {
                    return Err(Error::unsupported(format!(
                        "{} with an operator where a value is expected",
                        op.qualified_name()
                    )));
                }
            }
        }
        self.push(Node::LibHo(op, out.into()))
    }

    /// Records whether a value-only library call can replace a repeated-demand
    /// TLA+ definition without changing argument effects.
    fn lib_node(&self, op: StdOp, args: Vec<P>) -> Node {
        let repeatable_args = args.iter().all(|&p| {
            let info = &self.info[p as usize];
            // Calls and free slots can hide effects in a callee or capture.
            !info.effect && !info.calls && info.free.is_empty()
        });
        Node::Lib {
            op,
            args: args.into(),
            repeatable_args,
        }
    }

    fn std_apply(&mut self, op: StdOp, args: &[Arg], env: usize, mode: Mode) -> Result<P, Error> {
        if let Some(&t) = self.h.std_redirects.get(&op) {
            return if args.is_empty() {
                self.def_use(t, env, mode)
            } else {
                self.apply(&OpRef::Def(t), args, env, mode)
            };
        }
        if crate::stdlib::higher_order(op) {
            return self.lib_ho(op, args, env, mode);
        }
        // TLC evaluates a primed expression in the successor state, so a
        // primed `TLCGet("level")` is the successor's level, which the core
        // does not track: `Machine::level` is the source's in a step.
        if mode == Mode::Primed
            && op == StdOp::TlcTLCGet
            && !matches!(args, [Arg::Expr { expr, .. }]
                if matches!(&self.ir.node(*expr).expr, Expr::Num(_))
                    || matches!(&self.ir.node(*expr).expr, Expr::Str(k) if k.as_ref() != "level"))
        {
            return Err(Error::unsupported(
                "TLCGet(\"level\") under a prime, which TLC evaluates at the successor's level (M1 core)",
            ));
        }
        let mut ps = Vec::with_capacity(args.len());
        for a in args {
            let Arg::Expr { expr, .. } = a else {
                return Err(Error::unsupported(format!(
                    "{} with an operator argument",
                    op.qualified_name()
                )));
            };
            ps.push(self.p(*expr, env, mode)?);
        }
        self.std_node(op, ps, Some(args))
    }

    /// The node of the value-only standard operator `op` applied to the
    /// compiled arguments `ps`; `args` are their source arguments, absent
    /// when the operator is applied by a higher-order operator to values.
    fn std_node(&mut self, op: StdOp, ps: Vec<P>, args: Option<&[Arg]>) -> Result<P, Error> {
        use StdOp as S;
        let arg = |i: usize| {
            ps.get(i)
                .copied()
                .ok_or_else(|| Error::internal("missing argument"))
        };
        let arith = |o: Arith| -> Result<Node, Error> { Ok(Node::Arith(o, arg(0)?, arg(1)?)) };
        let cmp = |o: Cmp| -> Result<Node, Error> { Ok(Node::Cmp(o, arg(0)?, arg(1)?)) };
        let n = match op {
            S::NaturalsPlus | S::IntegersPlus => arith(Arith::Add)?,
            S::NaturalsMinus | S::IntegersMinus => arith(Arith::Sub)?,
            S::NaturalsTimes | S::IntegersTimes => arith(Arith::Mul)?,
            S::IntegersDiv => arith(Arith::Div)?,
            S::NaturalsDiv => arith(Arith::DivNaturals)?,
            S::NaturalsMod | S::IntegersMod => arith(Arith::Mod)?,
            S::NaturalsExpt | S::IntegersExpt => arith(Arith::Pow)?,
            S::NaturalsLt | S::IntegersLt => cmp(Cmp::Lt)?,
            S::NaturalsLeq | S::IntegersLeq => cmp(Cmp::Le)?,
            S::NaturalsGt | S::IntegersGt => cmp(Cmp::Gt)?,
            S::NaturalsGeq | S::IntegersGeq => cmp(Cmp::Ge)?,
            S::NaturalsDotDot | S::IntegersDotDot => Node::Range(arg(0)?, arg(1)?),
            S::IntegersNeg => Node::Neg(arg(0)?),
            S::NaturalsNat | S::IntegersNat => {
                let h = self.m.heap.symbolic(Kind::Nat, 0, &[]);
                let h = self.m.heap.intern_const(h)?;
                Node::Const(h)
            }
            S::IntegersInt => {
                let h = self.m.heap.symbolic(Kind::Int, 0, &[]);
                let h = self.m.heap.intern_const(h)?;
                Node::Const(h)
            }
            S::SequencesLen => Node::Std(StdFn::Len, ps.into()),
            S::SequencesHead => Node::Std(StdFn::Head, ps.into()),
            S::SequencesTail => Node::Std(StdFn::Tail, ps.into()),
            S::SequencesAppend => Node::Std(StdFn::Append, ps.into()),
            S::SequencesConcat => Node::Std(StdFn::Concat, ps.into()),
            S::SequencesSubSeq => Node::Std(StdFn::SubSeq, ps.into()),
            S::SequencesSeq => Node::Std(StdFn::Seq, ps.into()),
            S::FiniteSetsCardinality => Node::Std(StdFn::Cardinality, ps.into()),
            S::FiniteSetsIsFiniteSet => Node::Std(StdFn::IsFiniteSet, ps.into()),
            S::BagsEmptyBag => Node::Std(StdFn::EmptyBag, ps.into()),
            S::BagsSetToBag => Node::Std(StdFn::SetToBag, ps.into()),
            S::BagsBagToSet => Node::Std(StdFn::BagToSet, ps.into()),
            S::BagsBagIn => Node::Std(StdFn::BagIn, ps.into()),
            S::BagsCopiesIn => Node::Std(StdFn::CopiesIn, ps.into()),
            S::TlcTLCGet => {
                // TLC wraps an error raised while evaluating the argument as
                // TLCGet's own (`TLCGetEval`), so the argument is a literal;
                // `"level"` is the engine's, any other key a register.
                let lit = match args {
                    Some([Arg::Expr { expr, .. }]) => match &self.ir.node(*expr).expr {
                        Expr::Str(k) => Some(k.as_ref() != "level"),
                        Expr::Num(_) => Some(true),
                        _ => None,
                    },
                    _ => None,
                };
                let Some(register) = lit else {
                    return Err(Error::unsupported(
                        "TLCGet of an expression other than a literal, whose errors TLC reports inside TLCGet (M1 core)",
                    ));
                };
                self.effects.registers |= register;
                self.effects.level |= !register;
                self.lib_node(op, ps)
            }
            other if crate::stdlib::implements(other) => self.lib_node(other, ps),
            other => {
                return Err(Error::unsupported(format!(
                    "the standard operator {} (M0 core)",
                    other.qualified_name()
                )));
            }
        };
        self.push(n)
    }

    /// `S` in `UNION {S}` when `S` is a set constructor (`[D -> R]`,
    /// `[a : R]`, `SUBSET R`, `A \X B`). `UNION {S}` is then `S`: TLC's
    /// `UnionValue` tests membership in each member, so `S` stays lazy
    /// instead of being enumerated as the element of a set in every state.
    /// Other operands keep TLC's check that the member is a set.
    fn union_of_one_constructor(&self, args: &[ExprId]) -> Option<ExprId> {
        let a = *args.first()?;
        let Expr::SetEnum(items) = &self.ir.node(a).expr else {
            return None;
        };
        let [item] = items.as_ref() else {
            return None;
        };
        matches!(
            &self.ir.node(*item).expr,
            Expr::FcnSet { .. }
                | Expr::RecordSet(_)
                | Expr::Cartesian(_)
                | Expr::Builtin {
                    op: BuiltinOp::PowerSet | BuiltinOp::Times,
                    ..
                }
        )
        .then_some(*item)
    }

    #[allow(clippy::too_many_lines, reason = "one arm per built-in operator")]
    fn builtin(
        &mut self,
        op: BuiltinOp,
        args: &[ExprId],
        env: usize,
        mode: Mode,
    ) -> Result<P, Error> {
        use BuiltinOp as B;
        match op {
            B::Prime => {
                let a = *args
                    .first()
                    .ok_or_else(|| Error::internal("prime without operand"))?;
                if mode == Mode::Primed || self.init_mode {
                    return Err(Error::unsupported(
                        "a doubly primed expression or a prime in Init",
                    ));
                }
                return self.p(a, env, Mode::Primed);
            }
            B::Unchanged => {
                let a = *args
                    .first()
                    .ok_or_else(|| Error::internal("UNCHANGED without operand"))?;
                return self.unchanged_value(a, env, mode);
            }
            B::Boolean => {
                let mut v = vec![Handle::FALSE, Handle::TRUE];
                let h = self.m.heap.set_from(&mut v);
                let h = self.m.heap.intern_const(h)?;
                return self.konst(h);
            }
            B::BigUnion => {
                if let Some(item) = self.union_of_one_constructor(args) {
                    return self.p(item, env, mode);
                }
            }
            B::String => return Err(Error::unsupported("STRING (M0 core)")),
            B::Enabled => return self.enabled(args.first().copied(), None, env, mode),
            B::Cdot => {
                let [a, b] = args else {
                    return Err(Error::internal("action composition without two operands"));
                };
                return self.composition_value(*a, *b, env, mode);
            }
            B::Always | B::Eventually | B::LeadsTo | B::WhilePlus => {
                return Err(Error::unsupported(
                    "a temporal operator in a state or action role",
                ));
            }
            _ => {}
        }
        let ps = self.ps(args, env, mode)?;
        let a = |i: usize| {
            ps.get(i)
                .copied()
                .ok_or_else(|| Error::internal("missing operand"))
        };
        let n = match op {
            B::Cup | B::Cap | B::SetMinus => {
                let o = match op {
                    B::Cup => SetOp::Cup,
                    B::Cap => SetOp::Cap,
                    _ => SetOp::Minus,
                };
                return self.push_lazy(Node::SetBin(o, a(0)?, a(1)?));
            }
            B::In | B::NotIn => {
                let (x, set) = (a(0)?, a(1)?);
                if self.lazy_set(set) {
                    return self.push(Node::InLazy {
                        elem: x,
                        set,
                        neg: op == B::NotIn,
                    });
                }
                if op == B::In {
                    Node::In(x, set)
                } else {
                    Node::NotIn(x, set)
                }
            }
            B::Eq => Node::Eq(a(0)?, a(1)?),
            B::Neq => Node::Neq(a(0)?, a(1)?),
            B::Subseteq => Node::Subseteq(a(0)?, a(1)?),
            B::PowerSet => Node::Powerset(a(0)?),
            B::BigUnion => Node::BigUnion(a(0)?),
            B::Domain => {
                let f = a(0)?;
                if let Some(d) = self.lambda_domain(f)? {
                    return Ok(d);
                }
                Node::Domain(f)
            }
            B::Times => Node::Product(ps.clone().into()),
            B::Not => Node::Not(a(0)?),
            B::And => Node::And(ps.clone().into()),
            B::Or => Node::Or(ps.clone().into()),
            B::Implies => Node::Implies(a(0)?, a(1)?),
            B::Equiv => Node::Equiv(a(0)?, a(1)?),
            _ => {
                return Err(Error::unsupported(format!(
                    "the built-in {} (M0 core)",
                    op.sany_name()
                )));
            }
        };
        self.push(n)
    }

    // ------------------------------------------------------------------
    // Generator compilation
    // ------------------------------------------------------------------

    fn guard(&mut self, p: P) -> Result<G, Error> {
        let name = format!("{} guard", self.role_name);
        let p = self.site(name, p)?.unwrap_or(p);
        Ok(self.gpush(GNode::Guard(p)))
    }

    fn guard_expr(&mut self, e: ExprId, env: usize) -> Result<G, Error> {
        let p = self.p(e, env, Mode::Plain)?;
        self.guard(p)
    }

    fn g(&mut self, e: ExprId, env: usize) -> Result<G, Error> {
        if self.code.source_map.is_none() {
            return self.g_inner(e, env);
        }
        let previous = self.debug_current;
        self.debug_current = self.debug_context(e, env)?;
        let result = self.g_inner(e, env);
        self.debug_current = previous;
        result
    }

    #[allow(
        clippy::too_many_lines,
        clippy::many_single_char_names,
        reason = "one arm per generator rule"
    )]
    fn g_inner(&mut self, e: ExprId, env: usize) -> Result<G, Error> {
        // Each generator expression is evaluated by its own TLC call
        // (`Compiler::effect_thunk_use`).
        self.leaf += 1;
        let expr = &self.ir.node(e).expr;
        match expr {
            Expr::Cdot(a, b) => {
                let (first, then, _) = self.composition_parts(*a, *b, env)?;
                Ok(self.composition_gen(first, then))
            }
            Expr::Builtin {
                op: BuiltinOp::Cdot,
                args,
            } if args.len() == 2 => {
                let (first, then, _) = self.composition_parts(args[0], args[1], env)?;
                Ok(self.composition_gen(first, then))
            }
            Expr::Junction { kind, items, .. } => match kind {
                JunctionKind::And => {
                    let mut out = Vec::with_capacity(items.len());
                    for &i in items {
                        let g = self.g(i, env)?;
                        let p = self.p(i, env, Mode::Plain)?;
                        out.push((g, p));
                    }
                    Ok(self.gpush(GNode::Conj(out.into())))
                }
                JunctionKind::Or => {
                    let mut out = Vec::with_capacity(items.len());
                    for &i in items {
                        out.push(self.g(i, env)?);
                    }
                    Ok(self.gpush(GNode::Disj(out.into())))
                }
            },
            Expr::Quant {
                kind: kind @ (QuantKind::Exists | QuantKind::Forall),
                bounds,
                body,
            } if bounds.iter().all(|b| b.domain.is_some()) => {
                let exists = *kind == QuantKind::Exists;
                let body = *body;
                let (binds, saved) = self.binds(bounds, env, Mode::Plain)?;
                let r = (|| {
                    let bg = self.g(body, env)?;
                    let bp = self.p(body, env, Mode::Plain)?;
                    Ok((bg, bp))
                })();
                self.unbind(saved);
                let (bg, bp) = r?;
                let binds: Box<[Bind]> = binds.into();
                Ok(self.gpush(if exists {
                    GNode::Exists {
                        binds,
                        body: bg,
                        body_p: bp,
                    }
                } else {
                    GNode::Forall {
                        binds,
                        body: bg,
                        body_p: bp,
                    }
                }))
            }
            Expr::If { cond, then, other } => {
                let c = self.p(*cond, env, Mode::Plain)?;
                let t = self.g(*then, env)?;
                let o = self.g(*other, env)?;
                Ok(self.gpush(GNode::If {
                    cond: c,
                    then: t,
                    other: o,
                }))
            }
            Expr::Case { arms, other } => {
                let mut out = Vec::with_capacity(arms.len());
                for a in arms {
                    let p = self.p(a.guard, env, Mode::Plain)?;
                    let g = self.g(a.value, env)?;
                    out.push((p, g));
                }
                let o = match other {
                    Some(o) => Some(self.g(*o, env)?),
                    None => None,
                };
                Ok(self.gpush(GNode::Case {
                    arms: out.into(),
                    other: o,
                }))
            }
            Expr::Implies(a, b) => {
                let l = self.p(*a, env, Mode::Plain)?;
                let r = self.g(*b, env)?;
                Ok(self.gpush(GNode::Implies { lhs: l, rhs: r }))
            }
            Expr::Builtin {
                op: BuiltinOp::Eq,
                args,
            } if args.len() == 2 => {
                if let Some(var) = self.target(args[0], env, false)? {
                    let rhs = self.p(args[1], env, Mode::Plain)?;
                    return Ok(self.gpush(GNode::Assign { var, rhs }));
                }
                self.guard_expr(e, env)
            }
            Expr::Builtin {
                op: BuiltinOp::In,
                args,
            } if args.len() == 2 => {
                if let Some(var) = self.target(args[0], env, false)? {
                    // TLC enumerates a lazy set in full, as the core does:
                    // no speculation.
                    let set = self.p(args[1], env, Mode::Plain)?;
                    let set = self.unspec(set);
                    // TLC enumerates a lazy union without normalizing it,
                    // so its elements can repeat (§6).
                    if let Some(raw) = self.raw_plan(args[1], env)? {
                        return Ok(self.gpush(GNode::AssignInRaw { var, set, raw }));
                    }
                    return Ok(self.gpush(GNode::AssignIn { var, set }));
                }
                self.guard_expr(e, env)
            }
            Expr::Builtin {
                op: BuiltinOp::Subseteq,
                args,
            } if args.len() == 2 => {
                // `x' \subseteq S` enumerates `SUBSET S`, normalized
                // (`Tool.java:1379-1421`).
                if let Some(var) = self.target(args[0], env, false)? {
                    let base = self.p(args[1], env, Mode::Plain)?;
                    let set = self.push(Node::Powerset(base))?;
                    return Ok(self.gpush(GNode::AssignIn { var, set }));
                }
                self.guard_expr(e, env)
            }
            Expr::Builtin {
                op: BuiltinOp::Unchanged,
                args,
            } if args.len() == 1 => {
                if self.init_mode {
                    return self.guard_expr(e, env);
                }
                let mut items = Vec::new();
                self.unchanged_items(args[0], env, &mut items)?;
                Ok(self.gpush(GNode::Unchanged(items.into())))
            }
            Expr::Unchanged(a) => {
                if self.init_mode {
                    return self.guard_expr(e, env);
                }
                let mut items = Vec::new();
                self.unchanged_items(*a, env, &mut items)?;
                Ok(self.gpush(GNode::Unchanged(items.into())))
            }
            Expr::StepBox { action, sub } => {
                if self.init_mode {
                    return self.guard_expr(e, env);
                }
                let a = self.g(*action, env)?;
                let mut items = Vec::new();
                self.unchanged_items(*sub, env, &mut items)?;
                Ok(self.gpush(GNode::StepBox {
                    action: a,
                    vars: items.into(),
                }))
            }
            Expr::StepAngle { action, sub } => {
                if self.init_mode {
                    return self.guard_expr(e, env);
                }
                let (action, sub) = (*action, *sub);
                let a = self.g(action, env)?;
                let same = self.changed_test(sub, env)?;
                Ok(self.gpush(GNode::StepAngle { action: a, same }))
            }
            Expr::FcnApply { fcn, arg } => {
                let (fcn, arg) = (*fcn, *arg);
                let Some((lambda, lenv)) = self.fcn_lambda(fcn, env, 0)? else {
                    // Applied recursive predicates are Boolean guards: Core
                    // counts the successors they emit rather than TLC's
                    // duplicate witnesses.
                    // Their whole-plan effect safety is checked after all
                    // function bodies and roles have been compiled.
                    if self.rec_target(fcn, env, Mode::Plain)?.is_some() {
                        self.recursive_action_predicate = true;
                    }
                    return self.guard_expr(e, env);
                };
                let Expr::FcnCons { bounds, body } = self.ir.node(lambda).expr.clone() else {
                    return self.guard_expr(e, env);
                };
                if bounds.iter().any(|b| b.domain.is_none()) {
                    return self.guard_expr(e, env);
                }
                let (binds, saved) = self.binds(&bounds, lenv, Mode::Plain)?;
                let r = (|| {
                    let a = self.p(arg, env, Mode::Plain)?;
                    let b = self.g(body, lenv)?;
                    Ok((a, b))
                })();
                self.unbind(saved);
                let (a, b) = r?;
                Ok(self.gpush(GNode::FcnAction {
                    binds: binds.into(),
                    arg: a,
                    body: b,
                }))
            }
            Expr::Let { defs, body } => {
                let body = *body;
                let defs = defs.clone();
                let (g, reset) = self.let_scope(&defs, env, |c| c.g(body, env))?;
                if reset.is_empty() {
                    Ok(g)
                } else {
                    Ok(self.gpush(GNode::Scope {
                        reset: reset.into(),
                        body: g,
                    }))
                }
            }
            Expr::Selected(a) | Expr::Label { body: a, .. } => self.g(*a, env),
            Expr::Subst { bindings, body } => {
                let (bindings, body) = (bindings.clone(), *body);
                let (g, reset) =
                    self.subst_scope(&bindings, env, Mode::Plain, |c| c.g(body, env))?;
                if reset.is_empty() {
                    Ok(g)
                } else {
                    Ok(self.gpush(GNode::Scope {
                        reset: reset.into(),
                        body: g,
                    }))
                }
            }
            // A substituted name used as an action is enumerated by name
            // (TLC binds substitutions uncached in the generator: B5).
            Expr::SubstRef {
                decl,
                primed: false,
            } if !self.subst_is_value(*decl) => match self.subst_expr(*decl) {
                Some(r) => {
                    let (expr, aenv, depth) = r?;
                    self.stats.by_name += 1;
                    self.outside(depth, |c| c.g(expr, aenv))
                }
                None => self.guard_expr(e, env),
            },
            Expr::Def(d) => {
                let d = self.redirect(*d);
                let def = self.ir.def(d);
                if self.has_startup_value(d)
                    || def.std.is_some()
                    || def.recursive
                    || !def.params.is_empty()
                    || matches!(def.scope, DefScope::LetValue { .. })
                {
                    return self.guard_expr(e, env);
                }
                let parent = self.lexical_parent(d, env)?;
                let inner = self.new_env(d, parent);
                self.g(def.body, inner)
            }
            Expr::Apply {
                callee: OpRef::Def(d),
                args,
            } => {
                let d = self.redirect(*d);
                let def = self.ir.def(d);
                if def.std.is_some() || def.recursive || args.is_empty() {
                    if args.is_empty()
                        && def.std.is_none()
                        && !def.recursive
                        && !self.has_startup_value(d)
                    {
                        let parent = self.lexical_parent(d, env)?;
                        let inner = self.new_env(d, parent);
                        return self.g(def.body, inner);
                    }
                    return self.guard_expr(e, env);
                }
                self.g_inline(d, args, env, env)
            }
            // An operator that stands for a definition, applied as an
            // action: a constant operator bound to a definition (`F <- D`),
            // an operator declaration an instance substitutes, or an
            // operator parameter (the argument, inlined where it was
            // passed).
            Expr::Apply {
                callee: OpRef::Const(c),
                args,
            } => self.g_apply_op(&OpRef::Const(*c), args, e, env, env),
            Expr::Apply {
                callee: OpRef::Subst(decl),
                args,
            } => {
                let op = self.subst_op(*decl)?;
                self.g_apply_op(&op, args, e, env, env)
            }
            Expr::Apply {
                callee: OpRef::Param(r),
                args,
            } => {
                let (op, aenv, enclosing) = self.resolve_param(*r, env)?;
                if enclosing {
                    return Err(Error::unsupported(
                        "an enclosing operator parameter used as an action inside a recursive function (M1 core)",
                    ));
                }
                self.g_apply_op(&op, args, e, env, aenv)
            }
            Expr::Local(r) => {
                let fe = self.frame_env(env, r.up)?;
                match self.envs[fe].slots.get(r.slot.index()).cloned() {
                    Some(Sb::Arg {
                        expr, env: aenv, ..
                    }) => {
                        self.stats.by_name += 1;
                        self.g(expr, aenv)
                    }
                    Some(Sb::LetVal { def, env: lenv, .. }) => {
                        let body = self.ir.def(def).body;
                        self.g(body, lenv)
                    }
                    _ => self.guard_expr(e, env),
                }
            }
            _ => self.guard_expr(e, env),
        }
    }

    /// The variable an assignment's left side names (TLC's `getPrimedVar`,
    /// or `getVar` in an initial predicate).
    fn target(&mut self, e: ExprId, env: usize, under_prime: bool) -> Result<Option<u16>, Error> {
        #[allow(clippy::cast_possible_truncation, reason = "at most 64 variables")]
        match &self.ir.node(e).expr {
            Expr::Var { var, primed } => {
                let ok = if self.init_mode {
                    !*primed && !under_prime
                } else {
                    *primed != under_prime
                };
                Ok(ok.then_some(var.index() as u16))
            }
            Expr::Prime(a) if !self.init_mode && !under_prime => self.target(*a, env, true),
            Expr::Builtin {
                op: BuiltinOp::Prime,
                args,
            } if !self.init_mode && !under_prime && args.len() == 1 => {
                self.target(args[0], env, true)
            }
            Expr::Label { body: a, .. } | Expr::Selected(a) => self.target(*a, env, under_prime),
            // `x'` with `x` substituted is the substitution's variable
            // (`getPrimedVar`); unsubstituted, the root variable.
            Expr::SubstRef { decl, primed } => {
                let (decl, primed) = (*decl, *primed);
                if primed && under_prime {
                    return Ok(None);
                }
                let under = under_prime || primed;
                if self.subst_is_value(decl) {
                    return Ok(None);
                }
                if let Some(r) = self.subst_expr(decl) {
                    let (expr, aenv, depth) = r?;
                    return self.outside(depth, |c| c.target(expr, aenv, under));
                }
                let Some(v) = self.ir.decl(decl).var else {
                    return Ok(None);
                };
                let ok = if self.init_mode { !under } else { under };
                Ok(ok.then_some(v.index() as u16))
            }
            Expr::Local(r) => {
                let fe = self.frame_env(env, r.up)?;
                match self.envs[fe].slots.get(r.slot.index()).cloned() {
                    Some(Sb::Arg {
                        expr, env: aenv, ..
                    }) => self.target(expr, aenv, under_prime),
                    Some(Sb::LetVal { def, env: lenv, .. }) => {
                        let body = self.ir.def(def).body;
                        self.target(body, lenv, under_prime)
                    }
                    _ => Ok(None),
                }
            }
            Expr::Def(d) => {
                let d = self.redirect(*d);
                let def = self.ir.def(d);
                if self.has_startup_value(d)
                    || def.std.is_some()
                    || !def.params.is_empty()
                    || def.recursive
                {
                    return Ok(None);
                }
                let parent = self.lexical_parent(d, env)?;
                let inner = self.new_env(d, parent);
                self.target(def.body, inner, under_prime)
            }
            _ => Ok(None),
        }
    }
}