everystate 0.4.6

A lightning-fast TLA+ model checker (TLC-compatible, no Java needed)
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
//! A compiled form of actions and invariants (the default; EVERYSTATE_EVAL=tree turns it off); the tree-walker of eval.rs stays
//! the reference.
//!
//! Before the search each top-level action and each invariant is turned into a tree of closures:
//! identifiers are resolved to what they denote (a state variable's index, a slot of a frame, a constant),
//! applications of definitions with value parameters are inlined, and the enumerator's work (which
//! conjunct assigns which primed variable, which leave variables unchanged, where the branches are) is
//! decided once instead of being rediscovered for every state. Nothing is memoised across states.
//!
//! The rules that keep it equal to the tree-walker:
//! * Whatever the compiler does not handle is compiled to a *fallback*: the expression is evaluated by the
//!   tree-walker in a context rebuilt from the frame. Coverage is a matter of speed only.
//! * A parameter of an inlined definition is bound by name: every use evaluates the argument where it is
//!   used (so an unused argument is never evaluated, as with the tree-walker's thunks); the value is kept
//!   for the rest of the call when the argument is a state-level expression.
//! * The compiled code only has to be right when it succeeds. If it fails in any way, what it produced
//!   for the action (or invariant) is discarded and the tree-walker evaluates it again from the start, so
//!   error messages, locations and precedence are the tree-walker's by construction. For that to be
//!   sound, an action that may reach an operator with an effect (printing, TLCSet, random choice, I/O, a
//!   new string) is not compiled at all.
use crate::ast::*;
use crate::eval::*;
use crate::intern::*;
use crate::modules::{for_children, level_of, tail_fn, BFn, Builtin, Def};
use crate::stepcache::{self as sc_, DOp, Loc, Table, Write};
use crate::value::*;
use std::cell::{Cell, OnceCell, RefCell};
use std::collections::HashSet;
use std::rc::Rc;

pub struct Cx<'a> {
    pub ev: &'a Evaluator,
    /// the frame: bound variables, values of by-name parameters and LET definitions, `@`
    pub f: &'a StateData,
    pub cur: &'a StateData,
    /// the next state being assigned (the blank state for an invariant)
    pub nxt: &'a StateData,
    pub nv: i64,
    pub fallbacks: &'a Cell<u64>,
    /// the step cache (stepcache.rs), when it is on; `rec_on` while a unit's evaluation is being recorded
    pub cache: Option<&'a RefCell<Table>>,
    pub rec_on: &'a Cell<bool>,
    pub rec: &'a RefCell<Rec>,
    pub cache_always: bool,
    pub meas: &'a Meas,
    /// the ids of the current state's variables (`hashcons`; `NOT_INTERNED` for a value that is not
    /// interned), for the step cache; empty when not known
    pub cur_ids: &'a [crate::hashcons::Id],
    /// where successors go as rows of ids, when the caller collects them so (a step-cache hit then adds
    /// its rows directly instead of handing each successor to the continuation)
    pub out: Option<&'a RefCell<sc_::Rows>>,
    /// when the action runs on ids (`Skel`): builds the current state's values in `cur` and sets the
    /// evaluator's state, the first time something needs them
    pub vals: Option<&'a dyn Fn()>,
    /// a successor found from a step-cache entry is fingerprinted there, and dropped when it is a known
    /// state
    pub fpx: Option<&'a FpCtx<'a>>,
}
/// What fingerprinting a successor from its parent's ids needs (see `Checker::row_fingerprint`).
pub struct FpCtx<'a> {
    pub seen: &'a crate::checker::FpSet,
    pub ids: crate::hashcons::Local,
    /// the parent's word and term per variable, and the sum of the terms
    pub words: &'a [u64],
    pub terms: &'a [u64],
    pub sum: u64,
    /// EVERYSTATE_VERIFY_DELTAS (see `verify_delta`)
    pub verify: bool,
}

/// The top of an action as it runs on ids (RFD0002): disjunctions, existential quantifiers over one
/// variable, LETs and inlined definitions above the units. A state whose units all hit is expanded
/// without building any of its values.
enum Skel {
    Or(Vec<Skel>),
    Exists {
        slot: usize,
        dom: Dom,
        body: Box<Skel>,
        /// the quantifier as compiled, for a domain that cannot be taken on ids
        run: Rc<AE>,
    },
    /// entering a LET or an inlined definition: what is done on values before its body
    Pre { ops: Vec<PreOp>, body: Box<Skel> },
    Unit(Rc<UnitNode>),
}
/// Where an existential quantifier of a skeleton takes its values from.
enum Dom {
    /// a set that does not depend on the state or on any bound variable: evaluated once
    Const { set: Rc<CE>, ids: OnceCell<Option<Box<[crate::hashcons::Id]>>> },
    /// `DOMAIN v`, `v` a variable
    Domain(usize),
}
/// A unit (see `Comp::unit`): what it depends on besides the state, and its compiled code.
struct UnitNode {
    id: u32,
    /// the slots of the variables bound by the quantifiers above it
    bound: Vec<usize>,
    /// slots of by-name bindings, computed again inside it when it is recorded
    clear: Vec<usize>,
    inner: AE,
    stat: Rc<UnitStat>,
    n: N,
}
/// A step of the way from the top of a skeleton to a unit, replayed on values when the unit needs them.
#[derive(Clone, Copy)]
enum Step<'a> {
    Bind(usize, crate::hashcons::Id),
    Pre(&'a [PreOp]),
}
/// The steps from the top of a skeleton to where it is being run. (A skeleton deeper than this has none.)
const PATH_MAX: usize = 24;
struct Path<'a> {
    n: usize,
    /// (the first `n` are set: an action runs its skeleton once per state, and this is not cleared)
    a: [std::mem::MaybeUninit<Step<'a>>; PATH_MAX],
}
impl<'a> Path<'a> {
    #[inline]
    fn new() -> Path<'a> {
        Path { n: 0, a: [std::mem::MaybeUninit::uninit(); PATH_MAX] }
    }
    #[inline]
    fn push(&mut self, s: Step<'a>) {
        self.a[self.n].write(s);
        self.n += 1;
    }
    #[inline]
    fn pop(&mut self) {
        self.n -= 1;
    }
    #[inline]
    fn steps(&self) -> impl Iterator<Item = &Step<'a>> {
        // SAFETY: the first `n` steps were written by `push`
        self.a[..self.n].iter().map(|s| unsafe { s.assume_init_ref() })
    }
}
impl Skel {
    fn depth(&self) -> usize {
        match self {
            Skel::Or(items) => items.iter().map(Skel::depth).max().unwrap_or(0),
            Skel::Exists { body, .. } | Skel::Pre { body, .. } => 1 + body.depth(),
            Skel::Unit(_) => 0,
        }
    }
}

/// Runs a skeleton on the current state's ids (see `Plans::run_skel`).
fn skel_run<'s>(sk: &'s Skel, cx: &Cx, path: &mut Path<'s>, bids: &mut SmallIds, k: &mut dyn FnMut() -> R<()>) -> R<()> {
    match sk {
        Skel::Or(items) => {
            for it in items {
                skel_run(it, cx, path, bids, k)?;
            }
            Ok(())
        }
        Skel::Pre { ops, body } => {
            path.push(Step::Pre(ops));
            let r = skel_run(body, cx, path, bids, k);
            path.pop();
            r
        }
        Skel::Exists { slot, dom, body, run } => {
            use crate::hashcons as hc;
            let n0 = bids.n;
            let each = |x: crate::hashcons::Id, path: &mut Path<'s>, bids: &mut SmallIds, k: &mut dyn FnMut() -> R<()>| -> R<()> {
                // (a skeleton has at most PATH_MAX steps, so its bound variables fit)
                bids.push(x);
                path.push(Step::Bind(*slot, x));
                let r = skel_run(body, cx, path, bids, k);
                path.pop();
                bids.n = n0;
                r
            };
            match dom {
                Dom::Domain(var) => {
                    let d = cx.cache.and_then(|t| t.borrow().domain_ids(cx.cur_ids[*var]));
                    if let Some(d) = d {
                        for &x in d.iter() {
                            each(x, path, bids, k)?;
                        }
                        return Ok(());
                    }
                }
                Dom::Const { set, ids } => {
                    let got = ids.get_or_init(|| {
                        on_values(cx, path);
                        let s = as_set(set(cx).ok()?).ok()?;
                        if let SetK::Interval(lo, hi) = &s.k {
                            return (*lo..=*hi).map(|i| hc::id(&Value::Int(i))).collect();
                        }
                        s.elems().ok()?.iter().map(hc::id).collect()
                    });
                    if let Some(xs) = got {
                        for &x in xs.iter() {
                            each(x, path, bids, k)?;
                        }
                        return Ok(());
                    }
                }
            }
            // (the quantifier as compiled says what this domain is, or what is wrong with it)
            on_values(cx, path);
            run(cx, k)
        }
        Skel::Unit(u) => {
            let table = cx.cache.expect("a skeleton runs with the step cache on");
            if !use_cache(cx, &u.stat) {
                on_values(cx, path);
                return (u.inner)(cx, k);
            }
            unit_cached(cx, k, table, u, bids.as_slice(), &|| on_values(cx, path))
        }
    }
}
/// The state's values in `cur`, the evaluator's state set, and the frame as the closures above the
/// current point of the skeleton would have left it.
fn on_values(cx: &Cx, path: &Path) {
    if let Some(v) = cx.vals {
        v();
    }
    for st in path.steps() {
        match st {
            Step::Bind(slot, x) => cx.f.set(*slot, crate::hashcons::value(*x)),
            Step::Pre(ops) => run_pre(ops, cx),
        }
    }
}
/// What the evaluation of a unit read and did, noted for the step cache.
#[derive(Default)]
pub struct Rec {
    reads: Vec<(Loc, Value)>,
    /// something happened that an entry cannot describe
    bad: bool,
    /// per variable: the changes that turn the parent's value into the value now assigned (None: the value
    /// was computed some other way)
    delta: Vec<Option<Vec<DOp>>>,
    succs: Vec<Vec<Write>>,
}
/// A program that, for an expression known to compute a change of one variable's value, produces the
/// changes instead of the value (false: not expressible this time).
type DProg = dyn Fn(&Cx, &mut Vec<DOp>) -> R<bool>;
#[derive(Clone)]
struct DShape {
    var: usize,
    /// the expression is the variable itself
    direct: bool,
    prog: Rc<DProg>,
}
/// The parent's value of a variable after the changes; None when one of them cannot be applied.
fn apply_ops(cx: &Cx, parent: &Value, ops: &[DOp], n: N) -> Option<Value> {
    let mut v = parent.clone();
    for op in ops {
        v = match op {
            DOp::Bag { e, plus } => crate::stdlib::bag_one(&v, e, *plus)?,
            DOp::Set { e, add } => match &v {
                Value::Set(s) => set_one(s, e, *add)?,
                _ => return None,
            },
            DOp::Exc { path, v: nv } => {
                let mut hit = false;
                let r = cx
                    .ev
                    .except_with(
                        v,
                        path,
                        0,
                        &mut |_| {
                            hit = true;
                            Ok(nv.clone())
                        },
                        n,
                    )
                    .ok()?;
                if !hit {
                    return None;
                }
                r
            }
        };
    }
    Some(v)
}
fn uses_at(n: N) -> bool {
    if matches!(n.e, E::At) {
        return true;
    }
    let mut r = false;
    for_children(n, &mut |c| {
        if !r && uses_at(c) {
            r = true;
        }
    });
    r
}
type CE = Box<dyn Fn(&Cx) -> R<Value>>;
/// The most copies a bag added to a variable's bag may have for the step cache to record the addition as
/// changes (`Comp::builtin`, B (+) C).
const BAG_DELTA_MAX: i64 = 64;
type AE = Box<dyn Fn(&Cx, &mut dyn FnMut() -> R<()>) -> R<()>>;

#[cold]
fn bail<T>() -> R<T> {
    // any failure: the caller discards the compiled attempt and asks the tree-walker
    eval_err(String::new())
}

// ---------- scopes: what the tree-walker's context would be ----------
struct Sc {
    k: ScK,
    next: Option<Rc<Sc>>,
}
enum ScK {
    /// the bottom: the context the tree-walker starts from (an action's own context, or none)
    Root(C),
    Slot { name: Name, slot: usize },
    At { slot: usize },
    /// a value parameter of an inlined definition, bound to an argument of the call
    Arg { name: Name, node: N, sc: Rc<Sc>, bd: ArgBd },
    /// one definition of a LET group; `below` is the scope under the whole group
    /// (`root`: the definition is part of the context the action starts from, see `root_scope`)
    Let { d: &'static DefNode, defs: &'static [LetDef], below: Rc<Sc>, head: bool, cache: usize, ce: RefCell<Option<(Rc<CE>, bool)>>, root: bool },
    /// a value bound in the context the action starts from
    RootVal { name: Name, v: Value },
}
enum ArgBd {
    Const(Value),
    /// `stable`: the value cannot change while the binding lives (no dependence on the next state)
    ByName { ce: Rc<CE>, cache: Option<usize>, stable: bool },
}

/// The tree-walker's context for a scope, from the current frame.
/// `share`: values the compiled code has already computed for parameters and LET definitions are passed
/// instead of thunks. Only for an expression that cannot prime, assign or test ENABLED: there a parameter
/// is used for the expression it stands for (`q' = ...` with `q` bound to a variable), not for its value.
fn build(sc: &Rc<Sc>, cx: &Cx, share: bool) -> R<C> {
    let below = |cx: &Cx| -> R<C> {
        match &sc.next {
            Some(n) => build(n, cx, share),
            None => Ok(None),
        }
    };
    Ok(match &sc.k {
        ScK::Root(c) => c.clone(),
        ScK::Slot { name, slot } => cons(*name, cx.f.get(*slot), &below(cx)?),
        ScK::At { slot } => cons(cx.ev.at, cx.f.get(*slot), &below(cx)?),
        ScK::Arg { name, node, sc: asc, bd } => {
            // a value the compiled code already has is passed on instead of a thunk that would compute it again
            let known = match bd {
                ArgBd::Const(v) => Some(v.clone()),
                ArgBd::ByName { cache: Some(slot), .. } if share => Some(cx.f.get(*slot)).filter(|v| !matches!(v, Value::Undef)),
                _ => None,
            };
            let v = match known {
                Some(v) => v,
                None => cx.ev.mk_arg(node, &build(asc, cx, share)?)?,
            };
            cons(*name, v, &below(cx)?)
        }
        ScK::Let { root: true, .. } | ScK::RootVal { .. } => below(cx)?,
        ScK::Let { defs, below: b, head, .. } => {
            debug_assert!(*head);
            let ctx = cx.ev.bind_let(defs, &build(b, cx, share)?);
            // likewise for the LET definitions already evaluated: their cells start out filled
            let mut s = if share { Some(sc) } else { None };
            while let Some(node) = s {
                match &node.k {
                    ScK::Let { d, cache, root: false, below: b2, .. } if Rc::ptr_eq(b2, b) => {
                        let v = cx.f.get(*cache);
                        if !matches!(v, Value::Undef) {
                            let mut c = ctx.as_ref();
                            while let Some(cn) = c {
                                if cn.name == d.name {
                                    if let Bind::LetLazy { v: cell, st, .. } = &cn.val {
                                        *cell.borrow_mut() = v;
                                        st.set(cx.cur.id());
                                    }
                                    break;
                                }
                                c = cn.next.as_ref();
                            }
                        }
                    }
                    _ => break,
                }
                s = node.next.as_ref();
            }
            ctx
        }
    })
}

