tclrs 0.4.0

Tcl as a fusevm frontend: a parser and compiler to fusevm::Chunk, with no bespoke VM or JIT
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
//! Running a compiled chunk: the numeric hook and extension ops that give
//! fusevm Tcl's arithmetic, the driver that owns interpreter state, error
//! unwinding and coroutine switching, and Tcl's number formatting.
//!
//! Two hooks carry all of the language-specific behavior:
//!
//! * the **numeric hook** catches operands the VM cannot compute on natively —
//!   strings, mostly — and applies Tcl's rules: an operand that parses as a
//!   number is one, comparisons fall back to string order when it does not, and
//!   arithmetic on a non-number is an error;
//! * the **extension handler** implements the operators whose Tcl meaning
//!   differs from the VM's generic one: `/` and `%` floor toward negative
//!   infinity, `**` stays integral for integral operands.
//!
//! Everything else runs as native ops, so the arithmetic the JIT cares about
//! stays visible to it.
//!
//! Three layers sit on top of that, and they are one mechanism rather than
//! three:
//!
//! * an [`Interp`] owns the variables and holds them between evaluations, which
//!   is what makes a REPL a REPL and what lets the `eval` command run a script
//!   built at run time and see the same state the script that built it sees;
//! * a `Machine` drives one evaluation. A script that uses no coroutine is
//!   one VM run in a loop that only ever restarts it at a `catch` handler; a
//!   script that creates coroutines has one VM per context, and the same loop
//!   also services the requests their ops raise. Both paths share one
//!   mechanism: an op stashes something in a cell and halts, and the driver
//!   reads the cell after `run()` returns — the pattern fusevm's scheduler is
//!   built on;
//! * `Hooks::install` is the only place a hook is put on a VM, so the main
//!   VM, every coroutine's VM and every nested `eval`'s VM behave alike.
//!
//! The two ways of holding variables meet at `seed` and `flush`. Within one
//! evaluation every VM runs the same chunk, so the global table is a `Vec` the
//! driver moves into whichever VM is about to run. Across evaluations the chunk
//! differs — a chunk interns its own name table — so the interpreter keeps the
//! variables keyed by name and the vector is projected out of that map on entry
//! and read back into it on exit.
//!
//! The VM is asked for its highest tier: `Hooks::install` also calls
//! `enable_tracing_jit`, which makes `VM::run` consult fusevm's block JIT for a
//! wholly-eligible chunk and arm the trace recorder at every backward branch
//! otherwise. [`crate::tiers`] reports which of those tiers a given script
//! actually reaches — see the JIT section of the README for what that measures
//! on Tcl today.

use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::io::Write;
use std::sync::{Arc, Mutex};

use fusevm::{Chunk, Frame, NumOp, VMResult, Value, VM};
use num_bigint::BigInt;
use num_traits::{FromPrimitive, Signed, ToPrimitive, Zero};

use crate::cache::ChunkCache;
use crate::compiler::{ext, ext_wide, Place};
use crate::coro::{self, Request};
use crate::list;

/// The outcome of running a script.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Outcome {
    /// The value of the script's last command.
    pub result: String,
    /// Everything the script wrote to stdout.
    pub output: String,
}

/// A script that would not compile, or that failed while running.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TclError {
    /// The message, in the reference interpreter's wording.
    pub msg: String,
    /// The 1-based script line, when the failure was located while compiling.
    /// A failure raised by a running chunk carries no line, as the reference
    /// interpreter's does not either.
    pub line: Option<usize>,
}

impl TclError {
    pub(crate) fn plain(msg: impl Into<String>) -> Self {
        TclError {
            msg: msg.into(),
            line: None,
        }
    }
}

impl fmt::Display for TclError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.line {
            Some(line) => write!(f, "{} (line {line})", self.msg),
            None => f.write_str(&self.msg),
        }
    }
}

impl std::error::Error for TclError {}

/// Parse and lower a script, with both failures reported the same way.
///
/// The interpreter reaches the same lowering through [`crate::cache`], which
/// keeps what it compiled; this is the entry for the callers that want the
/// chunk itself — the ahead-of-time compiler, the tier report, and `--disasm`.
pub fn compile(src: &str) -> Result<Chunk, String> {
    // As in [`crate::cache::ChunkCache::compile`]: an inline `rust { ... }`
    // block is rewritten into a command before the parser sees the script.
    let rewritten = crate::rust_ffi::desugar(src);
    let script = crate::parser::parse(&rewritten).map_err(|e| e.to_string())?;
    crate::compiler::compile(&script).map_err(|e| e.to_string())
}

/// Compile and run a script in a fresh interpreter, capturing its output.
///
/// A one-shot convenience over [`Interp`]: the state it builds is discarded
/// when it returns.
pub fn eval(src: &str) -> Result<Outcome, String> {
    let (result, output) = eval_captured(src);
    result.map(|result| Outcome { result, output })
}

/// Compile and run a script, reporting what it wrote even when it fails.
///
/// [`eval`] drops the output of a failing script, which is the convenient
/// shape for a caller that only wants the value. A conformance harness needs
/// both halves: a Tcl program that prints and then fails has an observable
/// outcome on stdout as well as an error, and comparing only the error would
/// let a divergence in the printed part go unnoticed.
pub fn eval_captured(src: &str) -> (Result<String, String>, String) {
    let mut interp = Interp::capturing();
    let result = interp.eval(src).map_err(|e| e.to_string());
    (result, interp.take_output())
}

// ── the interpreter ──────────────────────────────────────────────────────

/// How deep `eval` may nest before the interpreter refuses to go further —
/// `interp recursionlimit`'s default in the reference interpreter, and the same
/// message when it is reached.
///
/// A nested script runs on a VM of its own, so nesting costs native stack.
/// Refusing at a fixed depth turns what would be a stack overflow — a signal,
/// not an error — into a script error the script can be blamed for. A host
/// running on a small stack should lower it with
/// [`Interp::set_recursion_limit`]; [`RECOMMENDED_STACK`] is what this default
/// needs.
pub const DEFAULT_RECURSION_LIMIT: usize = 1000;

/// The thread stack [`DEFAULT_RECURSION_LIMIT`] levels of nesting need, with
/// room to spare for an unoptimized build. The `tclrs` binary runs on a thread
/// this size; a host embedding the library and keeping the default limit needs
/// as much.
pub const RECOMMENDED_STACK: usize = 256 * 1024 * 1024;

/// Where an interpreter's scripts write.
///
/// One of these per interpreter, cloned into every VM's sink, so a coroutine's
/// output and a nested `eval`'s output land in the same place and in the order
/// they were produced. The stdout form buffers: a script that prints in a loop
/// should not be measuring one syscall per line.
#[derive(Clone)]
enum Output {
    Capture(Arc<Mutex<String>>),
    Stdout(Arc<Mutex<std::io::BufWriter<std::io::Stdout>>>),
}

impl Output {
    fn stdout() -> Output {
        Output::Stdout(Arc::new(Mutex::new(std::io::BufWriter::new(
            std::io::stdout(),
        ))))
    }

    fn write(&self, s: &str) {
        match self {
            Output::Capture(buf) => buf.lock().expect("output lock").push_str(s),
            Output::Stdout(out) => {
                let _ = out.lock().expect("output lock").write_all(s.as_bytes());
            }
        }
    }

    /// Push what is buffered out to the operating system. Called at the end of
    /// every evaluation, so an error the caller prints afterwards cannot
    /// overtake the output of the script that raised it.
    fn flush(&self) {
        if let Output::Stdout(out) = self {
            let _ = out.lock().expect("output lock").flush();
        }
    }
}

/// Everything an interpreter carries between evaluations.
///
/// It lives behind an `Arc<Mutex<…>>` because a running chunk reaches back into
/// it: the `eval` command compiles and runs a nested script from inside the
/// extension handler of the chunk that invoked it. No lock is ever held across
/// a `VM::run`, so that nesting can go as deep as `limit` allows.
struct State {
    /// The variables, keyed by name. This is the authority, not the VM's slot
    /// vector — see `seed`.
    globals: HashMap<String, Value>,
    cache: ChunkCache,
    /// Where the scripts of this interpreter write.
    output: Output,
    /// How many scripts are running, counting the outermost.
    depth: usize,
    limit: usize,
    /// The contexts whose VMs are running, outermost first: the coroutine's
    /// name, or `None` for a script's own main context.
    ///
    /// A nested script runs a machine of its own, which cannot see the machine
    /// that started it. This is what lets a `yield` in an `eval`'d script tell
    /// that it is inside a coroutine, and say so, rather than report the
    /// reference interpreter's message for a `yield` that is in no coroutine.
    running: Vec<Option<String>>,
}

type Shared = Arc<Mutex<State>>;

/// A Tcl interpreter: the variables of a session, and the chunks compiled for
/// it.
///
/// Every evaluation runs against the same state, so a variable set by one
/// survives into the next. That is what a REPL needs, and what the `eval`
/// command needs, and the two are the same mechanism.
pub struct Interp {
    shared: Shared,
}

impl Interp {
    /// An interpreter whose scripts write to the process's stdout.
    pub fn new() -> Self {
        Interp::with_output(Output::stdout())
    }

    /// An interpreter that collects what its scripts write, for
    /// [`Interp::take_output`].
    pub fn capturing() -> Self {
        Interp::with_output(Output::Capture(Arc::new(Mutex::new(String::new()))))
    }

    fn with_output(output: Output) -> Self {
        Interp {
            shared: Arc::new(Mutex::new(State {
                globals: HashMap::new(),
                cache: ChunkCache::new(),
                output,
                depth: 0,
                limit: DEFAULT_RECURSION_LIMIT,
                running: Vec::new(),
            })),
        }
    }

    /// How deep `eval` may nest. Lower it when the interpreter runs on a stack
    /// smaller than [`RECOMMENDED_STACK`], because the depth is the only thing
    /// standing between a runaway script and a stack overflow.
    pub fn set_recursion_limit(&mut self, limit: usize) {
        self.lock().limit = limit.max(1);
    }

    /// Compile and run a script, returning the value of its last command.
    pub fn eval(&mut self, src: &str) -> Result<String, TclError> {
        run_source(&self.shared, src).map(|v| to_tcl_string(&v))
    }

    /// Run a chunk this interpreter did not compile, against its variables.
    ///
    /// [`Interp::eval`] is the ordinary way in, and it compiles through the
    /// cache. This is for a caller holding a chunk that was lowered
    /// differently — the debug adapter runs
    /// [`crate::compiler::compile_debug`]'s output, which is the same script
    /// with a line marker before every command.
    pub fn run_chunk(&mut self, chunk: fusevm::Chunk) -> Result<String, TclError> {
        Machine::run(&self.shared, chunk).map(|v| to_tcl_string(&v))
    }

    /// Set a variable from the host — how the binary supplies `argv0`, `argc`
    /// and `argv`.
    pub fn set_global(&mut self, name: &str, value: impl Into<String>) {
        let value = Value::Str(Arc::new(value.into()));
        self.lock().globals.insert(name.to_string(), value);
    }

    /// Read a variable's string form, or `None` when it is not set.
    pub fn global(&self, name: &str) -> Option<String> {
        self.lock().globals.get(name).map(to_tcl_string)
    }

    /// Every variable this interpreter holds, sorted. The REPL completes `$`
    /// from it; nothing about evaluation reads it. An array is one variable
    /// here, under its own name — its elements are inside its value, and
    /// `array names` is what lists those.
    pub fn global_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.lock().globals.keys().cloned().collect();
        names.sort();
        names
    }

    /// Take everything captured so far, leaving the buffer empty. Always empty
    /// for an interpreter built by [`Interp::new`], which does not capture.
    pub fn take_output(&mut self) -> String {
        match &self.lock().output {
            Output::Capture(buf) => std::mem::take(&mut buf.lock().expect("output lock")),
            Output::Stdout(_) => String::new(),
        }
    }

    /// `(hits, misses)` from the chunk cache — one miss per compilation.
    pub fn cache_stats(&self) -> (u64, u64) {
        self.lock().cache.stats()
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, State> {
        self.shared.lock().expect("interpreter lock")
    }
}

impl Default for Interp {
    fn default() -> Self {
        Interp::new()
    }
}

/// Compile `src` — reusing the cached chunk when the same text has been
/// evaluated before — and run it against `shared`.
fn run_source(shared: &Shared, src: &str) -> Result<Value, TclError> {
    let compiled = {
        let mut state = shared.lock().expect("interpreter lock");
        // The limit counts nested evaluations, so the outermost script — the
        // one that is not nested in anything — does not spend a level, as it
        // does not in the reference interpreter.
        if state.depth > state.limit {
            return Err(TclError::plain(
                "too many nested evaluations (infinite loop?)",
            ));
        }
        state.depth += 1;
        state.cache.compile(src)
    };
    // The depth is given back however this returns, including the compile
    // failure above, which is why it is not a `?` in the block.
    let result = compiled.and_then(|chunk| {
        // `VM::new` takes the chunk by value, so the cached one is cloned
        // rather than moved out; the parse and the lowering are what the cache
        // saves.
        Machine::run(shared, (*chunk).clone())
    });
    shared.lock().expect("interpreter lock").depth -= 1;
    result
}

