tclrs 0.4.2

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
//! The `clock` ensemble.
//!
//! What is here and what is refused, stated plainly, because a wrong
//! `clock format` is worse than one that says it cannot answer:
//!
//! * `seconds`, `milliseconds`, `microseconds`, `clicks` — complete.
//! * `format` — the whole token set of tclsh 9.0.4's `FmtSTokenMap`, the
//!   `%E` and `%O` maps beside it (`generic/tclClockFmt.c`) and the
//!   locale-format expansions `::tcl::clock::LocalizeFormat` performs
//!   (`library/clock.tcl`).
//! * `-locale` — every catalogue the release ships, read from the vendored
//!   copies in [`crate::clock_msgs`] through [`crate::clock_locale`]. A name
//!   with no catalogue anywhere in its fallback chain is the root locale, as
//!   it is there.
//! * `scan` — the `-format` form only, with the whole of `ScnSTokenMap` and
//!   the `%E` and `%O` maps beside it. tclsh's free-form parser is a
//!   several-thousand-line grammar over relative words, month names, ISO
//!   forms and time zone abbreviations; it is refused by name rather than
//!   approximated.
//! * `add` — every unit tclsh accepts, with the calendar arithmetic for
//!   months and years and the weekday walk for `weekdays`.
//! * Time zones — `-gmt`, a fixed numeric offset, and any zone with a `TZif`
//!   file, read with the same reader tclsh's `LoadZoneinfoFile` implements in
//!   Tcl. The default zone comes from `TZ` or `/etc/localtime`, as tclsh's
//!   does.
//!
//! Refused, each with its own message:
//!
//! * Any instant before the Gregorian changeover of 1752-09-14, which tclsh
//!   reckons in the Julian calendar and this module has no calendar for. See
//!   `EARLIEST`, and note the date is not the locale's.
//! * A POSIX `TZ` *rule* string (`EST5EDT,M3.2.0,M11.1.0`) with no matching
//!   zone file, and a time zone named by abbreviation in `clock scan`.
//! * `clock scan` without `-format`.
//!
//! Not refused but not tclsh's answer either: a `clock scan` whose format
//! names a weekday and no day of the month reads the weekday as choosing a day
//! within the base week there, and is ignored here.

use std::sync::Arc;

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

use crate::clock_locale::Catalog;
use crate::compiler::{CompileError, Compiler};
use crate::parser::Word;
use crate::runtime::{tcl_str, to_tcl_string, Num};

/// Extension opcode ids owned by this module. One per subcommand; the inline
/// operand is the number of stack values the op consumes.
pub mod ext {
    pub use crate::compiler::ext::CLOCK_BASE as BASE;
    /// `[]` → the current time. `arg` selects the unit: 0 seconds,
    /// 1 milliseconds, 2 microseconds, 3 `clicks` (whose switch is on the
    /// stack).
    pub const NOW: u16 = BASE;
    /// `[value …]` → the formatted time, with the option words pushed in the
    /// order the script wrote them.
    pub const FORMAT: u16 = BASE + 1;
    /// `[value …]` → the instant the input names.
    pub const SCAN: u16 = BASE + 2;
    /// `[value …]` → the instant the offsets reach.
    pub const ADD: u16 = BASE + 3;
}

/// The command names this module claims, for the REPL's completion and for the
/// reference page.
pub const COMMANDS: &[&str] = &["clock"];

/// Every subcommand, in the order the interpreter lists them when it rejects
/// one.
pub const SUBCOMMANDS: &[&str] = &[
    "add",
    "clicks",
    "format",
    "microseconds",
    "milliseconds",
    "scan",
    "seconds",
];

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

/// Lower `clock …`. Only the subcommand is resolved here; every option is a
/// value and travels to the handler, because `clock format $t {*}$opts` and
/// `clock format $t -format $f` have to reach the same code.
pub(crate) fn compile(c: &mut Compiler, args: &[Word]) -> Result<(), CompileError> {
    let Some(first) = args.first() else {
        return c.error("wrong # args: should be \"clock subcommand ?arg ...?\"");
    };
    let given = c.literal_of(first, "subcommand")?.to_string();
    let Some(sub) = resolve(&given, SUBCOMMANDS) else {
        return c.error(format!(
            "unknown or ambiguous subcommand \"{given}\": must be {}",
            listing(SUBCOMMANDS)
        ));
    };
    let rest = &args[1..];
    match sub {
        "seconds" | "milliseconds" | "microseconds" => {
            if !rest.is_empty() {
                return c.error(format!("wrong # args: should be \"clock {sub}\""));
            }
            let unit = match sub {
                "seconds" => 0,
                "milliseconds" => 1,
                _ => 2,
            };
            c.emit(Op::Extended(ext::NOW, unit), 1);
            Ok(())
        }
        "clicks" => {
            if rest.len() > 1 {
                return c.error("wrong # args: should be \"clock clicks ?-switch?\"");
            }
            // The switch always rides on the stack, empty when absent, so the
            // handler has one shape rather than two.
            match rest.first() {
                Some(w) => c.word(w)?,
                None => c.push_str(""),
            }
            c.emit(Op::Extended(ext::NOW, 3), 0);
            Ok(())
        }
        other => {
            let id = match other {
                "format" => ext::FORMAT,
                "scan" => ext::SCAN,
                _ => ext::ADD,
            };
            let Ok(argc) = u8::try_from(rest.len()) else {
                return c.error("too many arguments for one command");
            };
            for w in rest {
                c.word(w)?;
            }
            c.emit(Op::Extended(id, argc), 1 - rest.len() as i32);
            Ok(())
        }
    }
}

/// `Tcl_GetIndexFromObj`'s rule: 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
}

// ── the calendar ─────────────────────────────────────────────────────────

/// The first instant this module will reckon: 1752-09-14T00:00:00Z, Julian day
/// 2361222. Before it tclsh reckons in the Julian calendar and this module has
/// one calendar, so it refuses rather than answering a Gregorian date for a
/// Julian one.
///
/// The changeover is not the locale's. Catalogues carry a
/// `GREGORIAN_CHANGE_DATE` and `clock.tcl` sets one for a dozen languages, but
/// Tcl 9's formatter passes the compile-time `GREGORIAN_CHANGE_DATE`
/// (`generic/tclClock.c`) to `TclConvertUTCToLocal` and never reads the
/// catalogue's — measured: `clock format -11676096000 -format %Y-%m-%d -gmt 1`
/// answers `1599-12-22` under `-locale en`, `it`, `ru`, `el` and the root
/// locale alike, and `1752-09-02` is the last Julian date every one of them
/// writes.
const EARLIEST: i64 = -6_857_222_400;

fn too_early() -> String {
    "clock: dates before the Gregorian changeover of 1752-09-14 are not supported yet".to_string()
}

/// A civil date and time, always proleptic Gregorian.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Civil {
    year: i64,
    month: u32,
    day: u32,
    hour: u32,
    minute: u32,
    second: u32,
    /// Days since 1970-01-01, which every derived field is computed from.
    epoch_day: i64,
}

fn is_leap(year: i64) -> bool {
    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}

const MONTH_LENGTHS: [u32; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

fn month_length(year: i64, month: u32) -> u32 {
    if month == 2 && is_leap(year) {
        29
    } else {
        MONTH_LENGTHS[(month - 1) as usize]
    }
}

/// Days since 1970-01-01 for a proleptic Gregorian date — Hinnant's
/// `days_from_civil`, which is exact for every year an `i64` holds.
fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
    let y = if month <= 2 { year - 1 } else { year };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let m = month as i64;
    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day as i64 - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146097 + doe - 719468
}

/// The inverse, `civil_from_days`.
fn civil_from_days(days: i64) -> (i64, u32, u32) {
    let z = days + 719468;
    let era = if z >= 0 { z } else { z - 146096 } / 146097;
    let doe = z - era * 146097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
    let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
    (if m <= 2 { y + 1 } else { y }, m, d)
}

/// Split a local time — seconds since the epoch with the zone's offset already
/// added — into its civil fields.
fn civil_of(local: i64) -> Civil {
    let days = local.div_euclid(86400);
    let secs = local.rem_euclid(86400);
    let (year, month, day) = civil_from_days(days);
    Civil {
        year,
        month,
        day,
        hour: (secs / 3600) as u32,
        minute: (secs / 60 % 60) as u32,
        second: (secs % 60) as u32,
        epoch_day: days,
    }
}

impl Civil {
    /// 1 for Monday through 7 for Sunday — `%u`'s numbering, which the other
    /// weekday tokens are derived from. 1970-01-01 was a Thursday.
    fn iso_weekday(&self) -> u32 {
        (self.epoch_day + 3).rem_euclid(7) as u32 + 1
    }