/// EVERYSTATE_EVAL_DEBUG: each fallback site reports itself the first time it runs.
fn debug_fb(seen: &Cell<bool>, what: &str, node: N) {
    if !seen.replace(true) && std::env::var_os("EVERYSTATE_EVAL_DEBUG").is_some() {
        eprintln!("fallback {} at line {} col {} to line {} col {}", what, node.loc[0], node.loc[1], node.loc[2], node.loc[3]);
    }
}
/// Nothing reachable from `n` primes, assigns, or asks what is enabled.
fn primeless(n: N, seen: &mut HashSet<usize>) -> bool {
    match &n.e {
        E::Op(K::Prime | K::Enabled | K::Unchanged | K::Cdot | K::BoxAct | K::AngleAct | K::Always | K::Eventually | K::LeadsTo | K::Wf | K::Sf | K::Guarantee, _) => return false,
        E::TQuant { .. } | E::StepRef | E::AssumeProve => return false,
        E::App { r, .. } => {
            let d = match r.get() {
                Res::Def(d) => Some(d),
                Res::Decl(d) => d.subst.get(),
                Res::Local => None,
                Res::None => return false,
            };
            if let Some(d) = d {
                let d = d.over.get().unwrap_or(d);
                if seen.insert(d as *const Def as usize) {
                    if let Some(inst) = &d.inst {
                        let _ = inst;
                        return false;
                    }
                    if d.builtin.get().is_none() {
                        match d.body.get() {
                            Some(b) => {
                                if !primeless(b, seen) {
                                    return false;
                                }
                            }
                            None => return false,
                        }
                    }
                }
            }
        }
        E::Let { defs, .. } => {
            if defs.iter().any(|d| matches!(d, LetDef::Inst(_))) {
                return false;
            }
        }
        _ => {}
    }
    let mut ok = true;
    for_children(n, &mut |c| {
        if ok && !primeless(c, seen) {
            ok = false;
        }
    });
    ok
}
fn fb(node: N, sc: &Rc<Sc>) -> CE {
    let sc = sc.clone();
    let seen = Cell::new(false);
    let share = primeless(node, &mut HashSet::new());
    Box::new(move |cx| {
        debug_fb(&seen, "expression", node);
        cx.fallbacks.set(cx.fallbacks.get() + 1);
        let ctx = build(&sc, cx, share)?;
        cx.ev.eval(node, &ctx)
    })
}
fn fb_act(node: N, sc: &Rc<Sc>) -> AE {
    let sc = sc.clone();
    let seen = Cell::new(false);
    Box::new(move |cx, k| {
        debug_fb(&seen, "action", node);
        cx.fallbacks.set(cx.fallbacks.get() + 1);
        let ctx = build(&sc, cx, false)?;
        cx.ev.enumerate(node, &ctx, k)
    })
}

#[inline]
fn truth(v: Value) -> R<bool> {
    match &v {
        Value::Bool(b) => {
            let b = *b;
            std::mem::forget(v); // nothing to drop: spares the call of the drop glue
            Ok(b)
        }
        _ => bail(),
    }
}
#[inline]
fn as_set(v: Value) -> R<Rc<SetV>> {
    match v {
        Value::Set(s) => Ok(s),
        _ => bail(),
    }
}
fn plain(v: &Value) -> bool {
    match v {
        Value::Int(_) | Value::Bool(_) | Value::Str(_) | Value::Model(_) | Value::Tuple(_) | Value::Record(_) | Value::Fcn(_) => true,
        Value::Set(s) => s.reducible(),
        _ => false,
    }
}