/// A chunk interns its own name table, so the slot holding a given variable
/// differs from chunk to chunk and a slot vector cannot be carried from one run
/// to the next. The interpreter's map is the authority; a chunk's slots are a
/// projection of it, built here on entry and read back by `flush` on exit.
fn seed(chunk: &Chunk, shared: &Shared) -> Vec<Value> {
    let state = shared.lock().expect("interpreter lock");
    chunk
        .names
        .iter()
        .map(|name| state.globals.get(name).cloned().unwrap_or(Value::Undef))
        .collect()
}

/// Write a finished chunk's slots back into the interpreter's variables. A slot
/// left `Undef` — never assigned, or unset — removes the variable rather than
/// storing an empty value, so `unset` survives into the next evaluation.
fn flush(chunk: &Chunk, shared: &Shared, globals: &[Value]) {
    let mut state = shared.lock().expect("interpreter lock");
    for (slot, name) in chunk.names.iter().enumerate() {
        // The compiler's own loop state is named with a leading NUL so that no
        // Tcl variable can collide with it. It is rebuilt on every entry to the
        // loop that owns it, so it is not interpreter state.
        if name.starts_with('\u{0}') {
            continue;
        }
        match globals.get(slot) {
            Some(Value::Undef) | None => {
                state.globals.remove(name);
            }
            Some(value) => {
                state.globals.insert(name.clone(), value.clone());
            }
        }
    }
}

// ── the hooks ────────────────────────────────────────────────────────────

/// A `catch` region the VM has entered and not yet left.
///
/// The two depths are what makes resuming possible: an error can be raised
/// anywhere below, including inside a procedure the guarded script called, and
/// restoring them puts the VM back exactly where the handler was compiled to
/// expect it.
struct CatchFrame {
    /// Op index of the handler block the compiler emitted for this region.
    handler: usize,
    /// Value-stack length when the region was entered.
    stack: usize,
    /// Call-frame count when the region was entered.
    frames: usize,
}

/// Install everything a Tcl chunk needs on a VM — the output sink, the numeric
/// hook, the extension dispatch and fusevm's tracing JIT — for a caller that
/// drives the VM itself rather than through an [`Interp`].
///
/// That caller is fusevm's ahead-of-time entry ([`crate::aot_runtime`]), which
/// owns the run and never hands control back mid-way. `catch` and coroutines
/// need a driver that does, so [`crate::aot`] refuses a script using either
/// before it compiles one.
pub fn install_hooks(vm: &mut VM) -> Hooks {
    let hooks = Hooks::new(Interp::new().shared);
    hooks.install(vm);
    hooks
}

/// The same, with the script's output collected into `buf` rather than written
/// to stdout — what the in-process ahead-of-time run reads back.
///
/// It has to be installed here rather than by replacing the VM's output sink
/// afterwards, because `puts` is a frontend op and writes through these hooks
/// rather than through the VM (see [`ext::PUTS`]); a sink swapped in after the
/// fact would catch only what fusevm's own ops print.
pub fn install_hooks_capturing(vm: &mut VM, buf: Arc<Mutex<String>>) -> Hooks {
    let hooks = Hooks::new(Interp::with_output(Output::Capture(buf)).shared);
    hooks.install(vm);
    hooks
}

/// The cells every VM's hooks write into. One set is shared by the main VM and
/// every coroutine's; the driver swaps the per-context ones (`catches`,
/// `current`) around each `run()`, so a hook never has to know which VM it is
/// running inside.
pub struct Hooks {
    /// Where the script's writes go.
    output: Output,
    error: Arc<Mutex<Option<TclError>>>,
    /// `catch` regions the *running* VM has entered and not yet left.
    catches: Arc<Mutex<Vec<CatchFrame>>>,
    /// The coroutine request an op raised, for the driver to service.
    pending: Arc<Mutex<Option<Request>>>,
    /// The name of the coroutine whose VM is running, for `info coroutine`.
    current: Arc<Mutex<Option<String>>>,
    /// The interpreter a nested `eval` runs against.
    interp: Shared,
}

impl Hooks {
    fn new(interp: Shared) -> Hooks {
        let output = interp.lock().expect("interpreter lock").output.clone();
        Hooks {
            output,
            error: Arc::new(Mutex::new(None)),
            catches: Arc::new(Mutex::new(Vec::new())),
            pending: Arc::new(Mutex::new(None)),
            current: Arc::new(Mutex::new(None)),
            interp,
        }
    }

    /// The message an extension op parked, if one did. What an ahead-of-time
    /// run reports: fusevm's AOT entry maps the VM's result to an exit code and
    /// cannot see an error the frontend raised.
    pub fn take_error(&self) -> Option<String> {
        self.error.lock().expect("error lock").take().map(|e| e.msg)
    }

    /// Give `vm` the frontend's hooks. This is the only place a hook is
    /// installed, so a coroutine prints to the same stdout, raises errors
    /// through the same cell, evaluates nested scripts against the same
    /// variables and reaches the same JIT tiers as the script that created it.
    fn install(&self, vm: &mut VM) {
        let sink = self.output.clone();
        vm.set_output_sink(Box::new(move |s: &str| sink.write(s)));
        // Sited rather than plain, so `incr`'s operand refusal can be worded
        // as `incr`'s: it and `expr {$x + 1}` lower to the same `Op::Add` on
        // the same value, and only the site tells them apart. Keeping the
        // arithmetic a native op is what keeps a counted loop traced, so the
        // distinction cannot live in an extension op here.
        vm.set_sited_numeric_hook(Arc::new(|call: fusevm::NumericCall<'_>| {
            // At an `incr` site the operands are held to `incr`'s rule before
            // the arithmetic runs, not after it fails: `incr` takes an integer,
            // so `set x 1.5; incr x` is refused where the addition would
            // happily have answered 2.5. An operand that *is* an integer falls
            // through, so promotion to a bignum still works here.
            if is_incr_site(call.chunk, call.ip) {
                if let Some(e) = incr_operand_error(call.a, call.b) {
                    return Err(e);
                }
            }
            numeric(call.op, call.a, call.b)
        }));
        // Reading a variable that was never assigned is an error in Tcl, not
        // the empty string. fusevm calls this for every variable read that
        // finds `Undef` (`VM::set_undef_hook`); answering here rather than
        // through a frontend op is what keeps the read a native op, and a
        // counted loop traced — an extension op in a loop body costs that loop
        // its JIT trace.
        vm.set_undef_hook(Arc::new(|read: fusevm::UndefRead<'_>| {
            if tolerates_undef(read.chunk, read.ip) {
                // `incr x` on a variable that does not exist creates it at
                // zero. It is the same read op on the same name as `$x`, so
                // only the site tells them apart.
                return Ok(Value::Undef);
            }
            match read.name {
                // The compiler generates hidden globals for its own loop
                // state, named so that no script can spell them. One reaching
                // here is not a script's variable and must not be reported as
                // one.
                Some(name) if !name.starts_with('\u{0}') => {
                    Err(format!("can't read \"{name}\": no such variable"))
                }
                // fusevm builds this read's `UndefRead` with `name: None` for a
                // frame slot, so a procedure's local keeps the old reading:
                // `Undef` is exactly that reading. The chunk *does* carry the
                // names now — `src/procs.rs` publishes them and `uplevel` and
                // `apply` run against them — so what is left is for fusevm to
                // resolve one at its `Op::GetSlot` arm. See BUGS.md.
                _ => Ok(Value::Undef),
            }
        }));

        let err_cell = Arc::clone(&self.error);
        let open = Arc::clone(&self.catches);
        let pending = Arc::clone(&self.pending);
        let current = Arc::clone(&self.current);
        let interp = Arc::clone(&self.interp);
        // `puts` writes here rather than through fusevm's `PrintLn`, so that
        // what reaches the channel is Tcl's string form of the value; see
        // [`ext::PUTS`]. It is the same sink the VM's own output goes to, so
        // the two interleave in the order the script wrote them.
        let out = self.output.clone();
        vm.set_extension_handler(Box::new(move |vm: &mut VM, id: u16, arg: u8| {
            if id == ext::CATCH_END {
                open.lock().expect("catch lock").pop();
                return;
            }
            if id == ext::PUTS {
                let mut text = to_tcl_string(&vm.pop());
                if arg == 1 {
                    text.push('\n');
                }
                out.write(&text);
                vm.push(Value::Str(Arc::new(String::new())));
                return;
            }
            if coro::is_op(id) {
                let name = current.lock().expect("coroutine lock").clone();
                if let Some(request) = coro::extension(vm, id, arg, name.as_deref()) {
                    *pending.lock().expect("request lock") = Some(request);
                    vm.request_halt();
                }
                return;
            }
            let outcome = match id {
                ext::EVAL => eval_op(&interp, vm, arg),
                // `info globals` / `vars` answer from the interpreter's own
                // table, not the chunk's name pool: `argc`, `argv` and `argv0`
                // are set by the host and are interned only if the script
                // happens to mention them, so a chunk-only answer omits exactly
                // the variables every script starts with.
                crate::cmd_info::ext::NAMES => info_names_op(&interp, vm, arg),
                ext::EVAL_FRAME => eval_frame_op(&interp, vm, arg),
                ext::UPLEVEL => uplevel_op(&interp, vm, arg),
                ext::APPLY => apply_op(&interp, vm, arg),
                ext::FFI_CALL => ffi_op(vm, arg).map_err(TclError::plain),
                _ => extension(vm, id, arg).map_err(TclError::plain),
            };
            if let Err(e) = outcome {
                *err_cell.lock().expect("error lock") = Some(e);
                // `VM::run` pops one value when it stops, so leave it one to
                // pop: the stack then still holds what the failing op left, and
                // the catch driver's depth arithmetic stays exact.
                vm.push(Value::Undef);
                vm.request_halt();
            }
        }));

        let entered = Arc::clone(&self.catches);
        let wide_err = Arc::clone(&self.error);
        vm.set_extension_wide_handler(Box::new(move |vm: &mut VM, id: u16, payload: usize| {
            if id == ext_wide::DBG_LINE {
                // Only a chunk compiled by `compile_debug` carries these, and
                // only `--dap` answers them; without a session attached this is
                // one `Option` check.
                crate::dap::at_line(vm, payload);
                return;
            }
            if id == ext_wide::ERROR_AT {
                // A failure the compiler found and lowered as code (see
                // `Compiler::defer`). It carries the line the refusal would have
                // been reported at, so deferring it costs the diagnostic
                // nothing but its timing.
                let msg = to_tcl_string(&vm.pop());
                *wide_err.lock().expect("error lock") = Some(TclError {
                    msg,
                    line: Some(payload),
                });
                vm.push(Value::Undef);
                vm.request_halt();
                return;
            }
            if id == ext_wide::CATCH {
                entered.lock().expect("catch lock").push(CatchFrame {
                    handler: payload,
                    stack: vm.stack.len(),
                    frames: vm.frames.len(),
                });
            }
        }));

        // Hot loops trace-compile through fusevm's Cranelift JIT, and a chunk
        // the block tier can take whole runs in native code with no dispatch
        // loop at all. With `jit-disk-cache` the compiled code outlives the
        // process.
        if jit_enabled() {
            vm.enable_tracing_jit();
        }
    }
}

/// Whether to arm the JIT — off when `TCLRS_JIT` is `off`, `0` or `no`.
///
/// The switch exists so the benchmark can measure the interpreter and the
/// JIT-armed VM as separate rows on the same binary — which cuts both ways. A
/// loop inside a procedure trace-compiles and the JIT row is a large win; a loop
/// at a script's top level cannot, and then arming the tier is pure cost: the
/// dispatch loop checks the recorder at every op and consults the block tier once
/// per run.
fn jit_enabled() -> bool {
    !matches!(
        std::env::var("TCLRS_JIT").as_deref(),
        Ok("off") | Ok("0") | Ok("no")
    )
}

/// A call to a function an inline `rust { ... }` block exported: the name was
/// pushed first, then the arguments. The library is already loaded — the
/// compiler registered it while lowering the block — so this only marshals.
fn ffi_op(vm: &mut VM, argc: u8) -> Result<(), String> {
    let mut values = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        values.push(vm.pop());
    }
    values.reverse();
    let (name, args) = values.split_first().expect("the name is pushed first");
    let result = crate::rust_ffi::call(&to_tcl_string(name), args)?;
    vm.push(result);
    Ok(())
}