    /// Day of the year, 1-based.
    fn day_of_year(&self) -> i64 {
        self.epoch_day - days_from_civil(self.year, 1, 1) + 1
    }

    /// The ISO-8601 week-numbering year and week — `%G` and `%V`. The week
    /// holding the year's first Thursday is week 1.
    fn iso_week(&self) -> (i64, i64) {
        let thursday = self.epoch_day + 4 - self.iso_weekday() as i64;
        let (year, _, _) = civil_from_days(thursday);
        let week = (thursday - days_from_civil(year, 1, 1)) / 7 + 1;
        (year, week)
    }

    /// `%U` and `%W`: the week of the year counted from the first `start`
    /// weekday, where `start` is 0 for Sunday (`%U`) and 1 for Monday (`%W`).
    fn week_of_year(&self, start: u32) -> i64 {
        let weekday = self.iso_weekday() % 7; // 0 = Sunday
        let shifted = (weekday + 7 - start) % 7;
        (self.day_of_year() + 6 - shifted as i64) / 7
    }

    /// The Julian Day Number of the calendar day, `%J`'s value.
    fn julian_day(&self) -> i64 {
        self.epoch_day + 2440588
    }

    /// Seconds since local midnight — `DateInfo.secondOfDay`, which the tokens
    /// that write a time of day are all derived from.
    fn second_of_day(&self) -> i64 {
        self.hour as i64 * 3600 + self.minute as i64 * 60 + self.second as i64
    }
}

/// `SECONDS_PER_DAY`, which the Julian-day and stardate tokens divide by.
const SECONDS_PER_DAY: i64 = 86_400;

// ── time zones ───────────────────────────────────────────────────────────

/// A resolved time zone: the offsets it applies and how it names itself.
struct Zone {
    /// Transitions, ascending by the UTC instant they take effect at, paired
    /// with the state in force from then on.
    transitions: Vec<(i64, State)>,
    /// The state before the first transition, and the whole zone when there
    /// are none.
    initial: State,
}

#[derive(Clone)]
struct State {
    offset: i32,
    abbreviation: String,
}

impl Zone {
    /// A zone with one fixed offset, which is what `-gmt 1` and a numeric
    /// `-timezone` produce.
    fn fixed(offset: i32, name: &str) -> Zone {
        Zone {
            transitions: Vec::new(),
            initial: State {
                offset,
                abbreviation: name.to_string(),
            },
        }
    }

    /// The state in force at a UTC instant.
    fn at(&self, utc: i64) -> &State {
        match self.transitions.partition_point(|(when, _)| *when <= utc) {
            0 => &self.initial,
            n => &self.transitions[n - 1].1,
        }
    }

    /// The state to use for a *local* time, which is what `clock scan` has:
    /// the offset is the thing being looked for, so it is guessed once from
    /// the local value and then checked. tclsh's `ConvertLocalToUTC` takes the
    /// same two steps.
    fn for_local(&self, local: i64) -> &State {
        let guess = self.at(local - self.at(local).offset as i64);
        self.at(local - guess.offset as i64)
    }
}

/// Read a `TZif` file — the format `tzfile(5)` describes and the one tclsh's
/// `LoadZoneinfoFile` parses in Tcl. Version 2 and 3 files carry a second,
/// 64-bit block after the 32-bit one; that block is the one read, since the
/// 32-bit block cannot name an instant past 2038.
fn parse_tzif(bytes: &[u8]) -> Option<Zone> {
    if bytes.len() < 44 || &bytes[..4] != b"TZif" {
        return None;
    }
    if bytes[4] >= b'2' {
        let second = block_length(bytes, 4)?;
        let rest = bytes.get(second..)?;
        if rest.len() >= 44 && &rest[..4] == b"TZif" {
            return read_block(rest, 8);
        }
    }
    read_block(bytes, 4)
}

/// How many bytes one whole block occupies, header included.
fn block_length(bytes: &[u8], width: usize) -> Option<usize> {
    let (isutc, isstd, leaps, times, types, chars) = counts_of(bytes)?;
    Some(44 + times * (width + 1) + types * 6 + chars + leaps * (width + 4) + isstd + isutc)
}

/// The six counts at the end of a `TZif` header.
fn counts_of(bytes: &[u8]) -> Option<(usize, usize, usize, usize, usize, usize)> {
    if bytes.len() < 44 {
        return None;
    }
    let at = |i: usize| -> usize {
        u32::from_be_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]) as usize
    };
    Some((at(20), at(24), at(28), at(32), at(36), at(40)))
}

/// One block's transitions and types, given the width of a transition time.
fn read_block(block: &[u8], width: usize) -> Option<Zone> {
    let (_, _, _, times, types, chars) = counts_of(block)?;
    if types == 0 {
        return None;
    }
    let body = block.get(44..)?;
    let mut at = 0usize;
    let mut when = Vec::with_capacity(times);
    for _ in 0..times {
        when.push(read_int(body, &mut at, width)?);
    }
    let mut index = Vec::with_capacity(times);
    for _ in 0..times {
        index.push(*body.get(at)? as usize);
        at += 1;
    }
    let mut infos = Vec::with_capacity(types);
    for _ in 0..types {
        let offset = read_int(body, &mut at, 4)? as i32;
        at += 1; // isdst, which nothing here reads
        let abbreviation = *body.get(at)? as usize;
        at += 1;
        infos.push((offset, abbreviation));
    }
    let names = body.get(at..at + chars)?;
    let state = |i: usize| -> State {
        let (offset, start) = infos[i];
        let start = start.min(names.len());
        let end = names[start..]
            .iter()
            .position(|b| *b == 0)
            .map_or(names.len(), |n| start + n);
        State {
            offset,
            abbreviation: String::from_utf8_lossy(&names[start..end]).into_owned(),
        }
    };
    let transitions: Vec<(i64, State)> = when
        .into_iter()
        .zip(index)
        .filter(|(_, i)| *i < infos.len())
        .map(|(w, i)| (w, state(i)))
        .collect();
    Some(Zone {
        // Before the first transition `tzfile(5)` directs the first
        // non-daylight type, and type 0 stands in when the file has none.
        initial: state(0),
        transitions,
    })
}

fn read_int(body: &[u8], at: &mut usize, width: usize) -> Option<i64> {
    let slice = body.get(*at..*at + width)?;
    *at += width;
    Some(match width {
        4 => i32::from_be_bytes(slice.try_into().ok()?) as i64,
        _ => i64::from_be_bytes(slice.try_into().ok()?),
    })
}

/// The directories tclsh's `LoadZoneinfoFile` searches, in its order.
const ZONE_DIRECTORIES: &[&str] = &[
    "/usr/share/zoneinfo",
    "/usr/share/lib/zoneinfo",
    "/usr/lib/zoneinfo",
    "/usr/local/etc/zoneinfo",
];

/// Resolve a zone name.
fn load_zone(name: &str) -> Result<Zone, String> {
    let trimmed = name.strip_prefix(':').unwrap_or(name);
    if trimmed.is_empty() {
        return Ok(Zone::fixed(0, "GMT"));
    }
    if trimmed.eq_ignore_ascii_case("utc") || trimmed.eq_ignore_ascii_case("gmt") {
        return Ok(Zone::fixed(0, trimmed));
    }
    if trimmed == "localtime" {
        return system_zone();
    }
    if let Some(offset) = fixed_offset(name) {
        return Ok(Zone::fixed(offset, name));
    }
    // A traversal would read a file outside the zone database, which is not
    // something a zone name may do.
    if trimmed.starts_with('/') || trimmed.split('/').any(|part| part == "..") {
        return Err(format!("time zone \"{name}\" not found"));
    }
    for directory in ZONE_DIRECTORIES {
        let path = std::path::Path::new(directory).join(trimmed);
        if let Ok(bytes) = std::fs::read(&path) {
            if let Some(zone) = parse_tzif(&bytes) {
                return Ok(zone);
            }
        }
    }
    Err(format!(
        "time zone \"{name}\" not found: no zone file names it, and a POSIX time zone rule is not supported yet"
    ))
}