/// Builtin operators of these modules have no effect and read nothing but their arguments.
fn pure_module(m: Name) -> bool {
    thread_local! {
        static PURE: Vec<Name> = ["Naturals", "Integers", "Reals", "Sequences", "FiniteSets", "Bags"].iter().map(|s| name(s)).collect();
    }
    PURE.with(|p| p.contains(&m))
}
fn pure_builtin(d: &'static Def) -> bool {
    if pure_module(d.module) {
        return true;
    }
    let (m, n) = (name_str(d.module), name_str(d.name));
    if m.as_ref() == "TLC" && matches!(n.as_ref(), ":>" | "@@") {
        return true;
    }
    // (`same_again`: operators the compiler and the step cache do not handle, but which have no effect
    // and give the same value every time)
    AGAIN.with(|a| a.get())
        && match m.as_ref() {
            "TLC" => matches!(n.as_ref(), "Assert" | "ToString" | "Permutations" | "SortSeq" | "TLCEval"),
            "Functions" | "FiniteSetsExt" | "SequencesExt" | "Folds" | "Bitwise" | "BagsExt" | "Combinatorics" | "Relation" | "Graphs" | "UndirectedGraphs" | "DyadicRationals" | "VectorClocks" => true,
            _ => false,
        }
}
thread_local! {
    static AGAIN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Does evaluating `n` a second time, in the same state, give the same value and have no effect (no
/// output, no register or file written or read, no random choice, no clock)? Conservative, as `impure`.
pub(crate) fn same_again(n: N) -> bool {
    AGAIN.with(|a| a.set(true));
    let r = !impure(n, &mut HashSet::new());
    AGAIN.with(|a| a.set(false));
    r
}

/// May evaluating `n` reach an operator with an effect? (Conservative: anything not understood counts.)
fn impure(n: N, seen: &mut HashSet<usize>) -> bool {
    let r = impure0(n, seen);
    if r && std::env::var_os("EVERYSTATE_EVAL_DEBUG").is_some() {
        if let E::App { name, r, .. } = &n.e {
            eprintln!("  (may have an effect, or is not understood: {}{} at line {})", name, match r.get() { Res::Def(d) => format!(" of module {}{}", d.module, if d.inst.is_some() { " (instance)" } else { "" }), Res::Decl(_) => " (substituted declaration)".into(), _ => String::new() }, n.loc[0]);
        }
    }
    r
}
/// May evaluating `n` have an effect that a later evaluation could see (TLCSet, Print, a file, ...)?
pub(crate) fn may_have_effect(n: N) -> bool {
    impure(n, &mut HashSet::new())
}
fn impure_def(d: &'static Def, seen: &mut HashSet<usize>) -> bool {
    let d = d.over.get().unwrap_or(d);
    if !seen.insert(d as *const Def as usize) {
        return false;
    }
    if let Some(bi) = d.builtin.get() {
        // a value given by the configuration is as pure as an operator of the standard modules
        return !(pure_builtin(d) || matches!(bi.f, BFn::Const(_) | BFn::Table(..)));
    }
    if let Some(inst) = &d.inst {
        // a definition of an instantiated module: the original and what is substituted into it
        return impure_def(inst.orig, seen) || inst.substs.iter().any(|s| impure(s.e, seen));
    }
    match d.body.get() {
        Some(b) => impure(b, seen),
        None => true,
    }
}
fn impure0(n: N, seen: &mut HashSet<usize>) -> bool {
    if let E::App { r, .. } = &n.e {
        match r.get() {
            Res::Def(d) => {
                if impure_def(d, seen) {
                    return true;
                }
            }
            Res::Decl(d) => {
                // a constant the configuration replaces by a definition
                if let Some(sd) = d.subst.get() {
                    if impure_def(sd, seen) {
                        return true;
                    }
                }
            }
            Res::Local => {}
            Res::None => return true,
        }
    }
    if matches!(n.e, E::Let { .. }) {
        if let E::Let { defs, .. } = &n.e {
            if defs.iter().any(|d| matches!(d, LetDef::Inst(_))) {
                return true;
            }
        }
    }
    let mut bad = false;
    for_children(n, &mut |c| {
        if !bad && impure(c, seen) {
            bad = true;
        }
    });
    bad
}

// ---------- the compiler ----------
struct Comp {
    nslots: usize,
    /// definitions and LET definitions being inlined (recursion guard)
    stack: Vec<usize>,
    budget: i64,
    /// set while compiling an expression whose value may depend on the next state
    unstable: bool,
    /// what the expression just compiled is known to build (see `One`); `shape_ok` is set by the cases
    /// of `expr0` that leave a shape for their caller
    shape: Option<One>,
    shape_ok: bool,
    /// likewise, the expression just compiled computes a change of a variable's value
    dshape: Option<DShape>,
    dshape_ok: bool,
    /// the step cache is on: units are marked out (`top`: still above the units; `descend`: the node being
    /// compiled passes `top` on to its parts)
    cache: bool,
    top: bool,
    descend: bool,
    /// every slot that keeps the value of a by-name binding
    cache_slots: Vec<usize>,
    /// the slots of the variables bound by the existential quantifiers above the units
    top_slots: Vec<usize>,
    units: u32,
    unit_stats: Vec<Rc<UnitStat>>,
    plan_id: u32,
    /// the skeleton of what `act_inner` just compiled, when it can run on ids (see `Skel`); `skel_out`:
    /// the one a structural node of `act_inner1` leaves for `act_inner0` to pass on
    skel: Option<Skel>,
    skel_out: Option<Skel>,
}
pub struct UnitStat {
    loc: Loc4,
    lookups: Cell<u64>,
    hits: Cell<u64>,
    /// the last measurement said the cache does not pay for this unit
    off: Cell<bool>,
    skip: Cell<u64>,
    penalty: Cell<u64>,
    phase: Cell<u8>,
    /// evaluations in the current phase
    count: Cell<u64>,
    /// on trial: the time per state expanded without (0) and with (1) the cache
    acc: [Acc; 2],
    /// on trial: the last expansion this unit was evaluated in, and whether it uses the cache in it
    seen: Cell<u64>,
    arm: Cell<bool>,
    /// the means at the last verdict, and the number of states it was based on
    last: Cell<(f64, f64)>,
    trials: Cell<u64>,
    /// evaluations before the next trial (16 times the length of the last one, at least 262144)
    again: Cell<u64>,
    /// on trial: the unit had the cache before
    held: Cell<bool>,
    /// hits and lookups when the warm-up or the current window began
    mark: Cell<u64>,
    mark_l: Cell<u64>,
    /// evaluations whose result was stored, and that count when the warm-up began
    stored: Cell<u64>,
    mark_s: Cell<u64>,
}
type Loc4 = [u32; 4];
/// What the measurements of one unit of the step cache concluded (`Plans::verdicts`), with where the
/// unit is (the plans of one model on two threads have the same units in the same order).
#[derive(Clone, Copy, Debug)]
pub struct Verdict {
    loc: Loc4,
    kind: VerdictKind,
}
#[derive(Clone, Copy, Debug)]
enum VerdictKind {
    Unknown,
    Pays,
    DoesNotPay { penalty: u64, skip: u64 },
}

/// The expression just compiled is `{e}` or `SetToBag({e})`, possibly behind inlined definitions:
/// `elem` computes `e` after the slots in `clear` are reset. Consumers (`S \cup {e}`, `S \ {e}`,
/// `B (+) SetToBag({e})`, `B (-) SetToBag({e})`) then update the set or bag directly instead of building
/// the one-element value first.
#[derive(Clone)]
struct One {
    bag: bool,
    elem: Rc<CE>,
    clear: Vec<PreOp>,
}
/// What happens when an inlined call (or a LET) is entered, before its body.
#[derive(Clone, Copy)]
enum PreOp {
    /// forget the value kept for a by-name binding
    Clear(usize),
    /// a string literal passed as an argument: the tree-walker evaluates it when it binds the parameter,
    /// which is when the string gets its number if it is new
    Intern(N),
}
#[inline]
fn run_pre(pre: &[PreOp], cx: &Cx) {
    for op in pre {
        match op {
            PreOp::Clear(s) => cx.f.clear(*s),
            PreOp::Intern(n) => {
                if let E::Str(s, id) = &n.e {
                    cx.ev.str_node(s, id);
                }
            }
        }
    }
}
impl One {
    #[inline]
    fn eval(&self, cx: &Cx) -> R<Value> {
        run_pre(&self.clear, cx);
        (self.elem)(cx)
    }
}

/// Position of `e` in the sorted `es`: (index, found). None when a comparison fails.
fn locate(es: &[Value], e: &Value) -> Option<(usize, bool)> {
    let (mut lo, mut hi) = (0, es.len());
    while lo < hi {
        let mid = (lo + hi) / 2;
        let c = match scalar_cmp(&es[mid], e) {
            Some(c) => c,
            None => compare(&es[mid], e).ok()?,
        };
        match c {
            std::cmp::Ordering::Less => lo = mid + 1,
            std::cmp::Ordering::Greater => hi = mid,
            std::cmp::Ordering::Equal => return Some((mid, true)),
        }
    }
    Some((lo, false))
}
/// `s \cup {e}` (add) or `s \ {e}` for an explicit set; None for the general code to decide.
fn set_one(s: &Rc<SetV>, e: &Value, add: bool) -> Option<Value> {
    let es = match &s.k {
        SetK::Enum(es) => es,
        _ => return None,
    };
    let (i, found) = locate(es, e)?;
    if found == add {
        return Some(Value::Set(s.clone()));
    }
    let mut out = Vec::with_capacity(if add { es.len() + 1 } else { es.len() - 1 });
    out.extend_from_slice(&es[..i]);
    if add {
        out.push(e.clone());
        out.extend_from_slice(&es[i..]);
    } else {
        out.extend_from_slice(&es[i + 1..]);
    }
    Some(SetV::of(out))
}

enum Found {
    Slot(usize),
    Const(Value),
    ByName(Rc<CE>, Option<usize>),
    /// a LET definition: its scope node and the head of its group
    Let(Rc<Sc>, Rc<Sc>),
    Arg(Rc<Sc>),
    No,
}

fn lookup(sc: &Rc<Sc>, nm: Name) -> Found {
    let mut cur = Some(sc);
    let mut head: Option<&Rc<Sc>> = None;
    while let Some(s) = cur {
        match &s.k {
            ScK::Slot { name, slot } if *name == nm => return Found::Slot(*slot),
            ScK::Arg { name, .. } if *name == nm => return Found::Arg(s.clone()),
            ScK::Let { d, head: h, .. } => {
                if *h {
                    head = Some(s);
                }
                if d.name == nm {
                    return match head {
                        Some(h) => Found::Let(s.clone(), h.clone()),
                        None => Found::No,
                    };
                }
            }
            ScK::RootVal { name, v } if *name == nm => return Found::Const(v.clone()),
            ScK::Root(_) => return Found::No,
            _ => {}
        }
        cur = s.next.as_ref();
    }
    Found::No
}
fn lookup_at(sc: &Rc<Sc>) -> Option<usize> {
    let mut cur = Some(sc);
    while let Some(s) = cur {
        if let ScK::At { slot } = &s.k {
            return Some(*slot);
        }
        cur = s.next.as_ref();
    }
    None
}
fn push(sc: &Rc<Sc>, k: ScK) -> Rc<Sc> {
    Rc::new(Sc { k, next: Some(sc.clone()) })
}
/// Several bounds, several names per bound, tuple patterns: `\E x, y \in S, <<a, b>> \in T : ...`.
struct Bnds {
    sets: Vec<CE>,
    /// one entry per bound name or tuple pattern, in the order written
    flat: Vec<FlatB>,
}
struct FlatB {
    set: usize,
    slots: Vec<usize>,
    tuple: bool,
}
impl Bnds {
    /// Calls `f` for every binding, in the tree-walker's order (the first name varies fastest), until it
    /// returns true; all the sets are evaluated and enumerated before the first binding.
    fn each(&self, cx: &Cx, f: &mut dyn FnMut() -> R<bool>) -> R<bool> {
        let mut sets: Vec<Rc<SetV>> = Vec::with_capacity(self.sets.len());
        for s in &self.sets {
            let s = as_set(s(cx)?)?;
            s.elems()?;
            sets.push(s);
        }
        fn rec(b: &Bnds, sets: &[Rc<SetV>], i: isize, cx: &Cx, f: &mut dyn FnMut() -> R<bool>) -> R<bool> {
            if i < 0 {
                return f();
            }
            let fb = &b.flat[i as usize];
            for v in sets[fb.set].elems()? {
                if fb.tuple {
                    match v {
                        Value::Tuple(t) if t.len() == fb.slots.len() => {
                            for (j, &s) in fb.slots.iter().enumerate() {
                                cx.f.set(s, t[j].clone());
                            }
                        }
                        _ => return bail(),
                    }
                } else {
                    cx.f.set(fb.slots[0], v.clone());
                }
                if rec(b, sets, i - 1, cx, f)? {
                    return Ok(true);
                }
            }
            Ok(false)
        }
        rec(self, &sets, self.flat.len() as isize - 1, cx, f)
    }
}
fn simple_bound(bounds: &'static [Bound]) -> Option<(Name, N)> {
    if bounds.len() != 1 {
        return None;
    }
    one_bound(&bounds[0])
}
fn one_bound(b: &'static Bound) -> Option<(Name, N)> {
    match (&b.names, &b.tuple, &b.set) {
        (Some(ns), None, Some(set)) if ns.len() == 1 => Some((ns[0], set)),
        _ => None,
    }
}
/// `n` does not depend on the state, on a bound variable, a parameter or a LET definition: its value is
/// the same wherever it is evaluated. (A conservative test: an expression that binds names of its own is
/// not taken.)
fn closed_const(n: N) -> bool {
    fn walk(n: N) -> bool {
        match &n.e {
            E::Num(_) | E::Str(..) | E::Bool(_) => true,
            E::Op(_, a) => a.iter().all(walk),
            E::App { args, sel: None, r, .. } => {
                args.iter().all(walk)
                    && match r.get() {
                        Res::Decl(d) => !d.is_var,
                        Res::Def(d) => d.over.get().unwrap_or(d).inst.is_none(),
                        _ => false,
                    }
            }
            E::Rec(fields, _) => fields.iter().all(|(_, x)| walk(x)),
            _ => false,
        }
    }
    walk(n) && crate::modules::level_of(n) == 0
}
fn var_of(n: N) -> Option<usize> {
    if let E::App { args, r, .. } = &n.e {
        if let Res::Decl(d) = r.get() {
            if d.is_var && d.idx.get() >= 0 && args.is_empty() {
                return Some(d.idx.get() as usize);
            }
        }
    }
    None
}

impl Comp {
    fn new(cache: bool, plan_id: u32) -> Comp {
        Comp { nslots: 0, stack: vec![], budget: 20_000, unstable: false, shape: None, shape_ok: false, dshape: None, dshape_ok: false, cache, top: false, descend: false, cache_slots: vec![], top_slots: vec![], units: 0, unit_stats: vec![], plan_id, skel: None, skel_out: None }
    }
    /// The compiled bounds of a quantifier and the scope of its body. None when a bound has no set.
    fn bounds(&mut self, bounds: &'static [Bound], sc: &Rc<Sc>) -> Option<(Bnds, Rc<Sc>)> {
        if bounds.iter().any(|b| b.set.is_none() || (b.names.is_none() && b.tuple.is_none())) {
            return None;
        }
        let mut sets = vec![];
        let mut flat: Vec<(FlatB, Vec<Name>)> = vec![];
        for (i, b) in bounds.iter().enumerate() {
            sets.push(self.expr(b.set.as_ref().unwrap(), sc));
            if let Some(t) = &b.tuple {
                let slots = t.iter().map(|_| self.slot()).collect();
                flat.push((FlatB { set: i, slots, tuple: true }, t.clone()));
            } else {
                for nm in b.names.as_ref().unwrap() {
                    let s = self.slot();
                    flat.push((FlatB { set: i, slots: vec![s], tuple: false }, vec![*nm]));
                }
            }
        }
        // the last name is the outermost loop, so it is bound first
        let mut inner = sc.clone();
        for (fb, names) in flat.iter().rev() {
            for (j, nm) in names.iter().enumerate() {
                inner = push(&inner, ScK::Slot { name: *nm, slot: fb.slots[j] });
            }
        }
        Some((Bnds { sets, flat: flat.into_iter().map(|x| x.0).collect() }, inner))
    }
    fn slot(&mut self) -> usize {
        self.nslots += 1;
        self.nslots - 1
    }
    fn fallback(&mut self, n: N, sc: &Rc<Sc>) -> CE {
        if level_of(n) >= 2 {
            self.unstable = true;
        }
        fb(n, sc)
    }

    /// The scope and prologue for inlining a definition: its parameters bound by name to the arguments.
    /// `base` is the scope the body sees under its parameters. None when the call cannot be inlined.
    fn bind_args(&mut self, params: &'static [Param], args: &'static [Node], base: Rc<Sc>, sc: &Rc<Sc>) -> Option<(Rc<Sc>, Vec<PreOp>)> {
        if params.len() != args.len() || params.iter().any(|p| p.arity != 0) {
            return None;
        }
        let mut inner = base;
        let mut clear = vec![];
        for (p, a) in params.iter().zip(args.iter()) {
            if matches!(a.e, E::Lambda { .. }) {
                return None;
            }
            let bd = match &a.e {
                E::Num(v) => ArgBd::Const(Value::Int(*v)),
                E::Bool(b) => ArgBd::Const(Value::Bool(*b)),
                _ => {
                    let was = std::mem::replace(&mut self.unstable, false);
                    let ce = self.expr(a, sc);
                    let stable = !self.unstable;
                    self.unstable |= was;
                    // a value that cannot change during the call is kept in a slot after its first use
                    // (not worth it for a string or a name that is itself a slot or a constant)
                    let trivial = matches!(a.e, E::Str(..))
                        || matches!(&a.e, E::App { name, args, r, .. } if args.is_empty() && matches!(r.get(), Res::Local) && matches!(lookup(sc, *name), Found::Slot(_) | Found::Const(_)));
                    if matches!(a.e, E::Str(..)) {
                        clear.push(PreOp::Intern(a));
                    }
                    let cache = if stable && !trivial {
                        let s = self.slot();
                        self.cache_slots.push(s);
                        clear.push(PreOp::Clear(s));
                        Some(s)
                    } else {
                        None
                    };
                    ArgBd::ByName { ce: Rc::new(ce), cache, stable }
                }
            };
            inner = push(&inner, ScK::Arg { name: p.name, node: a, sc: sc.clone(), bd });
        }
        Some((inner, clear))
    }

    /// What a use of a by-name binding evaluates.
    fn by_name(ce: Rc<CE>, cache: Option<usize>) -> CE {
        match cache {
            None => Box::new(move |cx| ce(cx)),
            Some(slot) => Box::new(move |cx| {
                let v = cx.f.get(slot);
                if !matches!(v, Value::Undef) {
                    return Ok(v);
                }
                let v = ce(cx)?;
                cx.f.set(slot, v.clone());
                Ok(v)
            }),
        }
    }

    /// The compiled body of a LET definition without parameters (compiled once, on first use).
    fn let_value(&mut self, def_sc: &Rc<Sc>, head: &Rc<Sc>) -> Option<CE> {
        if let ScK::Let { d, cache, ce, .. } = &def_sc.k {
            if !d.params.is_empty() {
                return None;
            }
            if ce.borrow().is_none() {
                let id = *d as *const DefNode as usize;
                if self.stack.contains(&id) {
                    return None;
                }
                self.stack.push(id);
                let was = std::mem::replace(&mut self.unstable, false);
                let body = self.expr(&d.body, head);
                let stable = !self.unstable;
                self.unstable |= was;
                self.stack.pop();
                *ce.borrow_mut() = Some((Rc::new(body), stable));
            }
            let (c, stable) = ce.borrow().as_ref().unwrap().clone();
            if !stable {
                self.unstable = true;
            }
            return Some(Comp::by_name(c, if stable { Some(*cache) } else { None }));
        }
        None
    }

    /// The scope of a LET body: one node per definition, as the tree-walker's `bind_let`.
    fn let_scope(&mut self, defs: &'static [LetDef], sc: &Rc<Sc>) -> Option<(Rc<Sc>, Vec<PreOp>)> {
        let mut inner = sc.clone();
        let mut clear = vec![];
        let n = defs.len();
        for (i, d) in defs.iter().enumerate() {
            let d = match d {
                LetDef::Def(d) => d,
                LetDef::Inst(_) => return None,
            };
            let cache = self.slot();
            self.cache_slots.push(cache);
            clear.push(PreOp::Clear(cache));
            inner = push(&inner, ScK::Let { d, defs, below: sc.clone(), head: i + 1 == n, cache, ce: RefCell::new(None), root: false });
        }
        if n == 0 {
            return None;
        }
        Some((inner, clear))
    }

    /// Can the function operand of `f[x]` / `DOMAIN f` be evaluated as an ordinary value? (The tree-walker
    /// keeps a function constructor unevaluated there.)
    fn operand_ok(&self, f: N, sc: &Rc<Sc>) -> bool {
        if tail_fn(f) {
            return false;
        }
        match &f.e {
            E::App { name, args, r, .. } if args.is_empty() => match r.get() {
                Res::Local => match lookup(sc, *name) {
                    Found::Slot(_) | Found::Const(_) => true,
                    Found::Arg(a) => match &a.k {
                        ScK::Arg { node, sc: asc, .. } => self.operand_ok(node, asc),
                        _ => false,
                    },
                    // a LET definition that cannot be a function constructor: the tree-walker evaluates it in full
                    Found::Let(d, _) => matches!(&d.k, ScK::Let { d, .. } if d.params.is_empty()),
                    _ => false,
                },
                Res::Decl(d) => d.subst.get().is_none(),
                Res::Def(_) => false,
                Res::None => false,
            },
            E::Dot { .. } | E::FnApp { .. } | E::Except { .. } | E::Rec(..) => true,
            E::Op(K::Tuple, _) => true,
            _ => false,
        }
    }

    fn expr(&mut self, n: N, sc: &Rc<Sc>) -> CE {
        self.shape = None;
        self.shape_ok = false;
        self.dshape = None;
        self.dshape_ok = false;
        let ce = self.expr0(n, sc);
        if !std::mem::replace(&mut self.shape_ok, false) {
            self.shape = None;
        }
        if !std::mem::replace(&mut self.dshape_ok, false) {
            self.dshape = None;
        }
        ce
    }
    /// Passes the shape of an inlined body on to the caller of the inlining: the slots of the call are
    /// reset before the element is computed.
    fn keep_shape(&mut self, clear: &[PreOp]) {
        if let Some(sh) = &mut self.shape {
            sh.clear.extend_from_slice(clear);
            self.shape_ok = true;
        }
        if let Some(d) = self.dshape.take() {
            let pre = clear.to_vec();
            let prog = d.prog.clone();
            self.dshape = Some(DShape {
                var: d.var,
                direct: d.direct && pre.is_empty(),
                prog: Rc::new(move |cx, ops| {
                    run_pre(&pre, cx);
                    prog(cx, ops)
                }),
            });
            self.dshape_ok = true;
        }
    }
    fn expr0(&mut self, n: N, sc: &Rc<Sc>) -> CE {
        self.budget -= 1;
        if self.budget < 0 {
            return self.fallback(n, sc);
        }
        match &n.e {
            E::Num(v) => {
                let v = *v;
                Box::new(move |_| Ok(Value::Int(v)))
            }
            E::Bool(b) => {
                let b = *b;
                Box::new(move |_| Ok(Value::Bool(b)))
            }
            E::Str(s, id) => Box::new(move |cx| Ok(Value::Str(cx.ev.str_node(s, id)))),
            E::At => match lookup_at(sc) {
                Some(slot) => Box::new(move |cx| Ok(cx.f.get(slot))),
                None => self.fallback(n, sc),
            },
            E::App { name, args, r, .. } => {
                match r.get() {
                    Res::Local => match lookup(sc, *name) {
                        Found::Slot(slot) if args.is_empty() => Box::new(move |cx| Ok(cx.f.get(slot))),
                        Found::Const(v) if args.is_empty() => Box::new(move |_| Ok(v.clone())),
                        Found::Arg(a) if args.is_empty() => match &a.k {
                            ScK::Arg { bd: ArgBd::Const(v), .. } => {
                                let v = v.clone();
                                Box::new(move |_| Ok(v.clone()))
                            }
                            ScK::Arg { bd: ArgBd::ByName { ce, cache, stable }, .. } => {
                                if !*stable {
                                    self.unstable = true;
                                }
                                Comp::by_name(ce.clone(), *cache)
                            }
                            _ => self.fallback(n, sc),
                        },
                        Found::Let(def_sc, head) => {
                            let d = match &def_sc.k {
                                ScK::Let { d, .. } => *d,
                                _ => unreachable!(),
                            };
                            if d.params.is_empty() {
                                if !args.is_empty() {
                                    return self.fallback(n, sc);
                                }
                                match self.let_value(&def_sc, &head) {
                                    Some(ce) => ce,
                                    None => self.fallback(n, sc),
                                }
                            } else {
                                // a LET operator applied to arguments: its body, inlined
                                let id = d as *const DefNode as usize;
                                if self.stack.contains(&id) || self.stack.len() > 40 {
                                    return self.fallback(n, sc);
                                }
                                match self.bind_args(&d.params, args, head.clone(), sc) {
                                    Some((inner, clear)) => {
                                        self.stack.push(id);
                                        let body = self.expr(&d.body, &inner);
                                        self.stack.pop();
                                        with_clear(clear, body)
                                    }
                                    None => self.fallback(n, sc),
                                }
                            }
                        }
                        _ => self.fallback(n, sc),
                    },
                    Res::Decl(d) => {
                        if !args.is_empty() || d.subst.get().is_some() {
                            return self.fallback(n, sc);
                        }
                        if d.is_var {
                            let idx = d.idx.get();
                            if idx < 0 {
                                return self.fallback(n, sc);
                            }
                            let idx = idx as usize;
                            self.dshape = Some(DShape { var: idx, direct: true, prog: Rc::new(|_, _| Ok(true)) });
                            self.dshape_ok = true;
                            return Box::new(move |cx| {
                                let v = cx.cur.get(idx);
                                if matches!(v, Value::Undef) {
                                    return bail();
                                }
                                if cx.rec_on.get() {
                                    cx.rec.borrow_mut().reads.push((Loc::Whole(idx as u32), v.clone()));
                                }
                                Ok(v)
                            });
                        }
                        let v = d.value.borrow().clone();
                        match v {
                            Some(v) if plain(&v) => Box::new(move |_| Ok(v.clone())),
                            _ => self.fallback(n, sc),
                        }
                    }
                    Res::Def(d) => self.def_app(n, d, args, sc),
                    Res::None => self.fallback(n, sc),
                }
            }
            E::Op(k, a) => self.op(n, *k, a, sc),
            E::Case { arms, other } => {
                let arms: Vec<(CE, CE)> = arms.iter().map(|(c, e)| (self.expr(c, sc), self.expr(e, sc))).collect();
                let other = other.as_ref().map(|o| self.expr(o, sc));
                Box::new(move |cx| {
                    for (c, e) in &arms {
                        if truth(c(cx)?)? {
                            return e(cx);
                        }
                    }
                    match &other {
                        Some(o) => o(cx),
                        None => bail(),
                    }
                })
            }
            E::Let { defs, body } => match self.let_scope(defs, sc) {
                Some((inner, clear)) => {
                    let body = self.expr(body, &inner);
                    with_clear(clear, body)
                }
                None => self.fallback(n, sc),
            },
            E::Quant { forall, bounds, body } => {
                let (nm, set) = match simple_bound(bounds) {
                    Some(x) => x,
                    None => {
                        let (b, inner) = match self.bounds(bounds, sc) {
                            Some(x) => x,
                            None => return self.fallback(n, sc),
                        };
                        let body = self.expr(body, &inner);
                        let forall = *forall;
                        return Box::new(move |cx| {
                            let stopped = b.each(cx, &mut || Ok(truth(body(cx)?)? != forall))?;
                            Ok(Value::Bool(stopped != forall))
                        });
                    }
                };
                let set = self.expr(set, sc);
                let slot = self.slot();
                let body = self.expr(body, &push(sc, ScK::Slot { name: nm, slot }));
                let forall = *forall;
                Box::new(move |cx| {
                    let s = as_set(set(cx)?)?;
                    if let SetK::Interval(lo, hi) = &s.k {
                        for i in *lo..=*hi {
                            cx.f.set(slot, Value::Int(i));
                            if truth(body(cx)?)? != forall {
                                return Ok(Value::Bool(!forall));
                            }
                        }
                        return Ok(Value::Bool(forall));
                    }
                    for x in s.elems()? {
                        cx.f.set(slot, x.clone());
                        if truth(body(cx)?)? != forall {
                            return Ok(Value::Bool(!forall));
                        }
                    }
                    Ok(Value::Bool(forall))
                })
            }
            E::Choose { bound, body } => {
                let (nm, set) = match one_bound(bound) {
                    Some(x) => x,
                    None => return self.fallback(n, sc),
                };
                let set = self.expr(set, sc);
                let slot = self.slot();
                let always = matches!(body.e, E::Bool(true));
                let body = self.expr(body, &push(sc, ScK::Slot { name: nm, slot }));
                Box::new(move |cx| {
                    let s = as_set(set(cx)?)?;
                    let es = s.elems()?;
                    if always {
                        if let Some(x) = es.first() {
                            return Ok(x.clone());
                        }
                    }
                    for x in es {
                        cx.f.set(slot, x.clone());
                        if truth(body(cx)?)? {
                            return Ok(x.clone());
                        }
                    }
                    bail()
                })
            }
            E::SetFilter { bound, pred } => {
                let (nm, set) = match one_bound(bound) {
                    Some(x) => x,
                    None => return self.fallback(n, sc),
                };
                let set = self.expr(set, sc);
                let slot = self.slot();
                let pred = self.expr(pred, &push(sc, ScK::Slot { name: nm, slot }));
                // over a set that is not explicit the tree-walker builds a lazy set that keeps its context
                let lazy = self.fallback(n, sc);
                Box::new(move |cx| {
                    let s = as_set(set(cx)?)?;
                    if !s.reducible() {
                        return lazy(cx);
                    }
                    let mut out = Vec::new();
                    for x in s.elems()? {
                        cx.f.set(slot, x.clone());
                        if truth(pred(cx)?)? {
                            out.push(x.clone());
                        }
                    }
                    Ok(SetV::of(out))
                })
            }
            E::SetMap { e, bounds } => {
                let (nm, set) = match simple_bound(bounds) {
                    Some(x) => x,
                    None => {
                        let (b, inner) = match self.bounds(bounds, sc) {
                            Some(x) => x,
                            None => return self.fallback(n, sc),
                        };
                        let e = self.expr(e, &inner);
                        return Box::new(move |cx| {
                            let mut out: Vec<Value> = Vec::new();
                            b.each(cx, &mut || {
                                out.push(e(cx)?);
                                Ok(false)
                            })?;
                            mk_set(out)
                        });
                    }
                };
                let set = self.expr(set, sc);
                let slot = self.slot();
                let e = self.expr(e, &push(sc, ScK::Slot { name: nm, slot }));
                Box::new(move |cx| {
                    let s = as_set(set(cx)?)?;
                    let mut out: Vec<Value> = Vec::new();
                    if let SetK::Interval(lo, hi) = &s.k {
                        for i in *lo..=*hi {
                            cx.f.set(slot, Value::Int(i));
                            out.push(e(cx)?);
                        }
                    } else {
                        for x in s.elems()? {
                            cx.f.set(slot, x.clone());
                            out.push(e(cx)?);
                        }
                    }
                    mk_set(out)
                })
            }
            E::FnDef { bounds, body, is_rec, .. } => {
                let (nm, set) = match simple_bound(bounds) {
                    Some(x) if !is_rec.get() => x,
                    _ => return self.fallback(n, sc),
                };
                let set = self.expr(set, sc);
                let slot = self.slot();
                let body = self.expr(body, &push(sc, ScK::Slot { name: nm, slot }));
                let lazy = self.fallback(n, sc);
                Box::new(move |cx| {
                    let s = as_set(set(cx)?)?;
                    if !s.enumerable() {
                        return lazy(cx);
                    }
                    if let SetK::Interval(1, hi) = &s.k {
                        let mut vals = Vec::with_capacity((*hi).max(0) as usize);
                        for i in 1..=*hi {
                            cx.f.set(slot, Value::Int(i));
                            vals.push(body(cx)?);
                        }
                        return Ok(if vals.is_empty() { empty_tuple() } else { Value::Tuple(TupleV::rc(vals)) });
                    }
                    let dom = s.elems()?;
                    let mut vals = Vec::with_capacity(dom.len());
                    for d in dom {
                        cx.f.set(slot, d.clone());
                        vals.push(body(cx)?);
                    }
                    Ok(s.fcn_shape()?.make(vals))
                })
            }
            E::Rec(fields, shape) => {
                let ces: Vec<CE> = fields.iter().map(|(_, e)| self.expr(e, sc)).collect();
                Box::new(move |cx| {
                    let mut vals = Vec::with_capacity(ces.len());
                    for c in &ces {
                        vals.push(c(cx)?);
                    }
                    let sh = shape.get_or_init(|| {
                        let mut idx: Vec<usize> = (0..fields.len()).collect();
                        idx.sort_by_key(|&i| fields[i].0 .0);
                        let sorted = idx.iter().enumerate().all(|(i, &j)| i == j);
                        RecShape { names: Rc::new(idx.iter().map(|&i| fields[i].0).collect()), order: if sorted { None } else { Some(idx) } }
                    });
                    let vals = match &sh.order {
                        None => vals,
                        Some(idx) => {
                            let mut slots: Vec<Option<Value>> = vals.into_iter().map(Some).collect();
                            idx.iter().map(|&i| slots[i].take().unwrap()).collect()
                        }
                    };
                    Ok(Value::Record(Rc::new(RecordV::new(sh.names.clone(), vals))))
                })
            }
            E::Except { base, updates } => {
                let base = self.expr(base, sc);
                let dbase = self.dshape.take();
                let at = self.slot();
                let inner = push(sc, ScK::At { slot: at });
                if let (Some(d), true, true) = (&dbase, updates.len() == 1, self.cache) {
                    if d.direct {
                        // [var EXCEPT !path = v]: for the step cache, a change of the variable at that path
                        let (path, val) = &updates[0];
                        let pces: Rc<Vec<CE>> = Rc::new(path.iter().map(|x| self.expr(x, sc)).collect());
                        let vce: Rc<CE> = Rc::new(self.expr(val, &inner));
                        let needs_old = path.len() > 1 || uses_at(val);
                        let var = d.var;
                        let (p2, v2) = (pces.clone(), vce.clone());
                        self.dshape = Some(DShape {
                            var,
                            direct: false,
                            prog: Rc::new(move |cx, ops| {
                                let mut keys = Vec::with_capacity(p2.len());
                                for x in p2.iter() {
                                    keys.push(x(cx)?);
                                }
                                let cur = cx.cur.get(var);
                                let mut newv = None;
                                cx.ev.except_with(
                                    cur.clone(),
                                    &keys,
                                    0,
                                    &mut |old| {
                                        cx.f.set(at, old);
                                        let v = v2(cx)?;
                                        newv = Some(v.clone());
                                        Ok(v)
                                    },
                                    n,
                                )?;
                                let v = match newv {
                                    Some(v) => v,
                                    None => return Ok(false),
                                };
                                if needs_old {
                                    match sc_::elem_at(&cur, &keys[0]) {
                                        Some(old) => cx.rec.borrow_mut().reads.push((Loc::Elem(var as u32, keys[0].clone()), old)),
                                        None => return Ok(false),
                                    }
                                }
                                ops.push(DOp::Exc { path: keys, v });
                                Ok(true)
                            }),
                        });
                        self.dshape_ok = true;
                        return Box::new(move |cx| {
                            let f = base(cx)?;
                            let mut short: [Value; 2] = [Value::Undef, Value::Undef];
                            let long: Vec<Value>;
                            let keys: &[Value] = if pces.len() <= 2 {
                                for (i, x) in pces.iter().enumerate() {
                                    short[i] = x(cx)?;
                                }
                                &short[..pces.len()]
                            } else {
                                let mut v = Vec::with_capacity(pces.len());
                                for x in pces.iter() {
                                    v.push(x(cx)?);
                                }
                                long = v;
                                &long
                            };
                            cx.ev.except_with(
                                f,
                                keys,
                                0,
                                &mut |old| {
                                    cx.f.set(at, old);
                                    vce(cx)
                                },
                                n,
                            )
                        });
                    }
                }
                let ups: Vec<(Vec<CE>, CE)> = updates.iter().map(|(path, val)| (path.iter().map(|x| self.expr(x, sc)).collect(), self.expr(val, &inner))).collect();
                Box::new(move |cx| {
                    let mut f = base(cx)?;
                    for (path, val) in &ups {
                        let mut short: [Value; 2] = [Value::Undef, Value::Undef];
                        let long: Vec<Value>;
                        let p: &[Value] = if path.len() <= 2 {
                            for (i, x) in path.iter().enumerate() {
                                short[i] = x(cx)?;
                            }
                            &short[..path.len()]
                        } else {
                            let mut v = Vec::with_capacity(path.len());
                            for x in path {
                                v.push(x(cx)?);
                            }
                            long = v;
                            &long
                        };
                        f = cx.ev.except_with(
                            f,
                            p,
                            0,
                            &mut |old| {
                                cx.f.set(at, old);
                                val(cx)
                            },
                            n,
                        )?;
                    }
                    Ok(f)
                })
            }
            E::FnApp { f, args } => {
                if !self.operand_ok(f, sc) {
                    return self.fallback(n, sc);
                }
                let fvar = var_of(f);
                let fce = self.expr(f, sc);
                let args: Vec<CE> = args.iter().map(|a| self.expr(a, sc)).collect();
                if let (Some(idx), true) = (fvar, self.cache) {
                    // var[k]: for the step cache this reads one element of the variable
                    return Box::new(move |cx| {
                        let fv = cx.cur.get(idx);
                        let arg = if args.len() == 1 {
                            args[0](cx)?
                        } else {
                            let mut t = Vec::with_capacity(args.len());
                            for a in &args {
                                t.push(a(cx)?);
                            }
                            Value::Tuple(TupleV::rc(t))
                        };
                        let v = cx.ev.apply_fcn(&fv, &arg, Some(n))?;
                        if cx.rec_on.get() {
                            cx.rec.borrow_mut().reads.push((Loc::Elem(idx as u32, arg), v.clone()));
                        }
                        if let Value::LazyFcn(lf) = &v {
                            return lf.force(cx.ev);
                        }
                        Ok(v)
                    });
                }
                Box::new(move |cx| {
                    let fv = fce(cx)?;
                    let arg = if args.len() == 1 {
                        args[0](cx)?
                    } else {
                        let mut t = Vec::with_capacity(args.len());
                        for a in &args {
                            t.push(a(cx)?);
                        }
                        Value::Tuple(TupleV::rc(t))
                    };
                    let v = cx.ev.apply_fcn(&fv, &arg, Some(n))?;
                    if let Value::LazyFcn(lf) = &v {
                        return lf.force(cx.ev);
                    }
                    Ok(v)
                })
            }
            E::Dot { e, field } => {
                let e = self.expr(e, sc);
                let field = *field;
                Box::new(move |cx| match e(cx)? {
                    Value::Record(rec) => match rec.get(field) {
                        Some(v) => Ok(v.clone()),
                        None => bail(),
                    },
                    _ => bail(),
                })
            }
            _ => self.fallback(n, sc),
        }
    }

    fn def_app(&mut self, n: N, d: &'static Def, args: &'static [Node], sc: &Rc<Sc>) -> CE {
        let d = d.over.get().unwrap_or(d);
        if let Some(bi) = d.builtin.get() {
            return self.builtin(n, d, bi, args, sc);
        }
        let body = match d.body.get() {
            Some(b) if d.inst.is_none() => b,
            _ => return self.fallback(n, sc),
        };
        let id = d as *const Def as usize;
        if self.stack.contains(&id) || self.stack.len() > 40 {
            return self.fallback(n, sc);
        }
        if d.params.is_empty() && args.is_empty() && crate::modules::def_level(d) == 0 {
            // a constant definition: the tree-walker evaluates it once and keeps the value on the definition
            let cell: OnceCell<Value> = OnceCell::new();
            return Box::new(move |cx| {
                if let Some(v) = cell.get() {
                    return Ok(v.clone());
                }
                let v = cx.ev.eval(n, &None)?;
                if d.cache.borrow().is_some() && plain(&v) {
                    let _ = cell.set(v.clone());
                }
                Ok(v)
            });
        }
        let root = Rc::new(Sc { k: ScK::Root(None), next: None });
        match self.bind_args(&d.params, args, root, sc) {
            Some((inner, clear)) => {
                self.stack.push(id);
                let b = self.expr(body, &inner);
                self.stack.pop();
                self.keep_shape(&clear);
                with_clear(clear, b)
            }
            None => self.fallback(n, sc),
        }
    }

    fn builtin(&mut self, n: N, d: &'static Def, bi: &'static Builtin, args: &'static [Node], sc: &Rc<Sc>) -> CE {
        if bi.lazy || bi.ops != 0 {
            return self.fallback(n, sc);
        }
        if let BFn::Const(v) = &bi.f {
            if args.is_empty() && plain(v) {
                return Box::new(move |_| Ok(v.clone()));
            }
        }
        let bags = name_str(d.module).as_ref() == "Bags";
        let opname = name_str(d.name);
        let mut ces: Vec<CE> = Vec::with_capacity(args.len());
        let mut last_shape = None;
        let mut first_d = None;
        for (i, a) in args.iter().enumerate() {
            ces.push(self.expr(a, sc));
            last_shape = self.shape.take();
            if i == 0 {
                first_d = self.dshape.take();
            }
        }
        if bags && args.len() == 2 && opname.as_ref() == "BagIn" && self.cache {
            if let Some(idx) = var_of(&args[1]) {
                // BagIn(x, var): for the step cache this reads whether one value is in the bag
                let x = ces.into_iter().next().unwrap();
                return Box::new(move |cx| {
                    let x = x(cx)?;
                    let b = cx.cur.get(idx);
                    let r = cx.ev.call_builtin(bi, &[x.clone(), b])?;
                    if cx.rec_on.get() {
                        cx.rec.borrow_mut().reads.push((Loc::Member(idx as u32, x), r.clone()));
                    }
                    Ok(r)
                });
            }
        }
        if bags && args.len() == 1 && opname.as_ref() == "SetToBag" {
            // SetToBag({e}): remembered for a consumer
            if let Some(sh) = last_shape.take() {
                if !sh.bag {
                    self.shape = Some(One { bag: true, ..sh });
                    self.shape_ok = true;
                }
            }
        }
        if bags && args.len() == 2 && matches!(opname.as_ref(), "\\oplus" | "\\ominus") {
            if let Some(sh) = last_shape.take() {
                if sh.bag {
                    // B (+) SetToBag({e}) / B (-) SetToBag({e}): one element in or out of the bag
                    let plus = opname.as_ref() == "\\oplus";
                    if let Some(d) = first_d {
                        let sh2 = sh.clone();
                        self.dshape = Some(DShape {
                            var: d.var,
                            direct: false,
                            prog: Rc::new(move |cx, ops| {
                                if !(d.prog)(cx, ops)? {
                                    return Ok(false);
                                }
                                ops.push(DOp::Bag { e: sh2.eval(cx)?, plus });
                                Ok(true)
                            }),
                        });
                        self.dshape_ok = true;
                    }
                    let mut it = ces.into_iter();
                    let (b, one) = (it.next().unwrap(), it.next().unwrap());
                    return Box::new(move |cx| {
                        let bv = b(cx)?;
                        let e = sh.eval(cx)?;
                        if let Some(v) = crate::stdlib::bag_one(&bv, &e, plus) {
                            return Ok(v);
                        }
                        // anything unusual: the operator itself, on the one-element bag
                        let y = one(cx)?;
                        cx.ev.call_builtin(bi, &[bv, y])
                    });
                }
            }
            if let (Some(d), true) = (first_d, opname.as_ref() == "\\oplus") {
                // B (+) C, C any bag: for the step cache, C's elements added to B one at a time (what
                // `bag_one` does), so that B is not read whole; C must be a small proper bag
                let mut it = ces.into_iter();
                let (b, c) = (it.next().unwrap(), Rc::new(it.next().unwrap()));
                let c2 = c.clone();
                self.dshape = Some(DShape {
                    var: d.var,
                    direct: false,
                    prog: Rc::new(move |cx, ops| {
                        if !(d.prog)(cx, ops)? {
                            return Ok(false);
                        }
                        let cv = c2(cx)?;
                        if !crate::value::is_fcn(&cv) {
                            return Ok(false);
                        }
                        let (es, ns) = (crate::value::domain_elems(&cv)?, crate::value::fcn_values(&cv)?);
                        let mut total = 0;
                        for (e, k) in es.iter().zip(ns) {
                            let Value::Int(k) = k else { return Ok(false) };
                            total += *k;
                            if *k < 1 || total > BAG_DELTA_MAX {
                                return Ok(false);
                            }
                            for _ in 0..*k {
                                ops.push(DOp::Bag { e: e.clone(), plus: true });
                            }
                        }
                        Ok(true)
                    }),
                });
                self.dshape_ok = true;
                return Box::new(move |cx| {
                    let bv = b(cx)?;
                    let cv = c(cx)?;
                    cx.ev.call_builtin(bi, &[bv, cv])
                });
            }
        }
        if bi.arith != 0 && ces.len() == 2 {
            let mut it = ces.into_iter();
            let (x, y) = (it.next().unwrap(), it.next().unwrap());
            let arith = bi.arith;
            return Box::new(move |cx| {
                let x = x(cx)?;
                let y = y(cx)?;
                if let (Value::Int(a), Value::Int(b)) = (&x, &y) {
                    let (a, b) = (*a, *b);
                    std::mem::forget(x); // two integers: nothing to drop
                    std::mem::forget(y);
                    match arith {
                        1 | 2 => {
                            let r = if arith == 1 { a.checked_add(b) } else { a.checked_sub(b) };
                            if let Some(r) = r {
                                if (-2147483648..=2147483647).contains(&r) {
                                    return Ok(Value::Int(r));
                                }
                            }
                        }
                        3 => return Ok(Value::Bool(a < b)),
                        4 => return Ok(Value::Bool(a > b)),
                        5 => return Ok(Value::Bool(a <= b)),
                        _ => return Ok(Value::Bool(a >= b)),
                    }
                    // out of range: the operator itself reports it
                    return cx.ev.call_builtin(bi, &[Value::Int(a), Value::Int(b)]);
                }
                cx.ev.call_builtin(bi, &[x, y])
            });
        }
        match ces.len() {
            1 => {
                let a = ces.into_iter().next().unwrap();
                Box::new(move |cx| cx.ev.call_builtin(bi, &[a(cx)?]))
            }
            2 => {
                let mut it = ces.into_iter();
                let (a, b) = (it.next().unwrap(), it.next().unwrap());
                Box::new(move |cx| {
                    let x = a(cx)?;
                    let y = b(cx)?;
                    cx.ev.call_builtin(bi, &[x, y])
                })
            }
            _ => Box::new(move |cx| {
                let mut v = Vec::with_capacity(ces.len());
                for c in &ces {
                    v.push(c(cx)?);
                }
                cx.ev.call_builtin(bi, &v)
            }),
        }
    }

    fn op(&mut self, n: N, k: K, a: &'static [Node], sc: &Rc<Sc>) -> CE {
        match k {
            K::And | K::Or => {
                let ces: Vec<CE> = a.iter().map(|x| self.expr(x, sc)).collect();
                let stop = k == K::Or;
                Box::new(move |cx| {
                    for c in &ces {
                        if truth(c(cx)?)? == stop {
                            return Ok(Value::Bool(stop));
                        }
                    }
                    Ok(Value::Bool(!stop))
                })
            }
            K::Not => {
                let x = self.expr(&a[0], sc);
                Box::new(move |cx| Ok(Value::Bool(!truth(x(cx)?)?)))
            }
            K::Imp => {
                let (x, y) = (self.expr(&a[0], sc), self.expr(&a[1], sc));
                Box::new(move |cx| Ok(Value::Bool(!truth(x(cx)?)? || truth(y(cx)?)?)))
            }
            K::Eqv => {
                let (x, y) = (self.expr(&a[0], sc), self.expr(&a[1], sc));
                Box::new(move |cx| Ok(Value::Bool(truth(x(cx)?)? == truth(y(cx)?)?)))
            }
            K::Eq | K::Ne => {
                let want = k == K::Eq;
                let x = self.expr(&a[0], sc);
                if matches!(&a[1].e, E::Op(K::SetEnum, e) if e.is_empty()) {
                    return Box::new(move |cx| {
                        let x = x(cx)?;
                        let eq = match &x {
                            Value::Set(s) if matches!(s.k, SetK::Enum(_)) => match &s.k {
                                SetK::Enum(el) => el.is_empty(),
                                _ => unreachable!(),
                            },
                            _ => val_eq(&x, &Value::Set(empty_set()))?,
                        };
                        Ok(Value::Bool(eq == want))
                    });
                }
                let y = self.expr(&a[1], sc);
                Box::new(move |cx| {
                    let (x, y) = (x(cx)?, y(cx)?);
                    let eq = match scalar_cmp(&x, &y) {
                        Some(c) => c == std::cmp::Ordering::Equal,
                        None => val_eq(&x, &y)?,
                    };
                    Ok(Value::Bool(eq == want))
                })
            }
            K::If => {
                let c: Rc<CE> = Rc::new(self.expr(&a[0], sc));
                let t = self.expr(&a[1], sc);
                let dt = self.dshape.take();
                let e = self.expr(&a[2], sc);
                let de = self.dshape.take();
                if let (Some(dt), Some(de)) = (dt, de) {
                    if dt.var == de.var {
                        let c2 = c.clone();
                        self.dshape = Some(DShape { var: dt.var, direct: false, prog: Rc::new(move |cx, ops| if truth(c2(cx)?)? { (dt.prog)(cx, ops) } else { (de.prog)(cx, ops) }) });
                        self.dshape_ok = true;
                    }
                }
                Box::new(move |cx| if truth(c(cx)?)? { t(cx) } else { e(cx) })
            }
            K::In | K::NotIn => {
                let want = k == K::In;
                let (x, s) = (self.expr(&a[0], sc), self.expr(&a[1], sc));
                if let (Some(idx), true) = (var_of(&a[1]), self.cache) {
                    // x \in var: for the step cache this reads whether one value is in the variable
                    return Box::new(move |cx| {
                        let x = x(cx)?;
                        let r = as_set(cx.cur.get(idx))?.contains(&x)?;
                        if cx.rec_on.get() {
                            cx.rec.borrow_mut().reads.push((Loc::Member(idx as u32, x), Value::Bool(r)));
                        }
                        Ok(Value::Bool(r == want))
                    });
                }
                Box::new(move |cx| {
                    let x = x(cx)?;
                    Ok(Value::Bool(as_set(s(cx)?)?.contains(&x)? == want))
                })
            }
            K::Cup => {
                let x = self.expr(&a[0], sc);
                let dx = self.dshape.take();
                let y = self.expr(&a[1], sc);
                if let Some(sh) = self.shape.take().filter(|sh| !sh.bag) {
                    if let Some(d) = dx {
                        let sh2 = sh.clone();
                        self.dshape = Some(DShape {
                            var: d.var,
                            direct: false,
                            prog: Rc::new(move |cx, ops| {
                                if !(d.prog)(cx, ops)? {
                                    return Ok(false);
                                }
                                ops.push(DOp::Set { e: sh2.eval(cx)?, add: true });
                                Ok(true)
                            }),
                        });
                        self.dshape_ok = true;
                    }
                    // S \cup {e}
                    return Box::new(move |cx| {
                        let xs = as_set(x(cx)?)?;
                        let e = sh.eval(cx)?;
                        if let Some(v) = set_one(&xs, &e, true) {
                            return Ok(v);
                        }
                        let ys = as_set(y(cx)?)?;
                        cx.ev.set_union(xs, ys)
                    });
                }
                Box::new(move |cx| {
                    let x = as_set(x(cx)?)?;
                    let y = as_set(y(cx)?)?;
                    cx.ev.set_union(x, y)
                })
            }
            K::Diff | K::Cap => {
                let x = self.expr(&a[0], sc);
                let dx = self.dshape.take();
                let y = self.expr(&a[1], sc);
                let diff = k == K::Diff;
                let one = self.shape.take().filter(|sh| !sh.bag && diff);
                if let (Some(d), Some(sh2)) = (dx, one.clone()) {
                    self.dshape = Some(DShape {
                        var: d.var,
                        direct: false,
                        prog: Rc::new(move |cx, ops| {
                            if !(d.prog)(cx, ops)? {
                                return Ok(false);
                            }
                            ops.push(DOp::Set { e: sh2.eval(cx)?, add: false });
                            Ok(true)
                        }),
                    });
                    self.dshape_ok = true;
                }
                Box::new(move |cx| {
                    if let Some(sh) = &one {
                        // S \ {e}
                        let xs = as_set(x(cx)?)?;
                        let e = sh.eval(cx)?;
                        if let Some(v) = set_one(&xs, &e, false) {
                            return Ok(v);
                        }
                    }
                    let x = as_set(x(cx)?)?;
                    let y = as_set(y(cx)?)?;
                    if x.reducible() && (diff || y.reducible()) {
                        let mut out = Vec::new();
                        for e in x.elems()? {
                            if y.contains(e)? != diff {
                                out.push(e.clone());
                            }
                        }
                        return Ok(SetV::of(out));
                    }
                    Ok(Value::Set(Rc::new(SetV::new(if diff { SetK::Diff(x, y) } else { SetK::Cap(x, y) }))))
                })
            }
            K::SetEnum if a.len() == 1 => {
                let e: Rc<CE> = Rc::new(self.expr(&a[0], sc));
                self.shape = Some(One { bag: false, elem: e.clone(), clear: vec![] });
                self.shape_ok = true;
                Box::new(move |cx| Ok(SetV::of(vec![e(cx)?])))
            }
            K::SetEnum => {
                let ces: Vec<CE> = a.iter().map(|x| self.expr(x, sc)).collect();
                Box::new(move |cx| {
                    let mut out = Vec::with_capacity(ces.len());
                    for c in &ces {
                        out.push(c(cx)?);
                    }
                    mk_set(out)
                })
            }
            K::Tuple => {
                let ces: Vec<CE> = a.iter().map(|x| self.expr(x, sc)).collect();
                Box::new(move |cx| {
                    let mut out = Vec::with_capacity(ces.len());
                    for c in &ces {
                        out.push(c(cx)?);
                    }
                    Ok(Value::Tuple(TupleV::rc(out)))
                })
            }
            K::Domain => {
                if !self.operand_ok(&a[0], sc) {
                    return self.fallback(n, sc);
                }
                let f = self.expr(&a[0], sc);
                Box::new(move |cx| {
                    let f = f(cx)?;
                    if let Value::LazyFcn(lf) = &f {
                        return Ok(Value::Set(lf.domain(cx.ev)?));
                    }
                    match domain_of(&f) {
                        Some(d) => Ok(Value::Set(d)),
                        None => bail(),
                    }
                })
            }
            _ => self.fallback(n, sc),
        }
    }

    // ---------- actions ----------
    /// The variables of `UNCHANGED e` when `e` is a variable, a tuple of such, or a name for one.
    fn unchanged_vars(&self, e: N, out: &mut Vec<u32>, depth: u32) -> bool {
        if depth > 16 {
            return false;
        }
        if let Some(i) = var_of(e) {
            out.push(i as u32);
            return true;
        }
        match &e.e {
            E::Op(K::Tuple, items) => items.iter().all(|x| self.unchanged_vars(x, out, depth + 1)),
            E::App { args, r, .. } if args.is_empty() => match r.get() {
                Res::Def(d) => {
                    let d = d.over.get().unwrap_or(d);
                    match d.body.get() {
                        Some(b) if d.builtin.get().is_none() && d.inst.is_none() && d.params.is_empty() && matches!(b.e, E::Op(K::Tuple, _)) => self.unchanged_vars(b, out, depth + 1),
                        _ => false,
                    }
                }
                _ => false,
            },
            _ => false,
        }
    }

    fn act(&mut self, n: N, sc: &Rc<Sc>) -> AE {
        let inner = self.act_inner(n, sc);
        // once every variable is assigned the tree-walker treats what follows as a plain predicate
        let sc = sc.clone();
        Box::new(move |cx, k| {
            if cx.ev.n_assigned.get() == cx.nv {
                if std::env::var_os("EVERYSTATE_EVAL_DEBUG").is_some() {
                    eprintln!("fallback all-assigned at line {} col {}", n.loc[0], n.loc[1]);
                }
                cx.fallbacks.set(cx.fallbacks.get() + 1);
                let ctx = build(&sc, cx, false)?;
                return cx.ev.enumerate(n, &ctx, k);
            }
            inner(cx, k)
        })
    }

    fn guard(&mut self, n: N, sc: &Rc<Sc>) -> AE {
        let ce = self.expr(n, sc);
        Box::new(move |cx, k| if truth(ce(cx)?)? { k() } else { Ok(()) })
    }

    /// With the step cache on: above the units the action is only disjunctions, existential quantifiers,
    /// LETs and inlined definitions; whatever else is met there is a unit.
    fn act_inner(&mut self, n: N, sc: &Rc<Sc>) -> AE {
        let top = std::mem::replace(&mut self.top, false);
        if !top || !self.cache {
            let r = self.act_inner0(n, sc);
            self.skel = None;
            return r;
        }
        let structural = match &n.e {
            E::Op(K::Or, _) | E::Let { .. } | E::Quant { forall: false, .. } => true,
            E::App { r, .. } => matches!(r.get(), Res::Def(d) if d.over.get().unwrap_or(d).builtin.get().is_none()),
            _ => false,
        };
        if structural {
            self.descend = true;
            let r = self.act_inner0(n, sc);
            self.descend = false;
            return r;
        }
        self.unit(n, sc)
    }
    fn unit(&mut self, n: N, sc: &Rc<Sc>) -> AE {
        let inner = self.act_inner0(n, sc);
        // what the unit depends on besides the state: the variables bound by the quantifiers above it
        // (whether or not its own scope names them: an inlined definition sees them through its arguments)
        let bound = self.top_slots.clone();
        // values kept for by-name bindings may have been computed before the unit: they are computed
        // again inside it when it is recorded, so that what they read is noted
        let clear = self.cache_slots.clone();
        let id = (self.plan_id << 16) | self.units;
        self.units += 1;
        let stat = Rc::new(UnitStat { loc: n.loc, lookups: Cell::new(0), hits: Cell::new(0), off: Cell::new(false), skip: Cell::new(0), penalty: Cell::new(0), phase: Cell::new(PH_WARM), count: Cell::new(0), acc: Default::default(), seen: Cell::new(0), arm: Cell::new(false), last: Cell::new((0.0, 0.0)), trials: Cell::new(0), again: Cell::new(1 << 20), held: Cell::new(false), mark: Cell::new(0), mark_l: Cell::new(0), stored: Cell::new(0), mark_s: Cell::new(0) });
        self.unit_stats.push(stat.clone());
        let node = Rc::new(UnitNode { id, bound, clear, inner, stat, n });
        self.skel = Some(Skel::Unit(node.clone()));
        Box::new(move |cx, k| unit_run(cx, k, &node))
    }
    /// Compiles `n` above the units (`desc`), leaving its skeleton in `self.skel` when it has one.
    fn act_inner0(&mut self, n: N, sc: &Rc<Sc>) -> AE {
        let desc = self.descend;
        self.skel_out = None;
        let r = self.act_inner1(n, sc);
        let out = self.skel_out.take();
        self.skel = if desc { out } else { None };
        r
    }
    fn act_inner1(&mut self, n: N, sc: &Rc<Sc>) -> AE {
        let desc = std::mem::replace(&mut self.descend, false);
        self.budget -= 1;
        if self.budget < 0 {
            return fb_act(n, sc);
        }
        match &n.e {
            E::Op(k, a) => match k {
                K::And => {
                    // (the first conjunct starts with the same assignments as the conjunction itself)
                    let items: Vec<AE> = a.iter().enumerate().map(|(i, x)| if i == 0 { self.act_inner(x, sc) } else { self.act(x, sc) }).collect();
                    if items.is_empty() {
                        return Box::new(|_, k| k());
                    }
                    fn conj(items: &[AE], i: usize, cx: &Cx, k: &mut dyn FnMut() -> R<()>) -> R<()> {
                        if i + 1 == items.len() {
                            return items[i](cx, k);
                        }
                        items[i](cx, &mut || conj(items, i + 1, cx, &mut *k))
                    }
                    Box::new(move |cx, k| conj(&items, 0, cx, k))
                }
                K::Or => {
                    let mut sks = Some(vec![]);
                    let items: Vec<AE> = a
                        .iter()
                        .map(|x| {
                            self.top = desc;
                            let it = self.act_inner(x, sc);
                            match (self.skel.take(), &mut sks) {
                                (Some(s), Some(v)) => v.push(s),
                                _ => sks = None,
                            }
                            it
                        })
                        .collect();
                    self.skel_out = sks.map(Skel::Or);
                    Box::new(move |cx, k| {
                        for it in &items {
                            it(cx, k)?;
                        }
                        Ok(())
                    })
                }
                K::If => {
                    let c = self.expr(&a[0], sc);
                    let (t, e) = (self.act_inner(&a[1], sc), self.act_inner(&a[2], sc));
                    Box::new(move |cx, k| if truth(c(cx)?)? { t(cx, k) } else { e(cx, k) })
                }
                K::Eq | K::In => {
                    // x' = e / x' \in S with x' a variable named directly
                    let tgt = match &a[0].e {
                        E::Op(K::Prime, p) => var_of(&p[0]),
                        _ => None,
                    };
                    match tgt {
                        Some(idx) => {
                            let rhs = self.expr(&a[1], sc);
                            let dprog = self.dshape.take().filter(|d| d.var == idx && self.cache && *k == K::Eq).map(|d| d.prog);
                            let assigned = fb_act(n, sc);
                            let is_eq = *k == K::Eq;
                            Box::new(move |cx, k| {
                                if !cx.nxt.is_undef(idx) {
                                    // already assigned: a condition on the next state
                                    return assigned(cx, k);
                                }
                                let ev = cx.ev;
                                if let (Some(prog), true) = (&dprog, cx.rec_on.get()) {
                                    // recording for the step cache: the new value as changes to the old one
                                    let mut ops = vec![];
                                    if prog(cx, &mut ops)? {
                                        if let Some(v) = apply_ops(cx, &cx.cur.get(idx), &ops, n) {
                                            cx.nxt.set(idx, v);
                                            cx.rec.borrow_mut().delta[idx] = Some(ops);
                                            ev.n_assigned.set(ev.n_assigned.get() + 1);
                                            let r = k();
                                            cx.nxt.clear(idx);
                                            cx.rec.borrow_mut().delta[idx] = None;
                                            ev.n_assigned.set(ev.n_assigned.get() - 1);
                                            return r;
                                        }
                                    }
                                }
                                if is_eq {
                                    let v = ev.settle(rhs(cx)?)?;
                                    cx.nxt.set(idx, v);
                                    ev.n_assigned.set(ev.n_assigned.get() + 1);
                                    let r = k();
                                    cx.nxt.clear(idx);
                                    ev.n_assigned.set(ev.n_assigned.get() - 1);
                                    return r;
                                }
                                let s = as_set(rhs(cx)?)?;
                                let es = s.elems()?;
                                ev.n_assigned.set(ev.n_assigned.get() + 1);
                                let mut r = Ok(());
                                for x in es {
                                    cx.nxt.set(idx, ev.settle(x.clone())?);
                                    r = k();
                                    if r.is_err() {
                                        break;
                                    }
                                }
                                cx.nxt.clear(idx);
                                ev.n_assigned.set(ev.n_assigned.get() - 1);
                                r
                            })
                        }
                        None => match &a[0].e {
                            // the left side may still denote a primed variable (a parameter, a definition)
                            E::Op(K::Prime, _) | E::Let { .. } => fb_act(n, sc),
                            E::App { name, args, r, .. } if args.is_empty() => match r.get() {
                                Res::Local if matches!(lookup(sc, *name), Found::Slot(_) | Found::Const(_)) => self.guard(n, sc),
                                Res::Decl(d) if d.subst.get().is_none() => self.guard(n, sc),
                                _ => fb_act(n, sc),
                            },
                            _ => self.guard(n, sc),
                        },
                    }
                }
                K::Unchanged => {
                    let mut idxs = vec![];
                    if !self.unchanged_vars(&a[0], &mut idxs, 0) || idxs.len() > 32 {
                        return fb_act(n, sc);
                    }
                    let mut seen: u64 = 0;
                    let distinct = idxs.iter().all(|&i| {
                        let fresh = i < 64 && seen & (1 << i) == 0;
                        seen |= 1 << (i & 63);
                        fresh
                    });
                    Box::new(move |cx, k| {
                        let ev = cx.ev;
                        if distinct && cx.nxt.can_fill(cx.cur, &idxs) {
                            cx.nxt.fill(cx.cur, &idxs);
                            ev.n_assigned.set(ev.n_assigned.get() + idxs.len() as i64);
                            if cx.rec_on.get() {
                                let mut rec = cx.rec.borrow_mut();
                                for &i in &idxs {
                                    rec.delta[i as usize] = Some(vec![]);
                                }
                            }
                            let r = k();
                            if cx.rec_on.get() {
                                let mut rec = cx.rec.borrow_mut();
                                for &i in &idxs {
                                    rec.delta[i as usize] = None;
                                }
                            }
                            for &i in idxs.iter().rev() {
                                cx.nxt.clear(i as usize);
                            }
                            ev.n_assigned.set(ev.n_assigned.get() - idxs.len() as i64);
                            return r;
                        }
                        if cx.rec_on.get() {
                            // (a comparison with the next state: not something an entry describes)
                            cx.rec.borrow_mut().bad = true;
                        }
                        let mut set: u32 = 0;
                        let mut r: R<()> = Ok(());
                        let mut go_on = true;
                        for (j, &i) in idxs.iter().enumerate() {
                            let i = i as usize;
                            if cx.nxt.is_undef(i) {
                                let v = cx.cur.get(i);
                                if matches!(v, Value::Undef) {
                                    r = bail();
                                    go_on = false;
                                    break;
                                }
                                cx.nxt.set(i, v);
                                ev.n_assigned.set(ev.n_assigned.get() + 1);
                                set |= 1 << j;
                            } else {
                                match val_eq(&cx.nxt.get(i), &cx.cur.get(i)) {
                                    Ok(true) => {}
                                    Ok(false) => {
                                        go_on = false;
                                        break;
                                    }
                                    Err(e) => {
                                        r = Err(e);
                                        go_on = false;
                                        break;
                                    }
                                }
                            }
                        }
                        if go_on {
                            r = k();
                        }
                        for j in (0..idxs.len()).rev() {
                            if set & (1 << j) != 0 {
                                cx.nxt.clear(idxs[j] as usize);
                            }
                        }
                        ev.n_assigned.set(ev.n_assigned.get() - set.count_ones() as i64);
                        r
                    })
                }
                // the enumerator has its own rules for these
                K::Imp | K::Subseteq | K::BoxAct | K::AngleAct | K::Cdot => fb_act(n, sc),
                _ => self.guard(n, sc),
            },
            E::Quant { forall: false, bounds, body } => {
                let (nm, set) = match simple_bound(bounds) {
                    Some(x) => x,
                    None => {
                        let (b, inner) = match self.bounds(bounds, sc) {
                            Some(x) => x,
                            None => return fb_act(n, sc),
                        };
                        self.top = desc;
                        let mark = self.top_slots.len();
                        if desc {
                            for fb in &b.flat {
                                self.top_slots.extend_from_slice(&fb.slots);
                            }
                        }
                        let body = self.act_inner(body, &inner);
                        self.top_slots.truncate(mark);
                        return Box::new(move |cx, k| {
                            b.each(cx, &mut || {
                                body(cx, &mut *k)?;
                                Ok(false)
                            })?;
                            Ok(())
                        });
                    }
                };
                let set_n = set;
                let set: Rc<CE> = Rc::new(self.expr(set, sc));
                let slot = self.slot();
                self.top = desc;
                if desc {
                    self.top_slots.push(slot);
                }
                let body = self.act_inner(body, &push(sc, ScK::Slot { name: nm, slot }));
                let body_skel = self.skel.take();
                if desc {
                    self.top_slots.pop();
                }
                let set2 = set.clone();
                let run: Rc<AE> = Rc::new(Box::new(move |cx, k| {
                    let s = as_set(set(cx)?)?;
                    if let SetK::Interval(lo, hi) = &s.k {
                        for i in *lo..=*hi {
                            cx.f.set(slot, Value::Int(i));
                            body(cx, k)?;
                        }
                        return Ok(());
                    }
                    for x in s.elems()? {
                        cx.f.set(slot, x.clone());
                        body(cx, k)?;
                    }
                    Ok(())
                }));
                if let (true, Some(b)) = (desc, body_skel) {
                    let dom = match &set_n.e {
                        E::Op(K::Domain, a) if a.len() == 1 && var_of(&a[0]).is_some() => Some(Dom::Domain(var_of(&a[0]).unwrap())),
                        _ if closed_const(set_n) => Some(Dom::Const { set: set2, ids: OnceCell::new() }),
                        _ => None,
                    };
                    self.skel_out = dom.map(|dom| Skel::Exists { slot, dom, body: Box::new(b), run: run.clone() });
                }
                Box::new(move |cx, k| run(cx, k))
            }
            E::Quant { .. } => fb_act(n, sc),
            E::Case { arms, other } => {
                let arms: Vec<(CE, AE)> = arms.iter().map(|(c, e)| (self.expr(c, sc), self.act_inner(e, sc))).collect();
                let other = other.as_ref().map(|o| self.act_inner(o, sc));
                Box::new(move |cx, k| {
                    for (c, e) in &arms {
                        if truth(c(cx)?)? {
                            return e(cx, k);
                        }
                    }
                    match &other {
                        Some(o) => o(cx, k),
                        None => bail(),
                    }
                })
            }
            E::Let { defs, body } => match self.let_scope(defs, sc) {
                Some((inner, clear)) => {
                    self.top = desc;
                    let body = self.act_inner(body, &inner);
                    if let (true, Some(b)) = (desc, self.skel.take()) {
                        self.skel_out = Some(Skel::Pre { ops: clear.clone(), body: Box::new(b) });
                    }
                    Box::new(move |cx, k| {
                        run_pre(&clear, cx);
                        body(cx, k)
                    })
                }
                None => fb_act(n, sc),
            },
            E::App { name, args, r, .. } => {
                match r.get() {
                    Res::Def(d) => {
                        let d = d.over.get().unwrap_or(d);
                        if d.builtin.get().is_some() {
                            return self.guard(n, sc);
                        }
                        let body = match d.body.get() {
                            Some(b) if d.inst.is_none() => b,
                            _ => return fb_act(n, sc),
                        };
                        let id = d as *const Def as usize;
                        if self.stack.contains(&id) || self.stack.len() > 40 {
                            return fb_act(n, sc);
                        }
                        let root = Rc::new(Sc { k: ScK::Root(None), next: None });
                        match self.bind_args(&d.params, args, root, sc) {
                            Some((inner, clear)) => {
                                self.stack.push(id);
                                self.top = desc;
                                let b = self.act_inner(body, &inner);
                                self.stack.pop();
                                if let (true, Some(s)) = (desc, self.skel.take()) {
                                    self.skel_out = Some(Skel::Pre { ops: clear.clone(), body: Box::new(s) });
                                }
                                Box::new(move |cx, k| {
                                    run_pre(&clear, cx);
                                    b(cx, k)
                                })
                            }
                            None => fb_act(n, sc),
                        }
                    }
                    Res::Decl(d) => {
                        if d.subst.get().is_some() {
                            fb_act(n, sc)
                        } else {
                            self.guard(n, sc)
                        }
                    }
                    Res::Local => match lookup(sc, *name) {
                        // a bound variable or a constant: a plain condition
                        Found::Slot(_) | Found::Const(_) if args.is_empty() => self.guard(n, sc),
                        // a parameter or a LET definition: the enumerator enters the expression it stands for
                        _ => fb_act(n, sc),
                    },
                    Res::None => fb_act(n, sc),
                }
            }
            // the enumerator enters the body of a lazily evaluated function; a state variable is not one
            E::FnApp { f, .. } if var_of(f).is_some() => self.guard(n, sc),
            E::FnApp { .. } => fb_act(n, sc),
            _ => self.guard(n, sc),
        }
    }
}

/// A unit with the step cache on: the stored successors when an entry matches the state, else an
/// evaluation that is recorded and stored.
fn unit_run(cx: &Cx, k: &mut dyn FnMut() -> R<()>, u: &UnitNode) -> R<()> {
    let table = match cx.cache {
        Some(t) if !cx.rec_on.get() && cx.ev.n_assigned.get() == 0 => t,
        _ => return (u.inner)(cx, k),
    };
    if !use_cache(cx, &u.stat) {
        return (u.inner)(cx, k);
    }
    let nv = cx.nv as usize;
    if cx.cur_ids.len() < nv {
        return (u.inner)(cx, k);
    }
    let mut bids: SmallIds = SmallIds::new();
    let all = cx.f.with(|fv| u.bound.iter().all(|&s| matches!(fv.get(s).and_then(crate::hashcons::id), Some(x) if bids.push(x))));
    if !all {
        return (u.inner)(cx, k);
    }
    unit_cached(cx, k, table, u, bids.as_slice(), &|| {})
}
/// Whether this evaluation of the unit goes through the cache (and the bookkeeping of that decision).
#[inline(always)]
fn use_cache(cx: &Cx, stat: &Rc<UnitStat>) -> bool {
    // (the common case: a unit that has the cache, between two looks at how it does)
    let c = stat.count.get() + 1;
    if stat.phase.get() == PH_ON && c % 4096 != 0 && !cx.cache_always {
        stat.count.set(c);
        return true;
    }
    use_cache_slow(cx, stat)
}
#[inline(never)]
fn use_cache_slow(cx: &Cx, stat: &Rc<UnitStat>) -> bool {
    // Whether the cache pays is measured, not assumed, and measured on the whole work per state rather
    // than on the unit alone (a successor built from an entry shares its new values with its parent and
    // with the other successors built from that entry, which saves time after the unit, in fingerprinting
    // and in memory). After a warm-up the unit goes on trial: each state expanded is taken with or without
    // the cache, by a hash of its number, and the time from that expansion to the next is added to the one
    // or the other mean of every unit on trial evaluated in it (`UnitStat::sample`). The choice is the same
    // for all units on trial, so units that are tried together are judged together, on their joint effect
    // (the effect of one unit alone is often too small to tell from noise in a reasonable time, while
    // twenty such effects add up). A unit gets the cache when the mean with it is lower by 2.5 standard
    // errors (looked at every 256 states from 512 per side on), or by one standard error after 4096
    // states per side; the trial ends without the cache when the mean with it is higher by as much, or
    // higher at all past 1024 states per side (a trial costs time too). A unit that has the cache goes on
    // trial again after a million evaluations (or 16 times the length of its last trial, if that is more),
    // or when 4096 evaluations missed more than one time in five, and keeps it unless that trial goes
    // against it; a unit that does not pay is evaluated without the cache for as long, longer when it
    // fails again (up to 4 million evaluations; at once 4 million when it is far from paying).
    if cx.cache_always {
        // EVERYSTATE_STEP_CACHE=always (for testing): every unit uses the cache, whether or not it pays
        return true;
    }
    let c = stat.count.get() + 1;
    stat.count.set(c);
    match stat.phase.get() {
        PH_OFF => {
            if c >= stat.skip.get() {
                stat.enter(PH_WARM);
            }
            false
        }
        PH_WARM => {
            if c == 1 {
                stat.mark.set(stat.hits.get());
                stat.mark_l.set(stat.lookups.get());
                stat.mark_s.set(stat.stored.get());
            }
            if c == 32 && stat.hits.get() == stat.mark.get() && stat.stored.get() == stat.mark_s.get() {
                // nothing could be stored in 32 evaluations (the tree-walker was needed, or the key is too
                // large): no entry will ever be found
                stat.turn_off(true);
            } else if c == 256 {
                // a table that is still mostly missing after 256 lookups is not going to pay
                if (stat.hits.get() - stat.mark.get()) * 2 < 256 {
                    stat.turn_off(true);
                } else {
                    stat.begin_trial(cx.meas);
                }
            }
            true
        }
        PH_TRIAL => {
            let e = cx.meas.exp.get();
            if stat.seen.get() != e {
                stat.seen.set(e);
                stat.arm.set((sc_::mix(e, 0x7A11) >> 17) & 1 == 1);
                cx.meas.touched.borrow_mut().push(stat.clone());
            }
            stat.arm.get()
        }
        _ => {
            if c % 4096 == 0 {
                let (looked, hit) = (stat.lookups.get() - stat.mark_l.get(), stat.hits.get() - stat.mark.get());
                if c >= stat.again.get() || hit * 5 < looked * 4 {
                    stat.begin_trial(cx.meas);
                } else {
                    stat.mark.set(stat.hits.get());
                    stat.mark_l.set(stat.lookups.get());
                }
            }
            true
        }
    }
}
const PH_WARM: u8 = 0;
const PH_TRIAL: u8 = 1;
const PH_ON: u8 = 3;
const PH_OFF: u8 = 4;
/// Nanoseconds from some fixed moment. (No clock in WebAssembly; the step cache is off there.)
#[cfg(not(target_arch = "wasm32"))]
fn now_ns() -> u64 {
    use std::sync::OnceLock;
    static T0: OnceLock<std::time::Instant> = OnceLock::new();
    T0.get_or_init(std::time::Instant::now).elapsed().as_nanos() as u64 + 1
}
#[cfg(target_arch = "wasm32")]
fn now_ns() -> u64 {
    0
}
/// The measurement shared by the units of one `Plans`: the number of the state being expanded, when its
/// expansion began, and the units on trial that were evaluated in it.
pub struct Meas {
    /// units on trial
    active: Cell<u32>,
    t0: Cell<u64>,
    exp: Cell<u64>,
    touched: RefCell<Vec<Rc<UnitStat>>>,
}
impl Meas {
    fn new() -> Meas {
        Meas { active: Cell::new(0), t0: Cell::new(0), exp: Cell::new(1), touched: RefCell::new(Vec::new()) }
    }
    /// A state is about to be expanded: the time since the last such moment goes to the units on trial
    /// that were evaluated in between. (No clock is read while no unit is on trial.)
    #[inline]
    fn tick(&self) {
        if self.active.get() == 0 && self.t0.get() == 0 {
            return;
        }
        let now = now_ns();
        let t0 = self.t0.replace(if self.active.get() == 0 { 0 } else { now });
        self.exp.set(self.exp.get() + 1);
        let mut t = self.touched.borrow_mut();
        if t0 != 0 {
            for u in t.iter() {
                u.sample((now - t0) as f64, self);
            }
        }
        t.clear();
    }
}
#[derive(Default)]
struct Acc {
    sum: Cell<f64>,
    sq: Cell<f64>,
    n: Cell<u64>,
}
impl Acc {
    fn add(&self, x: f64) {
        self.sum.set(self.sum.get() + x);
        self.sq.set(self.sq.get() + x * x);
        self.n.set(self.n.get() + 1);
    }
    fn reset(&self) {
        self.sum.set(0.0);
        self.sq.set(0.0);
        self.n.set(0);
    }
    fn mean(&self) -> f64 {
        self.sum.get() / self.n.get().max(1) as f64
    }
    /// the variance of the mean
    fn var_mean(&self) -> f64 {
        let n = self.n.get().max(2) as f64;
        let m = self.sum.get() / n;
        ((self.sq.get() / n - m * m).max(0.0)) / (n - 1.0)
    }
}
impl UnitStat {
    fn enter(&self, phase: u8) {
        self.phase.set(phase);
        self.count.set(0);
    }
    fn begin_trial(&self, meas: &Meas) {
        self.held.set(self.phase.get() == PH_ON);
        self.acc[0].reset();
        self.acc[1].reset();
        meas.active.set(meas.active.get() + 1);
        self.enter(PH_TRIAL);
    }
    /// One state expanded with this unit on trial took `dt` ns (to the next expansion).
    fn sample(&self, dt: f64, meas: &Meas) {
        if self.phase.get() != PH_TRIAL {
            return;
        }
        let (a, b) = (&self.acc[0], &self.acc[1]);
        let total = a.n.get() + b.n.get();
        // (one descheduled sample, or one that grew the fingerprint set, must not decide)
        let x = if total >= 32 { dt.min(8.0 * (a.sum.get() + b.sum.get()) / total as f64) } else { dt };
        self.acc[self.arm.get() as usize].add(x);
        let least = a.n.get().min(b.n.get());
        if least < 512 || (total + 1) % 256 != 0 {
            return;
        }
        let (plain, cached) = (a.mean(), b.mean());
        let se = (a.var_mean() + b.var_mean()).sqrt();
        let d = cached - plain;
        self.last.set((plain, cached));
        self.trials.set(total + 1);
        let done = least >= 4096;
        // (a trial of n evaluations is followed by at least 16 n evaluations without one)
        self.again.set((self.count.get() * 16).max(1 << 20));
        // (a unit that had the cache keeps it unless the trial goes against it)
        let held = self.held.get();
        if d < -2.5 * se || (done && d < if held { se } else { -se }) {
            meas.active.set(meas.active.get() - 1);
            self.penalty.set(0);
            self.off.set(false);
            self.mark.set(self.hits.get());
            self.mark_l.set(self.lookups.get());
            self.enter(PH_ON);
        } else if d > 2.5 * se || done || (!held && least >= 1024 && d > 0.0) {
            // (a trial costs time too: past 1024 states per side it goes on only while the cache is ahead)
            meas.active.set(meas.active.get() - 1);
            self.turn_off(d > 3.0 * se && d > 0.05 * plain);
        }
    }
    /// The cache does not pay for this unit; `far`: not worth trying again soon.
    fn turn_off(&self, far: bool) {
        let p = if far { 1 << 22 } else { (self.penalty.get() * 2).clamp(1 << 18, 1 << 22) };
        self.penalty.set(p);
        self.skip.set(p.max(self.again.get()));
        self.off.set(true);
        self.enter(PH_OFF);
    }
}
/// A unit through the cache, with these bound values: the stored successors when an entry matches the
/// state, else an evaluation that is recorded and stored. `before` is called before anything is evaluated
/// on values (the skeleton builds them then).
#[inline(always)]
fn unit_cached(cx: &Cx, k: &mut dyn FnMut() -> R<()>, table: &RefCell<Table>, u: &UnitNode, bids: &[crate::hashcons::Id], before: &dyn Fn()) -> R<()> {
    let stat = &u.stat;
    stat.lookups.set(stat.lookups.get() + 1);
    // 1. an entry whose unit, bound values and located values all match this state (successors collected
    // as ids: the rows go straight there)
    if let Some(out) = cx.out {
        let t = table.borrow();
        let mut o = out.borrow_mut();
        let mark = o.mark();
        let o = &mut *o;
        if cached_rows(&t, cx, u.id, bids, u.n, &mut o.ids, Some(&mut o.meta)).is_some() {
            // (the table's counts of lookups and hits are those of its units: see `Plans::report`)
            stat.hits.set(stat.hits.get() + 1);
            return Ok(());
        }
        o.truncate(mark);
    }
    unit_cached_values(cx, k, table, u, bids, before)
}
/// `unit_cached` past an entry for the ids: successors as values, or a miss.
#[inline(never)]
fn unit_cached_values(cx: &Cx, k: &mut dyn FnMut() -> R<()>, table: &RefCell<Table>, u: &UnitNode, bids: &[crate::hashcons::Id], before: &dyn Fn()) -> R<()> {
    let nv = cx.nv as usize;
    let stat = &u.stat;
    let ev = cx.ev;
    if cx.out.is_none() {
        let mut rows = vec![];
        let hit = cached_rows(&table.borrow(), cx, u.id, bids, u.n, &mut rows, None);
        if hit.is_some() {
            stat.hits.set(stat.hits.get() + 1);
            return emit_values(cx, k, ev, &rows, nv);
        }
    }
    // 2. evaluate, noting what is read and how each variable gets its value
    before();
    for &s in &u.clear {
        cx.f.clear(s);
    }
    {
        let mut rec = cx.rec.borrow_mut();
        rec.reads.clear();
        rec.bad = false;
        rec.succs.clear();
        rec.delta.clear();
        rec.delta.resize(nv, None);
    }
    let f0 = cx.fallbacks.get();
    cx.rec_on.set(true);
    let r = (u.inner)(cx, &mut || {
        cx.nxt.with(|nx| {
            let mut rec = cx.rec.borrow_mut();
            let mut ws = Vec::with_capacity(nv);
            for i in 0..nv {
                match rec.delta[i].clone() {
                    Some(ops) => ws.push(Write::Delta(ops)),
                    None => {
                        if i >= nx.len() || matches!(nx[i], Value::Undef) {
                            rec.bad = true;
                        } else {
                            ws.push(Write::Val(nx[i].clone()));
                        }
                    }
                }
            }
            rec.succs.push(ws);
        });
        k()
    });
    cx.rec_on.set(false);
    let mut t = table.borrow_mut();
    let rec = cx.rec.borrow();
    let stored = r.is_ok() && !rec.bad && cx.fallbacks.get() == f0 && sc_::store(&mut t, cx.cur_ids, sc_::Recorded { unit: u.id, bound: bids, reads: &rec.reads, succs: &rec.succs });
    if !stored {
        t.n.uncacheable += 1;
    } else {
        stat.stored.set(stat.stored.get() + 1);
    }
    r
}

/// Up to 24 ids on the stack (the bound values of a unit, or the located values of a template).
struct SmallIds {
    n: usize,
    a: [crate::hashcons::Id; 24],
}
impl SmallIds {
    #[inline]
    fn new() -> SmallIds {
        SmallIds { n: 0, a: [0; 24] }
    }
    /// False when full.
    #[inline]
    fn push(&mut self, x: crate::hashcons::Id) -> bool {
        if self.n == self.a.len() {
            return false;
        }
        self.a[self.n] = x;
        self.n += 1;
        true
    }
    #[inline]
    fn as_slice(&self) -> &[crate::hashcons::Id] {
        &self.a[..self.n]
    }
}

/// The successors an entry gives for this state; how many. Without `meta` they are appended to `ids` as
/// rows of `nv` ids. With it each is noted there; with `cx.fpx` too, a successor whose fingerprint can
/// be told from the changes is noted as a recipe, to be built only if it is a new state (most are
/// not), and the rest as rows with their fingerprints. None: no entry matches, or a change cannot be
/// applied (part of a row may then have been added).
fn cached_rows(t: &Table, cx: &Cx, unit: u32, bids: &[crate::hashcons::Id], n: N, ids: &mut Vec<crate::hashcons::Id>, mut meta: Option<&mut sc_::RowMeta>) -> Option<usize> {
    let cur = cx.cur_ids;
    let tm = t.template(sc_::template_hash(unit, bids), unit, bids)?;
    let mut key = SmallIds::new();
    let mut h = sc_::leaf_hash_start(tm.version);
    for &loc in tm.locs.iter() {
        let x = t.locate(cur, loc)?;
        key.push(x);
        h = sc_::mix(h, x as u64);
    }
    let (slot, leaf) = t.leaf_slot(h, tm.version, key.as_slice())?;
    let nv = cx.nv as usize;
    for (si, s) in leaf.succs.iter().enumerate() {
        if let (Some(m), Some(fx)) = (&mut meta, cx.fpx) {
            if let Some(fp) = delta_fingerprint(t, fx, cur, s) {
                if fx.verify {
                    verify_delta(t, cx, fx, cur, s, n, fp);
                }
                // (the search looks it up in the seen set soon: the load starts now)
                fx.seen.prefetch(fp);
                m.recipe(fp, sc_::Recipe { slot: slot.clone(), succ: si as u32, n });
                continue;
            }
        }
        let base = ids.len();
        ids.extend_from_slice(&cur[..nv]);
        build_puts(t, cx, cur, s, n, &mut ids[base..base + nv])?;
        let Some(m) = &mut meta else {
            continue;
        };
        let Some(fx) = cx.fpx else {
            m.added(0);
            continue;
        };
        // the parent's fingerprint with the terms of the changed variables replaced
        let mut sum = fx.sum;
        for (var, _) in s.iter() {
            let i = *var as usize;
            let x = ids[base + i];
            if x != cur[i] {
                sum = sum.wrapping_sub(fx.terms[i]).wrapping_add(crate::checker::var_term(i, fx.ids.word(x)));
            }
        }
        m.added(crate::checker::fp_finish(sum));
    }
    Some(leaf.succs.len())
}
/// `row` (a copy of the parent's, `cur`) with the changes `s` made. None when a change cannot be applied.
#[inline]
fn build_puts(t: &Table, cx: &Cx, cur: &[crate::hashcons::Id], s: &[(u32, sc_::Put)], n: N, row: &mut [crate::hashcons::Id]) -> Option<()> {
    for (var, put) in s.iter() {
        let i = *var as usize;
        row[i] = match put {
            sc_::Put::Id { id, .. } => *id,
            sc_::Put::Delta { id, ops, .. } => t.applied(cur[i], *id, |parent| apply_ops(cx, parent, ops, n))?,
        };
    }
    Some(())
}
/// Checks that the successor the changes `s` give has the fingerprint `fp`, and that they apply.
#[cold]
fn verify_delta(t: &Table, cx: &Cx, fx: &FpCtx, cur: &[crate::hashcons::Id], s: &[(u32, sc_::Put)], n: N, fp: u64) {
    let nv = cx.nv as usize;
    let mut row = cur[..nv].to_vec();
    build_puts(t, cx, cur, s, n, &mut row).expect("changes whose fingerprint is known apply");
    let mut sum = fx.sum;
    for k in 0..nv {
        if row[k] != cur[k] {
            sum = sum.wrapping_sub(fx.terms[k]).wrapping_add(crate::checker::var_term(k, crate::value::value_word(&crate::hashcons::value(row[k])).unwrap()));
        }
    }
    assert_eq!(crate::checker::fp_finish(sum), fp, "the fingerprint of a successor from its changes");
}
/// EVERYSTATE_VERIFY_DELTAS=1: every fingerprint computed from changes is checked against the one of the
/// successor built (for testing).
pub fn verify_deltas() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| std::env::var_os("EVERYSTATE_VERIFY_DELTAS").is_some())
}
/// The fingerprint of the successor of the state with ids `cur` that the changes `s` give, from the
/// parent's terms, without building it. None when a change has to be applied to tell.
#[inline]
fn delta_fingerprint(t: &Table, fx: &FpCtx, cur: &[crate::hashcons::Id], s: &[(u32, sc_::Put)]) -> Option<u64> {
    let mut sum = fx.sum;
    for (var, put) in s.iter() {
        let i = *var as usize;
        let w = match put {
            sc_::Put::Id { id, .. } if *id == cur[i] => continue,
            sc_::Put::Id { word, .. } => *word,
            sc_::Put::Delta { shift: Some(d), .. } => fx.words[i].wrapping_add(*d),
            sc_::Put::Delta { iops: Some(ops), id, .. } => t.delta_word(fx.ids, cur[i], *id, ops)?,
            sc_::Put::Delta { iops: None, .. } => return None,
        };
        sum = sum.wrapping_sub(fx.terms[i]).wrapping_add(crate::checker::var_term(i, w));
    }
    Some(crate::checker::fp_finish(sum))
}