/// The `eval` command: concatenate the arguments and run the result as a
/// script, against the state of the interpreter that reached this op.
///
/// The running chunk's slots are written back before the nested script runs and
/// re-read after it, so the two see one set of variables in both directions —
/// including when the nested script fails, since what it did set before failing
/// is set.
/// `info commands` / `procs` / `globals` / `vars`.
///
/// Lives here rather than in `cmd_info` because two of the four can only be
/// answered from [`State::globals`], which the extension handler reaches and a
/// bare `&mut VM` does not.
fn info_names_op(interp: &Shared, vm: &mut VM, which: u8) -> Result<(), TclError> {
    let given = matches!(vm.pop(), Value::Int(1));
    let pattern = to_tcl_string(&vm.pop());
    let filter = given.then_some(pattern.as_str());

    let mut names: Vec<String> = match which {
        // commands: every builtin the compiler dispatches, plus this chunk's
        // procedures.
        0 => crate::compiler::Compiler::BUILTINS
            .iter()
            .map(|s| (*s).to_string())
            .chain(chunk_procs(vm))
            .collect(),
        1 => chunk_procs(vm).collect(),
        // globals and vars: the union of both halves of where a global lives
        // mid-run. The interpreter's table is the authority *between*
        // evaluations and holds what the host set — `argc`, `argv`, `argv0`;
        // the values a running script has assigned are in the VM and are only
        // flushed back when the run ends. Asking either alone omits the other's.
        // A hidden loop-state global is not a script's variable.
        _ => {
            let held: Vec<String> = interp
                .lock()
                .expect("interpreter lock")
                .globals
                .keys()
                .cloned()
                .collect();
            held.into_iter()
                .chain(vm.chunk.names.iter().enumerate().filter_map(|(i, name)| {
                    let set = !matches!(vm.globals.get(i), None | Some(Value::Undef));
                    set.then(|| name.clone())
                }))
                .filter(|name| !name.starts_with('\u{0}'))
                .collect()
        }
    };
    if let Some(p) = filter {
        names.retain(|name| crate::list::glob_match(p, name));
    }
    names.sort();
    names.dedup();
    vm.push(Value::Str(Arc::new(crate::list::join(&names))));
    Ok(())
}

fn eval_op(interp: &Shared, vm: &mut VM, argc: u8) -> Result<(), TclError> {
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(to_tcl_string(&vm.pop()));
    }
    args.reverse();
    // One argument is the script; several are concatenated as `concat` does,
    // which is where `eval $cmd $args` gets its meaning.
    let src = if args.len() == 1 {
        args.remove(0)
    } else {
        crate::cmd_list::concat(&args)
    };

    flush(&vm.chunk, interp, &vm.globals);
    let result = run_source(interp, &src);
    let globals = seed(&vm.chunk, interp);
    vm.globals = globals;
    vm.push(result?);
    Ok(())
}

/// `eval` inside a procedure body: `[declared, arg …]`.
///
/// The script runs against the procedure's own frame, which is what tclsh does —
/// see [`run_in_frame`].
fn eval_frame_op(interp: &Shared, vm: &mut VM, argc: u8) -> Result<(), TclError> {
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(to_tcl_string(&vm.pop()));
    }
    args.reverse();
    let declared = args.remove(0);
    let src = script_of(args);
    // The current level, which is the innermost procedure frame — not the
    // innermost VM frame, which a scope or a side exit may have pushed inside it.
    let up = levels(vm).first().copied().unwrap_or(0);
    run_in_frame(interp, vm, &src, up, &declared)
}

/// `uplevel ?level? arg …`: `[declared, level, arg …]`.
///
/// `#0` is the global level, which is what an ordinary `eval` already runs
/// against; any other level is a frame, counted outwards from this one.
fn uplevel_op(interp: &Shared, vm: &mut VM, argc: u8) -> Result<(), TclError> {
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(to_tcl_string(&vm.pop()));
    }
    args.reverse();
    let declared = args.remove(0);
    let level = args.remove(0);
    let src = script_of(args);

    // The levels this context has: one per active procedure call, which is what
    // Tcl counts. The global level is not one of them — it is what `#0` names,
    // and what a relative level reaches by counting past the outermost call.
    let ups = levels(vm);
    let up = match parse_level(&level, ups.len()) {
        Some(Level::Global) => {
            flush(&vm.chunk, interp, &vm.globals);
            let result = run_source(interp, &src);
            vm.globals = seed(&vm.chunk, interp);
            vm.push(result?);
            return Ok(());
        }
        // A level counted in calls, resolved to the frame that call pushed.
        Some(Level::Up(out)) => match ups.get(out) {
            Some(&up) => up,
            None => return Err(TclError::plain(format!("bad level \"{level}\""))),
        },
        None => return Err(TclError::plain(format!("bad level \"{level}\""))),
    };
    run_in_frame(interp, vm, &src, up, &declared)
}

/// The `up` distances of the frames that are Tcl levels, innermost first.
///
/// A Tcl level is a procedure call, and fusevm pushes a frame for other reasons
/// too: the base frame a script's top level runs in, the frame a scope opens, and
/// one materialized after a JIT side exit. Only a call to a named subroutine
/// records an `entry_ip`, so that is what tells a level from a frame.
///
/// Counting VM frames instead is what made `uplevel 1` at the top level find the
/// base frame and answer, where tclsh reports `bad level "1"` — there is no level
/// above the global one.
fn levels(vm: &VM) -> Vec<usize> {
    let n = vm.frames.len();
    (0..n)
        .filter(|&up| vm.frames[n - 1 - up].entry_ip.is_some())
        .collect()
}

/// Which level a `level` word names.
enum Level {
    /// `#0`, or a relative level that reaches past the outermost call.
    Global,
    /// This many calls outwards from the running one.
    Up(usize),
}

/// Read `uplevel`'s level word the way `Tcl_GetFrame` reads it: `#n` counts from
/// the global level inwards, a bare number counts outwards from here, and
/// anything else is not a level at all.
fn parse_level(word: &str, depth: usize) -> Option<Level> {
    if let Some(abs) = word.strip_prefix('#') {
        let abs: usize = abs.parse().ok()?;
        // `#0` is the global level; `#1` is the outermost frame, and so on.
        if abs == 0 {
            return Some(Level::Global);
        }
        return depth.checked_sub(abs).map(Level::Up);
    }
    let rel: usize = word.parse().ok()?;
    if rel > depth {
        return None;
    }
    if rel == depth {
        Some(Level::Global)
    } else {
        Some(Level::Up(rel))
    }
}

/// One argument is the script; several are concatenated as `concat` does, which
/// is where `eval $cmd $args` gets its meaning — and why `uplevel 1 set y {a b}`
/// loses the braces and becomes three words, as it does in tclsh.
fn script_of(mut args: Vec<String>) -> String {
    if args.len() == 1 {
        args.remove(0)
    } else {
        crate::cmd_list::concat(&args)
    }
}

/// Run `src` against the variables of the frame `up` levels out.
///
/// tclsh runs an `eval`'s script in *exactly* the calling frame's context: a
/// local is visible and writable, a variable the script creates becomes a local,
/// `unset` removes one, and a bare read of a global **refuses** unless the body
/// linked it with `global`. So the interpreter's variable table is replaced for
/// the duration by a projection of that frame — its named slots, plus the names
/// the body declared global — and read back afterwards. Nothing else is visible,
/// which is the half that a projection merely *added* to the globals would get
/// wrong.
fn run_in_frame(
    interp: &Shared,
    vm: &mut VM,
    src: &str,
    up: usize,
    declared: &str,
) -> Result<(), TclError> {
    let names: Vec<String> = vm.slot_names_at(up).to_vec();
    let frame = match vm.frames.len().checked_sub(up + 1) {
        // A frame with no name for its slots — the base frame, a scope frame, or
        // one materialized after a JIT side exit — cannot be projected, so the
        // script runs against the globals, as an ordinary `eval` does.
        Some(_) if names.is_empty() => {
            flush(&vm.chunk, interp, &vm.globals);
            let result = run_source(interp, src);
            vm.globals = seed(&vm.chunk, interp);
            vm.push(result?);
            return Ok(());
        }
        Some(index) => index,
        None => return Err(TclError::plain("bad level".to_string())),
    };
    let declared = crate::list::split(declared).unwrap_or_default();

    // The enclosing chunk's globals are the authority for a declared name, so
    // they go into the table before anything is read out of it.
    flush(&vm.chunk, interp, &vm.globals);
    let outer = std::mem::take(&mut interp.lock().expect("interpreter lock").globals);

    let mut view: HashMap<String, Value> = HashMap::new();
    for name in &declared {
        if let Some(v) = outer.get(name) {
            view.insert(name.clone(), v.clone());
        }
    }
    for (slot, name) in names.iter().enumerate() {
        if name.is_empty() {
            continue;
        }
        match vm.frames[frame].slots.get(slot) {
            Some(v) if *v != Value::Undef => {
                view.insert(name.clone(), v.clone());
            }
            // An unset local is absent rather than empty, so a read of it in the
            // nested script refuses exactly as it would in the body.
            _ => {
                view.remove(name);
            }
        }
    }
    interp.lock().expect("interpreter lock").globals = view;

    let result = run_source(interp, src);

    let after = std::mem::take(&mut interp.lock().expect("interpreter lock").globals);
    for (slot, name) in names.iter().enumerate() {
        if name.is_empty() {
            continue;
        }
        let value = after.get(name).cloned().unwrap_or(Value::Undef);
        let slots = &mut vm.frames[frame].slots;
        if slot >= slots.len() {
            slots.resize(slot + 1, Value::Undef);
        }
        slots[slot] = value;
    }
    let mut outer = outer;
    for name in &declared {
        match after.get(name) {
            Some(v) => outer.insert(name.clone(), v.clone()),
            None => outer.remove(name),
        };
    }
    interp.lock().expect("interpreter lock").globals = outer;
    vm.globals = seed(&vm.chunk, interp);
    vm.push(result?);
    Ok(())
}

/// `apply lambdaExpr ?arg …?`: `[lambda, arg …]`.
///
/// A lambda is a procedure body with its own frame — its parameters are locals,
/// a bare name is a local, a global needs `$::g`, and `return` returns from it —
/// so it is run as one rather than given a second calling convention. The
/// procedure is named with a leading NUL, which no Tcl name can be, and lives
/// only in the chunk built for this call.
fn apply_op(interp: &Shared, vm: &mut VM, argc: u8) -> Result<(), TclError> {
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(to_tcl_string(&vm.pop()));
    }
    args.reverse();
    let lambda = args.remove(0);

    let parts = crate::list::split(&lambda)
        .map_err(|_| TclError::plain(bad_lambda(&lambda)))?;
    let (params, body) = match parts.as_slice() {
        [params, body] => (params, body),
        // The third element is a namespace. This frontend has one namespace, so
        // any other is refused rather than silently ignored.
        [params, body, ns] if ns == "::" || ns.is_empty() => (params, body),
        [_, _, ns] => {
            return Err(TclError::plain(format!(
                "the namespace \"{ns}\" of a lambda is not supported yet: this frontend has only \"::\""
            )))
        }
        _ => return Err(TclError::plain(bad_lambda(&lambda))),
    };

    const NAME: &str = "\u{0}apply";
    let mut src = String::with_capacity(body.len() + params.len() + 32);
    src.push_str("proc ");
    src.push_str(NAME);
    src.push(' ');
    src.push_str(&crate::list::quote(params, false));
    src.push(' ');
    src.push_str(&crate::list::quote(body, false));
    src.push('\n');
    src.push_str(NAME);
    for a in &args {
        src.push(' ');
        src.push_str(&crate::list::quote(a, false));
    }

    flush(&vm.chunk, interp, &vm.globals);
    let result = run_source(interp, &src);
    vm.globals = seed(&vm.chunk, interp);
    // The synthesized name must not surface in a diagnostic the script can see:
    // tclsh reports a lambda's arity against `apply lambdaExpr`.
    vm.push(result.map_err(|e| TclError::plain(rename_lambda(&e.msg)))?);
    Ok(())
}

fn bad_lambda(lambda: &str) -> String {
    format!("can't interpret \"{lambda}\" as a lambda expression")
}

/// Replace the synthesized procedure's name in a diagnostic with what tclsh
/// names: `apply lambdaExpr`, followed by the lambda's own parameters.
fn rename_lambda(msg: &str) -> String {
    msg.replace("\u{0}apply", "apply lambdaExpr")
}

// ── the driver ───────────────────────────────────────────────────────────

/// How a context is suspended, which decides what resuming it may pass in.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Park {
    /// Running, or about to be — the main script's context always is.
    Running,
    /// Suspended by `yield`, which takes at most one resumption value.
    AtYield,
    /// Suspended by `yieldto`, whose value is the whole resumption argument
    /// list.
    AtYieldTo,
}

/// One execution context: the main script, or a live coroutine.
struct Context {
    /// `None` once the context has been retired.
    vm: Option<VM>,
    /// The `catch` regions this context has open, parked while another runs.
    catches: Vec<CatchFrame>,
    /// The coroutine's name; `None` for the main script.
    name: Option<String>,
    /// Where control goes when this context yields, finishes or fails.
    resumer: Option<usize>,
    park: Park,
}

/// The driver of one evaluation: every execution context of one script, and
/// the loop that runs them.
struct Machine {
    hooks: Hooks,
    /// The compiled program, from which each coroutine's VM is built.
    chunk: Chunk,
    contexts: Vec<Context>,
    /// Live coroutines by name. A name leaves as soon as its body ends, which
    /// is what makes a later call report `invalid command name`.
    live: HashMap<String, usize>,
    /// Every name this run has ever made a coroutine of, so a `yieldto` at a
    /// name that is not one can be told apart from one at a coroutine that has
    /// since finished.
    created: HashSet<String>,
    /// The one global variable table, moved into whichever VM runs.
    globals: Vec<Value>,
    /// The context currently running.
    current: usize,
}