/// `SetupTimeZone`'s fixed-offset form: `[+-]hh`, `hhmm`, `hh:mm`, `hhmmss` or
/// `hh:mm:ss` (`library/clock.tcl`).
fn fixed_offset(text: &str) -> Option<i32> {
    let chars: Vec<char> = text.chars().collect();
    let sign = match chars.first()? {
        '+' => 1,
        '-' => -1,
        _ => return None,
    };
    let two = |from: usize| -> Option<i32> {
        let a = chars.get(from)?.to_digit(10)?;
        let b = chars.get(from + 1)?.to_digit(10)?;
        Some((a * 10 + b) as i32)
    };
    let hours = two(1)?;
    let mut at = 3;
    let field = |at: &mut usize| -> Option<i32> {
        let start = if chars.get(*at) == Some(&':') {
            *at + 1
        } else {
            *at
        };
        let value = two(start)?;
        *at = start + 2;
        Some(value)
    };
    let minutes = match field(&mut at) {
        Some(m) => m,
        // Trailing text that is not a minute field means this is a name and
        // not an offset: `+foo` is not `+00`.
        None => return (at == chars.len()).then_some(sign * hours * 3600),
    };
    let seconds = field(&mut at).unwrap_or(0);
    if at != chars.len() {
        return None;
    }
    Some(sign * ((hours * 60 + minutes) * 60 + seconds))
}

/// The zone a script gets when it names none: `TZ` when it is set, and the
/// system's own zone otherwise. tclsh reads the same two.
fn system_zone() -> Result<Zone, String> {
    if let Ok(tz) = std::env::var("TZ") {
        if !tz.is_empty() {
            return load_zone(&tz);
        }
    }
    match std::fs::read("/etc/localtime") {
        Ok(bytes) => parse_tzif(&bytes)
            .ok_or_else(|| "clock: /etc/localtime is not a time zone file".to_string()),
        Err(_) => Ok(Zone::fixed(0, "GMT")),
    }
}

// ── the message catalogue ────────────────────────────────────────────────

/// `::tcl::clock::LocalizeFormat`'s substitution list for one catalogue
/// (`library/clock.tcl:852`), in its order. Each entry is expanded through the
/// entries already in the list before it joins them, which is what lets `%c`
/// be written in terms of `%X` and `%X` in terms of `%T`.
fn format_map(cat: &Catalog) -> Vec<(String, String)> {
    let mut map = vec![
        ("%%".to_string(), "%%".to_string()),
        ("%D".to_string(), "%m/%d/%Y".to_string()),
        ("%+".to_string(), "%a %b %e %H:%M:%S %Z %Y".to_string()),
    ];
    for (key, value) in [
        ("%EY", &cat.locale_year_format),
        ("%T", &cat.time_format_24_secs),
        ("%R", &cat.time_format_24),
        ("%r", &cat.time_format_12),
        ("%X", &cat.time_format),
        ("%EX", &cat.locale_time_format),
        ("%x", &cat.date_format),
        ("%Ex", &cat.locale_date_format),
        ("%c", &cat.date_time_format),
        ("%Ec", &cat.locale_date_time_format),
    ] {
        let expanded = string_map(&map, value);
        map.push((key.to_string(), expanded));
    }
    map
}

/// Tcl's `string map`: one left-to-right pass over the subject in which the
/// first pair that matches at a position wins and its replacement is not
/// rescanned. `%%` maps to itself, so an escaped percent cannot start a group.
fn string_map(map: &[(String, String)], text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    'outer: while !rest.is_empty() {
        for (from, to) in map {
            if rest.starts_with(from.as_str()) {
                out.push_str(to);
                rest = &rest[from.len()..];
                continue 'outer;
            }
        }
        let ch = rest.chars().next().expect("not empty");
        out.push(ch);
        rest = &rest[ch.len_utf8()..];
    }
    out
}

/// A `string map` pair list: what to look for and what to write instead.
type Substitutions = Arc<Vec<(String, String)>>;

thread_local! {
    /// `::tcl::clock::LocFmtMap`: the substitution list per locale, since
    /// building it reads ten catalogue entries and expands each one.
    static LOC_FMT_MAP: std::cell::RefCell<std::collections::HashMap<String, Substitutions>> =
        std::cell::RefCell::new(std::collections::HashMap::new());
}

/// Expand the locale format groups the way `LocalizeFormat` does.
fn localize(format: &str, cat: &Catalog) -> String {
    let map = LOC_FMT_MAP.with(|cache| {
        if let Some(hit) = cache.borrow().get(&cat.name) {
            return hit.clone();
        }
        let built = Arc::new(format_map(cat));
        cache.borrow_mut().insert(cat.name.clone(), built.clone());
        built
    });
    string_map(&map, format)
}

// ── formatting ───────────────────────────────────────────────────────────

/// The default `-format`, which `clock format` uses when the script names
/// none (`library/clock.tcl`).
const DEFAULT_FORMAT: &str = "%a %b %d %H:%M:%S %Z %Y";

/// A number padded to `width` with `fill`, with the sign kept outside the
/// padding — `Clock_itoaw`'s layout.
fn pad(value: i64, width: usize, fill: char) -> String {
    let digits = value.unsigned_abs().to_string();
    let sign = if value < 0 { 1 } else { 0 };
    let mut out = String::with_capacity(width.max(digits.len() + sign));
    if sign == 1 {
        out.push('-');
    }
    for _ in digits.len() + sign..width {
        out.push(fill);
    }
    out.push_str(&digits);
    out
}

/// The zone offset as `%z` writes it.
fn offset_text(offset: i32) -> String {
    let sign = if offset < 0 { '-' } else { '+' };
    let total = offset.unsigned_abs();
    let (hours, minutes, seconds) = (total / 3600, total / 60 % 60, total % 60);
    if seconds == 0 {
        format!("{sign}{hours:02}{minutes:02}")
    } else {
        format!("{sign}{hours:02}{minutes:02}{seconds:02}")
    }
}

fn format_time(seconds: i64, format: &str, zone: &Zone, cat: &Catalog) -> Result<String, String> {
    if seconds < EARLIEST {
        return Err(too_early());
    }
    let state = zone.at(seconds);
    let local = seconds
        .checked_add(state.offset as i64)
        .ok_or_else(overflow)?;
    let civil = civil_of(local);
    let expanded = localize(format, cat);
    let mut out = String::with_capacity(expanded.len() + 16);
    let mut rest = expanded.as_str();
    while let Some(at) = rest.find('%') {
        out.push_str(&rest[..at]);
        rest = &rest[at + 1..];
        // `%E` and `%O` select a token map of their own, and a character that
        // is in neither this map nor the plain one leaves the whole group —
        // percent, modifier and all — in the output.
        let modifier = rest.chars().next().filter(|c| matches!(c, 'E' | 'O'));
        let after = match modifier {
            Some(m) => &rest[m.len_utf8()..],
            None => rest,
        };
        let Some(token) = after.chars().next() else {
            // A trailing `%` is itself, as tclsh's scanner leaves it.
            out.push('%');
            if let Some(m) = modifier {
                out.push(m);
            }
            return Ok(out);
        };
        match one_token(modifier, token, &civil, seconds, local, state, cat)? {
            Some(text) => {
                out.push_str(&text);
                rest = &after[token.len_utf8()..];
            }
            // A token that is in no map is copied through unchanged, which is
            // what tclsh does for `%F` and `%i` — measured, not assumed.
            // `rest` still points at the modifier, or at the token when there
            // was none, so the next pass copies the rest of the group.
            None => out.push('%'),
        }
    }
    out.push_str(rest);
    Ok(out)
}