/// Hands on the successors of a hit, given as rows of ids, as values in the next state, one successor at
/// a time.
fn emit_values(cx: &Cx, k: &mut dyn FnMut() -> R<()>, ev: &Evaluator, rows: &[crate::hashcons::Id], nv: usize) -> R<()> {
    for row in rows.chunks_exact(nv) {
        cx.cur.with(|cv| {
            for i in 0..nv {
                cx.nxt.set(i, if row[i] == cx.cur_ids[i] { cv[i].clone() } else { crate::hashcons::value(row[i]) });
            }
        });
        ev.n_assigned.set(nv as i64);
        let r = k();
        for i in 0..nv {
            cx.nxt.clear(i);
        }
        ev.n_assigned.set(0);
        r?;
    }
    Ok(())
}
fn with_clear(clear: Vec<PreOp>, body: CE) -> CE {
    if clear.is_empty() {
        return body;
    }
    Box::new(move |cx| {
        run_pre(&clear, cx);
        body(cx)
    })
}

/// The scope for the context a top-level action or invariant starts from: plain values and LET
/// definitions (an action that was split out of a LET). None when the context holds anything else, or a
/// LET definition that may reach an operator with an effect. Also the slots to clear at each evaluation.
fn root_scope(ctx: &C, c: &mut Comp, seen: &mut HashSet<usize>) -> Option<(Rc<Sc>, Vec<PreOp>)> {
    let mut nodes: Vec<&Rc<Ctx>> = vec![];
    let mut cur = ctx.as_ref();
    while let Some(node) = cur {
        if node.env || node.base.is_some() {
            return None;
        }
        nodes.push(node);
        cur = node.next.as_ref();
    }
    let mut sc = Rc::new(Sc { k: ScK::Root(ctx.clone()), next: None });
    let mut clear = vec![];
    for node in nodes.iter().rev() {
        let k = match &node.val {
            Bind::Val(v) if plain(v) => ScK::RootVal { name: node.name, v: v.clone() },
            Bind::LetLazy { d, .. } | Bind::LetOp(d) => {
                if impure(&d.body, seen) {
                    return None;
                }
                let cache = c.slot();
                c.cache_slots.push(cache);
                clear.push(PreOp::Clear(cache));
                ScK::Let { d, defs: &[], below: sc.clone(), head: node.let_head, cache, ce: RefCell::new(None), root: true }
            }
            _ => return None,
        };
        sc = push(&sc, k);
    }
    Some((sc, clear))
}