impl Machine {
    /// Run one chunk against the interpreter's variables, from the first op to
    /// the end of the main context.
    fn run(shared: &Shared, chunk: Chunk) -> Result<Value, TclError> {
        let hooks = Hooks::new(Arc::clone(shared));
        let mut main = VM::new(chunk.clone());
        hooks.install(&mut main);
        let globals = seed(&chunk, shared);

        let mut machine = Machine {
            hooks,
            chunk,
            contexts: vec![Context {
                vm: Some(main),
                catches: Vec::new(),
                name: None,
                resumer: None,
                park: Park::Running,
            }],
            live: HashMap::new(),
            created: HashSet::new(),
            globals,
            current: 0,
        };
        let outcome = machine.drive();
        // The variables a failing script did set are still set, as they are in
        // the reference interpreter, so the write-back happens either way.
        flush(&machine.chunk, shared, &machine.globals);
        // Likewise the output: an error the caller prints must not overtake
        // what the failing script had already written.
        machine.hooks.output.flush();

        match outcome? {
            VMResult::Ok(v) => Ok(v),
            VMResult::Halted => Ok(Value::Str(Arc::new(String::new()))),
            VMResult::Error(e) => Err(TclError::plain(e)),
        }
    }

    /// Run contexts until the main script finishes or an error escapes it.
    fn drive(&mut self) -> Result<VMResult, TclError> {
        loop {
            let outcome = self.run_current();

            let raised = self
                .hooks
                .error
                .lock()
                .expect("error lock")
                .take()
                .or_else(|| match &outcome {
                    VMResult::Error(e) => Some(TclError::plain(e.clone())),
                    _ => None,
                });
            if let Some(e) = raised {
                self.raise(e)?;
                continue;
            }

            let request = self.hooks.pending.lock().expect("request lock").take();
            if let Some(request) = request {
                // The op halted mid-expression, so `run` popped a live value
                // from underneath it. Put it back before anything else touches
                // this stack.
                if let VMResult::Ok(v) = outcome {
                    self.vm(self.current).stack.push(v);
                }
                if let Err(e) = self.service(request) {
                    self.raise(e)?;
                }
                continue;
            }

            // Nothing was raised and nothing was requested: this context ran to
            // the end of its program.
            if self.current == 0 {
                return Ok(outcome);
            }
            self.retire(outcome);
        }
    }

    /// Swap the running context's state in, run its VM, and take the state back
    /// out. Only one VM runs at a time, so the global table and the open
    /// `catch` regions move rather than being copied.
    fn run_current(&mut self) -> VMResult {
        let current = self.current;
        let name = self.contexts[current].name.clone();
        *self.hooks.current.lock().expect("coroutine lock") = name.clone();
        *self.hooks.catches.lock().expect("catch lock") =
            std::mem::take(&mut self.contexts[current].catches);
        let globals = std::mem::take(&mut self.globals);
        // A script this VM starts runs a machine of its own, which reads this to
        // see what is running around it — see `State::running`.
        self.hooks
            .interp
            .lock()
            .expect("interpreter lock")
            .running
            .push(name);

        let vm = self.vm(current);
        vm.globals = globals;
        vm.clear_halt();
        let outcome = vm.run();
        let globals = std::mem::take(&mut vm.globals);
        self.hooks
            .interp
            .lock()
            .expect("interpreter lock")
            .running
            .pop();

        self.globals = globals;
        self.contexts[current].catches =
            std::mem::take(&mut self.hooks.catches.lock().expect("catch lock"));
        outcome
    }

    fn vm(&mut self, context: usize) -> &mut VM {
        self.contexts[context].vm.as_mut().expect("live context")
    }

    /// Report a Tcl error in the running context: resume at its innermost open
    /// `catch` handler, or — for a coroutine with none — end the coroutine and
    /// report the error to whoever resumed it, as the reference implementation
    /// does. `Err` means nothing was left to catch it.
    fn raise(&mut self, e: TclError) -> Result<(), TclError> {
        loop {
            if let Some(frame) = self.contexts[self.current].catches.pop() {
                let vm = self.vm(self.current);
                // Unwind to the guarded script's entry state and hand the
                // handler the message.
                vm.frames.truncate(frame.frames);
                vm.stack.truncate(frame.stack);
                vm.stack.resize(frame.stack, Value::Undef);
                vm.push(Value::Str(Arc::new(e.msg)));
                vm.ip = frame.handler;
                return Ok(());
            }
            if self.current == 0 {
                return Err(e);
            }
            match self.discard(self.current) {
                Some(resumer) => self.current = resumer,
                None => return Err(e),
            }
        }
    }

    /// The running coroutine's body returned: its value is the value of the
    /// call that resumed it, and the coroutine is gone.
    fn retire(&mut self, outcome: VMResult) {
        let result = match outcome {
            VMResult::Ok(v) => v,
            _ => Value::Str(Arc::new(String::new())),
        };
        let resumer = self
            .discard(self.current)
            .expect("a running coroutine has a resumer");
        self.vm(resumer).stack.push(result);
        self.current = resumer;
    }

    /// Delete a coroutine's context, answering where control returns to.
    fn discard(&mut self, context: usize) -> Option<usize> {
        if let Some(name) = self.contexts[context].name.take() {
            self.live.remove(&name);
        }
        self.contexts[context].vm = None;
        self.contexts[context].catches.clear();
        self.contexts[context].resumer.take()
    }

    /// Service one coroutine request. `Err` is a Tcl error raised in the
    /// context that made the request.
    fn service(&mut self, request: Request) -> Result<(), TclError> {
        self.service_inner(request).map_err(TclError::plain)
    }

    fn service_inner(&mut self, request: Request) -> Result<(), String> {
        match request {
            Request::Create {
                name,
                command,
                args,
            } => self.create(name, &command, args),
            Request::Resume { name, args } => {
                let target = self.suspended(&name)?;
                let value = self.resumption(target, &name, args)?;
                let resumer = self.current;
                self.enter(target, value, Some(resumer));
                Ok(())
            }
            Request::Yield(value) => {
                self.in_coroutine("yield")?;
                self.contexts[self.current].park = Park::AtYield;
                let resumer = self.contexts[self.current]
                    .resumer
                    .take()
                    .expect("a running coroutine has a resumer");
                self.vm(resumer).stack.push(value);
                self.current = resumer;
                Ok(())
            }
            Request::YieldTo { name, args } => {
                self.in_coroutine("yieldto")?;
                // `info coroutine` reports a qualified name and the juggler
                // example cedes control to exactly that; with one namespace,
                // `::c` and `c` are the same command.
                let name = name.strip_prefix("::").unwrap_or(&name).to_string();
                if !self.created.contains(&name) {
                    // A `yieldto` whose target is a word could name any
                    // command; only a coroutine of this script can be ceded to.
                    return Err(format!(
                        "\"yieldto {name}\": ceding control to a command that is not a \
                         coroutine of this script is not supported"
                    ));
                }
                let target = self.suspended(&name)?;
                // The argument check happens before control moves, so a bad
                // one is an error in the coroutine that wrote the `yieldto`.
                let value = self.resumption(target, &name, args)?;
                self.contexts[self.current].park = Park::AtYieldTo;
                // The target inherits this coroutine's resumer: whatever it
                // eventually produces is the value of the call that got us
                // here, and this coroutine now has nowhere of its own to
                // return to until something resumes it.
                let inherited = self.contexts[self.current].resumer.take();
                self.enter(target, value, inherited);
                Ok(())
            }
        }
    }

    /// `coroutine name command ?arg…?`: a fresh VM over the same chunk,
    /// positioned at the command's entry with the actual arguments below a
    /// frame that returns past the end of the program, so the body returning
    /// ends that VM's run.
    fn create(&mut self, name: String, command: &str, args: Vec<Value>) -> Result<(), String> {
        let entry = self
            .chunk
            .names
            .iter()
            .position(|n| n == command)
            .and_then(|idx| self.chunk.find_sub(idx as u16))
            .ok_or_else(|| format!("invalid command name \"{command}\""))?;

        let mut vm = VM::new(self.chunk.clone());
        self.hooks.install(&mut vm);
        let base = vm.stack.len();
        for a in args {
            vm.stack.push(a);
        }
        vm.frames.push(Frame {
            return_ip: self.chunk.ops.len(),
            stack_base: base,
            slots: Vec::new(),
            // The body is a procedure of this chunk, so the frame carries which
            // one: that is what lets the VM answer a slot's name inside a
            // coroutine, as it does inside an ordinary call.
            entry_ip: Some(entry),
        });
        vm.ip = entry;

        // A name that is still live is being re-created: the old context goes,
        // as it does in the reference implementation.
        if let Some(&old) = self.live.get(&name) {
            self.discard(old);
        }
        let context = self.contexts.len();
        self.contexts.push(Context {
            vm: Some(vm),
            catches: Vec::new(),
            name: Some(name.clone()),
            resumer: Some(self.current),
            park: Park::Running,
        });
        self.created.insert(name.clone());
        self.live.insert(name, context);
        self.current = context;
        Ok(())
    }

    /// Give a suspended context its resumption value and run it, recording
    /// where it returns to.
    fn enter(&mut self, target: usize, value: Value, resumer: Option<usize>) {
        self.vm(target).stack.push(value);
        self.contexts[target].resumer = resumer;
        self.contexts[target].park = Park::Running;
        self.current = target;
    }

    /// The context of the suspended coroutine `name`.
    fn suspended(&self, name: &str) -> Result<usize, String> {
        let Some(&context) = self.live.get(name) else {
            return Err(format!("invalid command name \"{name}\""));
        };
        if self.contexts[context].park == Park::Running {
            return Err(format!("coroutine \"{name}\" is already running"));
        }
        Ok(context)
    }

    /// The single value a resumption delivers, which depends on how the
    /// coroutine suspended: `yield` produces its argument, so it takes at most
    /// one; `yieldto` produces the whole argument list.
    fn resumption(&self, target: usize, name: &str, args: Vec<Value>) -> Result<Value, String> {
        match self.contexts[target].park {
            Park::AtYieldTo => {
                let words: Vec<String> = args.iter().map(to_tcl_string).collect();
                Ok(Value::Str(Arc::new(list::join(&words))))
            }
            _ => match <[Value; 1]>::try_from(args) {
                Ok([value]) => Ok(value),
                Err(rest) if rest.is_empty() => Ok(Value::Str(Arc::new(String::new()))),
                Err(_) => Err(format!("wrong # args: should be \"{name} ?arg?\"")),
            },
        }
    }

    /// `yield` and `yieldto` are errors outside a coroutine — and are refused,
    /// for a different reason and with a different message, inside a script that
    /// a coroutine reached through `eval`, `uplevel` or `apply`.
    fn in_coroutine(&self, command: &str) -> Result<(), String> {
        if self.contexts[self.current].name.is_some() {
            return Ok(());
        }
        // Suspending here would have to park a VM that is waiting inside an op
        // handler, several Rust frames below this one: the nested script's state
        // is not part of what the outer VM saves when it parks, so resuming it
        // could not come back to the middle of this script. It is refused
        // outright rather than approximated, because every approximation loses
        // whatever the nested script had set.
        let nested = self
            .hooks
            .interp
            .lock()
            .expect("interpreter lock")
            .running
            .iter()
            .any(Option::is_some);
        if nested {
            return Err(format!(
                "{command} inside a script run by \"eval\", \"uplevel\" or \"apply\" is not \
                 supported: a coroutine cannot suspend across one"
            ));
        }
        Err(format!("{command} can only be called in a coroutine"))
    }
}

/// A Tcl number: integral until something forces a double.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Num {
    Int(i64),
    Float(f64),
    /// An integer past what an `i64` holds. Tcl 9's integers are arbitrary
    /// precision, so this is a value like any other rather than an error.
    ///
    /// It is reached only by a spelling that does not fit or by an operation
    /// that overflowed: the VM computes on `i64` in registers and hands the
    /// frontend the operands only when its checked arithmetic fails, so nothing
    /// on a hot path ever builds one (`fusevm`'s `NumericHook`, and
    /// [`numeric`]).
    Big(BigInt),
}

impl Num {
    fn as_f64(&self) -> f64 {
        match self {
            Num::Int(i) => *i as f64,
            Num::Float(f) => *f,
            // `to_f64` saturates to an infinity for a magnitude no double can
            // hold, which is what Tcl answers for the same conversion.
            Num::Big(b) => b.to_f64().unwrap_or(f64::INFINITY),
        }
    }

    /// The value as a `BigInt`, for an operation with a bignum on either side.
    /// `None` for a double, which promotes the *other* side instead.
    fn as_big(&self) -> Option<BigInt> {
        match self {
            Num::Int(i) => Some(BigInt::from(*i)),
            Num::Big(b) => Some(b.clone()),
            Num::Float(_) => None,
        }
    }

    fn is_big(&self) -> bool {
        matches!(self, Num::Big(_))
    }
}