/// One `%`-token's text, or `Ok(None)` when the token is in no map — in which
/// case the caller copies the group through. `modifier` is the `E` or `O` that
/// picked `FmtETokenMap` or `FmtOTokenMap` over `FmtSTokenMap`. The error is
/// [`indexed`]'s.
fn one_token(
    modifier: Option<char>,
    token: char,
    civil: &Civil,
    seconds: i64,
    local: i64,
    state: &State,
    cat: &Catalog,
) -> Result<Option<String>, String> {
    let weekday = civil.iso_weekday();
    let hour12 = match civil.hour % 12 {
        0 => 12,
        other => other,
    };
    Ok(match modifier {
        // `FmtETokenMap`, whose index is `EJjys` with `C` aliased onto `y`.
        Some('E') => Some(match token {
            'E' => if civil.year <= 0 { &cat.bce } else { &cat.ce }.clone(),
            'J' => julian_fraction(civil.julian_day(), civil.second_of_day(), 0),
            'j' => julian_fraction(
                civil.julian_day(),
                civil.second_of_day(),
                SECONDS_PER_DAY / 2,
            ),
            'y' | 'C' => era_year(token, civil, local, cat),
            's' => local.to_string(),
            _ => return Ok(None),
        }),
        // `FmtOTokenMap`, whose index is `dmyHIMSuw` with `ekl` aliased onto
        // `dHI`. Every entry writes its value as a locale numeral.
        Some('O') => {
            let value = match token {
                'd' | 'e' => civil.day as i64,
                'm' => civil.month as i64,
                'y' => civil.year.rem_euclid(100),
                'H' | 'k' => civil.hour as i64,
                'I' | 'l' => hour12 as i64,
                'M' => civil.minute as i64,
                'S' => civil.second as i64,
                'u' => weekday as i64,
                'w' => (weekday % 7) as i64,
                _ => return Ok(None),
            };
            Some(indexed(&cat.numerals, value)?)
        }
        // `FmtSTokenMap`.
        _ => Some(match token {
            '%' => "%".to_string(),
            'd' => pad(civil.day as i64, 2, '0'),
            'e' => pad(civil.day as i64, 2, ' '),
            'm' => pad(civil.month as i64, 2, '0'),
            'N' => pad(civil.month as i64, 2, ' '),
            'b' | 'h' => indexed(&cat.months_abbrev, civil.month as i64 - 1)?,
            'B' => indexed(&cat.months_full, civil.month as i64 - 1)?,
            'y' => pad(civil.year.rem_euclid(100), 2, '0'),
            'Y' => pad(civil.year, 4, '0'),
            'C' => pad(civil.year.div_euclid(100), 2, '0'),
            'H' => pad(civil.hour as i64, 2, '0'),
            'M' => pad(civil.minute as i64, 2, '0'),
            'S' => pad(civil.second as i64, 2, '0'),
            'I' => pad(hour12 as i64, 2, '0'),
            'k' => pad(civil.hour as i64, 2, ' '),
            'l' => pad(hour12 as i64, 2, ' '),
            // `%p` is the catalogue's word upper-cased and `%P` is the word as
            // it stands — `ClockFmtToken_AMPM_Proc` reads the same two entries
            // for both and only `p` calls `Tcl_UtfToUpper`.
            'p' => meridiem(civil, cat).to_uppercase(),
            'P' => meridiem(civil, cat).to_string(),
            'a' => indexed(&cat.days_abbrev, (weekday % 7) as i64)?,
            'A' => indexed(&cat.days_full, (weekday % 7) as i64)?,
            'u' => weekday.to_string(),
            'w' => (weekday % 7).to_string(),
            'U' => pad(civil.week_of_year(0), 2, '0'),
            'W' => pad(civil.week_of_year(1), 2, '0'),
            'V' => pad(civil.iso_week().1, 2, '0'),
            'g' => pad(civil.iso_week().0.rem_euclid(100), 2, '0'),
            'G' => pad(civil.iso_week().0, 4, '0'),
            'j' => pad(civil.day_of_year(), 3, '0'),
            'J' => pad(civil.julian_day(), 7, '0'),
            's' => seconds.to_string(),
            'n' => "\n".to_string(),
            't' => "\t".to_string(),
            'z' => offset_text(state.offset),
            'Z' => state.abbreviation.clone(),
            'Q' => stardate(civil),
            _ => return Ok(None),
        }),
    })
}

/// One entry of a catalogue list. Past its end tclsh's `Tcl_ListObjIndex`
/// fails and `ClockFormat` reports that with no message at all — measured:
/// `clock format 946684800 -format %a -gmt 1 -locale mt` raises an empty error
/// under `errorCode NONE`, because `mt.msg` ships six weekday abbreviations
/// and that instant is a Saturday.
fn indexed(list: &[String], at: i64) -> Result<String, String> {
    usize::try_from(at)
        .ok()
        .and_then(|i| list.get(i))
        .cloned()
        .ok_or_else(String::new)
}

/// The catalogue's `AM` or `PM` word for this time of day.
fn meridiem<'c>(civil: &Civil, cat: &'c Catalog) -> &'c str {
    if civil.hour < 12 {
        &cat.am
    } else {
        &cat.pm
    }
}

/// `%EC` and `%Ey` — `ClockFmtToken_LocaleERAYear_Proc`. With no era covering
/// the instant the two are the century and the year within it; with one they
/// are the era's name and the year counted from the era's own epoch, that year
/// written as a locale numeral while it fits in two digits.
fn era_year(token: char, civil: &Civil, local: i64, cat: &Catalog) -> String {
    let Some(era) = cat.era_at(local) else {
        return if token == 'C' {
            pad(civil.year.div_euclid(100), 2, '0')
        } else {
            pad(civil.year.rem_euclid(100), 2, '0')
        };
    };
    if token == 'C' {
        return era.name.clone();
    }
    let year = civil.year - era.year;
    match usize::try_from(year).ok().and_then(|y| cat.numerals.get(y)) {
        Some(numeral) => numeral.clone(),
        None => pad(year, 2, '0'),
    }
}

/// `%EJ` and `%Ej` — `ClockFmtToken_JDN_Proc`. The Julian day with the time of
/// day as a fraction, `offset` being the moment the day is reckoned from:
/// midnight for the calendar day number and noon for the astronomical one.
fn julian_fraction(julian_day: i64, second_of_day: i64, offset: i64) -> String {
    let mut day = julian_day;
    let mut fraction = second_of_day - offset;
    if fraction < 0 {
        day -= 1;
        fraction += SECONDS_PER_DAY;
    }
    let mut sign = "";
    if fraction != 0 && day < 0 {
        // Stepping the integer part towards zero would lose the sign of a
        // day that rounds to `-0`, so the sign is written out instead.
        day += 1;
        if day == 0 {
            sign = "-";
        }
        fraction = SECONDS_PER_DAY - fraction;
    }
    if fraction == 0 || fraction == SECONDS_PER_DAY / 2 {
        let half = if fraction == 0 { '0' } else { '5' };
        return format!("{sign}{day}.{half}");
    }
    // Eight digits, rounded, with the trailing zeroes cut.
    let scaled = (fraction as f64 * 100_000_000.0 / SECONDS_PER_DAY as f64 + 0.5) as i64;
    let digits = pad(scaled, 8, '0');
    format!("{sign}{day}.{}", digits.trim_end_matches('0'))
}

/// `%Q` — `ClockFmtToken_StarDate_Proc`, whose epoch is 1946.
fn stardate(civil: &Civil) -> String {
    let day = civil.day_of_year() - 1;
    let year_length = if is_leap(civil.year) { 366 } else { 365 };
    let fraction_of_year = 1000 * day / year_length;
    let tenth = civil.second_of_day() / (SECONDS_PER_DAY / 10);
    format!(
        "Stardate {}{}.{}",
        pad(civil.year - 1946, 2, '0'),
        pad(fraction_of_year, 3, '0'),
        pad(if tenth < 0 { 10 + tenth } else { tenth }, 1, '0')
    )
}

// ── scanning ─────────────────────────────────────────────────────────────

/// The fields a `-format` scan fills in, before they are turned into an
/// instant.
#[derive(Default)]
struct Scanned {
    year: Option<i64>,
    century: Option<i64>,
    year_in_century: Option<i64>,
    month: Option<u32>,
    day: Option<u32>,
    day_of_year: Option<i64>,
    hour: Option<u32>,
    minute: Option<u32>,
    second: Option<u32>,
    pm: Option<bool>,
    hour_is_12: bool,
    epoch: Option<i64>,
    offset: Option<i32>,
    /// The weekday the input named, 1 for Monday through 7 for Sunday. tclsh
    /// checks it against the date rather than ignoring it.
    weekday: Option<u32>,
    /// A Julian Day Number the input carried whole — `%J`, and `%EJ` written
    /// without a fraction. It names a *local* day, so it still crosses the
    /// zone on the way out.
    julian_day: Option<i64>,
    /// `%Es`: seconds since the epoch read as local time.
    local_seconds: Option<i64>,
    /// `%EE`: whether the input said the year is before the common era.
    bce: Option<bool>,
}

fn no_match() -> String {
    "input string does not match supplied format".to_string()
}

/// Read up to `max` digits.
fn take_digits(text: &[char], at: &mut usize, max: usize) -> Option<i64> {
    let start = *at;
    let mut value: i64 = 0;
    while *at < text.len() && *at - start < max && text[*at].is_ascii_digit() {
        value = value * 10 + text[*at].to_digit(10)? as i64;
        *at += 1;
    }
    (*at != start).then_some(value)
}

/// Lower-case one character, one for one — `Tcl_UtfToLower`, which the index
/// tree's keys and the input are both put through. A folding that expanded a
/// character into two would move the input position off the character it
/// matched, so only the first is taken.
fn lower(c: char) -> char {
    c.to_lowercase().next().unwrap_or(c)
}