pub struct ActPlan {
    run: AE,
    frame: StateRef,
    use_: Usage,
    /// the top of the action on ids, when it has one (`Plans::run_skel`)
    skel: Option<Skel>,
}
pub struct PredPlan {
    run: CE,
    frame: StateRef,
    use_: Usage,
}
/// Compiled code that mostly hands over to the tree-walker costs more than the tree-walker alone (a
/// context is rebuilt for every fallback). Such a plan is switched off after a trial; the result is the
/// same either way.
#[derive(Default)]
struct Usage {
    runs: Cell<u32>,
    fallbacks: Cell<u64>,
    off: Cell<bool>,
}
impl Usage {
    #[inline]
    fn note(&self, fallbacks: u64) {
        let r = self.runs.get();
        if r < 512 {
            self.runs.set(r + 1);
            self.fallbacks.set(self.fallbacks.get() + fallbacks);
            if r + 1 == 512 && self.fallbacks.get() > 4 * 512 {
                self.off.set(true);
            }
        }
    }
}
#[derive(Default)]
pub struct Counters {
    /// actions / invariants evaluated by compiled code, by the tree-walker because they are not compiled,
    /// and by the tree-walker after the compiled attempt failed
    pub compiled: Cell<u64>,
    pub uncompiled: Cell<u64>,
    pub redone: Cell<u64>,
    /// fallback expressions evaluated inside compiled code
    pub fallbacks: Cell<u64>,
}
pub struct Plans {
    pub actions: Vec<Option<ActPlan>>,
    pub invariants: Vec<Option<PredPlan>>,
    pub n: Counters,
    blank: StateRef,
    /// the step cache, when it is on
    cache: Option<RefCell<Table>>,
    rec_on: Cell<bool>,
    rec: RefCell<Rec>,
    units: Vec<Rc<UnitStat>>,
    cache_always: bool,
    meas: Meas,
}