/// Order two numbers exactly when at least one is wider than an `i64`.
///
/// Going through `f64` would be wrong in both directions: it rounds a bignum to
/// the nearest double, which makes distinct integers compare equal, and it
/// cannot represent one larger than `f64::MAX` at all. `None` only for a NaN,
/// which has no ordering.
fn big_cmp(p: &Num, q: &Num) -> Option<std::cmp::Ordering> {
    match (p, q) {
        (Num::Float(f), _) | (_, Num::Float(f)) if f.is_nan() => None,
        // An infinity is beyond every integer, so its side decides outright.
        (Num::Float(f), _) if f.is_infinite() => Some(if *f < 0.0 {
            std::cmp::Ordering::Less
        } else {
            std::cmp::Ordering::Greater
        }),
        (_, Num::Float(f)) if f.is_infinite() => Some(if *f < 0.0 {
            std::cmp::Ordering::Greater
        } else {
            std::cmp::Ordering::Less
        }),
        // One side a finite double: compare against its integer part, and let
        // the fraction break a tie. `2 < 2.5` and `3 > 2.5` both fall out of
        // that, exactly, without either side becoming the other's type.
        (left, Num::Float(f)) => {
            let whole = BigInt::from_f64(f.trunc())?;
            Some(match left.as_big()?.cmp(&whole) {
                std::cmp::Ordering::Equal => 0.0.partial_cmp(&(f - f.trunc()))?,
                other => other,
            })
        }
        (Num::Float(f), right) => {
            let whole = BigInt::from_f64(f.trunc())?;
            Some(match whole.cmp(&right.as_big()?) {
                std::cmp::Ordering::Equal => (f - f.trunc()).partial_cmp(&0.0)?,
                other => other,
            })
        }
        (left, right) => Some(left.as_big()?.cmp(&right.as_big()?)),
    }
}

/// A `BigInt` as the value a script sees: an `i64` when it fits, and its
/// canonical decimal spelling when it does not.
///
/// Demoting matters as much as promoting. `expr {(1 << 64) >> 64}` is 1 in
/// tclsh, an ordinary integer again, and a value that stayed wide would compare
/// and print the same but would take the slow path on every later operation.
pub(crate) fn from_big(b: BigInt) -> Value {
    match i64::try_from(&b) {
        Ok(i) => Value::Int(i),
        Err(_) => Value::Str(Arc::new(b.to_string())),
    }
}

/// Why a string is not a number this frontend can use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NotNumeric {
    /// No numeric spelling at all.
    Unparsable,
}

/// Interpret a value as a Tcl number. Leading and trailing whitespace is
/// allowed, as are the radix prefixes `0x`, `0o` and `0b`.
fn tcl_num(v: &Value) -> Result<Num, NotNumeric> {
    match v {
        Value::Int(i) => Ok(Num::Int(*i)),
        Value::Float(f) => Ok(Num::Float(*f)),
        Value::Bool(b) => Ok(Num::Int(*b as i64)),
        _ => parse_number(v.as_str_cow().trim()),
    }
}

/// A number, falling back to the nearest double for a spelling that is not one.
///
/// Only comparison uses this, and an integer of any width now parses exactly
/// through [`parse_number`], so the fallback is reached only by a spelling
/// `tcl_num` rejects outright. Ordering a bignum goes through [`big_cmp`]
/// instead, which is exact — the nearest double would make distinct integers
/// compare equal.
fn approx_num(v: &Value) -> Option<Num> {
    if let Ok(n) = tcl_num(v) {
        return Some(n);
    }
    let text = v.as_str_cow();
    let body = text.trim();
    let (sign, digits) = match body.strip_prefix('-') {
        Some(rest) => (-1.0, rest),
        None => (1.0, body.strip_prefix('+').unwrap_or(body)),
    };
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    digits.parse::<f64>().ok().map(|f| Num::Float(sign * f))
}

pub(crate) fn parse_number(text: &str) -> Result<Num, NotNumeric> {
    if text.is_empty() {
        return Err(NotNumeric::Unparsable);
    }
    let (sign, body) = match text.as_bytes()[0] {
        b'-' => (-1i64, &text[1..]),
        b'+' => (1, &text[1..]),
        _ => (1, text),
    };
    // Tcl 9's radix prefixes. A leading zero is *not* one of them: `010` is ten,
    // as `0d10` is, which is why there is a `0d` at all.
    //
    // Matched on bytes. Slicing `&body[..2]` panics when the second character is
    // multi-byte — `héllo` has `é` across bytes 1..3 — and a condition reaches
    // this with whatever text a variable holds.
    let radix = match body.as_bytes() {
        [b'0', k, _, ..] => match k.to_ascii_lowercase() {
            b'x' => Some(16),
            b'o' => Some(8),
            b'b' => Some(2),
            b'd' => Some(10),
            _ => None,
        },
        _ => None,
    };

    // `_` is numeric whitespace, not part of any value.
    let cleaned;
    let body = if body.contains('_') {
        match without_separators(body, radix.unwrap_or(10)) {
            Some(text) => {
                cleaned = text;
                cleaned.as_str()
            }
            None => return Err(NotNumeric::Unparsable),
        }
    } else {
        body
    };

    if let Some(radix) = radix {
        let digits = &body[2..];
        return match i64::from_str_radix(digits, radix) {
            Ok(v) => Ok(Num::Int(sign * v)),
            // Digits of the right shape that do not fit are a bignum; a `0x`
            // with no valid digit at all is simply not a number.
            Err(_) if !digits.is_empty() && digits.chars().all(|c| c.is_digit(radix)) => {
                match BigInt::parse_bytes(digits.as_bytes(), radix) {
                    Some(b) => Ok(Num::Big(if sign < 0 { -b } else { b })),
                    None => Err(NotNumeric::Unparsable),
                }
            }
            Err(_) => Err(NotNumeric::Unparsable),
        };
    }
    if let Ok(i) = body.parse::<i64>() {
        return Ok(Num::Int(sign * i));
    }
    // An integer spelling that does not fit an `i64` is a bignum, and must not
    // fall through to the double parser — which would take it and answer with a
    // value the script never wrote.
    if !body.is_empty() && body.bytes().all(|b| b.is_ascii_digit()) {
        return match BigInt::parse_bytes(body.as_bytes(), 10) {
            Some(b) => Ok(Num::Big(if sign < 0 { -b } else { b })),
            None => Err(NotNumeric::Unparsable),
        };
    }
    // Tcl accepts Inf and NaN spellings that Rust's parser also takes; it does
    // not accept a bare `.` or an empty mantissa, and neither does Rust's.
    body.parse::<f64>()
        .map(|f| Num::Float(sign as f64 * f))
        .map_err(|_| NotNumeric::Unparsable)
}

/// Remove Tcl 9's numeric whitespace, or answer `None` when one of the `_` runs
/// is not where a separator may be.
///
/// `TclParseNumber` (`tclStrToD.c`) accepts a run of `_` only between two digits
/// of the number's own radix, and never at either end: `1_0`, `1__0`,
/// `1_000_000`, `0x1_0` and `1e1_0` are numbers, and `_1`, `1_`, `1_.5`,
/// `1_e3` and `0x_10` are not.
fn without_separators(body: &str, radix: u32) -> Option<String> {
    let bytes = body.as_bytes();
    let digit = |i: usize| -> bool { bytes.get(i).is_some_and(|b| (*b as char).is_digit(radix)) };
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] != b'_' {
            i += 1;
            continue;
        }
        let run_start = i;
        while i < bytes.len() && bytes[i] == b'_' {
            i += 1;
        }
        if run_start == 0 || !digit(run_start - 1) || !digit(i) {
            return None;
        }
    }
    Some(body.replace('_', ""))
}

/// Tcl's boolean rule, which is not the VM's truthiness rule: a condition must
/// be a number or one of the words `true`, `false`, `yes`, `no`, `on`, `off`,
/// abbreviated to any non-ambiguous prefix and in any case.
///
/// Ported from `ParseBoolean` and `Tcl_GetBoolFromObj` (`tclObj.c`): the word
/// table is tried first, and anything it rejects is offered to the number
/// parser, so `007`, `0x10`, `1_0`, ` 1 ` and `1e3` are all true and `b`, `o`
/// and `""` are errors. `o` is an error because it is a prefix of both `on` and
/// `off`, which is why the two are only accepted from two characters up.
pub(crate) fn tcl_bool(v: &Value) -> Result<bool, String> {
    match v {
        Value::Int(i) => return Ok(*i != 0),
        Value::Bool(b) => return Ok(*b),
        Value::Float(f) => return float_bool(*f),
        _ => {}
    }
    let text = v.as_str_cow();
    if let Some(b) = boolean_word(&text) {
        return Ok(b);
    }
    match parse_number(text.trim()) {
        Ok(Num::Int(i)) => Ok(i != 0),
        Ok(Num::Float(f)) => float_bool(f),
        // A spelling too wide for an `i64` has a magnitude larger than
        // `i64::MAX`, so it is nonzero without consulting the digits.
        Ok(Num::Big(_)) => Ok(true),
        Err(NotNumeric::Unparsable) => Err(format!(
            "expected boolean value but got {}",
            named(&text, 50)
        )),
    }
}

fn float_bool(f: f64) -> Result<bool, String> {
    if f.is_nan() {
        return Err("floating point value is Not a Number".to_string());
    }
    Ok(f != 0.0)
}

/// `ParseBoolean`'s word table. `None` means "not one of the words", which is
/// the cue to try the number parser rather than to fail.
pub(crate) fn boolean_word(text: &str) -> Option<bool> {
    // "false" is the longest spelling, so nothing longer can be one of these —
    // and the reference implementation measures bytes, not characters.
    if text.is_empty() || text.len() > 5 {
        return None;
    }
    if text == "0" {
        return Some(false);
    }
    if text == "1" {
        return Some(true);
    }
    let lower = text.to_ascii_lowercase();
    // Only the letters the six words are spelled with; anything else is not a
    // word, which keeps `0x10` out of the prefix matching below.
    if !lower.bytes().all(|b| b"aeflnorstuy".contains(&b)) {
        return None;
    }
    for (word, value) in [
        ("yes", true),
        ("no", false),
        ("true", true),
        ("false", false),
        ("on", true),
        ("off", false),
    ] {
        // `on` and `off` share their first letter, so a one-character prefix of
        // either is ambiguous and rejected.
        let shortest = if word.starts_with('o') { 2 } else { 1 };
        if lower.len() >= shortest && word.starts_with(&lower) {
            return Some(value);
        }
    }
    None
}

/// How the reference interpreter names an unusable value in a diagnostic: `a
/// list` when the text could be one, and otherwise the text quoted and cut at
/// `limit` bytes.
pub(crate) fn named(text: &str, limit: usize) -> String {
    if list::looks_like_a_list(text) {
        return "a list".to_string();
    }
    let mut end = text.len().min(limit);
    while end > 0 && !text.is_char_boundary(end) {
        end -= 1;
    }
    format!("\"{}\"", &text[..end])
}

/// An integer operand, in the wording of the commands that want one — `incr`
/// and `format`'s integer conversions — rather than of `expr`'s operators.
pub(crate) fn tcl_int(v: &Value) -> Result<i64, String> {
    if let Value::Int(i) = v {
        return Ok(*i);
    }
    let text = to_tcl_string(v);
    match parse_number(text.trim()) {
        Ok(Num::Int(i)) => Ok(i),
        // The callers here want a machine integer specifically: `format`'s
        // integer conversions are C's, and tclsh itself narrows for them —
        // `format %d 99999999999999999999` is 1661992959 there, the low 32
        // bits. Narrowing silently is the one thing this frontend will not do,
        // so the operand is refused and the divergence is recorded rather than
        // guessed at (BUGS.md).
        Ok(Num::Big(_)) => Err(too_large()),
        _ => Err(format!("expected integer but got {}", named(&text, 50))),
    }
}

/// Add two Tcl integers, promoting on overflow, for a command that increments a
/// value of its own rather than through `expr`.
///
/// `dict incr` is the caller. It cannot use [`tcl_int`], which refuses a bignum
/// because `format`'s integer conversions must narrow or refuse; incrementing
/// past an `i64` is ordinary in Tcl — `dict incr d k` on 9223372036854775807 is
/// 9223372036854775808 there — so this promotes instead. Floats are refused with
/// the wording tclsh's own `incr` uses.
pub(crate) fn incr_text(current: &str, by: &str) -> Result<String, String> {
    let one = incr_operand(current)?;
    let other = incr_operand(by)?;
    if let (Num::Int(x), Num::Int(y)) = (&one, &other) {
        if let Some(sum) = x.checked_add(*y) {
            return Ok(sum.to_string());
        }
    }
    // Either side is already wide, or the sum left the range: both widen.
    let (x, y) = (
        one.as_big().expect("an integer is never a float here"),
        other.as_big().expect("an integer is never a float here"),
    );
    Ok(to_tcl_string(&from_big(x + y)))
}

/// One operand of [`incr_text`]: an integer in any of Tcl's spellings, refused
/// the way tclsh's `incr` refuses it.
fn incr_operand(text: &str) -> Result<Num, String> {
    match parse_number(text.trim()) {
        Ok(n) if !matches!(n, Num::Float(_)) => Ok(n),
        _ => Err(format!("expected integer but got {}", named(text, 50))),
    }
}

/// The numeric hook: called when an operand is not something the VM can
/// compute on natively, or when an integer operation overflows.
/// `incr`'s own wording for an operand that is not an integer.
///
/// `incr` takes an integer, so it names the value rather than the operator, and
/// it names whichever of the two is at fault — the variable first, since that is
/// the one tclsh reports when both are. `None` when neither operand explains the
/// failure, which leaves the arithmetic's own message in place rather than
/// inventing one.
fn incr_operand_error(a: &Value, b: &Value) -> Option<String> {
    for operand in [a, b] {
        // `Undef` is the variable not existing, which `incr` reads as zero — the
        // undef hook answered it deliberately for this site. Absent is not the
        // same as not-an-integer.
        if matches!(operand, Value::Undef) {
            continue;
        }
        // Integral of *any* width, not `tcl_int`'s machine integer: a promoted
        // value is still an integer, and `incr y -1` on 10^20 is arithmetic
        // tclsh performs rather than refuses.
        let integral = matches!(
            parse_number(to_tcl_string(operand).trim()),
            Ok(Num::Int(_)) | Ok(Num::Big(_))
        );
        if !integral {
            return Some(format!(
                "expected integer but got {}",
                named(&to_tcl_string(operand), 50)
            ));
        }
    }
    None
}