/// Match the leading run of the input that names exactly one of the tables'
/// entries, where the tables share an index space — `TclStrIdxTreeSearch` over
/// the radix trie `ClockMCGetMultiListIdxTree` builds from the abbreviated and
/// the full list together (`generic/tclStrIdxTree.c:91`). A node a split
/// created carries a value only when its whole subtree agrees on one, so the
/// search reads as far as the input keeps matching some entry and answers only
/// if everything still matching means the same thing.
///
/// A name may therefore be abbreviated as far as it stays unique. Measured
/// against tclsh: `clock scan "13 f 2009" -format {%d %b %Y} -locale fr` is
/// February, because `févr.` is the only French month beginning with `f`;
/// `j` is refused because `janv.`, `juin` and `juil.` all do, and `ju` because
/// two still do. `Marc` is March, one character short of the full name.
fn take_prefix(text: &[char], at: &mut usize, tables: &[&[String]]) -> Option<usize> {
    let matches = |entry: &str, len: usize| {
        entry.chars().count() >= len
            && entry
                .chars()
                .take(len)
                .enumerate()
                .all(|(i, e)| text.get(*at + i).is_some_and(|&c| lower(c) == lower(e)))
    };
    // How far the input goes on matching some entry, which is where the walk
    // through the tree stops.
    let mut len = 0;
    for entry in tables.iter().flat_map(|t| t.iter()) {
        let reached = entry
            .chars()
            .enumerate()
            .take_while(|(i, e)| text.get(*at + i).is_some_and(|&c| lower(c) == lower(*e)))
            .count();
        len = len.max(reached);
    }
    if len == 0 {
        return None;
    }
    // Everything still matching there has to mean one thing.
    let mut value = None;
    for table in tables {
        for (index, entry) in table.iter().enumerate() {
            if !matches(entry, len) {
                continue;
            }
            if value.is_some_and(|found| found != index) {
                return None;
            }
            value = Some(index);
        }
    }
    *at += len;
    value
}

/// Match one of a table's entries case-insensitively, longest first so that
/// `January` is not read as `Jan` with `uary` left over.
fn take_name<S: AsRef<str>>(text: &[char], at: &mut usize, table: &[S]) -> Option<usize> {
    let mut best: Option<(usize, usize)> = None;
    for (i, name) in table.iter().enumerate() {
        let chars: Vec<char> = name.as_ref().chars().collect();
        if text.len() - *at >= chars.len()
            && text[*at..*at + chars.len()]
                .iter()
                .zip(&chars)
                .all(|(a, b)| a.eq_ignore_ascii_case(b))
            && best.is_none_or(|(_, len)| chars.len() > len)
        {
            best = Some((i, chars.len()));
        }
    }
    let (index, len) = best?;
    *at += len;
    Some(index)
}

/// The tokens whose value may be written with leading spaces — `%e`, `%k` and
/// `%l` do, and tclsh's scanner skips space ahead of every numeric field.
const NUMERIC_TOKENS: &str = "deEmNyYCHkIlMSjsUWVGgu w";

fn scan_time(
    input: &str,
    format: &str,
    zone: &Zone,
    cat: &Catalog,
    base_at: i64,
) -> Result<i64, String> {
    let text: Vec<char> = input.chars().collect();
    let pattern: Vec<char> = localize(format, cat).chars().collect();
    let mut got = Scanned::default();
    let mut at = 0usize;
    let mut p = 0usize;
    while p < pattern.len() {
        let ch = pattern[p];
        if ch != '%' {
            // Whitespace in the format matches any run of it, including none,
            // as tclsh's scanner does.
            if ch.is_whitespace() {
                p += 1;
                while at < text.len() && text[at].is_whitespace() {
                    at += 1;
                }
                continue;
            }
            if text.get(at) != Some(&ch) {
                return Err(no_match());
            }
            at += 1;
            p += 1;
            continue;
        }
        p += 1;
        // `%E` and `%O` select a scan map of their own, exactly as they select
        // a format map — `ScnETokenMap` and `ScnOTokenMap`.
        let modifier = pattern.get(p).copied().filter(|c| matches!(c, 'E' | 'O'));
        if modifier.is_some() {
            p += 1;
        }
        let Some(token) = pattern.get(p).copied() else {
            return Err(no_match());
        };
        p += 1;
        if let Some(m) = modifier {
            if scan_modified(m, token, &text, &mut at, &mut got, cat)? {
                continue;
            }
            return Err(format!(
                "clock scan: the format token \"%{m}{token}\" is not supported yet"
            ));
        }
        if NUMERIC_TOKENS.contains(token) {
            while at < text.len() && text[at] == ' ' {
                at += 1;
            }
        }
        let digits = |at: &mut usize, max: usize| take_digits(&text, at, max).ok_or_else(no_match);
        match token {
            '%' => {
                if text.get(at) != Some(&'%') {
                    return Err(no_match());
                }
                at += 1;
            }
            'n' | 't' => {
                if !text.get(at).is_some_and(|c| c.is_whitespace()) {
                    return Err(no_match());
                }
                at += 1;
            }
            'd' | 'e' => got.day = Some(digits(&mut at, 2)? as u32),
            'm' | 'N' => got.month = Some(digits(&mut at, 2)? as u32),
            'b' | 'h' | 'B' => {
                let index = take_prefix(&text, &mut at, &[&cat.months_full, &cat.months_abbrev])
                    .ok_or_else(no_match)?;
                got.month = Some(index as u32 + 1);
            }
            'a' | 'A' => {
                // The list is Sunday-first and `dayOfWeek` is Monday-first, so
                // `ClockScnToken_DayOfWeek_Proc` decrements the 1-based index
                // it gets and reads a resulting 0 as 7.
                let index = take_prefix(&text, &mut at, &[&cat.days_full, &cat.days_abbrev])
                    .ok_or_else(no_match)?;
                got.weekday = Some(if index == 0 { 7 } else { index as u32 });
            }
            'y' => got.year_in_century = Some(digits(&mut at, 2)?),
            'Y' => got.year = Some(digits(&mut at, 4)?),
            'C' => got.century = Some(digits(&mut at, 2)?),
            'H' | 'k' => got.hour = Some(digits(&mut at, 2)? as u32),
            'I' | 'l' => {
                got.hour = Some(digits(&mut at, 2)? as u32);
                got.hour_is_12 = true;
            }
            'M' => got.minute = Some(digits(&mut at, 2)? as u32),
            'S' => got.second = Some(digits(&mut at, 2)? as u32),
            'j' => got.day_of_year = Some(digits(&mut at, 3)?),
            'p' | 'P' => {
                let index = take_prefix(&text, &mut at, &[&[cat.am.clone(), cat.pm.clone()]])
                    .ok_or_else(no_match)?;
                got.pm = Some(index == 1);
            }
            's' => got.epoch = Some(signed(&text, &mut at)?),
            'u' | 'w' => {
                let day = digits(&mut at, 1)?;
                if day > 7 {
                    return Err("day of week is greater than 7".to_string());
                }
                // `%w` numbers Sunday 0 and `%u` numbers it 7; both reach
                // `dayOfWeek` through the same `if (val == 0) val = 7`.
                got.weekday = Some(if day == 0 { 7 } else { day as u32 });
            }
            'U' | 'W' | 'V' => {
                digits(&mut at, 2)?;
            }
            'G' => {
                digits(&mut at, 4)?;
            }
            'g' => {
                digits(&mut at, 2)?;
            }
            'z' | 'Z' => got.offset = Some(scan_zone(&text, &mut at)?),
            // A whole Julian Day Number, which names a local day.
            'J' => got.julian_day = Some(signed(&text, &mut at)?),
            'Q' => scan_stardate(&text, &mut at, &mut got)?,
            other => {
                return Err(format!(
                    "clock scan: the format token \"%{other}\" is not supported yet"
                ))
            }
        }
    }
    while at < text.len() && text[at].is_whitespace() {
        at += 1;
    }
    if at != text.len() {
        return Err(no_match());
    }
    assemble(got, zone, base_at)
}

/// A signed run of digits — `%s`, `%J` and the integer part of a Julian day.
/// The sign is read first because `Clock_str2wideInt` is handed one.
fn signed(text: &[char], at: &mut usize) -> Result<i64, String> {
    let negative = text.get(*at) == Some(&'-');
    if negative || text.get(*at) == Some(&'+') {
        *at += 1;
    }
    let value = take_digits(text, at, 19).ok_or_else(no_match)?;
    Ok(if negative { -value } else { value })
}