/// The step cache is on with the compiled evaluator; EVERYSTATE_STEP_CACHE=off turns it off. (`on` and
/// `always` ask for it even with EVERYSTATE_EVAL=tree; `always` gives it to every unit, for testing.)
/// In WebAssembly it is off: there is no clock to measure whether it pays, so no unit would ever keep it.
pub fn cache_enabled() -> bool {
    if cfg!(target_arch = "wasm32") {
        return false;
    }
    match std::env::var("EVERYSTATE_STEP_CACHE").as_deref() {
        Ok("off") => false,
        Ok("on") | Ok("always") => true,
        _ => !matches!(std::env::var("EVERYSTATE_EVAL").as_deref(), Ok("tree")),
    }
}
fn cache_budget() -> usize {
    let mb: f64 = std::env::var("EVERYSTATE_STEP_CACHE_MB").ok().and_then(|v| v.parse().ok()).unwrap_or(32.0);
    (mb.max(0.001) * 1024.0 * 1024.0) as usize
}

/// The compiled evaluator is the default; EVERYSTATE_EVAL=tree selects the tree-walker alone.
pub fn enabled() -> bool {
    !matches!(std::env::var("EVERYSTATE_EVAL").as_deref(), Ok("tree")) || cache_enabled()
}

/// `cache`: with the step cache, unless the environment turns it off (`cache_enabled`).
pub fn compile(model: &crate::model::Model, cache: bool) -> Plans {
    let mut cache_on = cache && cache_enabled();
    let mut plan_id: u32 = 0;
    let mut units = vec![];
    let mut actions = vec![];
    for a in &model.actions {
        let mut seen = HashSet::new();
        let mut c = Comp::new(cache_on, plan_id);
        plan_id += 1;
        let root = if impure(a.e, &mut seen) { None } else { root_scope(&a.ctx, &mut c, &mut seen) };
        let (root, clear) = match root {
            Some(x) => x,
            None => {
                if std::env::var_os("EVERYSTATE_EVAL_DEBUG").is_some() {
                    eprintln!("action {}{} is not compiled (an operator with an effect, or a context that is not plain values and LET definitions)", a.name, a.params);
                }
                actions.push(None);
                continue;
            }
        };
        c.top = true;
        let body = c.act(a.e, &root);
        units.append(&mut c.unit_stats);
        let skel = c.skel.take().filter(|_| model.vars.len() > 0).map(|sk| if clear.is_empty() { sk } else { Skel::Pre { ops: clear.clone(), body: Box::new(sk) } }).filter(|sk| sk.depth() <= PATH_MAX);
        if std::env::var_os("EVERYSTATE_EVAL_DEBUG").is_some() {
            eprintln!("action {}: {}", a.name, if skel.is_some() { "runs on ids" } else { "runs on values" });
        }
        let run: AE = if clear.is_empty() {
            body
        } else {
            Box::new(move |cx, k| {
                run_pre(&clear, cx);
                body(cx, k)
            })
        };
        actions.push(Some(ActPlan { run, frame: StateData::blank(c.nslots.max(1)), use_: Usage::default(), skel }));
    }
    let with_cache = cache_on;
    cache_on = false; // (invariants are not cached)
    let mut invariants = vec![];
    for p in &model.invariants {
        let mut seen = HashSet::new();
        let mut c = Comp::new(cache_on, plan_id);
        plan_id += 1;
        let root = if impure(p.e, &mut seen) || level_of(p.e) > 1 { None } else { root_scope(&p.ctx, &mut c, &mut seen) };
        let (root, clear) = match root {
            Some(x) => x,
            None => {
                invariants.push(None);
                continue;
            }
        };
        let run = with_clear(clear, c.expr(p.e, &root));
        invariants.push(Some(PredPlan { run, frame: StateData::blank(c.nslots.max(1)), use_: Usage::default() }));
    }
    Plans {
        actions,
        invariants,
        n: Counters::default(),
        blank: StateData::blank(model.vars.len()),
        cache: if with_cache { Some(RefCell::new(Table::new(cache_budget()))) } else { None },
        rec_on: Cell::new(false),
        rec: RefCell::new(Rec::default()),
        units,
        cache_always: matches!(std::env::var("EVERYSTATE_STEP_CACHE").as_deref(), Ok("always")),
        meas: Meas::new(),
    }
}