fn numeric(op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
    // Comparisons prefer numbers but fall back to string order, which is what
    // makes `expr {"10" < "9"}` false and `expr {10 < 9}` also false while
    // `expr {"abc" < "abd"}` is true.
    let cmp = matches!(
        op,
        NumOp::Lt | NumOp::Gt | NumOp::Le | NumOp::Ge | NumOp::Eq | NumOp::Ne
    );
    if cmp {
        let ordering = match (approx_num(a), approx_num(b)) {
            (Some(Num::Int(i)), Some(Num::Int(j))) => i.cmp(&j),
            // A bignum on either side orders exactly, never through a double.
            // The difference is observable: `99999999999999999999 < 1e20` is
            // true and `== 1e20` is false, though both sides are the same
            // double once converted — while `1e20 == 100000000000000000000` is
            // true, because that one really is the same integer.
            (Some(p), Some(q)) if p.is_big() || q.is_big() => match big_cmp(&p, &q) {
                Some(ordering) => ordering,
                None => return Ok(Value::Int(matches!(op, NumOp::Ne) as i64)),
            },
            (Some(p), Some(q)) => match p.as_f64().partial_cmp(&q.as_f64()) {
                Some(ordering) => ordering,
                // A NaN operand has no ordering at all, and IEEE 754 is what
                // Tcl follows here: every ordered comparison against one is
                // false, and `!=` is the single one that is true. No `Ordering`
                // can express that — calling it `Greater` made `nan > 1` and
                // `nan >= 1` answer 1 where tclsh answers 0 — so answer here.
                None => return Ok(Value::Int(matches!(op, NumOp::Ne) as i64)),
            },
            _ => a.as_str_cow().cmp(&b.as_str_cow()),
        };
        let truth = match op {
            NumOp::Lt => ordering.is_lt(),
            NumOp::Gt => ordering.is_gt(),
            NumOp::Le => ordering.is_le(),
            NumOp::Ge => ordering.is_ge(),
            NumOp::Eq => ordering.is_eq(),
            _ => !ordering.is_eq(),
        };
        return Ok(Value::Int(truth as i64));
    }

    let sym = match op {
        NumOp::Add => "+",
        NumOp::Sub => "-",
        NumOp::Mul => "*",
        NumOp::Div => "/",
        NumOp::Mod => "%",
        NumOp::Pow => "**",
        NumOp::Neg => "-",
        _ => "?",
    };
    // `Neg` is the one unary op that reaches here, and its operand is `a`; every
    // other op names the side its bad operand was on.
    let unary = matches!(op, NumOp::Neg);
    let left = if unary { Side::Only } else { Side::Left };
    // `incr` on a variable that does not exist counts from zero — `proc p {}
    // {incr n; return $n}` is 1 in tclsh — and `incr` lowers to a native
    // `Op::Add` on the variable's value, deliberately, so that a counting loop
    // stays trace-eligible (see `Compiler::cmd_incr`). An absent variable
    // reaches this hook as `Value::Undef`, which no assignment can produce —
    // `set x ""` stores `Value::Str("")` — so reading it as zero is exactly the
    // `incr` case and not the empty string. The cost is that `expr {$unset +
    // 1}` answers 1 rather than refusing the operand; tclrs already reads an
    // absent variable as absent rather than raising (BUGS.md, allowlist A1),
    // and this is that same deviation reaching arithmetic.
    let zeroed = |v: &Value| matches!(op, NumOp::Add) && *v == Value::Undef;
    let x = if zeroed(a) {
        Num::Int(0)
    } else {
        num_operand(a, left, sym)?
    };
    // A unary op has no right operand, and reads as zero for the same reason an
    // absent one does: the arm below adds it to `x` and answers `x`.
    let y = if unary || zeroed(b) {
        Num::Int(0)
    } else {
        num_operand(b, Side::Right, sym)?
    };

    let value = match (op, &x, &y) {
        (NumOp::Neg, Num::Float(f), _) => Value::Float(-f),
        (NumOp::Neg, _, _) => from_big(-x.as_big().expect("a non-float negates as an integer")),
        // Either operand a double makes the result a double, bignum or not:
        // `expr {99999999999999999999 + 0.5}` is 1e+20 in tclsh.
        (_, Num::Float(_), _) | (_, _, Num::Float(_)) => {
            let (p, q) = (x.as_f64(), y.as_f64());
            Value::Float(match op {
                NumOp::Add => p + q,
                NumOp::Sub => p - q,
                NumOp::Mul => p * q,
                _ => return Err(format!("unsupported operation {sym}")),
            })
        }
        // Two integers, at least one of which the VM could not fold — either it
        // overflowed `i64` or it arrived as a spelling wider than one. This is
        // the whole bignum path: it is reached only after fusevm's checked
        // arithmetic has already failed, so a loop that never overflows never
        // builds a `BigInt` at all.
        _ => {
            let (p, q) = (
                x.as_big().expect("an integer operand"),
                y.as_big().expect("an integer operand"),
            );
            from_big(match op {
                NumOp::Add => p + q,
                NumOp::Sub => p - q,
                NumOp::Mul => p * q,
                _ => return Err(format!("unsupported integer operation {sym}")),
            })
        }
    };
    Ok(value)
}

/// Which operand of an operator a diagnostic is about. `expr(n)` words a
/// binary operator's two sides differently and a unary operator's only side
/// differently again, so the side travels with the refusal rather than being
/// guessed from the operator's spelling — `-` is both.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Side {
    Left,
    Right,
    /// A unary operator's only operand: `as operand of`, with no side named.
    Only,
}

impl Side {
    fn phrase(self) -> &'static str {
        match self {
            Side::Left => "as left operand of",
            Side::Right => "as right operand of",
            Side::Only => "as operand of",
        }
    }
}

/// How `expr(n)` names an operand it will not compute on.
///
/// Three shapes, measured against tclsh 9.0.4:
///
/// ```text
/// expr {"a" + 1}   cannot use non-numeric string "a" as left operand of "+"
/// expr {1.5 % 2}   cannot use floating-point value "1.5" as left operand of "%"
/// expr {"a b" + 1} cannot use a list as left operand of "+"
/// expr {~1.5}      cannot use floating-point value "1.5" as operand of "~"
/// ```
///
/// A value that could hold several elements is named `a list` and never quoted,
/// which is [`looks_like_a_list`](crate::list::looks_like_a_list) — the same
/// screen `incr` and `format` use — and the text is *not* truncated here, unlike
/// theirs: `expr {[string repeat q 80] + 1}` quotes all eighty.
fn operand(v: &Value, kind: &str, side: Side, op: &str) -> String {
    let text = to_tcl_string(v);
    if list::looks_like_a_list(&text) {
        return format!("cannot use a list {} \"{op}\"", side.phrase());
    }
    format!("cannot use {kind} \"{text}\" {} \"{op}\"", side.phrase())
}

/// An operand that is not a number at all.
fn non_numeric(v: &Value, side: Side, op: &str) -> String {
    operand(v, "non-numeric string", side, op)
}

/// An operand that is a perfectly good double where the operator wants an
/// integer — `%` and the bitwise operators.
fn non_integer(v: &Value, side: Side, op: &str) -> String {
    operand(v, "floating-point value", side, op)
}

/// What an operator says about an operand it cannot use: the overflow this
/// frontend documents in place of a bignum, or the non-numeric refusal.
fn operand_error(why: NotNumeric, v: &Value, side: Side, op: &str) -> String {
    match why {
        NotNumeric::Unparsable => non_numeric(v, side, op),
    }
}

/// An operand of an arithmetic operator, refused in `expr(n)`'s words.
///
/// A NaN is named as its own third kind — `expr {"nan" + 0}` is `cannot use
/// non-numeric floating-point value "nan" as left operand of "+"` — because a
/// NaN reaching an operator is a refusal, where a NaN *produced* by one is the
/// domain error [`nan_checked`] reports.
fn num_operand(v: &Value, side: Side, op: &str) -> Result<Num, String> {
    match tcl_num(v) {
        Ok(Num::Float(f)) if f.is_nan() => {
            Err(operand(v, "non-numeric floating-point value", side, op))
        }
        Ok(n) => Ok(n),
        Err(why) => Err(operand_error(why, v, side, op)),
    }
}

/// The refusal for an integer this frontend will not build: past `i64` is a
/// promotion now, but past [`MAX_INT_BITS`] is still an error, and so is a
/// value handed to a command that wants a machine integer specifically.
fn too_large() -> String {
    "integer value too large to represent".to_string()
}

/// The frontend's extension ops.
fn extension(vm: &mut VM, id: u16, arg: u8) -> Result<(), String> {
    match id {
        ext::DIV | ext::POW => {
            let b = vm.pop();
            let a = vm.pop();
            let x = num_operand(&a, Side::Left, sym_of(id))?;
            let y = num_operand(&b, Side::Right, sym_of(id))?;
            vm.push(arith(id, x, y)?);
            Ok(())
        }
        // `%` wants two integers, and checks the left operand completely before
        // looking at the right: `expr {1.5 % "a"}` reports the float, not the
        // string (measured against tclsh 9.0.4).
        ext::MOD => {
            let b = vm.pop();
            let a = vm.pop();
            let x = match big_operand(&a, Side::Left, "%")? {
                BigOperand::Int(i) => Num::Int(i),
                BigOperand::Big(b) => Num::Big(b),
            };
            let y = match big_operand(&b, Side::Right, "%")? {
                BigOperand::Int(i) => Num::Int(i),
                BigOperand::Big(b) => Num::Big(b),
            };
            vm.push(arith(id, x, y)?);
            Ok(())
        }
        ext::BIT_AND | ext::BIT_OR | ext::BIT_XOR => {
            let b = vm.pop();
            let a = vm.pop();
            let sym = sym_of(id);
            let x = big_operand(&a, Side::Left, sym)?;
            let y = big_operand(&b, Side::Right, sym)?;
            // Two `i64`s answer as one, which is every ordinary script; a
            // bignum on either side widens both, since `num-bigint`'s bitwise
            // operators are two's-complement over an infinite sign extension —
            // the same model Tcl's are (`expr {99999999999999999999 & 255}` is
            // 255 there, and `~99999999999999999999` is negative).
            let value = match (x, y) {
                (BigOperand::Int(x), BigOperand::Int(y)) => Value::Int(match id {
                    ext::BIT_AND => x & y,
                    ext::BIT_OR => x | y,
                    _ => x ^ y,
                }),
                (x, y) => {
                    let (x, y) = (x.into_big(), y.into_big());
                    from_big(match id {
                        ext::BIT_AND => x & y,
                        ext::BIT_OR => x | y,
                        _ => x ^ y,
                    })
                }
            };
            vm.push(value);
            Ok(())
        }
        ext::SHL | ext::SHR => {
            let b = vm.pop();
            let a = vm.pop();
            let sym = sym_of(id);
            let x = big_operand(&a, Side::Left, sym)?;
            // The distance is an `i64` in every case: tclsh refuses a negative
            // one, and a positive one wide enough not to fit would ask for a
            // value no memory holds.
            let by = int_operand(&b, Side::Right, sym)?;
            vm.push(shift(id, x, by)?);
            Ok(())
        }
        ext::BIT_NOT => {
            let a = vm.pop();
            let value = match big_operand(&a, Side::Only, "~")? {
                BigOperand::Int(i) => Value::Int(!i),
                BigOperand::Big(b) => from_big(!b),
            };
            vm.push(value);
            Ok(())
        }
        // Tcl's boolean rule, which the VM's own truthiness is not: the value a
        // condition produced is 1 or 0, or the condition is refused.
        ext::BOOL => {
            let v = vm.pop();
            let truth = if arg == 1 {
                // `!`, whose refusal is an operand error rather than a boolean
                // one, because `expr(n)` gives it a numeric operand and accepts
                // a boolean word only as a second reading.
                match tcl_num(&v) {
                    Ok(Num::Int(i)) => i == 0,
                    // A NaN is `!`'s operand refusal, not the boolean rule's
                    // "floating point value is Not a Number" — which is what a
                    // *condition* answers for the same value (`if {"nan"} …`).
                    Ok(Num::Float(f)) if f.is_nan() => {
                        return Err(operand(
                            &v,
                            "non-numeric floating-point value",
                            Side::Only,
                            "!",
                        ))
                    }
                    Ok(Num::Float(f)) => !float_bool(f)?,
                    // `!` of a bignum is 0: it is nonzero by construction, so
                    // negating its truth needs none of its digits.
                    Ok(Num::Big(_)) => false,
                    Err(NotNumeric::Unparsable) => !boolean_word(&v.as_str_cow())
                        .ok_or_else(|| non_numeric(&v, Side::Only, "!"))?,
                }
            } else {
                tcl_bool(&v)?
            };
            vm.push(Value::Int(truth as i64));
            Ok(())
        }
        // Membership is a string test against the list's elements: `1 in {01}`
        // is false even though the two are numerically equal.
        ext::IN | ext::NI => {
            let haystack = vm.pop();
            let needle = vm.pop();
            // Tcl's string form of the list, not the VM's: a double reaching
            // here as a `Value::Float` — which a literal operand now does —
            // spells itself `3` through `as_str_cow` and `3.0` through Tcl's
            // formatter, and the membership test is on the latter.
            let elements = crate::list::split(&to_tcl_string(&haystack))?;
            let needle = to_tcl_string(&needle);
            let found = elements.contains(&needle);
            vm.push(Value::Int(i64::from(found == (id == ext::IN))));
            Ok(())
        }
        // `expr`'s always-string comparisons, on Tcl's string form of each
        // operand rather than the VM's.
        ext::STR_CMP => {
            let b = to_tcl_string(&vm.pop());
            let a = to_tcl_string(&vm.pop());
            let hit = match arg {
                0 => a < b,
                1 => a > b,
                2 => a <= b,
                3 => a >= b,
                4 => a == b,
                _ => a != b,
            };
            vm.push(Value::Int(hit as i64));
            Ok(())
        }
        // The value an `expr` answers with when its result is a bare operand
        // rather than something arithmetic: the *number* the operand spells,
        // and a refusal if that number is a NaN.
        //
        // This is what the old normalizing op did after every expression. It is
        // emitted only where [`crate::compiler::Compiler::yields_number`] says
        // the result could still be a string — never after arithmetic — so a
        // counted loop keeps a body of native ops and the tracing JIT keeps it.
        ext::CANON => {
            let v = vm.pop();
            let canonical = match v {
                // A double is already a number; what it still needs is the NaN
                // refusal and Tcl's spelling.
                Value::Float(f) => Value::Str(Arc::new(nan_checked(f)?)),
                other => canonical_number(other)?,
            };
            vm.push(canonical);
            Ok(())
        }
        // Unary `+`: the identity on a number, a refusal on anything else. The
        // number it answers with is the canonical one, as `expr {+007}` is 7.
        ext::UPLUS => {
            let v = vm.pop();
            // `num_operand` rather than `tcl_num`: a NaN operand is `+`'s own
            // refusal, and reaching `canonical_number` with one would report the
            // domain error a NaN *result* gets instead.
            num_operand(&v, Side::Only, "+")?;
            vm.push(canonical_number(v)?);
            Ok(())
        }
        ext::MATCH => {
            let pattern = to_tcl_string(&vm.pop());
            let subject = to_tcl_string(&vm.pop());
            let hit = if arg == 1 {
                list::glob_match(&pattern, &subject)
            } else {
                subject == pattern
            };
            vm.push(Value::Int(hit as i64));
            Ok(())
        }
        // `error` and `return -code error` raise the message as the error, so
        // the enclosing `catch` — or the caller of `eval` — receives it.
        ext::ERROR => Err(to_tcl_string(&vm.pop())),
        // The ranges are tested from the highest base down, so that a lower
        // one's `id >= BASE` does not swallow a higher module's ops.
        id if id >= ext::INFO_BASE => crate::cmd_info::extension(vm, id, arg),
        id if id >= ext::REGEXP_BASE => crate::regexp::extension(vm, id, arg),
        id if id >= ext::STRING_BASE => crate::cmd_string::extension(vm, id, arg),
        id if id >= ext::ASSOC_BASE => crate::assoc::extension(vm, id, arg),
        id if id >= ext::LIST_BASE => crate::cmd_list::run(vm, id, arg),
        other => Err(format!("unknown extension op {other}")),
    }
}

