tclrs 0.3.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
//! Tcl's string handling: the `string` ensemble, `append`, and `format`.
//!
//! Each command lowers to one frontend extension op. The compiler resolves
//! everything that is fixed at compile time — the ensemble subcommand, its
//! options, the `string is` class — and pushes only the values that have to be
//! computed, so the runtime side never re-parses an argument list. Optional
//! arguments are not padded with sentinels; the operand count carried in the
//! op's payload byte tells the handler which variant it is, which keeps a real
//! argument that happens to look like a sentinel from being mistaken for one.
//!
//! Tcl counts and indexes by code point, so the runtime works over `Vec<char>`
//! rather than bytes. Behavior is ported from tclsh 9.0.4 — `Tcl_StringCaseMatch`
//! and `TclFindElement` in `generic/tclUtil.c`, `StringMapCmd` and friends in
//! `generic/tclCmdMZ.c`, `Tcl_UtfToTitle` in `generic/tclUtf.c` — and every
//! subcommand is pinned against that interpreter by the differential suite.
//!
//! Two areas are refused rather than approximated. Tcl's Unicode character
//! classes come from its own general-category tables, which Rust's standard
//! library does not expose and which are a different Unicode revision besides;
//! the classes that need them accept ASCII and report an error otherwise. Case
//! conversion is exact: Rust's simple case mappings agree with Tcl's over every
//! code point up to U+2FFFF once Tcl's three quirks are reproduced — the
//! in-place length guard, the Greek ypogegrammeni capitals, and Georgian
//! Mkhedruli having no titlecase.

use std::sync::Arc;

use fusevm::{Op, Value, VM};

use crate::compiler::{CompileError, Compiler, Place};
use crate::parser::Word;
use crate::runtime::{place_at, take_var, tcl_str, to_tcl_string, var_cell};

/// Extension opcode ids owned by this module. The base is declared with every
/// other module's in [`crate::compiler::ext`], which is where the frontend's
/// one id space is laid out; [`crate::runtime`] dispatches by range from the
/// highest base down.
pub mod ext {
    pub use crate::compiler::ext::STRING_BASE as BASE;
    pub const CAT: u16 = BASE;
    pub const COMPARE: u16 = BASE + 1;
    pub const EQUAL: u16 = BASE + 2;
    pub const FIRST: u16 = BASE + 3;
    pub const INDEX: u16 = BASE + 4;
    pub const INSERT: u16 = BASE + 5;
    pub const IS: u16 = BASE + 6;
    pub const LAST: u16 = BASE + 7;
    pub const LENGTH: u16 = BASE + 8;
    pub const MAP: u16 = BASE + 9;
    pub const MATCH: u16 = BASE + 10;
    pub const RANGE: u16 = BASE + 11;
    pub const REPEAT: u16 = BASE + 12;
    pub const REPLACE: u16 = BASE + 13;
    pub const REVERSE: u16 = BASE + 14;
    pub const TOLOWER: u16 = BASE + 15;
    pub const TOTITLE: u16 = BASE + 16;
    pub const TOUPPER: u16 = BASE + 17;
    pub const TRIM: u16 = BASE + 18;
    pub const TRIMLEFT: u16 = BASE + 19;
    pub const TRIMRIGHT: u16 = BASE + 20;
    pub const APPEND: u16 = BASE + 21;
    pub const FORMAT: u16 = BASE + 22;
    /// `[name, place, value …]` → the extended string, stored in the variable
    /// the op reaches itself: `APPEND_VAR` at a name index in the VM's global
    /// table, `APPEND_SLOT` at a frame slot. Reaching the variable here rather
    /// than through `GetVar` / `SetVar` is what lets the values be appended to
    /// the string the variable already holds instead of a copy of it. The name
    /// travels along only so an unset variable can be reported by name.
    /// [`APPEND`] is still emitted for a name the script also uses as an array.
    pub const APPEND_VAR: u16 = BASE + 23;
    pub const APPEND_SLOT: u16 = BASE + 24;
}

/// Every subcommand the ensemble knows, in the order the interpreter lists them
/// when it rejects one. `wordend` and `wordstart` are listed because their
/// presence decides whether an abbreviation is ambiguous, but they are refused.
pub(crate) const SUBCOMMANDS: &[&str] = &[
    "cat",
    "compare",
    "equal",
    "first",
    "index",
    "insert",
    "is",
    "last",
    "length",
    "map",
    "match",
    "range",
    "repeat",
    "replace",
    "reverse",
    "tolower",
    "totitle",
    "toupper",
    "trim",
    "trimleft",
    "trimright",
    "wordend",
    "wordstart",
];

/// The `string is` classes, in the interpreter's listing order. Public for the
/// same reason as [`crate::expr::LEVELS`]: the reference page lists them, and
/// the list it prints has to be the one `string is` resolves against.
pub const CLASSES: &[&str] = &[
    "alnum",
    "alpha",
    "ascii",
    "control",
    "boolean",
    "dict",
    "digit",
    "double",
    "entier",
    "false",
    "graph",
    "integer",
    "list",
    "lower",
    "print",
    "punct",
    "space",
    "true",
    "upper",
    "wideinteger",
    "wordchar",
    "xdigit",
];

/// Resolve a name against a table the way `Tcl_GetIndexFromObj` does: an exact
/// match wins, otherwise a prefix that fits exactly one entry.
fn resolve<'t>(name: &str, table: &[&'t str]) -> Option<&'t str> {
    if let Some(exact) = table.iter().find(|c| **c == name) {
        return Some(exact);
    }
    let mut hit = None;
    for candidate in table {
        if candidate.starts_with(name) {
            if hit.is_some() {
                return None;
            }
            hit = Some(*candidate);
        }
    }
    hit
}

/// The interpreter's rendering of a table in an error message.
fn listing(table: &[&str]) -> String {
    let mut out = String::new();
    for (i, name) in table.iter().enumerate() {
        if i > 0 {
            out.push_str(", ");
        }
        if i + 1 == table.len() {
            out.push_str("or ");
        }
        out.push_str(name);
    }
    out
}

// ── compiling ────────────────────────────────────────────────────────────

impl Compiler {
    /// The one entry point the command dispatcher needs.
    pub(crate) fn cmd_string_family(
        &mut self,
        name: &str,
        args: &[Word],
    ) -> Result<(), CompileError> {
        match name {
            "string" => self.cmd_string(args),
            "append" => self.cmd_append(args),
            _ => self.cmd_format(args),
        }
    }

    /// Emit the extension op for a command whose operands are already pushed.
    fn string_op(&mut self, id: u16, argc: usize) -> Result<(), CompileError> {
        let Ok(argc8) = u8::try_from(argc) else {
            return self.error("too many arguments for one command");
        };
        self.emit(Op::Extended(id, argc8), 1 - argc as i32);
        Ok(())
    }

    fn push_flag(&mut self, on: bool) {
        self.push_value(Value::Int(on as i64));
    }

    /// Push every word in order and emit the op.
    fn words_op(&mut self, id: u16, words: &[Word]) -> Result<(), CompileError> {
        for w in words {
            self.word(w)?;
        }
        self.string_op(id, words.len())
    }