impl Plans {
    /// Runs the compiled form of action `ai` (the evaluator's current and next state are set as for
    /// `enumerate`). None: the action is not compiled. Some(Err): the attempt failed and must be redone
    /// by the tree-walker after discarding what it produced.
    #[allow(clippy::too_many_arguments)]
    pub fn run_action(&self, ev: &Evaluator, ai: usize, cur: &StateData, cur_ids: &[crate::hashcons::Id], nxt: &StateData, nv: usize, out: Option<&RefCell<sc_::Rows>>, fpx: Option<&FpCtx>, k: &mut dyn FnMut() -> R<()>) -> Option<R<()>> {
        let p = match &self.actions[ai] {
            Some(p) if !p.use_.off.get() => p,
            _ => {
                self.n.uncompiled.set(self.n.uncompiled.get() + 1);
                return None;
            }
        };
        let cx = Cx { ev, f: &p.frame, cur, nxt, nv: nv as i64, fallbacks: &self.n.fallbacks, cache: self.cache.as_ref(), rec_on: &self.rec_on, rec: &self.rec, cache_always: self.cache_always, meas: &self.meas, cur_ids, out, vals: None, fpx };
        let f0 = self.n.fallbacks.get();
        let r = (p.run)(&cx, k);
        self.rec_on.set(false);
        p.use_.note(self.n.fallbacks.get() - f0);
        if r.is_err() {
            self.n.redone.set(self.n.redone.get() + 1);
        } else {
            self.n.compiled.set(self.n.compiled.get() + 1);
        }
        Some(r)
    }
    /// The row of a successor noted as a recipe (`cached_rows`): the parent's, `cur`, with its changes
    /// made; `verify` (EVERYSTATE_VERIFY_DELTAS) checks that it has the fingerprint `fp` it was noted
    /// with. False when a change cannot be applied after all (the caller then expands the parent again
    /// without recipes).
    pub fn build_recipe(&self, ev: &Evaluator, r: &sc_::Recipe, cur: &[crate::hashcons::Id], nv: usize, row: &mut Vec<crate::hashcons::Id>) -> bool {
        let Some(t) = &self.cache else { return false };
        let t = t.borrow();
        let cx = Cx { ev, f: &self.blank, cur: &self.blank, nxt: &self.blank, nv: nv as i64, fallbacks: &self.n.fallbacks, cache: None, rec_on: &self.rec_on, rec: &self.rec, cache_always: self.cache_always, meas: &self.meas, cur_ids: cur, out: None, vals: None, fpx: None };
        row.clear();
        row.extend_from_slice(&cur[..nv]);
        build_puts(&t, &cx, cur, r.puts(), r.n, row).is_some()
    }
    /// Whether action `ai` can run on ids (`run_skel`).
    pub fn has_skel(&self, ai: usize) -> bool {
        self.cache.is_some() && matches!(&self.actions[ai], Some(p) if p.skel.is_some() && !p.use_.off.get())
    }
    /// Runs action `ai` on the ids of the current state (its skeleton, RFD0002): successors go to `out`.
    /// `cur` gets the state's values only when `vals` is called, which happens when something has to be
    /// evaluated on values. None: the action has no skeleton. Some(Err): as for `run_action`.
    #[allow(clippy::too_many_arguments)]
    pub fn run_skel(&self, ev: &Evaluator, ai: usize, cur: &StateData, cur_ids: &[crate::hashcons::Id], nxt: &StateData, nv: usize, out: &RefCell<sc_::Rows>, fpx: Option<&FpCtx>, vals: &dyn Fn(), k: &mut dyn FnMut() -> R<()>) -> Option<R<()>> {
        let p = match &self.actions[ai] {
            Some(p) if !p.use_.off.get() => p,
            _ => return None,
        };
        let sk = p.skel.as_ref()?;
        if self.cache.is_none() || cur_ids.len() < nv {
            return None;
        }
        let cx = Cx { ev, f: &p.frame, cur, nxt, nv: nv as i64, fallbacks: &self.n.fallbacks, cache: self.cache.as_ref(), rec_on: &self.rec_on, rec: &self.rec, cache_always: self.cache_always, meas: &self.meas, cur_ids, out: Some(out), vals: Some(vals), fpx };
        let f0 = self.n.fallbacks.get();
        let mut path = Path::new();
        let mut bids = SmallIds::new();
        let r = skel_run(sk, &cx, &mut path, &mut bids, k);
        self.rec_on.set(false);
        p.use_.note(self.n.fallbacks.get() - f0);
        if r.is_err() {
            self.n.redone.set(self.n.redone.get() + 1);
        } else {
            self.n.compiled.set(self.n.compiled.get() + 1);
        }
        Some(r)
    }
    /// The value of invariant `i` in `s` (the evaluator's current state), or None for the tree-walker to decide.
    pub fn run_invariant(&self, ev: &Evaluator, i: usize, s: &StateData, nv: usize) -> Option<bool> {
        let p = match &self.invariants[i] {
            Some(p) if !p.use_.off.get() => p,
            _ => {
                self.n.uncompiled.set(self.n.uncompiled.get() + 1);
                return None;
            }
        };
        let cx = Cx { ev, f: &p.frame, cur: s, nxt: &self.blank, nv: nv as i64, fallbacks: &self.n.fallbacks, cache: None, rec_on: &self.rec_on, rec: &self.rec, cache_always: self.cache_always, meas: &self.meas, cur_ids: &[], out: None, vals: None, fpx: None };
        let f0 = self.n.fallbacks.get();
        let r = (p.run)(&cx);
        p.use_.note(self.n.fallbacks.get() - f0);
        match r {
            Ok(Value::Bool(b)) => {
                self.n.compiled.set(self.n.compiled.get() + 1);
                Some(b)
            }
            _ => {
                self.n.redone.set(self.n.redone.get() + 1);
                None
            }
        }
    }
    /// Whether the step cache is on (it needs the ids of the current state).
    #[inline]
    pub fn caching(&self) -> bool {
        self.cache.is_some()
    }
    /// The step cache is on and some unit uses it at the moment (the others were measured as not paying).
    pub fn caching_now(&self) -> bool {
        self.cache.is_some() && self.units.iter().any(|u| !u.off.get())
    }
    /// What the measurements of the units concluded so far, for `adopt` by the plans of another thread.
    pub fn verdicts(&self) -> Vec<Verdict> {
        self.units
            .iter()
            .map(|u| Verdict {
                loc: u.loc,
                kind: match u.phase.get() {
                    PH_ON => VerdictKind::Pays,
                    PH_OFF => VerdictKind::DoesNotPay { penalty: u.penalty.get(), skip: u.skip.get() },
                    _ => VerdictKind::Unknown,
                },
            })
            .collect()
    }
    /// Takes the verdicts of the plans of the same model on another thread (`verdicts`) for the units
    /// that are still warming up here: a worker of the parallel search need not measure again what the
    /// sequential search measured before it. (They decide how fast, not what: an entry gives the
    /// successors the evaluation would.)
    pub fn adopt(&self, vs: &[Verdict]) {
        if vs.len() != self.units.len() {
            return;
        }
        for (u, v) in self.units.iter().zip(vs) {
            if u.phase.get() != PH_WARM || v.loc != u.loc {
                continue;
            }
            match v.kind {
                VerdictKind::Pays => {
                    u.mark.set(u.hits.get());
                    u.mark_l.set(u.lookups.get());
                    u.off.set(false);
                    u.enter(PH_ON);
                }
                VerdictKind::DoesNotPay { penalty, skip } => {
                    u.penalty.set(penalty);
                    u.skip.set(skip);
                    u.off.set(true);
                    u.enter(PH_OFF);
                }
                VerdictKind::Unknown => {}
            }
        }
    }
    /// To be called before each state is expanded (the step cache measures the time between such calls).
    #[inline]
    pub fn tick(&self) {
        self.meas.tick();
    }
    pub fn report(&self) -> String {
        let c = &self.n;
        let mut cache = String::new();
        if let Some(t) = &self.cache {
            let t = t.borrow();
            let off = self.units.iter().filter(|u| u.off.get()).count();
            let m: [u64; 4] = std::array::from_fn(|i| t.memo[i].get());
            cache = format!(
                "step cache: budget {:.1} MB, in use {:.1} MB (peak {:.1} MB); {} units, {} measured as not paying; {} lookups, {} hits ({:.2}%), {} stored, {} replaced, {} not stored for size, {} evaluations not cacheable; changes applied {} times, {} computed; locations looked up {} times, {} computed\n",
                t.budget as f64 / 1048576.0,
                t.used as f64 / 1048576.0,
                t.peak as f64 / 1048576.0,
                self.units.len(),
                off,
                self.units.iter().map(|u| u.lookups.get()).sum::<u64>(),
                self.units.iter().map(|u| u.hits.get()).sum::<u64>(),
                100.0 * self.units.iter().map(|u| u.hits.get()).sum::<u64>() as f64 / self.units.iter().map(|u| u.lookups.get()).sum::<u64>().max(1) as f64,
                t.n.stored,
                t.n.replaced,
                t.n.too_big,
                t.n.uncacheable,
                m[0],
                m[1],
                m[2],
                m[3]
            );
            if std::env::var_os("EVERYSTATE_EVAL_DEBUG").is_some() {
                for u in &self.units {
                    cache += &format!(
                        "  unit at line {} col {}: {} lookups, {} hits{}; last verdict on {:.0} ns per state without against {:.0} ns with the cache ({} states)\n",
                        u.loc[0],
                        u.loc[1],
                        u.lookups.get(),
                        u.hits.get(),
                        if u.off.get() { " (does not pay)" } else { "" },
                        u.last.get().0,
                        u.last.get().1,
                        u.trials.get()
                    );
                }
            }
        }
        cache + &format!(
            "compiled evaluator: {} of {} actions and {} of {} invariants compiled; evaluations: {} compiled, {} by the tree-walker (not compiled), {} redone by the tree-walker after a failed attempt; {} fallback expressions evaluated inside compiled code\n",
            self.actions.iter().filter(|a| a.is_some()).count(),
            self.actions.len(),
            self.invariants.iter().filter(|a| a.is_some()).count(),
            self.invariants.len(),
            c.compiled.get(),
            c.uncompiled.get(),
            c.redone.get(),
            c.fallbacks.get()
        )
    }
}