/// A token under an `%E` or `%O` modifier — `ScnETokenMap` and
/// `ScnOTokenMap`. `false` means the token is in neither map, which the caller
/// turns into its refusal.
///
/// Every `%O` entry reads a locale numeral rather than digits, which is why
/// `clock scan 5 -format %Od` fails where `clock scan 05 -format %Od` answers:
/// the root catalogue's numerals are `00` through `99` and nothing matches a
/// bare `5` (measured against tclsh).
fn scan_modified(
    modifier: char,
    token: char,
    text: &[char],
    at: &mut usize,
    got: &mut Scanned,
    cat: &Catalog,
) -> Result<bool, String> {
    if modifier == 'O' {
        // `ScnOTokenMapIndex` is `dmyHMSu`, with `ekIlw` aliased onto `dHHHu`.
        let numeral = |at: &mut usize| {
            take_prefix(text, at, &[&cat.numerals])
                .map(|n| n as i64)
                .ok_or_else(no_match)
        };
        match token {
            'd' | 'e' => got.day = Some(numeral(at)? as u32),
            'm' => got.month = Some(numeral(at)? as u32),
            'y' => got.year_in_century = Some(numeral(at)?),
            'H' | 'k' => got.hour = Some(numeral(at)? as u32),
            'I' | 'l' => {
                got.hour = Some(numeral(at)? as u32);
                got.hour_is_12 = true;
            }
            'M' => got.minute = Some(numeral(at)? as u32),
            'S' => got.second = Some(numeral(at)? as u32),
            // `ClockScnToken_DayOfWeek_Proc` with a locale list: the numeral's
            // index is the weekday, and 0 means Sunday as everywhere else.
            'u' | 'w' => {
                let day = numeral(at)?;
                if day > 7 {
                    return Err("day of week is greater than 7".to_string());
                }
                got.weekday = Some(if day == 0 { 7 } else { day as u32 });
            }
            _ => return Ok(false),
        }
        return Ok(true);
    }
    // `ScnETokenMapIndex` is `EJjys`.
    match token {
        'E' => got.bce = Some(!scan_era(text, at, cat).ok_or_else(no_match)?),
        // The calendar day number and the astronomical one, which starts at
        // noon. Whole, they name a local day; with a fraction they are the
        // instant itself and no zone applies.
        'J' | 'j' => {
            let offset = if token == 'j' { SECONDS_PER_DAY / 2 } else { 0 };
            let day = signed(text, at)?;
            let Some(fraction) = scan_day_fraction(text, at) else {
                if token == 'J' {
                    got.julian_day = Some(day);
                    return Ok(true);
                }
                got.epoch = Some((day - 2440588) * SECONDS_PER_DAY + offset);
                return Ok(true);
            };
            let mut seconds = offset + fraction;
            let mut day = day;
            if seconds >= SECONDS_PER_DAY {
                seconds -= SECONDS_PER_DAY;
                day += 1;
            }
            got.epoch = Some((day - 2440588) * SECONDS_PER_DAY + seconds);
        }
        // Parse-only: `ScnETokenMap`'s `%Ey` entry captures nothing, so a
        // matched numeral moves the input on and changes no field.
        'y' => {
            take_prefix(text, at, &[&cat.numerals]).ok_or_else(no_match)?;
        }
        's' => got.local_seconds = Some(signed(text, at)?),
        _ => return Ok(false),
    }
    Ok(true)
}

/// The `.ddd` of a Julian day, as a count of seconds into the day. `None` when
/// no fraction follows, which is a whole Julian day number.
fn scan_day_fraction(text: &[char], at: &mut usize) -> Option<i64> {
    if text.get(*at) != Some(&'.') {
        return None;
    }
    let start = *at + 1;
    let mut end = start;
    let mut divisor: i64 = 1;
    while text.get(end).is_some_and(|c| c.is_ascii_digit()) {
        divisor = divisor.saturating_mul(10);
        end += 1;
    }
    let mut value: i64 = 0;
    for c in &text[start..end] {
        value = value * 10 + c.to_digit(10).expect("a digit") as i64;
    }
    *at = end;
    Some(SECONDS_PER_DAY * value / divisor)
}

/// `%EE` — `ClockScnToken_LocaleERA_Proc`, which searches the catalogue's two
/// era words together with four fixed spellings: `b.c.e.`, `c.e.`, `b.c.` and
/// `a.d.`. `true` is the common era.
///
/// The answer is the era rather than the entry, because several entries mean
/// the same one: `b.c.` is a prefix of `b.c.e.` and both are before the common
/// era, so the input is not ambiguous even though the entry is.
fn scan_era(text: &[char], at: &mut usize, cat: &Catalog) -> Option<bool> {
    let table = [
        (cat.bce.as_str(), false),
        (cat.ce.as_str(), true),
        ("b.c.e.", false),
        ("c.e.", true),
        ("b.c.", false),
        ("a.d.", true),
    ];
    let mut len = 0;
    for (word, _) in table {
        let reached = word
            .chars()
            .enumerate()
            .take_while(|(i, w)| text.get(*at + i).is_some_and(|c| lower(*c) == lower(*w)))
            .count();
        len = len.max(reached);
    }
    if len == 0 {
        return None;
    }
    let mut era = None;
    for (word, common) in table {
        let matches = word.chars().count() >= len
            && word
                .chars()
                .take(len)
                .enumerate()
                .all(|(i, w)| text.get(*at + i).is_some_and(|c| lower(*c) == lower(w)));
        if matches {
            if era.is_some_and(|found| found != common) {
                return None;
            }
            era = Some(common);
        }
    }
    *at += len;
    era
}

/// `%Q` — `ClockScnToken_StarDate_Proc`. `Stardate NNNNN.d`: at least four
/// digits, of which the last three are the thousandths of the year elapsed and
/// the rest the year since 1946, then a fraction of the day.
fn scan_stardate(text: &[char], at: &mut usize, got: &mut Scanned) -> Result<(), String> {
    let prefix: Vec<char> = "stardate ".chars().collect();
    if text.len() < *at + prefix.len()
        || !text[*at..*at + prefix.len()]
            .iter()
            .zip(&prefix)
            .all(|(c, p)| lower(*c) == *p)
    {
        return Err(no_match());
    }
    let mut cursor = *at + prefix.len();
    while text.get(cursor).is_some_and(|c| c.is_whitespace()) {
        cursor += 1;
    }
    if text.get(cursor) == Some(&'+') {
        cursor += 1;
    }
    let start = cursor;
    while text.get(cursor).is_some_and(|c| c.is_ascii_digit()) {
        cursor += 1;
    }
    // The last three digits are the fraction of the year, so there has to be
    // at least one digit of year in front of them.
    if cursor - start < 4 {
        return Err(no_match());
    }
    let number = |slice: &[char]| -> i64 {
        slice
            .iter()
            .fold(0, |n, c| n * 10 + c.to_digit(10).expect("a digit") as i64)
    };
    let year = number(&text[start..cursor - 3]) + 1946;
    let elapsed = number(&text[cursor - 3..cursor]);
    if text.get(cursor) != Some(&'.') {
        return Err(no_match());
    }
    *at = cursor;
    let fraction = scan_day_fraction(text, at).ok_or_else(no_match)?;
    // The thousandths are of the whole year, rounded to a day.
    let length = if is_leap(year) { 366 } else { 365 };
    let scaled = elapsed * length;
    let day_of_year = scaled / 1000 + 1 + i64::from(scaled % 1000 >= 500);
    let day = days_from_civil(year, 1, 1) + day_of_year - 1;
    got.local_seconds = Some(day * SECONDS_PER_DAY + fraction);
    Ok(())
}

/// A zone in the input: a numeric offset, or one of the names that plainly
/// mean UTC. Reading an arbitrary abbreviation would need the table tclsh
/// builds from the whole zone database, and guessing one wrong moves the
/// answer by hours.
fn scan_zone(text: &[char], at: &mut usize) -> Result<i32, String> {
    if matches!(text.get(*at), Some('+') | Some('-')) {
        let start = *at;
        *at += 1;
        while text
            .get(*at)
            .is_some_and(|c| c.is_ascii_digit() || *c == ':')
        {
            *at += 1;
        }
        let candidate: String = text[start..*at].iter().collect();
        return fixed_offset(&candidate).ok_or_else(no_match);
    }
    match take_name(text, at, &["GMT", "UTC", "Z"]) {
        Some(_) => Ok(0),
        None => {
            Err("clock scan: reading a time zone by abbreviation is not supported yet".to_string())
        }
    }
}