    fn cmd_string(&mut self, args: &[Word]) -> Result<(), CompileError> {
        let Some(first) = args.first() else {
            return self.error("wrong # args: should be \"string subcommand ?arg ...?\"");
        };
        let given = self.literal_of(first, "subcommand")?.to_string();
        let Some(sub) = resolve(&given, SUBCOMMANDS) else {
            return self.error(format!(
                "unknown or ambiguous subcommand \"{given}\": must be {}",
                listing(SUBCOMMANDS)
            ));
        };
        let rest = &args[1..];

        match sub {
            "cat" => self.words_op(ext::CAT, rest),
            "compare" | "equal" => self.cmd_string_compare(sub, rest),
            "first" | "last" => {
                let id = if sub == "first" {
                    ext::FIRST
                } else {
                    ext::LAST
                };
                let what = if sub == "first" {
                    "needleString haystackString ?startIndex?"
                } else {
                    "needleString haystackString ?lastIndex?"
                };
                self.fixed(id, rest, 2, 3, sub, what)
            }
            "index" => self.fixed(ext::INDEX, rest, 2, 2, sub, "string charIndex"),
            "insert" => self.fixed(ext::INSERT, rest, 3, 3, sub, "string index insertString"),
            "is" => self.cmd_string_is(rest),
            "length" => self.fixed(ext::LENGTH, rest, 1, 1, sub, "string"),
            "reverse" => self.fixed(ext::REVERSE, rest, 1, 1, sub, "string"),
            "map" | "match" => self.cmd_string_nocase(sub, rest),
            "range" => self.fixed(ext::RANGE, rest, 3, 3, sub, "string first last"),
            "repeat" => self.fixed(ext::REPEAT, rest, 2, 2, sub, "string count"),
            "replace" => self.fixed(ext::REPLACE, rest, 3, 4, sub, "string first last ?string?"),
            "tolower" | "totitle" | "toupper" => {
                let id = match sub {
                    "tolower" => ext::TOLOWER,
                    "totitle" => ext::TOTITLE,
                    _ => ext::TOUPPER,
                };
                self.fixed(id, rest, 1, 3, sub, "string ?first? ?last?")
            }
            "trim" | "trimleft" | "trimright" => {
                let id = match sub {
                    "trim" => ext::TRIM,
                    "trimleft" => ext::TRIMLEFT,
                    _ => ext::TRIMRIGHT,
                };
                self.fixed(id, rest, 1, 2, sub, "string ?chars?")
            }
            other => self.error(format!("\"string {other}\" is not supported yet")),
        }
    }

    /// A subcommand whose arguments are all values, with an arity range.
    fn fixed(
        &mut self,
        id: u16,
        args: &[Word],
        min: usize,
        max: usize,
        sub: &str,
        usage: &str,
    ) -> Result<(), CompileError> {
        if args.len() < min || args.len() > max {
            return self.error(format!("wrong # args: should be \"string {sub} {usage}\""));
        }
        self.words_op(id, args)
    }

    /// `string compare` and `string equal`, whose options sit before the last
    /// two arguments. The `-nocase` flag is resolved here; `-length` is a value
    /// and is pushed, so the operand count distinguishes the two forms.
    fn cmd_string_compare(&mut self, sub: &str, args: &[Word]) -> Result<(), CompileError> {
        let usage = format!(
            "wrong # args: should be \"string {sub} ?-nocase? ?-length int? string1 string2\""
        );
        if args.len() < 2 || args.len() > 5 {
            return self.error(usage);
        }
        let (opts, operands) = args.split_at(args.len() - 2);
        let mut nocase = false;
        let mut length: Option<&Word> = None;
        let mut i = 0;
        while i < opts.len() {
            let opt = self.literal_of(&opts[i], "option")?;
            if opt.len() > 1 && "-nocase".starts_with(opt) {
                nocase = true;
                i += 1;
            } else if opt.len() > 1 && "-length".starts_with(opt) {
                if i + 1 >= opts.len() {
                    return self.error(usage);
                }
                length = Some(&opts[i + 1]);
                i += 2;
            } else {
                return self.error(format!("bad option \"{opt}\": must be -nocase or -length"));
            }
        }

        let id = if sub == "compare" {
            ext::COMPARE
        } else {
            ext::EQUAL
        };
        self.push_flag(nocase);
        let mut argc = 3;
        if let Some(w) = length {
            self.word(w)?;
            argc = 4;
        }
        self.word(&operands[0])?;
        self.word(&operands[1])?;
        self.string_op(id, argc)
    }

    /// `string map` and `string match`, which take only `-nocase`.
    fn cmd_string_nocase(&mut self, sub: &str, args: &[Word]) -> Result<(), CompileError> {
        let what = if sub == "map" {
            "charMap string"
        } else {
            "pattern string"
        };
        if args.len() < 2 || args.len() > 3 {
            return self.error(format!(
                "wrong # args: should be \"string {sub} ?-nocase? {what}\""
            ));
        }
        let mut nocase = false;
        if args.len() == 3 {
            let opt = self.literal_of(&args[0], "option")?;
            if opt.len() > 1 && "-nocase".starts_with(opt) {
                nocase = true;
            } else {
                return self.error(format!("bad option \"{opt}\": must be -nocase"));
            }
        }
        let id = if sub == "map" { ext::MAP } else { ext::MATCH };
        self.push_flag(nocase);
        self.word(&args[args.len() - 2])?;
        self.word(&args[args.len() - 1])?;
        self.string_op(id, 3)
    }

    /// `string is class ?-strict? str`. The class and the flag are compile-time
    /// constants; `-failindex` needs to write a variable from inside the op and
    /// is refused instead of being half-implemented.
    fn cmd_string_is(&mut self, args: &[Word]) -> Result<(), CompileError> {
        const USAGE: &str =
            "wrong # args: should be \"string is class ?-strict? ?-failindex var? str\"";
        if args.len() < 2 || args.len() > 5 {
            return self.error(USAGE);
        }
        let given = self.literal_of(&args[0], "class")?.to_string();
        let Some(class) = resolve(&given, CLASSES) else {
            let ambiguous = CLASSES.iter().filter(|c| c.starts_with(&given)).count() > 1;
            let what = if ambiguous { "ambiguous" } else { "bad" };
            return self.error(format!(
                "{what} class \"{given}\": must be {}",
                listing(CLASSES)
            ));
        };

        let mut strict = false;
        for w in &args[1..args.len() - 1] {
            let opt = self.literal_of(w, "option")?;
            if opt.len() > 1 && "-strict".starts_with(opt) {
                strict = true;
            } else if opt.len() > 1 && "-failindex".starts_with(opt) {
                return self.error("the -failindex option of \"string is\" is not supported yet");
            } else {
                return self.error(format!(
                    "bad option \"{opt}\": must be -strict or -failindex"
                ));
            }
        }
        if matches!(class, "dict" | "graph" | "print" | "punct") {
            return self.error(format!(
                "the \"{class}\" character class needs Unicode category tables, which are not built yet"
            ));
        }

        self.push_str(class);
        self.push_flag(strict);
        self.word(&args[args.len() - 1])?;
        self.string_op(ext::IS, 3)
    }

    /// `append varName ?value ...?` — append to the variable's own string and
    /// yield the new value.
    ///
    /// The values are on the stack before the op runs, and the variable is read
    /// by the op itself, which is the order `Tcl_AppendObjCmd` reads them in:
    /// `append s [set s x]` appends to what the argument left behind. Reaching
    /// the variable there is also what makes the append in place — see
    /// [`append_at`]. A name the script also uses as an array keeps the
    /// read-concatenate-store lowering, whose operand is a guarded read that
    /// refuses an array rather than stringifying one.
    fn cmd_append(&mut self, args: &[Word]) -> Result<(), CompileError> {
        let Some(target) = args.first() else {
            return self.error("wrong # args: should be \"append varName ?value ...?\"");
        };
        let name = self.var_name_of(target)?;

        if self.is_array(&name) {
            self.push_str(&name);
            self.scalar_get(&name);
            for w in &args[1..] {
                self.word(w)?;
            }
            self.string_op(ext::APPEND, args.len() + 1)?;
            self.emit(Op::Dup, 1);
            self.emit_set_var(&name);
            return Ok(());
        }

        let id = self.append_target(&name);
        for w in &args[1..] {
            self.word(w)?;
        }
        self.string_op(id, args.len() + 1)
    }

    /// Push what an in-place append addresses — the variable's name, then where
    /// it lives — and answer with the op that closes it. The caller pushes the
    /// values and emits `id` with `2 + values` operands.
    pub(crate) fn append_target(&mut self, name: &str) -> u16 {
        self.push_str(name);
        match self.var_place(name) {
            Place::Slot(slot) => {
                self.emit(Op::LoadInt(slot as i64), 1);
                ext::APPEND_SLOT
            }
            Place::Global(idx) => {
                self.emit(Op::LoadInt(idx as i64), 1);
                ext::APPEND_VAR
            }
        }
    }

    fn cmd_format(&mut self, args: &[Word]) -> Result<(), CompileError> {
        if args.is_empty() {
            return self.error("wrong # args: should be \"format formatString ?arg ...?\"");
        }
        self.words_op(ext::FORMAT, args)
    }
}

// ── running ──────────────────────────────────────────────────────────────