fn sym_of(id: u16) -> &'static str {
    match id {
        ext::DIV => "/",
        ext::MOD => "%",
        ext::BIT_AND => "&",
        ext::BIT_OR => "|",
        ext::BIT_XOR => "^",
        ext::SHL => "<<",
        ext::SHR => ">>",
        ext::BIT_NOT => "~",
        _ => "**",
    }
}

/// An operand of an integer-only operator — `%`, `&`, `|`, `^`, `<<`, `>>`, `~`
/// — refused in `expr(n)`'s own words when it is anything else.
///
/// The two refusals are distinct and both are the operator's, not a command's:
/// a string that is no number at all is `non-numeric string`, and a perfectly
/// good double is `floating-point value`. fusevm's native `Op::BitAnd` and
/// friends would take either, coercing through `Value::to_int` — `expr {1.5 |
/// 2}` answered 3 — so these operators are lowered to extension ops whenever
/// the compiler cannot prove both operands integral
/// ([`crate::compiler::Compiler::yields_integer`]).
fn int_operand(v: &Value, side: Side, op: &str) -> Result<i64, String> {
    match big_operand(v, side, op)? {
        BigOperand::Int(i) => Ok(i),
        // Every caller of this either handles a bignum itself before asking, or
        // is an operator with no bignum meaning; none can answer from a
        // truncation, so reaching here with one is a bug rather than a script
        // error.
        BigOperand::Big(b) => Err(format!(
            "integer value too large to represent: {b}"
        )),
    }
}

/// An integer operand that may be wider than an `i64`.
enum BigOperand {
    Int(i64),
    Big(BigInt),
}

impl BigOperand {
    fn into_big(self) -> BigInt {
        match self {
            BigOperand::Int(i) => BigInt::from(i),
            BigOperand::Big(b) => b,
        }
    }
}

/// The same refusals as [`int_operand`], with a bignum allowed through.
fn big_operand(v: &Value, side: Side, op: &str) -> Result<BigOperand, String> {
    match num_operand(v, side, op)? {
        Num::Int(i) => Ok(BigOperand::Int(i)),
        Num::Big(b) => Ok(BigOperand::Big(b)),
        Num::Float(_) => Err(non_integer(v, side, op)),
    }
}

/// `<<` and `>>` in tclsh 9.0.4's semantics.
///
/// A negative distance is refused outright. A left shift grows the value rather
/// than losing bits off the top — `1 << 64` is 18446744073709551616 — which is
/// what makes this a bignum operation and not an `i64` one. A right shift is
/// arithmetic and *saturates* rather than wrapping the distance: `1 >> 200` is
/// 0 and `-1 >> 200` is -1, where Rust's `>>` would mask the distance to
/// 200 % 64 = 8.
fn shift(id: u16, value: BigOperand, by: i64) -> Result<Value, String> {
    if by < 0 {
        return Err("negative shift argument".to_string());
    }
    if id == ext::SHR {
        return Ok(match value {
            // Every bit has left the word; only the sign remains.
            BigOperand::Int(v) if by >= 63 => Value::Int(if v < 0 { -1 } else { 0 }),
            BigOperand::Int(v) => Value::Int(v >> by),
            // A bignum has no word to leave, so the distance is used as given;
            // `>>` on a `BigInt` is already arithmetic.
            BigOperand::Big(b) => from_big(b >> shift_distance(by)?),
        });
    }
    Ok(match value {
        BigOperand::Int(0) => Value::Int(0),
        // The `i64` fast case, kept exact: `checked_shl` bounds the distance but
        // not the value, so the round trip is what says a bit was lost. Losing
        // one means the answer is wider than an `i64` and the shift is redone
        // as a bignum.
        BigOperand::Int(v) if by < 64 => match v
            .checked_shl(by as u32)
            .filter(|shifted| shifted >> by == v)
        {
            Some(shifted) => Value::Int(shifted),
            None => from_big(BigInt::from(v) << shift_distance(by)?),
        },
        BigOperand::Int(v) => from_big(BigInt::from(v) << shift_distance(by)?),
        BigOperand::Big(b) => from_big(b << shift_distance(by)?),
    })
}

/// How wide a promoted integer may get before this frontend refuses to build
/// it: 2^20 bits, a little over 315,000 decimal digits.
///
/// The bound is this frontend's, not Tcl's, and it is the same trade
/// `expr::MAX_EXPR_DEPTH` already makes. tclsh has no bound: `expr {10 **
/// 123456789}` asks it for a 123-million-digit number and it will sit there
/// trying — measured, still running after 30 seconds, where `10 ** 100000`
/// takes 3.5. A script that asks for that has almost always made a mistake, and
/// a Tcl error it can catch is a better answer than an allocation that ends the
/// process. Everything tclsh computes in reasonable time is well inside this:
/// `10 ** 100000` is 332,193 bits.
const MAX_INT_BITS: u64 = 1 << 20;

/// A shift distance as `num-bigint` takes it, bounded by [`MAX_INT_BITS`].
fn shift_distance(by: i64) -> Result<usize, String> {
    if by as u64 > MAX_INT_BITS {
        return Err(int_too_wide());
    }
    Ok(by as usize)
}

fn int_too_wide() -> String {
    "integer value too large to represent".to_string()
}

/// `/`, `%` and `**` where an `i64` cannot hold an operand or the answer.
///
/// The semantics are the same ones the `i64` arms implement, which is the point:
/// division and remainder floor toward negative infinity rather than truncating
/// toward zero, so `-99999999999999999999 / 7` is -14285714285714285715 and the
/// remainder is 6, both measured against tclsh 9.0.4.
fn big_arith(id: u16, p: BigInt, q: BigInt) -> Result<Value, String> {
    if matches!(id, ext::DIV | ext::MOD) && q.is_zero() {
        return Err("divide by zero".to_string());
    }
    match id {
        ext::DIV | ext::MOD => {
            // `BigInt`'s `/` and `%` truncate, as Rust's do. Floor by hand: a
            // remainder whose sign differs from the divisor's is one step past
            // the floor.
            let (quotient, remainder) = (&p / &q, &p % &q);
            let stepped = !remainder.is_zero() && (remainder.is_negative() != q.is_negative());
            Ok(if id == ext::DIV {
                from_big(if stepped { quotient - 1 } else { quotient })
            } else {
                from_big(if stepped { remainder + &q } else { remainder })
            })
        }
        _ => {
            if q.is_negative() {
                // An integral base raised to a negative power truncates toward
                // zero, and only ±1 survives it — the same rule the `i64` arm
                // applies, and a bignum base is never ±1.
                return match () {
                    _ if p.is_zero() => {
                        Err("exponentiation of zero by negative power".to_string())
                    }
                    _ => Ok(Value::Int(0)),
                };
            }
            let exp = u32::try_from(&q).map_err(|_| "exponent too large".to_string())?;
            // The width of the answer is the base's width times the exponent,
            // and it is knowable before a single digit is computed — which is
            // the only point at which refusing is still cheap.
            if p.bits() * u64::from(exp) > MAX_INT_BITS {
                return Err(int_too_wide());
            }
            Ok(from_big(p.pow(exp)))
        }
    }
}

/// Integer division and remainder floor toward negative infinity — `-57 / 10`
/// is -6 and `-57 % 10` is 3 — and `**` keeps integral operands integral.
fn arith(id: u16, x: Num, y: Num) -> Result<Value, String> {
    // A bignum on either side of an integer operator, before the `i64` arms
    // below: those are the fast path and stay exactly as they were.
    if matches!(id, ext::DIV | ext::MOD | ext::POW) && (x.is_big() || y.is_big()) {
        if let (Some(p), Some(q)) = (x.as_big(), y.as_big()) {
            return big_arith(id, p, q);
        }
    }
    match (id, x, y) {
        (ext::DIV, Num::Int(_), Num::Int(0)) | (ext::MOD, Num::Int(_), Num::Int(0)) => {
            Err("divide by zero".to_string())
        }
        // `i64::MIN / -1` is the one integer division whose true quotient does
        // not fit an `i64`; Tcl's answer is the bignum, and now so is this one.
        (ext::DIV, Num::Int(i64::MIN), Num::Int(-1)) => {
            Ok(from_big(-BigInt::from(i64::MIN)))
        }
        (ext::DIV, Num::Int(i), Num::Int(j)) => Ok(Value::Int(
            i.div_euclid(j)
                - i64::from(
                    // div_euclid rounds toward negative infinity only for a positive
                    // divisor; for a negative one it rounds the other way.
                    j < 0 && i.rem_euclid(j) != 0,
                ),
        )),
        (ext::MOD, Num::Int(i), Num::Int(j)) => {
            // The same pair overflows `%` on the way to a remainder that is
            // plainly 0, so answer directly instead of computing it.
            let r = i.checked_rem(j).unwrap_or(0);
            Ok(Value::Int(if r != 0 && (r < 0) != (j < 0) {
                r + j
            } else {
                r
            }))
        }
        // An exponent past what `checked_pow` even takes is its own diagnostic
        // in tclsh 9.0.4 — `expr {2 ** 9999999999}` is "exponent too large",
        // not the overflow the product would report.
        (ext::POW, Num::Int(i), Num::Int(j)) if j >= 0 => {
            let exp = u32::try_from(j).map_err(|_| "exponent too large".to_string())?;
            match i.checked_pow(exp) {
                Some(v) => Ok(Value::Int(v)),
                // The product left `i64`, which is a promotion and not an
                // error: `expr {2 ** 100}` is exact in tclsh.
                None => big_arith(id, BigInt::from(i), BigInt::from(j)),
            }
        }
        // Integral operands keep an integral result even when the exponent is
        // negative, so the true value is truncated toward zero: `2 ** -1` is 0,
        // not 0.5. Only ±1 survives, and 1/0 has no value at all. Measured
        // against tclsh 9.0.4, which answers 0 / 1 / -1 / the error here and
        // uses `powf` only when an operand is itself a double.
        (ext::POW, Num::Int(i), Num::Int(j)) => match i {
            0 => Err("exponentiation of zero by negative power".to_string()),
            1 => Ok(Value::Int(1)),
            // `j` may be `i64::MIN`, whose `abs()` does not fit, so read the
            // parity off the low bit rather than off a negated copy.
            -1 => Ok(Value::Int(if j % 2 == 0 { 1 } else { -1 })),
            _ => Ok(Value::Int(0)),
        },
        (ext::DIV, p, q) => float_result(p.as_f64() / q.as_f64()),
        // `%` never reaches here with a double: `int_operand` refused it, in the
        // order tclsh checks the two sides.
        (ext::MOD, _, _) => unreachable!("`%` operands are integers by now"),
        // A double operand anywhere makes the result a double, and a zero base
        // raised to a negative power still has no value.
        (_, p, q) => {
            if p.as_f64() == 0.0 && q.as_f64() < 0.0 {
                return Err("exponentiation of zero by negative power".to_string());
            }
            float_result(p.as_f64().powf(q.as_f64()))
        }
    }
}