/// Turn scanned fields into an instant.
fn assemble(got: Scanned, zone: &Zone, base_at: i64) -> Result<i64, String> {
    // `%s` and a Julian day written with a fraction are the instant itself:
    // `CLF_POSIXSEC`, which no zone and no calendar touches.
    if let Some(epoch) = got.epoch {
        return Ok(epoch);
    }
    // A whole Julian day and `%Es` name a *local* moment, so they cross the
    // zone but skip the civil date entirely — which is why
    // `clock scan 0 -format %J -gmt 1` answers -210866803200 rather than being
    // refused for standing before the Gregorian changeover: no calendar was
    // consulted to reach it.
    let direct = got
        .local_seconds
        .or_else(|| got.julian_day.map(|day| (day - 2440588) * SECONDS_PER_DAY));
    if let Some(local) = direct {
        return Ok(match got.offset {
            Some(offset) => local - offset as i64,
            None => local - zone.for_local(local).offset as i64,
        });
    }
    // Fields the format did not carry come from the current day in the target
    // zone, which is the base tclsh uses when `-base` is absent.
    let base = civil_of(base_at + zone.at(base_at).offset as i64);
    let year = match (got.year, got.century, got.year_in_century) {
        (Some(year), _, _) => year,
        (None, Some(century), Some(year)) => century * 100 + year,
        // tclsh's two-digit year rule: 00–68 are 2000s, 69–99 are 1900s.
        (None, None, Some(year)) => year + if year < 69 { 2000 } else { 1900 },
        // A century with no year within it changes nothing: `dateCentury` is
        // only ever read beside `date.year`, so `clock scan 19 -format %C`
        // answers on the base date (measured).
        (None, Some(_), None) | (None, None, None) => base.year,
    };
    // `%EE` said the year is counted backwards from the common era, and the
    // two numberings differ by one: there is no year zero, so 1 BCE is the
    // astronomical year 0.
    let year = if got.bce == Some(true) {
        1 - year
    } else {
        year
    };
    let mut hour = got.hour.unwrap_or(0);
    // Each field is held to its own range and named in its own refusal, in the
    // order tclsh checks them — measured: `clock scan {1970 13 32} -format
    // {%Y %m %d}` reports the month and `{1970 01 32 25}` the day, so a later
    // field is never reached while an earlier one is out of range. A rolled-over
    // value is not an answer either interpreter gives.
    let bad = |what: &str| Err(format!("unable to convert input string: invalid {what}"));
    if let Some(month) = got.month {
        if !(1..=12).contains(&month) {
            return bad("month");
        }
    }
    if let Some(day) = got.day {
        let month = got.month.unwrap_or(base.month);
        if day < 1 || day > month_length(year, month) {
            return bad("day");
        }
    }
    // `%H` reaches 24, which is the midnight ending the day; `%I` stops at 12.
    let hour_limit = if got.hour_is_12 { 12 } else { 24 };
    if hour > hour_limit {
        return bad("time (hour)");
    }
    if got.minute.is_some_and(|m| m > 59) {
        return bad("time (minutes)");
    }
    if got.second.is_some_and(|s| s > 59) {
        return bad("time");
    }
    if got.hour_is_12 {
        hour %= 12;
        if got.pm == Some(true) {
            hour += 12;
        }
    } else if got.pm == Some(true) && hour < 12 {
        hour += 12;
    }
    let days = match got.day_of_year {
        Some(day) => {
            let length = if is_leap(year) { 366 } else { 365 };
            if day < 1 || day > length {
                return bad("day of year");
            }
            days_from_civil(year, 1, 1) + day - 1
        }
        None => {
            // Every date field the format did not carry comes from the base
            // day, whether or not it carried another one. Measured against
            // tclsh on 2026-08-25: `clock scan 1970 -format %Y -gmt 1` is
            // 1970-08-25, `clock scan {1970 03} -format {%Y %m}` is
            // 1970-03-25, and `clock scan {1970 07} -format {%Y %d}` is
            // 1970-08-07. The time is not filled in the same way — a format
            // with no `%H` starts the day at midnight.
            let month = got.month.unwrap_or(base.month);
            let day = got.day.unwrap_or(base.day);
            days_from_civil(year, month, day)
        }
    };
    // A weekday in the input is checked against the date, not ignored — but
    // only once the date stands on its own. With a year and no day tclsh reads
    // the weekday as *choosing* the day, which needs the base date this
    // frontend does not carry yet.
    if let Some(named) = got.weekday {
        let year_given = got.year.is_some() || got.year_in_century.is_some();
        let dated_day = year_given && (got.day.is_some() || got.day_of_year.is_some());
        if dated_day && civil_of(days * 86400).iso_weekday() != named {
            return Err("unable to convert input string: invalid day of week".to_string());
        }
    }
    let local = days * 86400
        + hour as i64 * 3600
        + got.minute.unwrap_or(0) as i64 * 60
        + got.second.unwrap_or(0) as i64;
    let seconds = match got.offset {
        Some(offset) => local - offset as i64,
        None => local - zone.for_local(local).offset as i64,
    };
    if seconds < EARLIEST {
        return Err(too_early());
    }
    Ok(seconds)
}

// ── clock add ────────────────────────────────────────────────────────────

/// The units `clock add` takes, in the order it lists them when it rejects
/// one.
const UNITS: &[&str] = &[
    "years", "months", "week", "weeks", "days", "weekdays", "hours", "minutes", "seconds",
];

fn add_units(seconds: i64, count: i64, unit: &str, zone: &Zone) -> Result<i64, String> {
    let scale = match unit {
        "seconds" => Some(1),
        "minutes" => Some(60),
        "hours" => Some(3600),
        _ => None,
    };
    if let Some(scale) = scale {
        return seconds
            .checked_add(count.checked_mul(scale).ok_or_else(overflow)?)
            .ok_or_else(overflow);
    }
    // Every other unit is calendar arithmetic: the *local* date moves and the
    // zone offset is applied again, which is what makes adding a day across a
    // daylight change land at the same wall-clock time.
    let local = seconds
        .checked_add(zone.at(seconds).offset as i64)
        .ok_or_else(overflow)?;
    let civil = civil_of(local);
    let days = match unit {
        "days" => civil.epoch_day.checked_add(count).ok_or_else(overflow)?,
        "week" | "weeks" => civil
            .epoch_day
            .checked_add(count.checked_mul(7).ok_or_else(overflow)?)
            .ok_or_else(overflow)?,
        "weekdays" => weekday_walk(civil.epoch_day, count),
        _ => {
            let months = if unit == "years" {
                count.checked_mul(12).ok_or_else(overflow)?
            } else {
                count
            };
            let total = (civil.year * 12 + civil.month as i64 - 1)
                .checked_add(months)
                .ok_or_else(overflow)?;
            let year = total.div_euclid(12);
            let month = total.rem_euclid(12) as u32 + 1;
            // A day past the end of the target month is clamped to it, as
            // tclsh's `AddMonths` does.
            days_from_civil(year, month, civil.day.min(month_length(year, month)))
        }
    };
    let moved = days * 86400 + local.rem_euclid(86400);
    let result = moved - zone.for_local(moved).offset as i64;
    if result < EARLIEST {
        return Err(too_early());
    }
    Ok(result)
}

/// `weekdays` counts only Monday through Friday.
fn weekday_walk(start: i64, count: i64) -> i64 {
    let step = if count < 0 { -1 } else { 1 };
    let mut day = start;
    let mut left = count.abs();
    while left > 0 {
        day += step;
        if (day + 3).rem_euclid(7) < 5 {
            left -= 1;
        }
    }
    day
}

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

fn bad_unit(unit: &str) -> String {
    format!("bad unit \"{unit}\": must be {}", listing(UNITS))
}

// ── options ──────────────────────────────────────────────────────────────

/// The options `format`, `scan` and `add` share.
struct Options {
    format: Option<String>,
    gmt: Option<bool>,
    timezone: Option<String>,
    base: Option<i64>,
    locale: Option<String>,
}

impl Options {
    /// The message catalogue `-locale` asks for. With no `-locale` the answer
    /// is the current locale, which `::tcl::clock::EnterLocale` reads from
    /// `mclocale` and msgcat initialises from the environment — so an
    /// unadorned `clock format` answers in the caller's language, as tclsh's
    /// does.
    fn catalog(&self) -> Result<Arc<Catalog>, String> {
        crate::clock_locale::enter(self.locale.as_deref().unwrap_or("current"))
    }

    /// Resolve the zone the options ask for.
    fn zone(&self) -> Result<Zone, String> {
        if self.gmt.is_some() && self.timezone.is_some() {
            return Err("cannot use -gmt and -timezone in same call".to_string());
        }
        match (&self.timezone, self.gmt) {
            (Some(name), _) => load_zone(name),
            (None, Some(true)) => Ok(Zone::fixed(0, "GMT")),
            _ => system_zone(),
        }
    }
}