/// Run one of this module's ops: pop `argc` operands, push one result.
pub(crate) fn extension(vm: &mut VM, id: u16, argc: u8) -> Result<(), String> {
    if id == ext::APPEND_VAR || id == ext::APPEND_SLOT {
        return append_at(vm, id, argc);
    }
    let mut operands = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        operands.push(vm.pop());
    }
    operands.reverse();
    let result = dispatch(id, &operands)?;
    vm.push(Value::Str(Arc::new(result)));
    Ok(())
}

/// `append`, and every `set x "$x…"` that is one, with the variable as the op's
/// own operand: `[name, place, value …]`, leaving the new value.
///
/// The value is taken out of the variable rather than read from it, so the
/// string it holds is unshared and the values are appended to it. Growing a
/// string that way is amortized linear in the bytes appended; the
/// read-concatenate-store shape it replaces copied the whole accumulated string
/// on every iteration, which made a build loop quadratic. A string another
/// value is holding is copied instead — it must not change under whoever holds
/// it — and so is one the variable does not hold as a string at all.
fn append_at(vm: &mut VM, id: u16, argc: u8) -> Result<(), String> {
    // The operands are read where they sit rather than popped one at a time:
    // the values are already in order there, and a value that is a string is
    // appended straight out of the one it holds, with nothing copied on the way.
    let count = argc as usize - 2;
    let base = vm.stack.len() - count;
    let place = place_at(&vm.stack[base - 1], id == ext::APPEND_SLOT)?;

    let current = take_var(vm, place);
    // Reading an unset variable is an error only when there is nothing to
    // append — `append x a` creates `x`, `append x` cannot.
    if count == 0 && current == Value::Undef {
        let name = to_tcl_string(&vm.stack[base - 2]);
        vm.stack.truncate(base - 2);
        return Err(format!("can't read \"{name}\": no such variable"));
    }

    let extended = append_onto(current, &vm.stack[base..]);
    vm.stack.truncate(base - 2);
    if let Some(cell) = var_cell(vm, place) {
        *cell = Value::Str(Arc::clone(&extended));
    }
    vm.push(Value::Str(extended));
    Ok(())
}

fn append_onto(current: Value, values: &[Value]) -> Arc<String> {
    let extra: usize = values.iter().map(|value| tcl_str(value).len()).sum();
    if let Value::Str(mut held) = current {
        match Arc::get_mut(&mut held) {
            // Unshared: the values go onto the string the variable held.
            Some(text) => {
                text.reserve(extra);
                extend(text, values);
                return held;
            }
            // Shared with a value the script kept, which must not change under
            // it, so the append lands on a copy.
            None => {
                let mut text = String::with_capacity(held.len() + extra);
                text.push_str(&held);
                extend(&mut text, values);
                return Arc::new(text);
            }
        }
    }
    // Not a string yet — a number, or an unset variable being created.
    let mut text = to_tcl_string(&current);
    text.reserve(extra);
    extend(&mut text, values);
    Arc::new(text)
}

fn extend(text: &mut String, values: &[Value]) {
    for value in values {
        text.push_str(&tcl_str(value));
    }
}

fn dispatch(id: u16, operands: &[Value]) -> Result<String, String> {
    // `append` is the one op that needs an operand's identity rather than its
    // string form: an unset variable reads back as `Undef`, and appending to
    // one is only an error when there is nothing to append.
    if id == ext::APPEND {
        let name = to_tcl_string(&operands[0]);
        if operands.len() == 2 && operands[1] == Value::Undef {
            return Err(format!("can't read \"{name}\": no such variable"));
        }
        let mut out = to_tcl_string(&operands[1]);
        for v in &operands[2..] {
            out.push_str(&to_tcl_string(v));
        }
        return Ok(out);
    }

    let a: Vec<String> = operands.iter().map(to_tcl_string).collect();
    match id {
        ext::CAT => Ok(a.concat()),
        ext::COMPARE | ext::EQUAL => {
            let nocase = truth(&a[0]);
            let (req, s1, s2) = if a.len() == 4 {
                (Some(want_int(&a[1])?), &a[2], &a[3])
            } else {
                (None, &a[1], &a[2])
            };
            let ordering = compare(&chars(s1), &chars(s2), nocase, req);
            Ok(if id == ext::COMPARE {
                ordering.to_string()
            } else {
                ((ordering == 0) as i32).to_string()
            })
        }
        ext::FIRST => {
            let hay = chars(&a[1]);
            let start = match a.get(2) {
                Some(spec) => index_of(spec, hay.len() as i64 - 1)?,
                None => 0,
            };
            Ok(find_first(&chars(&a[0]), &hay, start).to_string())
        }
        ext::LAST => {
            let hay = chars(&a[1]);
            let last = match a.get(2) {
                Some(spec) => index_of(spec, hay.len() as i64 - 1)?,
                None => i64::MAX,
            };
            Ok(find_last(&chars(&a[0]), &hay, last).to_string())
        }
        ext::INDEX => {
            let s = chars(&a[0]);
            let i = index_of(&a[1], s.len() as i64 - 1)?;
            Ok(match usize::try_from(i).ok().and_then(|i| s.get(i)) {
                Some(c) => c.to_string(),
                None => String::new(),
            })
        }
        ext::INSERT => {
            let s = chars(&a[0]);
            let mut at = index_of(&a[1], s.len() as i64)?;
            at = at.clamp(0, s.len() as i64);
            let at = at as usize;
            let mut out: String = s[..at].iter().collect();
            out.push_str(&a[2]);
            out.extend(&s[at..]);
            Ok(out)
        }
        ext::IS => Ok((is_class(&a[0], truth(&a[1]), &a[2])? as i32).to_string()),
        ext::LENGTH => Ok(a[0].chars().count().to_string()),
        ext::MAP => map(truth(&a[0]), &a[1], &a[2]),
        ext::MATCH => Ok((matches(&chars(&a[1]), &chars(&a[2]), truth(&a[0])) as i32).to_string()),
        ext::RANGE => {
            let s = chars(&a[0]);
            let end = s.len() as i64 - 1;
            let first = index_of(&a[1], end)?.max(0);
            let last = index_of(&a[2], end)?.min(end);
            Ok(if first > last {
                String::new()
            } else {
                s[first as usize..=last as usize].iter().collect()
            })
        }
        ext::REPEAT => {
            let count = want_int(&a[1])?;
            if count <= 0 || a[0].is_empty() {
                return Ok(String::new());
            }
            // The interpreter tries the allocation and dies with the process
            // when it cannot have it; refusing is the more useful answer.
            let bytes = (count as i128) * (a[0].len() as i128);
            if bytes > i32::MAX as i128 {
                return Err("string repeat: result would exceed 2 GiB".to_string());
            }
            Ok(a[0].repeat(count as usize))
        }
        ext::REPLACE => {
            let s = chars(&a[0]);
            let end = s.len() as i64 - 1;
            let first = index_of(&a[1], end)?;
            let last = index_of(&a[2], end)?;
            if first > last || first > end || last < 0 {
                return Ok(a[0].clone());
            }
            let first = first.max(0) as usize;
            let last = last.min(end) as usize;
            let mut out: String = s[..first].iter().collect();
            if let Some(new) = a.get(3) {
                out.push_str(new);
            }
            out.extend(&s[last + 1..]);
            Ok(out)
        }
        ext::REVERSE => Ok(chars(&a[0]).iter().rev().collect()),
        ext::TOLOWER | ext::TOTITLE | ext::TOUPPER => convert_case(id, &a),
        ext::TRIM | ext::TRIMLEFT | ext::TRIMRIGHT => {
            let s = chars(&a[0]);
            let set = a.get(1).map(|c| chars(c));
            let keep = |c: &char| match &set {
                Some(set) => !set.contains(c),
                None => !(*c == '\0' || is_space(*c)),
            };
            let start = if id == ext::TRIMRIGHT {
                0
            } else {
                s.iter().position(keep).unwrap_or(s.len())
            };
            let stop = if id == ext::TRIMLEFT {
                s.len()
            } else {
                s.iter().rposition(keep).map_or(start, |i| i + 1).max(start)
            };
            Ok(s[start..stop].iter().collect())
        }
        ext::FORMAT => format_string(&a[0], &a[1..]),
        other => Err(format!("unknown extension op {other}")),
    }
}