/// The storage a variable lives in, grown to reach it — the same growth
/// `VM::set_var` and `VM::set_slot` do, which those cannot be used for here
/// because both hand back a clone rather than the value itself.
///
/// An op that *takes* the value out of this leaves it unshared, which is what
/// lets `lappend` and `append` extend the string the variable already holds
/// instead of building a copy of it every time (`crate::cmd_list`,
/// `crate::cmd_string`). `None` only for a frame slot with no frame.
pub(crate) fn var_cell(vm: &mut VM, place: Place) -> Option<&mut Value> {
    match place {
        Place::Global(index) => {
            let index = index as usize;
            if index >= vm.globals.len() {
                vm.globals.resize(index + 1, Value::Undef);
            }
            Some(&mut vm.globals[index])
        }
        Place::Slot(slot) => {
            let frame = vm.frames.last_mut()?;
            let slot = slot as usize;
            if slot >= frame.slots.len() {
                frame.slots.resize(slot + 1, Value::Undef);
            }
            Some(&mut frame.slots[slot])
        }
    }
}

/// An `expr` result that is a double: its Tcl spelling, unless it is a NaN,
/// which `expr(n)` reports rather than answers.
///
/// `expr {0.0/0.0}`, `expr {inf-inf}` and `expr {nan}` are all `domain error:
/// argument not in valid range` in tclsh 9.0.4 — measured, not inferred from
/// the C library's errno.
/// A double an arithmetic extension op computed, refused when it is a NaN.
///
/// tclsh raises at the operation that *produces* the NaN, not where the value
/// is later used: `set x [expr {0/0.0}]` never reaches the next command, and
/// `expr {(inf-inf) < 1}` reports rather than answering 0. `/` and `**` are the
/// two operators here that can make one out of operands that were not NaN
/// themselves; `+`, `-` and `*` are native ops and are covered by
/// `compiler::Compiler::may_be_non_finite` instead.
fn float_result(f: f64) -> Result<Value, String> {
    if f.is_nan() {
        return Err("domain error: argument not in valid range".to_string());
    }
    Ok(Value::Float(f))
}

fn nan_checked(f: f64) -> Result<String, String> {
    if f.is_nan() {
        return Err("domain error: argument not in valid range".to_string());
    }
    Ok(format_double(f))
}

/// The value an `expr` answers with when its result is a bare operand.
///
/// Tcl's `expr` yields the *number* an operand spells, not the text that spelt
/// it: `expr {007}` is 7, `expr {0x10}` is 16, `expr {" 42 "}` is 42 and `expr
/// {1e3}` is 1000.0. A string that spells no number at all is its own value —
/// `expr {"abc"}` is `abc` — and so is an integer too large for an `i64`, which
/// is the one case where the text is the only representation this frontend has
/// (see the note in `expr.rs` on decimal literals).
fn canonical_number(v: Value) -> Result<Value, String> {
    if matches!(v, Value::Int(_)) {
        return Ok(v);
    }
    let text = v.as_str_cow();
    match parse_number(text.trim()) {
        Ok(Num::Int(i)) => Ok(Value::Int(i)),
        Ok(Num::Float(f)) => Ok(Value::Str(Arc::new(nan_checked(f)?))),
        // `expr {0x1ffffffffffffffff}` is its decimal value in tclsh, as every
        // other radix spelling is; the canonical form of a bignum is the same
        // decimal `from_big` writes.
        Ok(Num::Big(b)) => Ok(from_big(b)),
        Err(_) => {
            drop(text);
            Ok(v)
        }
    }
}

/// Take a variable's value, leaving its place empty.
pub(crate) fn take_var(vm: &mut VM, place: Place) -> Value {
    match var_cell(vm, place) {
        Some(value) => std::mem::replace(value, Value::Undef),
        None => Value::Undef,
    }
}

/// Where an in-place op was told its variable lives: the operand the compiler
/// pushed, read back as a [`Place`].
pub(crate) fn place_of(vm: &mut VM, slot_form: bool) -> Result<Place, String> {
    let operand = vm.pop();
    place_at(&operand, slot_form)
}

/// The same, for an operand read where it sits on the stack.
pub(crate) fn place_at(operand: &Value, slot_form: bool) -> Result<Place, String> {
    match operand {
        Value::Int(index) => Ok(if slot_form {
            Place::Slot(*index as u16)
        } else {
            Place::Global(*index as u16)
        }),
        other => Err(format!("not a variable place: {other:?}")),
    }
}

/// The reads a lowering marked as tolerating an unset variable, keyed by the
/// chunk they belong to.
///
/// An op index alone does not identify a read: `eval` compiles a chunk of its
/// own whose indices start at zero again, so a set keyed by index would answer
/// for the wrong script — `eval {...}` followed by `incr counter` on an unset
/// counter would refuse where Tcl initialises. The key is fusevm's own
/// [`fusevm::UndefRead::chunk`] identity, and entries accumulate rather than
/// replacing, because a cached chunk can be run long after a later one was
/// lowered.
static TOLERANT_READS: Mutex<Option<HashSet<(u64, usize)>>> = Mutex::new(None);

/// fusevm's identity for a chunk: its ops **and** its names.
///
/// Deliberately not `Chunk::op_hash`, which ignores the name pool because it
/// keys the JIT's native-code cache, where a name is only an index. `incr x`
/// and `set y [expr {$z + 1}]` lower to the same op vector and disagree about
/// which read tolerates an unset variable, so a key that ignored names would
/// merge exactly the two this set exists to separate.
///
/// This must agree with `VM::chunk_identity`; the tests below run a script
/// through both sides, so a drift in either shows up as a refusal where Tcl
/// initialises rather than as a silent mismatch.
fn chunk_identity(chunk: &fusevm::Chunk) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    chunk.op_hash.hash(&mut h);
    chunk.names.hash(&mut h);
    h.finish() | 1
}

/// The arithmetic sites an `incr` lowered, as `(chunk identity, op index)`.
///
/// `incr x` and `expr {$x + 1}` are the same `Op::Add` on the same value, and
/// the reference interpreter refuses them in different words: `expected integer
/// but got "abc"` against `cannot use non-numeric string "abc" as left operand
/// of "+"`. Only the site separates them, which is what
/// `fusevm::NumericCall::ip` is for. Same shape as [`TOLERANT_READS`], and
/// accumulating for the same reason: a cached chunk runs long after a later one
/// was lowered.
static INCR_SITES: Mutex<Option<HashSet<(u64, usize)>>> = Mutex::new(None);

/// What `info args` and `info default` need about one procedure: each formal's
/// name and its default, in declaration order.
pub(crate) type ProcParams = Vec<(String, Option<String>)>;

/// Every procedure a chunk defines, keyed by chunk identity.
///
/// The compiler already collects signatures before it emits anything, to check
/// a call's arity; this publishes them so `info` can answer for a *computed*
/// procedure name as well as a literal one. Same shape as [`TOLERANT_READS`] and
/// [`INCR_SITES`], accumulating for the same reason: a cached chunk runs long
/// after a later one was lowered.
static PROC_TABLE: Mutex<Option<HashMap<(u64, String), ProcParams>>> = Mutex::new(None);

/// Record the procedures `chunk` defines and what their formals are.
pub(crate) fn note_procs(chunk: &fusevm::Chunk, procs: &[(String, ProcParams)]) {
    if procs.is_empty() {
        return;
    }
    let id = chunk_identity(chunk);
    let mut guard = PROC_TABLE.lock().expect("proc table lock");
    let table = guard.get_or_insert_with(HashMap::new);
    for (name, params) in procs {
        table.insert((id, name.clone()), params.clone());
    }
}

/// The formals of `name` as the running chunk declared it, or `None` when the
/// chunk defines no such procedure.
pub(crate) fn proc_params(vm: &VM, name: &str) -> Option<ProcParams> {
    let id = chunk_identity(&vm.chunk);
    PROC_TABLE
        .lock()
        .expect("proc table lock")
        .as_ref()
        .and_then(|t| t.get(&(id, name.to_string())).cloned())
}

/// The procedures the running chunk defines.
fn chunk_procs(vm: &VM) -> impl Iterator<Item = String> + '_ {
    let id = chunk_identity(&vm.chunk);
    let names: Vec<String> = PROC_TABLE
        .lock()
        .expect("proc table lock")
        .as_ref()
        .map(|t| {
            t.keys()
                .filter(|(chunk, _)| *chunk == id)
                .map(|(_, name)| name.clone())
                .collect()
        })
        .unwrap_or_default();
    names.into_iter()
}

/// The file `info script` reports — what the binary was asked to run, empty when
/// the script came from `-c` or stdin, as tclsh answers for those.
pub(crate) fn current_script() -> String {
    CURRENT_SCRIPT
        .lock()
        .expect("script lock")
        .clone()
        .unwrap_or_default()
}

/// Record the path of the file being run.
pub fn note_script(path: &str) {
    *CURRENT_SCRIPT.lock().expect("script lock") = Some(path.to_string());
}

static CURRENT_SCRIPT: Mutex<Option<String>> = Mutex::new(None);

/// Record where `chunk`'s `incr` commands put their arithmetic.
pub(crate) fn note_incr_sites(chunk: &fusevm::Chunk, ips: &[usize]) {
    if ips.is_empty() {
        return;
    }
    let id = chunk_identity(chunk);
    let mut guard = INCR_SITES.lock().expect("incr sites lock");
    let set = guard.get_or_insert_with(HashSet::new);
    for &ip in ips {
        set.insert((id, ip));
    }
}

/// Whether the arithmetic at `ip` in the chunk `id` is an `incr`'s.
fn is_incr_site(id: u64, ip: usize) -> bool {
    INCR_SITES
        .lock()
        .expect("incr sites lock")
        .as_ref()
        .is_some_and(|set| set.contains(&(id, ip)))
}

/// Record which of `chunk`'s reads tolerate an unset variable.
pub(crate) fn note_tolerant_reads(chunk: &fusevm::Chunk, ips: &[usize]) {
    if ips.is_empty() {
        return;
    }
    let id = chunk_identity(chunk);
    let mut guard = TOLERANT_READS.lock().expect("tolerant reads lock");
    let set = guard.get_or_insert_with(HashSet::new);
    for &ip in ips {
        set.insert((id, ip));
    }
}

/// Whether the read at `ip` in the chunk `id` was lowered as a tolerant one.
fn tolerates_undef(id: u64, ip: usize) -> bool {
    TOLERANT_READS
        .lock()
        .expect("tolerant reads lock")
        .as_ref()
        .is_some_and(|set| set.contains(&(id, ip)))
}

/// A value's Tcl string form, borrowed when the value already carries one.
pub(crate) fn tcl_str(v: &Value) -> Cow<'_, str> {
    match v {
        Value::Float(f) => Cow::Owned(format_double(*f)),
        Value::Bool(b) => Cow::Borrowed(if *b { "1" } else { "0" }),
        other => other.as_str_cow(),
    }
}

/// A value's Tcl string form.
pub fn to_tcl_string(v: &Value) -> String {
    tcl_str(v).into_owned()
}

/// Format a double the way Tcl does: the shortest representation that reads
/// back exactly, never looking like an integer, and in exponential form when
/// the magnitude is outside what `%g` would print positionally.
pub fn format_double(f: f64) -> String {
    if f.is_nan() {
        return "NaN".to_string();
    }
    if f.is_infinite() {
        return if f > 0.0 { "Inf" } else { "-Inf" }.to_string();
    }
    let mag = f.abs();
    if mag != 0.0 && !(1e-4..1e17).contains(&mag) {
        let raw = format!("{f:e}"); // e.g. "1e301", "1.5e-7"
        let (mantissa, exponent) = raw.split_once('e').expect("exponential form");
        let (sign, digits) = match exponent.strip_prefix('-') {
            Some(rest) => ('-', rest),
            None => ('+', exponent),
        };
        return format!("{mantissa}e{sign}{digits}");
    }
    let plain = format!("{f}");
    if plain.contains(['.', 'e', 'n', 'i']) {
        plain
    } else {
        format!("{plain}.0")
    }
}