/// Read the trailing `-option value` pairs. `usage` is the wording the command
/// reports when a value is missing, which differs per subcommand.
fn options(words: &[Value], allowed: &[&str], usage: &str) -> Result<Options, String> {
    let mut out = Options {
        format: None,
        gmt: None,
        timezone: None,
        base: None,
        locale: None,
    };
    let mut i = 0;
    while i < words.len() {
        let name = to_tcl_string(&words[i]);
        let Some(option) = resolve(&name, allowed) else {
            return Err(format!(
                "bad option \"{name}\": must be {}",
                listing(allowed)
            ));
        };
        let Some(value) = words.get(i + 1) else {
            return Err(usage.to_string());
        };
        match option {
            "-format" => out.format = Some(to_tcl_string(value)),
            "-gmt" => out.gmt = Some(crate::runtime::tcl_bool(value)?),
            "-timezone" => out.timezone = Some(to_tcl_string(value)),
            "-base" => out.base = Some(seconds_of(value)?),
            // The locale decides the month and day names, the AM/PM and era
            // words, the `%c`/`%x`/`%X` expansions, the digits `%O…` writes
            // and the Gregorian changeover. Every name resolves: one with no
            // catalogue anywhere in its fallback chain is the root locale.
            "-locale" => out.locale = Some(to_tcl_string(value)),
            _ => unreachable!("the option table and this match are one list"),
        }
        i += 2;
    }
    Ok(out)
}

/// A clock value: an integer, or `now`.
fn seconds_of(v: &Value) -> Result<i64, String> {
    let text = tcl_str(v);
    if text.trim() == "now" {
        return Ok(current_seconds());
    }
    match crate::runtime::parse_number(text.trim()) {
        Ok(Num::Int(i)) => Ok(i),
        _ => Err(format!("bad seconds \"{text}\": must be now or integer")),
    }
}

fn current_micros() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_micros() as i64)
        .unwrap_or(0)
}

fn current_seconds() -> i64 {
    current_micros().div_euclid(1_000_000)
}

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

const FORMAT_USAGE: &str = "wrong # args: should be \"clock format clockval|now ?-format string? ?-gmt boolean? ?-locale LOCALE? ?-timezone ZONE?\"";
const SCAN_USAGE: &str = "wrong # args: should be \"clock scan string ?-base seconds? ?-format string? ?-gmt boolean? ?-locale LOCALE? ?-timezone ZONE?\"";
const ADD_USAGE: &str = "wrong # args: should be \"clock add clockval ?number units?... ?-gmt boolean? ?-locale LOCALE? ?-timezone ZONE?\"";

pub(crate) fn extension(vm: &mut VM, id: u16, arg: u8) -> Result<(), String> {
    if id == ext::NOW {
        let switch = if arg == 3 { Some(vm.pop()) } else { None };
        let value = now(arg, switch.as_ref())?;
        vm.push(value);
        return Ok(());
    }
    let mut words = Vec::with_capacity(arg as usize);
    for _ in 0..arg {
        words.push(vm.pop());
    }
    words.reverse();
    let value = match id {
        ext::FORMAT => run_format(&words)?,
        ext::SCAN => run_scan(&words)?,
        _ => run_add(&words)?,
    };
    vm.push(value);
    Ok(())
}

fn now(unit: u8, switch: Option<&Value>) -> Result<Value, String> {
    if let Some(switch) = switch {
        // `clock clicks` with no switch answers the highest-resolution
        // counter the platform has, which here is the microsecond clock the
        // other two units are read from.
        return match to_tcl_string(switch).as_str() {
            "-milliseconds" => Ok(Value::Int(current_micros() / 1000)),
            "-microseconds" | "" => Ok(Value::Int(current_micros())),
            other => Err(format!(
                "bad option \"{other}\": must be -microseconds or -milliseconds"
            )),
        };
    }
    Ok(Value::Int(match unit {
        0 => current_seconds(),
        1 => current_micros() / 1000,
        _ => current_micros(),
    }))
}

fn run_format(words: &[Value]) -> Result<Value, String> {
    let Some(clock) = words.first() else {
        return Err(FORMAT_USAGE.to_string());
    };
    let seconds = seconds_of(clock)?;
    let opts = options(
        &words[1..],
        &["-format", "-gmt", "-locale", "-timezone"],
        FORMAT_USAGE,
    )?;
    let zone = opts.zone()?;
    let format = opts.format.as_deref().unwrap_or(DEFAULT_FORMAT);
    let cat = opts.catalog()?;
    Ok(Value::Str(Arc::new(format_time(
        seconds, format, &zone, &cat,
    )?)))
}

fn run_scan(words: &[Value]) -> Result<Value, String> {
    let Some(input) = words.first() else {
        return Err(SCAN_USAGE.to_string());
    };
    let opts = options(
        &words[1..],
        &["-base", "-format", "-gmt", "-locale", "-timezone"],
        SCAN_USAGE,
    )?;
    let zone = opts.zone()?;
    let Some(format) = opts.format.as_deref() else {
        return Err(
            "clock scan: the free-form parser is not supported yet; use -format".to_string(),
        );
    };
    let cat = opts.catalog()?;
    // `-base` is the instant the fields the format did not carry are taken
    // from, which is the current one when the script names none.
    let base_at = opts.base.unwrap_or_else(current_seconds);
    Ok(Value::Int(scan_time(
        &to_tcl_string(input),
        format,
        &zone,
        &cat,
        base_at,
    )?))
}

fn run_add(words: &[Value]) -> Result<Value, String> {
    let Some(clock) = words.first() else {
        return Err(ADD_USAGE.to_string());
    };
    let mut seconds = seconds_of(clock)?;
    // The offsets come first and the options after them; the first word that
    // reads as an option name ends the offset list.
    let rest = &words[1..];
    let split = rest
        .iter()
        .position(|w| {
            let text = to_tcl_string(w);
            text.starts_with('-') && text[1..].starts_with(|c: char| c.is_ascii_alphabetic())
        })
        .unwrap_or(rest.len());
    let (offsets, tail) = rest.split_at(split);
    let opts = options(tail, &["-base", "-gmt", "-locale", "-timezone"], ADD_USAGE)?;
    let zone = opts.zone()?;
    let mut i = 0;
    while i < offsets.len() {
        let count = match crate::runtime::parse_number(tcl_str(&offsets[i]).trim()) {
            Ok(Num::Int(n)) => n,
            _ => {
                return Err(format!(
                    "expected integer but got \"{}\"",
                    to_tcl_string(&offsets[i])
                ))
            }
        };
        let Some(unit) = offsets.get(i + 1) else {
            return Err(ADD_USAGE.to_string());
        };
        let unit = to_tcl_string(unit);
        let Some(resolved) = resolve(&unit, UNITS) else {
            return Err(bad_unit(&unit));
        };
        seconds = add_units(seconds, count, resolved, &zone)?;
        i += 2;
    }
    Ok(Value::Int(seconds))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The civil-date conversions are each other's inverse over the whole
    /// range this module answers for.
    #[test]
    fn the_calendar_round_trips() {
        for day in [-79366i64, -1, 0, 1, 14288, 100000, 2932896] {
            let (y, m, d) = civil_from_days(day);
            assert_eq!(days_from_civil(y, m, d), day, "day {day} -> {y}-{m}-{d}");
        }
    }

    /// A fixed epoch, so nothing here depends on when the test runs. The
    /// differential suite is what pins these against tclsh; this guards the
    /// pieces of the derivation a whole-process run would not localize.
    #[test]
    fn a_known_instant_formats() {
        let utc = Zone::fixed(0, "GMT");
        let out =
            format_time(1234567890, DEFAULT_FORMAT, &utc, &Catalog::default()).expect("formats");
        assert_eq!(out, "Fri Feb 13 23:31:30 GMT 2009");
        let iso = format_time(1234567890, "%G-W%V-%u %j %U %W", &utc, &Catalog::default())
            .expect("formats");
        assert_eq!(iso, "2009-W07-5 044 06 06");
    }

    /// Before the changeover the answer would depend on the locale's calendar,
    /// so there is no answer rather than a wrong one.
    #[test]
    fn early_dates_are_refused() {
        let utc = Zone::fixed(0, "GMT");
        let err = format_time(EARLIEST - 1, "%Y", &utc, &Catalog::default()).expect_err("refused");
        assert!(err.contains("Gregorian changeover"), "{err}");
    }

    /// The fixed-offset zone names `SetupTimeZone` accepts, and the ones it
    /// leaves for the zone database.
    #[test]
    fn numeric_zones_parse() {
        assert_eq!(fixed_offset("+0530"), Some(19800));
        assert_eq!(fixed_offset("-05:30"), Some(-19800));
        assert_eq!(fixed_offset("+01"), Some(3600));
        assert_eq!(fixed_offset("+01:02:03"), Some(3723));
        assert_eq!(fixed_offset("CET"), None);
        assert_eq!(fixed_offset("+abc"), None);
    }
}