fn chars(s: &str) -> Vec<char> {
    s.chars().collect()
}

/// A compiler-pushed flag.
fn truth(s: &str) -> bool {
    s == "1"
}

// ── indices ──────────────────────────────────────────────────────────────

/// A Tcl index: `integer?[+-]integer?` or `end?[+-]integer?`, where `end`
/// stands for `end_value`. Ported from `GetEndOffsetFromObj` in
/// `generic/tclUtil.c`; every index that works out negative collapses to -1,
/// which is what `Tcl_GetIntForIndex` hands its callers.
fn index_of(spec: &str, end_value: i64) -> Result<i64, String> {
    let bad = || {
        Err(format!(
            "bad index \"{spec}\": must be integer?[+-]integer? or end?[+-]integer?"
        ))
    };

    if let Some(v) = parse_int(spec.trim_matches(is_ascii_space)) {
        return Ok(if v < 0 { -1 } else { v });
    }

    if let Some(rest) = spec.strip_prefix("end") {
        if rest.is_empty() {
            return Ok(end_value);
        }
        // Split on the byte, not with `split_at(1)`: the character after `end`
        // may be multi-byte — `string index abc endé` — and slicing into one
        // aborts the process where tclsh reports `bad index`.
        let op = rest.as_bytes()[0];
        if (op != b'-' && op != b'+') || rest[1..].starts_with(is_ascii_space) {
            return bad();
        }
        let digits = &rest[1..];
        let Some(mut offset) = parse_int(digits.trim_end_matches(is_ascii_space)) else {
            return bad();
        };
        if op == b'-' {
            offset = offset.saturating_neg();
        }
        // The interpreter distinguishes "end+1" from "end+n" so that commands
        // like lset can tell an append from an out-of-range write; every caller
        // here only needs a number past the end.
        return Ok(match offset {
            1 => end_value.saturating_add(1),
            n if n > 1 => i64::MAX - 1,
            n => end_value.saturating_add(n),
        });
    }

    // `M+N`: no whitespace may touch the operator, but the whole may be padded.
    let body = spec.trim_start_matches(is_ascii_space);
    let split = body
        .char_indices()
        .skip(1)
        .find(|(_, c)| *c == '+' || *c == '-')
        .map(|(i, _)| i);
    let Some(at) = split else { return bad() };
    let (left, rest) = body.split_at(at);
    let (op, right) = rest.split_at(1);
    if right.starts_with(is_ascii_space) {
        return bad();
    }
    let (Some(m), Some(n)) = (
        parse_int(left),
        parse_int(right.trim_end_matches(is_ascii_space)),
    ) else {
        return bad();
    };
    let sum = if op == "-" {
        m.saturating_sub(n)
    } else {
        m.saturating_add(n)
    };
    Ok(if sum < 0 { -1 } else { sum })
}

fn is_ascii_space(c: char) -> bool {
    matches!(c, ' ' | '\t' | '\n' | '\u{b}' | '\u{c}' | '\r')
}

/// Tcl's integer syntax: an optional sign, an optional radix prefix, and digits
/// that may be separated by underscores. Values that do not fit a `i64`
/// saturate, which is all any index needs.
fn parse_int(text: &str) -> Option<i64> {
    let lit = scan_int(text)?;
    let mut value: i64 = 0;
    for d in lit.digits.chars().filter_map(|c| c.to_digit(lit.radix)) {
        value = value
            .saturating_mul(lit.radix as i64)
            .saturating_add(d as i64);
    }
    Some(if lit.negative { -value } else { value })
}

struct IntLit {
    negative: bool,
    radix: u32,
    digits: String,
}

/// Scan a complete Tcl integer literal, or `None` when the text is not one.
fn scan_int(text: &str) -> Option<IntLit> {
    let (negative, body) = match text.strip_prefix(['-', '+']) {
        Some(rest) => (text.starts_with('-'), rest),
        None => (false, text),
    };
    let (radix, digits) = match body.get(..2) {
        Some("0x") | Some("0X") => (16, &body[2..]),
        Some("0o") | Some("0O") => (8, &body[2..]),
        Some("0b") | Some("0B") => (2, &body[2..]),
        Some("0d") | Some("0D") => (10, &body[2..]),
        _ => (10, body),
    };
    if !valid_digits(digits, radix) {
        return None;
    }
    Some(IntLit {
        negative,
        radix,
        digits: digits.to_string(),
    })
}

/// Digits in `radix`, with underscore runs allowed only between digits.
fn valid_digits(text: &str, radix: u32) -> bool {
    if text.is_empty() {
        return false;
    }
    let mut previous_digit = false;
    let mut pending_underscore = false;
    for c in text.chars() {
        if c == '_' {
            if !previous_digit {
                return false;
            }
            pending_underscore = true;
        } else if c.is_digit(radix) {
            previous_digit = true;
            pending_underscore = false;
        } else {
            return false;
        }
    }
    !pending_underscore
}

/// An operand a command needs as an integer.
fn want_int(text: &str) -> Result<i64, String> {
    parse_int(text.trim_matches(is_ascii_space))
        .ok_or_else(|| format!("expected integer but got \"{text}\""))
}

// ── comparison and search ────────────────────────────────────────────────

/// `TclStringCmp`: compare by code point, optionally case-folded, optionally
/// only over the first `req` characters.
fn compare(a: &[char], b: &[char], nocase: bool, req: Option<i64>) -> i32 {
    if req == Some(0) {
        return 0;
    }
    let mut len = a.len().min(b.len());
    let req = req.filter(|r| *r > 0).map(|r| r as usize);
    if let Some(r) = req {
        len = len.min(r);
    }
    for i in 0..len {
        let (x, y) = if nocase {
            (lower(a[i]), lower(b[i]))
        } else {
            (a[i], b[i])
        };
        if x != y {
            return if x < y { -1 } else { 1 };
        }
    }
    match req {
        Some(r) if r <= len => 0,
        _ => (a.len() as i64 - b.len() as i64).signum() as i32,
    }
}

fn find_first(needle: &[char], hay: &[char], start: i64) -> i64 {
    if needle.is_empty() || needle.len() > hay.len() {
        return -1;
    }
    let from = start.max(0) as usize;
    for i in from..=hay.len().saturating_sub(needle.len()) {
        if hay[i..].starts_with(needle) {
            return i as i64;
        }
    }
    -1
}

fn find_last(needle: &[char], hay: &[char], last: i64) -> i64 {
    if needle.is_empty() || needle.len() > hay.len() || last < 0 {
        return -1;
    }
    let highest = hay.len() - needle.len();
    let limit = if last < highest as i64 {
        last as usize
    } else {
        highest
    };
    for i in (0..=limit).rev() {
        if hay[i..].starts_with(needle) {
            return i as i64;
        }
    }
    -1
}

// ── glob matching ────────────────────────────────────────────────────────

/// `Tcl_StringCaseMatch`, ported. `[` opens a set that ends at the first `]`;
/// `^` has no meaning inside one, an unterminated set matches only when both
/// pattern and string run out together, and a reversed range still matches.
fn matches(pattern: &[char], text: &[char], nocase: bool) -> bool {
    let (mut p, mut s) = (0usize, 0usize);
    loop {
        if p >= pattern.len() {
            return s >= text.len();
        }
        if s >= text.len() && pattern[p] != '*' {
            return false;
        }

        if pattern[p] == '*' {
            while p < pattern.len() && pattern[p] == '*' {
                p += 1;
            }
            if p >= pattern.len() {
                return true;
            }
            let head = fold(pattern[p], nocase);
            loop {
                if !matches!(pattern[p], '[' | '?' | '\\') {
                    while s < text.len() && fold(text[s], nocase) != head {
                        s += 1;
                    }
                }
                if matches(&pattern[p..], &text[s..], nocase) {
                    return true;
                }
                if s >= text.len() {
                    return false;
                }
                s += 1;
            }
        }

        if pattern[p] == '?' {
            p += 1;
            s += 1;
            continue;
        }

        if pattern[p] == '[' {
            p += 1;
            let ch = fold(text[s], nocase);
            s += 1;
            loop {
                if p >= pattern.len() || pattern[p] == ']' {
                    return false;
                }
                let start = fold(pattern[p], nocase);
                p += 1;
                if pattern.get(p) == Some(&'-') {
                    p += 1;
                    let Some(&raw) = pattern.get(p) else {
                        return false;
                    };
                    let stop = fold(raw, nocase);
                    p += 1;
                    if (start <= ch && ch <= stop) || (stop <= ch && ch <= start) {
                        break;
                    }
                } else if start == ch {
                    break;
                }
            }
            while pattern.get(p) != Some(&']') {
                if p >= pattern.len() {
                    // The set never closed; a match still stands if both ran out.
                    return s >= text.len();
                }
                p += 1;
            }
            p += 1;
            continue;
        }

        if pattern[p] == '\\' {
            p += 1;
            if p >= pattern.len() {
                return false;
            }
        }

        if fold(text[s], nocase) != fold(pattern[p], nocase) {
            return false;
        }
        s += 1;
        p += 1;
    }
}

fn fold(c: char, nocase: bool) -> char {
    if nocase {
        lower(c)
    } else {
        c
    }
}

// ── string map ───────────────────────────────────────────────────────────

/// `StringMapCmd`: one left-to-right pass, keys tried in list order, the first
/// that matches wins and the scan resumes after it.
fn map(nocase: bool, mapping: &str, text: &str) -> Result<String, String> {
    let pairs = split_list(mapping)?;
    if pairs.is_empty() {
        return Ok(text.to_string());
    }
    if pairs.len() % 2 != 0 {
        return Err("char map list unbalanced".to_string());
    }
    let keys: Vec<Vec<char>> = pairs.iter().step_by(2).map(|k| chars(k)).collect();
    let s = chars(text);
    let mut out = String::new();
    let mut i = 0;
    'outer: while i < s.len() {
        for (k, key) in keys.iter().enumerate() {
            if key.is_empty() || key.len() > s.len() - i {
                continue;
            }
            let hit = key
                .iter()
                .zip(&s[i..])
                .all(|(a, b)| fold(*a, nocase) == fold(*b, nocase));
            if hit {
                out.push_str(&pairs[2 * k + 1]);
                i += key.len();
                continue 'outer;
            }
        }
        out.push(s[i]);
        i += 1;
    }
    Ok(out)
}

/// `TclFindElement`, ported: split a Tcl list into its elements.
///
/// Byte offsets are safe here because every character the parse reacts to is
/// ASCII, and a UTF-8 continuation byte can never be one of them.
fn split_list(text: &str) -> Result<Vec<String>, String> {
    let b = text.as_bytes();
    let mut out = Vec::new();
    let mut i = 0usize;
    loop {
        while i < b.len() && is_list_space(b[i]) {
            i += 1;
        }
        if i >= b.len() {
            return Ok(out);
        }
        let (mut braces, mut quoted) = (0usize, false);
        match b[i] {
            b'{' => {
                braces = 1;
                i += 1;
            }
            b'"' => {
                quoted = true;
                i += 1;
            }
            _ => {}
        }
        let start = i;
        let mut literal = true;
        let stop;
        loop {
            if i >= b.len() {
                if braces != 0 {
                    return Err("unmatched open brace in list".to_string());
                }
                if quoted {
                    return Err("unmatched open quote in list".to_string());
                }
                stop = i;
                break;
            }
            match b[i] {
                b'{' if braces != 0 => {
                    braces += 1;
                    i += 1;
                }
                b'}' if braces > 1 => {
                    braces -= 1;
                    i += 1;
                }
                b'}' if braces == 1 => {
                    stop = i;
                    i += 1;
                    if i < b.len() && !is_list_space(b[i]) {
                        return Err("list element in braces followed by junk".to_string());
                    }
                    break;
                }
                b'\\' => {
                    if braces == 0 {
                        // The element's value differs from the text scanned, so
                        // the caller has to collapse it.
                        literal = false;
                    }
                    i = crate::parser::backslash_at(text, i).1;
                }
                b'"' if quoted => {
                    stop = i;
                    i += 1;
                    if i < b.len() && !is_list_space(b[i]) {
                        return Err("list element in quotes followed by junk".to_string());
                    }
                    break;
                }
                c if is_list_space(c) && braces == 0 && !quoted => {
                    stop = i;
                    break;
                }
                _ => i += 1,
            }
        }
        out.push(if literal {
            text[start..stop].to_string()
        } else {
            collapse(&text[start..stop])
        });
    }
}

/// `TclCopyAndCollapse`: resolve the backslash sequences of a list element,
/// which the splitter reports verbatim.
fn collapse(text: &str) -> String {
    let b = text.as_bytes();
    let mut out = String::new();
    let mut i = 0usize;
    while i < b.len() {
        if b[i] == b'\\' {
            let (value, next) = crate::parser::backslash_at(text, i);
            out.push_str(&value);
            i = next;
        } else {
            let start = i;
            i += 1;
            while i < b.len() && b[i] & 0xC0 == 0x80 {
                i += 1;
            }
            out.push_str(&text[start..i]);
        }
    }
    out
}

fn is_list_space(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')
}

// ── case conversion ──────────────────────────────────────────────────────

/// Tcl's simple uppercase. Rust's `to_uppercase` is the full mapping, which
/// expands some characters into several; Tcl uses the one-to-one mapping from
/// `UnicodeData`, and where none exists the character is unchanged. The Greek
/// ypogegrammeni letters are the set where the two disagree — their full
/// mapping is two characters but their simple mapping is the capital eight code
/// points along.
fn upper(c: char) -> char {
    let v = c as u32;
    let simple = match v {
        0x1F80..=0x1F87 | 0x1F90..=0x1F97 | 0x1FA0..=0x1FA7 => char::from_u32(v + 8).unwrap_or(c),
        0x1FB3 => '\u{1FBC}',
        0x1FC3 => '\u{1FCC}',
        0x1FF3 => '\u{1FFC}',
        _ => single(c.to_uppercase(), c),
    };
    guard(c, simple)
}

/// Tcl's simple lowercase. U+0130 is the only character whose full lowercase
/// runs to two code points, and its simple mapping is a plain `i`.
fn lower(c: char) -> char {
    let simple = if c == '\u{130}' {
        'i'
    } else {
        single(c.to_lowercase(), c)
    };
    guard(c, simple)
}

/// Tcl's titlecase. Georgian Mkhedruli has no titlecase in Tcl's tables even
/// though it has an uppercase, so it is left alone.
fn title(c: char) -> char {
    if matches!(c as u32, 0x10D0..=0x10FA | 0x10FD..=0x10FF) {
        return c;
    }
    let simple = match c {
        '\u{1C4}' | '\u{1C5}' | '\u{1C6}' => '\u{1C5}',
        '\u{1C7}' | '\u{1C8}' | '\u{1C9}' => '\u{1C8}',
        '\u{1CA}' | '\u{1CB}' | '\u{1CC}' => '\u{1CB}',
        '\u{1F1}' | '\u{1F2}' | '\u{1F3}' => '\u{1F2}',
        _ => return upper(c),
    };
    guard(c, simple)
}

fn single(mut mapping: impl Iterator<Item = char>, fallback: char) -> char {
    let first = mapping.next().unwrap_or(fallback);
    if mapping.next().is_some() {
        fallback
    } else {
        first
    }
}

/// Tcl converts case in place and keeps the original character whenever the
/// converted one would need more bytes, so `ɐ` (two bytes) never becomes `Ɐ`
/// (three).
fn guard(original: char, mapped: char) -> char {
    if mapped.len_utf8() > original.len_utf8() {
        original
    } else {
        mapped
    }
}

/// `string tolower`, `totitle` and `toupper`, with their optional index range.
fn convert_case(id: u16, a: &[String]) -> Result<String, String> {
    let s = chars(&a[0]);
    let end = s.len() as i64 - 1;
    let (first, last) = if a.len() == 1 {
        (0, end)
    } else {
        let first = index_of(&a[1], end)?.max(0);
        let last = match a.get(2) {
            Some(spec) => index_of(spec, end)?,
            None => first,
        };
        // The interpreter clamps the end of the range before deciding whether
        // the range is empty, so `string tolower ABCDEF 10` is a no-op.
        (first, last.min(end))
    };
    if last < first {
        return Ok(a[0].clone());
    }

    let (first, last) = (first as usize, last as usize);
    let mut out: String = s[..first].iter().collect();
    for (offset, &c) in s[first..=last].iter().enumerate() {
        out.push(match id {
            ext::TOUPPER => upper(c),
            ext::TOLOWER => lower(c),
            _ if offset == 0 => title(c),
            // The tail of a titlecased range is lowercased, except for Georgian
            // Asomtavruli, which `Tcl_UtfToTitle` skips.
            _ if matches!(c as u32, 0x1C90..=0x1CBF) => c,
            _ => lower(c),
        });
    }
    out.extend(&s[last + 1..]);
    Ok(out)
}

// ── character classes ────────────────────────────────────────────────────

/// Tcl's whitespace: the C0 set below U+0080, then the Unicode separators plus
/// four characters Tcl names explicitly. Verified equal to the interpreter over
/// every code point up to U+2FFFF.
fn is_space(c: char) -> bool {
    if (c as u32) < 0x80 {
        matches!(c, ' ' | '\t' | '\n' | '\u{b}' | '\u{c}' | '\r')
    } else {
        c.is_whitespace() || matches!(c, '\u{180E}' | '\u{200B}' | '\u{2060}' | '\u{FEFF}')
    }
}

/// `string is`. The classes that rest on Unicode general categories accept
/// ASCII, where the two implementations were verified to agree exactly, and
/// report an error on anything else rather than answering from Rust's tables,
/// which are a different Unicode revision than Tcl's.
fn is_class(class: &str, strict: bool, text: &str) -> Result<bool, String> {
    if class == "list" {
        // Strictness is ignored here: an empty string is a well-formed list.
        return Ok(split_list(text).is_ok());
    }
    if text.is_empty() {
        return Ok(!strict);
    }

    match class {
        "boolean" | "true" | "false" => {
            let Some(value) = parse_bool(text) else {
                return Ok(false);
            };
            return Ok(match class {
                "true" => value,
                "false" => !value,
                _ => true,
            });
        }
        "integer" | "entier" => return Ok(scan_int(text.trim_matches(is_ascii_space)).is_some()),
        "wideinteger" => {
            let body = text.trim_matches(is_ascii_space);
            return Ok(scan_int(body).is_some() && fits_wide(body));
        }
        "double" => return Ok(is_double(text.trim_matches(is_ascii_space))),
        _ => {}
    }

    let ok = |c: char| -> Result<bool, String> {
        if class == "ascii" {
            return Ok((c as u32) < 0x80);
        }
        if class == "xdigit" {
            return Ok(c.is_ascii_hexdigit());
        }
        if class == "space" {
            return Ok(is_space(c));
        }
        if (c as u32) >= 0x80 {
            return Err(format!(
                "string is {class}: characters beyond ASCII need Unicode category tables, which are not built yet"
            ));
        }
        Ok(match class {
            "alnum" => c.is_ascii_alphanumeric(),
            "alpha" => c.is_ascii_alphabetic(),
            "control" => c.is_ascii_control(),
            "digit" => c.is_ascii_digit(),
            "lower" => c.is_ascii_lowercase(),
            "upper" => c.is_ascii_uppercase(),
            "wordchar" => c.is_ascii_alphanumeric() || c == '_',
            _ => return Err(format!("unknown character class \"{class}\"")),
        })
    };

    for c in text.chars() {
        if !ok(c)? {
            return Ok(false);
        }
    }
    Ok(true)
}

/// `Tcl_GetBoolean`: literally `0` or `1`, or a unique case-insensitive prefix
/// of one of the six words.
fn parse_bool(text: &str) -> Option<bool> {
    if text == "0" {
        return Some(false);
    }
    if text == "1" {
        return Some(true);
    }
    let lowered = text.to_ascii_lowercase();
    const WORDS: [(&str, bool); 6] = [
        ("true", true),
        ("false", false),
        ("yes", true),
        ("no", false),
        ("on", true),
        ("off", false),
    ];
    let mut hit = None;
    for (word, value) in WORDS {
        if word.starts_with(&lowered) {
            if hit.is_some_and(|v| v != value) {
                return None;
            }
            hit = Some(value);
        }
    }
    hit
}

/// Whether an integer literal fits the wide range, which is what separates
/// `wideinteger` from `integer`.
fn fits_wide(text: &str) -> bool {
    let Some(lit) = scan_int(text) else {
        return false;
    };
    let mut value: i128 = 0;
    for d in lit.digits.chars().filter_map(|c| c.to_digit(lit.radix)) {
        value = value * lit.radix as i128 + d as i128;
        if value > u64::MAX as i128 {
            return false;
        }
    }
    if lit.negative {
        -value >= i64::MIN as i128
    } else {
        value <= i64::MAX as i128
    }
}

/// Tcl's double syntax: an integer literal, a decimal number, or one of the
/// non-finite spellings.
fn is_double(text: &str) -> bool {
    if scan_int(text).is_some() {
        return true;
    }
    let body = text.strip_prefix(['-', '+']).unwrap_or(text);
    let folded = body.to_ascii_lowercase();
    if matches!(folded.as_str(), "inf" | "infinity" | "nan") {
        return true;
    }
    let (mantissa, exponent) = match folded.split_once('e') {
        Some((m, e)) => (m, Some(e)),
        None => (folded.as_str(), None),
    };
    let (whole, fraction) = match mantissa.split_once('.') {
        Some((w, f)) => (w, f),
        None => (mantissa, ""),
    };
    let digits = |part: &str| part.is_empty() || valid_digits(part, 10);
    if whole.is_empty() && fraction.is_empty() {
        return false;
    }
    if !digits(whole) || !digits(fraction) {
        return false;
    }
    match exponent {
        None => true,
        Some(e) => {
            let e = e.strip_prefix(['-', '+']).unwrap_or(e);
            valid_digits(e, 10)
        }
    }
}

// ── format ───────────────────────────────────────────────────────────────

#[derive(Default, Clone, Copy)]
struct Flags {
    minus: bool,
    plus: bool,
    space: bool,
    zero: bool,
    hash: bool,
}

/// How wide the integer is before it is converted. Tcl truncates to 32 bits
/// unless the specifier says otherwise, so `format %d 4294967296` is 0.
#[derive(Clone, Copy, PartialEq)]
enum Width {
    Bits16,
    Bits32,
    Bits64,
    Untruncated,
}

/// `format`, following `Tcl_AppendFormatToObj`.
fn format_string(fmt: &str, args: &[String]) -> Result<String, String> {
    let f = chars(fmt);
    let mut out = String::new();
    let mut i = 0;
    let mut next_arg = 0usize;
    let mut positional: Option<bool> = None;

    let take = |index: usize| -> Result<&String, String> {
        args.get(index)
            .ok_or_else(|| "not enough arguments for all format specifiers".to_string())
    };

    while i < f.len() {
        if f[i] != '%' {
            out.push(f[i]);
            i += 1;
            continue;
        }
        i += 1;
        if f.get(i) == Some(&'%') {
            out.push('%');
            i += 1;
            continue;
        }

        // XPG3 position, which must be used by every specifier or by none.
        let mut argument = next_arg;
        let mut is_positional = false;
        let digits = digit_run(&f, i);
        if digits > i && f.get(digits) == Some(&'$') {
            let n: usize = f[i..digits].iter().collect::<String>().parse().unwrap_or(0);
            if n == 0 {
                return Err("\"%n$\" argument index out of range".to_string());
            }
            if n > args.len() {
                return Err("\"%n$\" argument index out of range".to_string());
            }
            argument = n - 1;
            is_positional = true;
            i = digits + 1;
        }
        match positional {
            Some(previous) if previous != is_positional => {
                return Err("cannot mix \"%\" and \"%n$\" conversion specifiers".to_string())
            }
            _ => positional = Some(is_positional),
        }

        let mut flags = Flags::default();
        loop {
            match f.get(i) {
                Some('-') => flags.minus = true,
                Some('+') => flags.plus = true,
                Some(' ') => flags.space = true,
                Some('0') => flags.zero = true,
                Some('#') => flags.hash = true,
                _ => break,
            }
            i += 1;
        }

        let mut width: i64 = 0;
        if f.get(i) == Some(&'*') {
            width = want_int(take(argument)?)?;
            argument += 1;
            i += 1;
        } else {
            let stop = digit_run(&f, i);
            if stop > i {
                width = f[i..stop]
                    .iter()
                    .collect::<String>()
                    .parse()
                    .map_err(|_| "integer value too large to represent".to_string())?;
                i = stop;
            }
        }
        if width < 0 {
            flags.minus = true;
            width = -width;
        }

        let mut precision: Option<i64> = None;
        if f.get(i) == Some(&'.') {
            i += 1;
            let value = if f.get(i) == Some(&'*') {
                argument += 1;
                i += 1;
                want_int(take(argument - 1)?)?
            } else {
                let stop = digit_run(&f, i);
                // A spelling too long for an `i64` saturates rather than
                // reading as zero: it is a precision larger than any result,
                // so it belongs on the far side of the size check below, not
                // on the "no precision at all" side. tclsh reports
                // `max size for a Tcl value exceeded` for
                // `format %.99999999999999999999d 1`, which is what saturating
                // produces here.
                //
                // `%.f` — a point with no digits after it — is a precision of
                // zero, so an *empty* run is still zero.
                let text = f[i..stop].iter().collect::<String>();
                i = stop;
                if text.is_empty() {
                    0
                } else {
                    text.parse().unwrap_or(i64::MAX)
                }
            };
            precision = Some(value.max(0));
        }

        let mut size = Width::Bits32;
        if f.get(i) == Some(&'l') && f.get(i + 1) == Some(&'l') {
            size = Width::Untruncated;
            i += 2;
        } else {
            match f.get(i) {
                Some('h') => {
                    size = Width::Bits16;
                    i += 1;
                }
                // `z` and `t` mean the platform's pointer width, which is the
                // wide range on every target this crate builds for.
                Some('l') | Some('j') | Some('q') | Some('z') | Some('t') => {
                    size = Width::Bits64;
                    i += 1;
                }
                Some('L') => {
                    size = Width::Untruncated;
                    i += 1;
                }
                _ => {}
            }
        }

        let Some(&conv) = f.get(i) else {
            return Err(if args.len() <= argument {
                "not enough arguments for all format specifiers".to_string()
            } else {
                "format string ended in middle of field specifier".to_string()
            });
        };
        i += 1;

        let value = take(argument)?;
        next_arg = argument + 1;
        let converted = match conv {
            's' => Signed::plain(match precision {
                Some(p) => value.chars().take(p as usize).collect(),
                None => value.clone(),
            }),
            'c' => Signed::plain(
                char::from_u32(want_int(value)? as u32)
                    .unwrap_or(char::REPLACEMENT_CHARACTER)
                    .to_string(),
            ),
            'd' | 'i' | 'u' | 'o' | 'x' | 'X' | 'b' => {
                integer(conv, flags, precision, size, value)?
            }
            'e' | 'E' | 'f' | 'g' | 'G' => floating(conv, flags, precision, value)?,
            'a' | 'A' | 'p' => {
                return Err(format!("the \"%{conv}\" conversion is not supported yet"))
            }
            other => return Err(format!("bad field specifier \"{other}\"")),
        };
        push_padded(&mut out, converted, flags, width)?;
    }
    Ok(out)
}

/// The largest string `format` will build.
///
/// A field width and a precision both come straight from the script, and both
/// scale the result: `format %9223372036854775807d 1` asked for a string of
/// 9 exabytes, and the allocator's refusal is an abort — the process dies with
/// nothing for the script to catch. tclsh 9.0.4 reports
/// [`TOO_BIG`] for the same input, so refusing before the allocation is asked
/// for both matches it and keeps the failure catchable.
///
/// The limit is 2 GiB rather than tclsh's own: tclsh 9.0's `Tcl_Size` is 64-bit
/// and `format %4294967296d 1` really does build a 4 GiB string there, which is
/// a memory bomb rather than a useful answer. `string repeat` already refuses
/// above 2 GiB (see [`ext::REPEAT`]'s arm), and the two now agree.
const MAX_VALUE_BYTES: usize = i32::MAX as usize;

/// What tclsh 9.0.4 reports when a `format` result cannot be had. Measured:
/// `format %9223372036854775807d 1` and `format %.9223372036854775807f 1e-5`
/// both print it.
const TOO_BIG: &str = "max size for a Tcl value exceeded";

/// The largest precision Rust's formatter accepts: it holds one in a `u16`, and
/// anything above is `Formatting argument out of range` — a panic, not an error.
///
/// `format`'s precision is whatever the script wrote, and tclsh prints every
/// digit asked for (`string length [format %.65536f 1.0]` is 65538 there), so
/// the digits past this are produced by [`extend_exact`] instead.
const RUST_MAX_PRECISION: usize = u16::MAX as usize;

/// Append the fraction digits Rust's formatter would not produce.
///
/// A double's exact decimal expansion is finite — at most 1_074 fraction digits,
/// for the smallest subnormal — so a precision above the expansion asks only for
/// zeroes, and every digit past [`RUST_MAX_PRECISION`] is one of them. Appending
/// them is therefore exact, not an approximation.
fn extend_exact(digits: &mut String, precision: usize) -> Result<(), String> {
    if precision <= RUST_MAX_PRECISION {
        return Ok(());
    }
    let extra = precision - RUST_MAX_PRECISION;
    if digits.len().saturating_add(extra) > MAX_VALUE_BYTES {
        return Err(TOO_BIG.to_string());
    }
    digits.extend(std::iter::repeat_n('0', extra));
    Ok(())
}

/// A converted number split so that padding can go between its sign and its
/// digits.
struct Signed {
    prefix: String,
    digits: String,
    /// C ignores the `0` flag when an integer conversion states a precision,
    /// and for a value that prints as `inf`.
    zero_pad: bool,
}

impl Signed {
    fn plain(digits: String) -> Signed {
        Signed {
            prefix: String::new(),
            digits,
            zero_pad: true,
        }
    }
}

fn push_padded(out: &mut String, value: Signed, flags: Flags, width: i64) -> Result<(), String> {
    let len = value.prefix.chars().count() + value.digits.chars().count();
    let fill = (width as usize).saturating_sub(len);
    // The width is the script's, so the padding is too. Refuse before asking the
    // allocator for something it will die on — see [`MAX_VALUE_BYTES`]. The
    // running total is checked, not just this field, so a format string of many
    // wide specifiers cannot walk past the limit one field at a time.
    if out
        .len()
        .saturating_add(fill)
        .saturating_add(value.digits.len())
        > MAX_VALUE_BYTES
    {
        return Err(TOO_BIG.to_string());
    }
    if fill == 0 {
        out.push_str(&value.prefix);
        out.push_str(&value.digits);
        return Ok(());
    }
    if flags.zero && value.zero_pad {
        // Tcl pads with zeroes even when the field is left-justified.
        out.push_str(&value.prefix);
        out.extend(std::iter::repeat_n('0', fill));
        out.push_str(&value.digits);
    } else if flags.minus {
        out.push_str(&value.prefix);
        out.push_str(&value.digits);
        out.extend(std::iter::repeat_n(' ', fill));
    } else {
        out.extend(std::iter::repeat_n(' ', fill));
        out.push_str(&value.prefix);
        out.push_str(&value.digits);
    }
    Ok(())
}

fn digit_run(f: &[char], from: usize) -> usize {
    let mut i = from;
    while i < f.len() && f[i].is_ascii_digit() {
        i += 1;
    }
    i
}

/// An integer conversion. Without a size modifier Tcl truncates to 32 bits;
/// `ll` skips truncation altogether and prints a sign with the magnitude, which
/// is how a bignum would come out.
fn integer(
    conv: char,
    flags: Flags,
    precision: Option<i64>,
    size: Width,
    value: &str,
) -> Result<Signed, String> {
    let n = parse_int(value.trim_matches(is_ascii_space))
        .ok_or_else(|| format!("expected integer but got \"{value}\""))?;
    let signed_conv = matches!(conv, 'd' | 'i');
    let radix = match conv {
        'o' => 8,
        'x' | 'X' => 16,
        'b' => 2,
        _ => 10,
    };

    let (negative, magnitude) = if size == Width::Untruncated {
        if conv == 'u' {
            return Err("unsigned bignum format is invalid".to_string());
        }
        (n < 0, n.unsigned_abs())
    } else {
        let truncated = match size {
            Width::Bits16 => n as i16 as i64,
            Width::Bits32 => n as i32 as i64,
            _ => n,
        };
        if signed_conv {
            (truncated < 0, truncated.unsigned_abs())
        } else {
            let unsigned = match size {
                Width::Bits16 => truncated as u16 as u64,
                Width::Bits32 => truncated as u32 as u64,
                _ => truncated as u64,
            };
            (false, unsigned)
        }
    };

    let mut digits = match radix {
        8 => format!("{magnitude:o}"),
        16 if conv == 'X' => format!("{magnitude:X}"),
        16 => format!("{magnitude:x}"),
        2 => format!("{magnitude:b}"),
        _ => magnitude.to_string(),
    };
    if let Some(p) = precision {
        // Unlike C, Tcl still prints one digit when the precision is zero.
        let p = (p as usize).max(1);
        if digits.len() < p {
            // An integer conversion pads on the *left*, so the precision scales
            // the result here the way it does for a double — and the number is
            // the script's. `format %.9223372036854775807d 1` asked for 9
            // exabytes of leading zeroes; see [`MAX_VALUE_BYTES`].
            if p > MAX_VALUE_BYTES {
                return Err(TOO_BIG.to_string());
            }
            digits.insert_str(0, &"0".repeat(p - digits.len()));
        }
    }

    let mut prefix = String::new();
    if negative {
        prefix.push('-');
    } else if signed_conv || size == Width::Untruncated {
        if flags.plus {
            prefix.push('+');
        } else if flags.space {
            prefix.push(' ');
        }
    }
    if flags.hash && magnitude != 0 {
        prefix.push_str(match conv {
            'o' => "0o",
            'x' => "0x",
            'X' => "0x",
            'b' => "0b",
            'd' | 'i' => "0d",
            _ => "",
        });
    }
    Ok(Signed {
        prefix,
        digits,
        zero_pad: precision.is_none(),
    })
}

/// A floating-point conversion. Rust's own formatting supplies the digits —
/// it rounds exactly the way C's does — and this reshapes them into C's layout.
fn floating(
    conv: char,
    flags: Flags,
    precision: Option<i64>,
    value: &str,
) -> Result<Signed, String> {
    let x = parse_double(value)
        .ok_or_else(|| format!("expected floating-point number but got \"{value}\""))?;
    if x.is_nan() {
        return Err("floating point value is Not a Number".to_string());
    }
    let upper_case = conv.is_ascii_uppercase();
    let mut prefix = String::new();
    if x.is_sign_negative() {
        prefix.push('-');
    } else if flags.plus {
        prefix.push('+');
    } else if flags.space {
        prefix.push(' ');
    }
    if x.is_infinite() {
        return Ok(Signed {
            prefix,
            digits: if upper_case { "INF" } else { "inf" }.to_string(),
            zero_pad: false,
        });
    }

    let magnitude = x.abs();
    let precision = precision.unwrap_or(6).max(0) as usize;
    // Checked once, up front, rather than only where the digits are built: `%g`
    // strips trailing zeroes, so its digits can be produced at a clamped
    // precision and come out identical — which would let a precision far past
    // any possible result quietly succeed. tclsh refuses on the precision
    // asked for, whatever the conversion does with it.
    if precision > MAX_VALUE_BYTES {
        return Err(TOO_BIG.to_string());
    }
    let digits = match conv.to_ascii_lowercase() {
        'f' => {
            let mut s = fixed(magnitude, precision)?;
            if precision == 0 && flags.hash {
                s.push('.');
            }
            s
        }
        'e' => exponential(magnitude, precision, flags.hash, upper_case)?,
        _ => {
            let significant = precision.max(1);
            let exponent = decimal_exponent(magnitude, significant - 1);
            // Compared as `i64`: `significant` is the script's precision, and
            // an `i32` cast of one past 2^31 wraps to a negative and sends the
            // conversion down the wrong branch.
            if exponent < -4 || exponent as i64 >= significant as i64 {
                if flags.hash {
                    exponential(magnitude, significant - 1, true, upper_case)?
                } else {
                    // The trailing zeroes are about to be stripped, so the
                    // digits past the double's exact expansion need never be
                    // produced: clamping to what Rust's formatter takes gives
                    // the same answer for a fraction of the work.
                    let s = exponential(
                        magnitude,
                        (significant - 1).min(RUST_MAX_PRECISION),
                        false,
                        upper_case,
                    )?;
                    let (mantissa, tail) = s.split_at(s.find(['e', 'E']).unwrap_or(s.len()));
                    format!("{}{tail}", strip_zeroes(mantissa))
                }
            } else {
                let places = (significant as i64 - 1 - exponent as i64).max(0) as usize;
                if flags.hash {
                    let s = fixed(magnitude, places)?;
                    if places == 0 {
                        format!("{s}.")
                    } else {
                        s
                    }
                } else {
                    // Stripped as above, so the clamp is again exact.
                    let s = fixed(magnitude, places.min(RUST_MAX_PRECISION))?;
                    strip_zeroes(&s).to_string()
                }
            }
        }
    };
    Ok(Signed {
        prefix,
        digits,
        zero_pad: true,
    })
}

/// `magnitude` with `precision` fraction digits, for a precision Rust's
/// formatter will not take. See [`RUST_MAX_PRECISION`].
fn fixed(magnitude: f64, precision: usize) -> Result<String, String> {
    let mut s = format!("{magnitude:.p$}", p = precision.min(RUST_MAX_PRECISION));
    extend_exact(&mut s, precision)?;
    Ok(s)
}

/// `x.yyye±zz`, with the two-digit exponent C guarantees.
fn exponential(
    magnitude: f64,
    precision: usize,
    hash: bool,
    upper_case: bool,
) -> Result<String, String> {
    let raw = format!("{magnitude:.p$e}", p = precision.min(RUST_MAX_PRECISION));
    let (mantissa, exponent) = raw.split_once('e').expect("exponential form");
    let exponent: i32 = exponent.parse().expect("exponent digits");
    let mut mantissa = mantissa.to_string();
    // The mantissa carries the fraction digits, so it is what grows past
    // Rust's ceiling.
    extend_exact(&mut mantissa, precision)?;
    if precision == 0 && hash {
        mantissa.push('.');
    }
    Ok(format!(
        "{mantissa}{}{}{:02}",
        if upper_case { 'E' } else { 'e' },
        if exponent < 0 { '-' } else { '+' },
        exponent.abs()
    ))
}

/// The exponent `%e` would print after rounding to `precision` fraction digits,
/// which is what decides whether `%g` uses fixed or exponential form.
///
/// The precision is clamped rather than extended: rounding a double past its
/// exact decimal expansion cannot move the decimal point, so every precision
/// above [`RUST_MAX_PRECISION`] gives the exponent that one gives.
fn decimal_exponent(magnitude: f64, precision: usize) -> i32 {
    let raw = format!("{magnitude:.p$e}", p = precision.min(RUST_MAX_PRECISION));
    raw.split_once('e')
        .and_then(|(_, e)| e.parse().ok())
        .unwrap_or(0)
}

/// Drop the trailing zeroes of a fraction, and the point if nothing is left.
fn strip_zeroes(s: &str) -> &str {
    if !s.contains('.') {
        return s;
    }
    s.trim_end_matches('0').trim_end_matches('.')
}

/// Tcl's double parser, which also takes the integer spellings.
fn parse_double(text: &str) -> Option<f64> {
    let body = text.trim_matches(is_ascii_space);
    if let Some(lit) = scan_int(body) {
        let mut value = 0f64;
        for d in lit.digits.chars().filter_map(|c| c.to_digit(lit.radix)) {
            value = value * lit.radix as f64 + d as f64;
        }
        // An integer spelling is converted as an integer, and an integer has no
        // negative zero — so `format %.2f -0` prints `0.00` where the *double*
        // `-0.0` prints `-0.00`. Measured against tclsh 9.0.4, which agrees for
        // `-00`, `-0x0`, `-0_0` and ` -0 ` and keeps the sign of every nonzero
        // magnitude, including one too large for an `i64`.
        return Some(if lit.negative && value != 0.0 {
            -value
        } else {
            value
        });
    }
    if !is_double(body) {
        return None;
    }
    let cleaned: String = body.chars().filter(|c| *c != '_').collect();
    cleaned.parse().ok()
}