nsh-js 0.8.0

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
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
//! `Intl` (ECMA-402) for what apps format most: `Intl.NumberFormat`
//! (decimal, percent, currency and unit styles; fraction and significant
//! digits; grouping; sign display; standard, scientific, engineering and
//! compact notation) and `Intl.DateTimeFormat` (the date and time fields,
//! `dateStyle` / `timeStyle`, 12- and 24-hour cycles; local time, UTC, a
//! fixed offset or a named zone the app ships), `Intl.ListFormat` (a
//! list joined with the language's conjunction, disjunction or unit
//! separator) and `Intl.RelativeTimeFormat` (a count in a unit as
//! "3 minutes ago" or "in 2 days", in the language's CLDR patterns), with
//! `format`, `formatToParts` and `resolvedOptions`;
//! and the locale-aware `toLocaleString` of numbers, BigInts and dates.
//! QuickJS has no `Intl`; this one formats natively, in Rust.
//!
//! The language data (`locale.rs`) is not CLDR: ICU4X's data for numbers
//! and dates in every locale would add megabytes to every app, a language
//! here is a JSON file of a few kilobytes. English is built in; the others
//! are the languages the app ships (nsh.json `locales`, the files of
//! `nsh-i18n`'s `data/`), which the bundle registers before the app runs
//! (`nsh:rt`'s `i18n`, [`add_languages`]). A locale without data resolves
//! to the next requested one, then the device's (`Environment::locale`),
//! then `en-US`. Local time is
//! `Date`'s, and is named as the zone it is computed in: as the C library
//! computing it reads that zone (`TZ`, `/etc/localtime`; the browser's on
//! the web), or where that is out of its sight (Windows, Android) as the
//! platform reports it (`LocaleSettings::time_zone`, `localeSettings()`'s
//! `timeZone`), so on a device `localeSettings()` names it too.
//! `resolvedOptions().timeZone` gives the name and a `timeZone` naming it
//! is local time; a `TZ` holding a POSIX rule
//! (`CET-1CEST,M3.5.0,M10.5.0/3`) is named by its text, so its daylight
//! saving time stays. A test's zone
//! (`open({ localeSettings: { timeZone } })`) names the device's zone
//! without moving local time, so `Intl` keeps naming the machine's. Other
//! named zones (`America/New_York`) are those the app ships (nsh.json
//! `timeZones`: their rules from the IANA database, `zone.rs`), registered
//! with the languages ([`add_zones`]); their short names are the
//! database's abbreviations (`EST`), their long names the English ones for
//! North American zones (`Eastern Standard Time`), else the offset
//! (`GMT+10:30`, `GMT+05:30`). `Intl.supportedValuesOf("timeZone")` lists the
//! named zones the app ships. TypeScript declares all of it in its
//! ECMAScript library (`lib.es2023`), so `globals.d.ts` does not.
//!
//! Not there: `Collator`, `PluralRules`, `DisplayNames`, `Segmenter`,
//! `Intl.Locale`; named time
//! zones the app does not ship, long zone names of languages other than
//! English;
//! calendars other than the Gregorian, non-Latin digits, `currencySign:
//! "accounting"` (written as `standard`) and currency names (written as
//! codes). The constructors need `new`.

mod date;
mod list;
mod locale;
mod number;
mod relative;
mod zone;

use std::ffi::c_int;

pub(crate) use locale::Languages;
use locale::Locale;
#[cfg(not(target_arch = "wasm32"))]
use nsh_core::platform::TimeZone;
use rquickjs::qjs;
pub(crate) use zone::Zones;

use super::{
    Class, Key, Object, Spec, data, instance,
    js::{self, Ctx, R, Raw, V, native, trace},
};

/// A piece of a formatted value (`formatToParts`).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Part {
    pub(crate) kind: &'static str,
    pub(crate) value: String,
}

fn join(parts: &[Part]) -> String {
    parts.iter().map(|p| p.value.as_str()).collect()
}

fn parts_array(cx: Ctx, parts: &[Part]) -> R<V> {
    let mut items = Vec::with_capacity(parts.len());
    for part in parts {
        let o = js::new_object(cx)?;
        js::define(cx, o.raw(), "type", js::string(cx, part.kind)?, true)?;
        js::define(cx, o.raw(), "value", js::string(cx, &part.value)?, true)?;
        items.push(o);
    }
    js::new_array(cx, items)
}

// --- Arguments ------------------------------------------------------------

/// The requested locales: `undefined`, a tag or a list of them.
fn requested(cx: Ctx, locales: Raw) -> R<Vec<String>> {
    if js::is_undefined(locales) {
        return Ok(Vec::new());
    }
    let tags = if !js::is_object(locales) {
        vec![js::to_string(cx, locales)?]
    } else {
        let length = js::to_number(cx, js::get(cx, locales, "length")?.raw())?;
        let mut tags = Vec::new();
        for i in 0..(length.max(0.0) as usize).min(64) {
            let item = js::get(cx, locales, &i.to_string())?;
            tags.push(js::to_string(cx, item.raw())?);
        }
        tags
    };
    let mut out = Vec::with_capacity(tags.len());
    for tag in tags {
        match nsh_core::platform::Locale::parse(&tag) {
            Some(t) if !out.iter().any(|o: &String| o == t.as_str()) => {
                out.push(t.as_str().to_owned())
            }
            Some(_) => {}
            None => {
                return Err(js::range_error(
                    cx,
                    &format!("Incorrect locale information provided: {tag}"),
                ));
            }
        }
    }
    Ok(out)
}

fn resolve(cx: Ctx, locales: Raw) -> R<Locale> {
    let requested = requested(cx, locales)?;
    let default = crate::env::locale(cx);
    Ok(super::web(cx)
        .languages
        .resolve(&requested, default.as_str()))
}

/// Registers the language data the app ships, by language (`"de"`).
pub(crate) fn add_languages(cx: Ctx, languages: serde_json::Map<String, serde_json::Value>) {
    super::web(cx).languages.add(languages);
}

/// Registers the named time zones the app ships (`nsh_i18n::zones`' data).
pub(crate) fn add_zones(cx: Ctx, zones: Vec<serde_json::Value>) {
    super::web(cx).zones.add(zones);
}

/// The options object (`undefined`: none).
fn options(cx: Ctx, options: Raw) -> R<Option<V>> {
    if js::is_undefined(options) {
        return Ok(None);
    }
    if !js::is_object(options) {
        if js::is_nullish(options) {
            return Err(js::type_error(cx, "options must be an object"));
        }
        return Ok(None);
    }
    Ok(Some(V::dup(cx, options)))
}

fn get(cx: Ctx, options: &Option<V>, key: &str) -> R<V> {
    match options {
        Some(o) => js::get(cx, o.raw(), key),
        None => Ok(V::undefined()),
    }
}

/// A string option, one of `allowed`.
fn string_option(
    cx: Ctx,
    o: &Option<V>,
    key: &str,
    allowed: &[&'static str],
) -> R<Option<&'static str>> {
    let v = get(cx, o, key)?;
    if v.is_undefined() {
        return Ok(None);
    }
    let s = js::to_string(cx, v.raw())?;
    allowed
        .iter()
        .find(|a| **a == s)
        .copied()
        .map(Some)
        .ok_or_else(|| js::range_error(cx, &format!("Value {s} out of range for option {key}")))
}

fn number_option(cx: Ctx, o: &Option<V>, key: &str, min: u8, max: u8) -> R<Option<u8>> {
    let v = get(cx, o, key)?;
    if v.is_undefined() {
        return Ok(None);
    }
    let n = js::to_number(cx, v.raw())?;
    if n.is_nan() || n < f64::from(min) || n > f64::from(max) {
        return Err(js::range_error(
            cx,
            &format!("{key} value is out of range."),
        ));
    }
    Ok(Some(n.floor() as u8))
}

fn bool_option(cx: Ctx, o: &Option<V>, key: &str) -> R<Option<bool>> {
    let v = get(cx, o, key)?;
    Ok((!v.is_undefined()).then(|| js::to_bool(cx, v.raw())))
}

// --- NumberFormat -----------------------------------------------------------

fn number_format(cx: Ctx, options: Raw) -> R<number::Format> {
    use number::{
        CurrencyDisplay, Format, Grouping, Notation, Rounding, SignDisplay, Style, UnitDisplay,
    };
    let o = self::options(cx, options)?;
    let style = string_option(cx, &o, "style", &["decimal", "percent", "currency", "unit"])?;
    let currency = get(cx, &o, "currency")?;
    let currency = if currency.is_undefined() {
        None
    } else {
        let code = js::to_string(cx, currency.raw())?;
        if code.len() != 3 || !code.bytes().all(|b| b.is_ascii_alphabetic()) {
            return Err(js::range_error(
                cx,
                &format!("Invalid currency code : {code}"),
            ));
        }
        Some(code.to_ascii_uppercase())
    };
    let currency_display = string_option(
        cx,
        &o,
        "currencyDisplay",
        &["code", "symbol", "narrowSymbol", "name"],
    )?;
    string_option(cx, &o, "currencySign", &["standard", "accounting"])?;
    let unit = get(cx, &o, "unit")?;
    let unit = if unit.is_undefined() {
        None
    } else {
        let unit = js::to_string(cx, unit.raw())?;
        if !number::known_unit(&unit) {
            return Err(js::range_error(
                cx,
                &format!("Invalid unit argument for Intl.NumberFormat() '{unit}'"),
            ));
        }
        Some(unit)
    };
    let unit_display = string_option(cx, &o, "unitDisplay", &["short", "narrow", "long"])?;
    let style = match style.unwrap_or("decimal") {
        "percent" => Style::Percent,
        "currency" => Style::Currency {
            code: currency.ok_or_else(|| {
                js::type_error(cx, "Currency code is required with currency style.")
            })?,
            display: match currency_display {
                Some("code") => CurrencyDisplay::Code,
                Some("narrowSymbol") => CurrencyDisplay::NarrowSymbol,
                Some("name") => CurrencyDisplay::Name,
                _ => CurrencyDisplay::Symbol,
            },
        },
        "unit" => Style::Unit {
            unit: unit.ok_or_else(|| js::type_error(cx, "Unit is required with unit style."))?,
            display: match unit_display {
                Some("narrow") => UnitDisplay::Narrow,
                Some("long") => UnitDisplay::Long,
                _ => UnitDisplay::Short,
            },
        },
        _ => Style::Decimal,
    };
    let notation = string_option(
        cx,
        &o,
        "notation",
        &["standard", "scientific", "engineering", "compact"],
    )?;
    // Read in the order of the specification (getters observe it).
    let min_integer = number_option(cx, &o, "minimumIntegerDigits", 1, 21)?.unwrap_or(1);
    let mnfd = number_option(cx, &o, "minimumFractionDigits", 0, 100)?;
    let mxfd = number_option(cx, &o, "maximumFractionDigits", 0, 100)?;
    let mnsd = number_option(cx, &o, "minimumSignificantDigits", 1, 21)?;
    let mxsd = number_option(cx, &o, "maximumSignificantDigits", 1, 21)?;
    let priority = string_option(
        cx,
        &o,
        "roundingPriority",
        &["auto", "morePrecision", "lessPrecision"],
    )?
    .unwrap_or("auto");
    let trailing = string_option(cx, &o, "trailingZeroDisplay", &["auto", "stripIfInteger"])?;
    let compact_display = string_option(cx, &o, "compactDisplay", &["short", "long"])?;
    let notation = match notation.unwrap_or("standard") {
        "scientific" => Notation::Scientific,
        "engineering" => Notation::Engineering,
        "compact" => Notation::Compact {
            long: compact_display == Some("long"),
        },
        _ => Notation::Standard,
    };
    let compact = matches!(notation, Notation::Compact { .. });
    let (fraction_min, fraction_max) = match &style {
        Style::Currency { code, .. } if !compact => {
            let digits = number::currency_digits(code);
            (digits, digits)
        }
        Style::Percent => (0, 0),
        _ if compact => (0, 0),
        _ => (0, 3),
    };
    let has_sd = mnsd.is_some() || mxsd.is_some();
    let has_fd = mnfd.is_some() || mxfd.is_some();
    let need_sd = priority != "auto" || has_sd;
    let need_fd = priority != "auto" || !(has_sd || (!has_fd && compact));
    let (min_sig, max_sig) = (mnsd.unwrap_or(1), mxsd.unwrap_or(21));
    if need_sd && min_sig > max_sig {
        return Err(js::range_error(
            cx,
            "maximumSignificantDigits value is out of range.",
        ));
    }
    let (min_frac, max_frac) = match (mnfd, mxfd) {
        _ if !has_fd => (fraction_min, fraction_max),
        (Some(min), Some(max)) if min > max => {
            return Err(js::range_error(
                cx,
                "maximumFractionDigits value is out of range.",
            ));
        }
        (Some(min), Some(max)) => (min, max),
        (Some(min), None) => (min, fraction_max.max(min)),
        (None, Some(max)) => (fraction_min.min(max), max),
        (None, None) => (fraction_min, fraction_max),
    };
    let rounding = match (need_sd, need_fd) {
        (true, false) => Rounding::Significant {
            min: min_sig,
            max: max_sig,
        },
        (false, true) => Rounding::Fraction {
            min: min_frac,
            max: max_frac,
        },
        // Compact's default: two significant digits for small numbers.
        (false, false) => Rounding::Both {
            min_fraction: 0,
            max_fraction: 0,
            min_significant: 1,
            max_significant: 2,
            more: true,
        },
        (true, true) => Rounding::Both {
            min_fraction: min_frac,
            max_fraction: max_frac,
            min_significant: min_sig,
            max_significant: max_sig,
            more: priority != "lessPrecision",
        },
    };
    let grouping = get(cx, &o, "useGrouping")?;
    let grouping = if grouping.is_undefined() {
        if compact {
            Grouping::Min2
        } else {
            Grouping::Auto
        }
    // SAFETY: an inline tag read.
    } else if unsafe { qjs::JS_VALUE_GET_TAG(grouping.raw()) } == qjs::JS_TAG_BOOL {
        if js::to_bool(cx, grouping.raw()) {
            Grouping::Always
        } else {
            Grouping::Off
        }
    } else {
        match js::to_string(cx, grouping.raw())?.as_str() {
            "always" => Grouping::Always,
            "min2" => Grouping::Min2,
            "auto" | "true" | "false" => Grouping::Auto,
            "" => Grouping::Off,
            other => {
                return Err(js::range_error(
                    cx,
                    &format!("Value {other} out of range for option useGrouping"),
                ));
            }
        }
    };
    let sign = match string_option(
        cx,
        &o,
        "signDisplay",
        &["auto", "never", "always", "exceptZero", "negative"],
    )? {
        Some("never") => SignDisplay::Never,
        Some("always") => SignDisplay::Always,
        Some("exceptZero") => SignDisplay::ExceptZero,
        Some("negative") => SignDisplay::Negative,
        _ => SignDisplay::Auto,
    };
    Ok(Format {
        style,
        notation,
        sign,
        grouping,
        min_integer,
        rounding,
        strip_if_integer: trailing == Some("stripIfInteger"),
    })
}

/// The number `v` stands for: a BigInt or a decimal string exactly, else
/// `ToNumber`.
fn number_value(cx: Ctx, v: Raw) -> R<number::Value> {
    // SAFETY: an inline tag read.
    let tag = unsafe { qjs::JS_VALUE_GET_TAG(v) };
    if tag == qjs::JS_TAG_BIG_INT || tag == qjs::JS_TAG_SHORT_BIG_INT || tag == qjs::JS_TAG_STRING {
        let text = js::to_string(cx, v)?;
        return Ok(number::Value::parse(&text).unwrap_or(number::Value::Nan));
    }
    Ok(number::Value::from_f64(js::to_number(cx, v)?))
}

struct NumberFormat {
    locale: Locale,
    format: number::Format,
    /// `format`, bound to the object (made on first read).
    bound: Option<V>,
}

trace!(NumberFormat { bound });

impl Object for NumberFormat {}

fn format_number(cx: Ctx, this: Raw, value: Raw) -> R<Vec<Part>> {
    let (locale, format) = {
        let nf = data::<NumberFormat>(cx, this, "NumberFormat")?;
        (nf.locale.clone(), nf.format.clone())
    };
    let value = number_value(cx, value)?;
    Ok(number::format(
        &value,
        &format,
        &locale.numbers,
        locale.tag.as_str(),
    ))
}

native!(
    fn number_format_constructor(cx, this, args) {
        let locale = resolve(cx, args.get(0))?;
        let format = number_format(cx, args.get(1))?;
        instance(cx, this, Class::NumberFormat, NumberFormat { locale, format, bound: None })
    }
);

native!(
    fn number_format_format(cx, this, args) {
        if let Some(bound) = &data::<NumberFormat>(cx, this, "NumberFormat")?.bound {
            return Ok(bound.clone_ref());
        }
        let f = js::closure(cx, vec![V::dup(cx, this)], |cx, captures, args| {
            let parts = format_number(cx, captures[0].raw(), args.get(0))?;
            js::string(cx, &join(&parts))
        })?;
        data::<NumberFormat>(cx, this, "NumberFormat")?.bound = Some(f.clone_ref());
        Ok(f)
    }
);

native!(
    fn number_format_to_parts(cx, this, args) {
        let parts = format_number(cx, this, args.get(0))?;
        parts_array(cx, &parts)
    }
);

native!(
    fn number_format_resolved_options(cx, this, args) {
        use number::{CurrencyDisplay, Grouping, Notation, Rounding, SignDisplay, Style, UnitDisplay};
        let (locale, f) = {
            let nf = data::<NumberFormat>(cx, this, "NumberFormat")?;
            (nf.locale.clone(), nf.format.clone())
        };
        let o = js::new_object(cx)?;
        let set = |key: &str, value: V| js::define(cx, o.raw(), key, value, true);
        let text = |s: &str| js::string(cx, s);
        set("locale", text(locale.tag.as_str())?)?;
        set("numberingSystem", text("latn")?)?;
        match &f.style {
            Style::Decimal => set("style", text("decimal")?)?,
            Style::Percent => set("style", text("percent")?)?,
            Style::Currency { code, display } => {
                set("style", text("currency")?)?;
                set("currency", text(code)?)?;
                set("currencyDisplay", text(match display {
                    CurrencyDisplay::Symbol => "symbol",
                    CurrencyDisplay::NarrowSymbol => "narrowSymbol",
                    CurrencyDisplay::Code => "code",
                    CurrencyDisplay::Name => "name",
                })?)?;
                set("currencySign", text("standard")?)?;
            }
            Style::Unit { unit, display } => {
                set("style", text("unit")?)?;
                set("unit", text(unit)?)?;
                set("unitDisplay", text(match display {
                    UnitDisplay::Short => "short",
                    UnitDisplay::Narrow => "narrow",
                    UnitDisplay::Long => "long",
                })?)?;
            }
        }
        set("minimumIntegerDigits", V::num(f64::from(f.min_integer)))?;
        let (fraction, significant, priority) = match f.rounding {
            Rounding::Fraction { min, max } => (Some((min, max)), None, "auto"),
            Rounding::Significant { min, max } => (None, Some((min, max)), "auto"),
            Rounding::Both { min_fraction, max_fraction, min_significant, max_significant, more } => (
                Some((min_fraction, max_fraction)),
                Some((min_significant, max_significant)),
                if more { "morePrecision" } else { "lessPrecision" },
            ),
        };
        if let Some((min, max)) = fraction {
            set("minimumFractionDigits", V::num(f64::from(min)))?;
            set("maximumFractionDigits", V::num(f64::from(max)))?;
        }
        if let Some((min, max)) = significant {
            set("minimumSignificantDigits", V::num(f64::from(min)))?;
            set("maximumSignificantDigits", V::num(f64::from(max)))?;
        }
        set("useGrouping", match f.grouping {
            Grouping::Off => V::bool(false),
            Grouping::Always => text("always")?,
            Grouping::Auto => text("auto")?,
            Grouping::Min2 => text("min2")?,
        })?;
        let (notation, compact) = match f.notation {
            Notation::Standard => ("standard", None),
            Notation::Scientific => ("scientific", None),
            Notation::Engineering => ("engineering", None),
            Notation::Compact { long } => ("compact", Some(if long { "long" } else { "short" })),
        };
        set("notation", text(notation)?)?;
        if let Some(display) = compact {
            set("compactDisplay", text(display)?)?;
        }
        set("signDisplay", text(match f.sign {
            SignDisplay::Auto => "auto",
            SignDisplay::Never => "never",
            SignDisplay::Always => "always",
            SignDisplay::ExceptZero => "exceptZero",
            SignDisplay::Negative => "negative",
        })?)?;
        set("roundingIncrement", V::num(1.0))?;
        set("roundingMode", text("halfExpand")?)?;
        set("roundingPriority", text(priority)?)?;
        set("trailingZeroDisplay", text(if f.strip_if_integer { "stripIfInteger" } else { "auto" })?)?;
        Ok(o)
    }
);

native!(
    /// `supportedLocalesOf` of the classes: the requested tags with data.
    fn supported_locales_of(cx, this, args) {
        let tags = requested(cx, args.get(0))?;
        let mut items = Vec::new();
        let tags: Vec<String> = {
            let languages = &super::web(cx).languages;
            tags.into_iter().filter(|t| languages.supported(t)).collect()
        };
        for tag in &tags {
            items.push(js::string(cx, tag)?);
        }
        js::new_array(cx, items)
    }
);

native!(
    fn get_canonical_locales(cx, this, args) {
        let mut items = Vec::new();
        for tag in requested(cx, args.get(0))? {
            items.push(js::string(cx, &tag)?);
        }
        js::new_array(cx, items)
    }
);

native!(
    /// `Intl.supportedValuesOf`: the named zones the app ships, sorted.
    fn supported_values_of(cx, this, args) {
        let key = js::to_string(cx, args.get(0))?;
        if key != "timeZone" {
            return Err(js::range_error(cx, &format!("Invalid key: {key}")));
        }
        let names = {
            let mut names: Vec<String> = super::web(cx).zones.names().map(str::to_owned).collect();
            names.sort_unstable();
            names
        };
        let mut items = Vec::with_capacity(names.len());
        for name in &names {
            items.push(js::string(cx, name)?);
        }
        js::new_array(cx, items)
    }
);

// --- ListFormat -------------------------------------------------------------

fn list_format(cx: Ctx, options: Raw) -> R<list::Format> {
    use list::{Format, Style, Type};
    let o = self::options(cx, options)?;
    let kind = match string_option(cx, &o, "type", &["conjunction", "disjunction", "unit"])? {
        Some("disjunction") => Type::Disjunction,
        Some("unit") => Type::Unit,
        _ => Type::Conjunction,
    };
    let style = match string_option(cx, &o, "style", &["long", "short", "narrow"])? {
        Some("short") => Style::Short,
        Some("narrow") => Style::Narrow,
        _ => Style::Long,
    };
    Ok(Format { kind, style })
}

/// The items of `list`: an array-like object whose items are strings
/// (ECMA-402's `ToStringList`).
fn list_items(cx: Ctx, list: Raw) -> R<Vec<String>> {
    if !js::is_object(list) {
        return Err(js::type_error(cx, "Argument must be an object"));
    }
    let length = js::to_number(cx, js::get(cx, list, "length")?.raw())?;
    let length = length.max(0.0).min(2f64.powi(53)) as usize;
    let mut items = Vec::with_capacity(length.min(256));
    for i in 0..length {
        let item = js::get(cx, list, &i.to_string())?;
        // SAFETY: an inline tag check.
        if !unsafe { qjs::JS_IsString(item.raw()) } {
            return Err(js::type_error(cx, "List items must be strings"));
        }
        items.push(js::to_string(cx, item.raw())?);
    }
    Ok(items)
}

struct ListFormat {
    locale: Locale,
    format: list::Format,
    /// `format`, bound to the object (made on first read).
    bound: Option<V>,
}

trace!(ListFormat { bound });

impl Object for ListFormat {}

fn format_list(cx: Ctx, this: Raw, value: Raw) -> R<Vec<Part>> {
    let (locale, format) = {
        let lf = data::<ListFormat>(cx, this, "ListFormat")?;
        (lf.locale.clone(), lf.format)
    };
    let items = list_items(cx, value)?;
    Ok(list::format(&items, &format, &locale.lists))
}

native!(
    fn list_format_constructor(cx, this, args) {
        let locale = resolve(cx, args.get(0))?;
        let format = list_format(cx, args.get(1))?;
        instance(cx, this, Class::ListFormat, ListFormat { locale, format, bound: None })
    }
);

native!(
    fn list_format_format(cx, this, args) {
        if let Some(bound) = &data::<ListFormat>(cx, this, "ListFormat")?.bound {
            return Ok(bound.clone_ref());
        }
        let f = js::closure(cx, vec![V::dup(cx, this)], |cx, captures, args| {
            let parts = format_list(cx, captures[0].raw(), args.get(0))?;
            js::string(cx, &join(&parts))
        })?;
        data::<ListFormat>(cx, this, "ListFormat")?.bound = Some(f.clone_ref());
        Ok(f)
    }
);

native!(
    fn list_format_to_parts(cx, this, args) {
        let parts = format_list(cx, this, args.get(0))?;
        parts_array(cx, &parts)
    }
);

native!(
    fn list_format_resolved_options(cx, this, args) {
        use list::{Style, Type};
        let (locale, f) = {
            let lf = data::<ListFormat>(cx, this, "ListFormat")?;
            (lf.locale.clone(), lf.format)
        };
        let o = js::new_object(cx)?;
        let set = |key: &str, value: V| js::define(cx, o.raw(), key, value, true);
        let text = |s: &str| js::string(cx, s);
        set("locale", text(locale.tag.as_str())?)?;
        set(
            "type",
            text(match f.kind {
                Type::Conjunction => "conjunction",
                Type::Disjunction => "disjunction",
                Type::Unit => "unit",
            })?,
        )?;
        set(
            "style",
            text(match f.style {
                Style::Long => "long",
                Style::Short => "short",
                Style::Narrow => "narrow",
            })?,
        )?;
        Ok(o)
    }
);

// --- RelativeTimeFormat ----------------------------------------------------

fn relative_time_format(cx: Ctx, options: Raw) -> R<relative::Format> {
    use relative::{Format, Numeric, Style};
    let o = self::options(cx, options)?;
    let style = match string_option(cx, &o, "style", &["long", "short", "narrow"])? {
        Some("short") => Style::Short,
        Some("narrow") => Style::Narrow,
        _ => Style::Long,
    };
    let numeric = match string_option(cx, &o, "numeric", &["always", "auto"])? {
        Some("auto") => Numeric::Auto,
        _ => Numeric::Always,
    };
    Ok(Format { style, numeric })
}

/// The finite number a relative time counts.
fn relative_time_value(cx: Ctx, value: Raw) -> R<f64> {
    let value = js::to_number(cx, value)?;
    if !value.is_finite() {
        return Err(js::range_error(cx, "Value must be finite"));
    }
    Ok(value)
}

fn relative_time_unit(cx: Ctx, unit: Raw) -> R<relative::Unit> {
    let unit = js::to_string(cx, unit)?;
    relative::Unit::parse(&unit).ok_or_else(|| {
        js::range_error(
            cx,
            &format!("Invalid unit argument for Intl.RelativeTimeFormat() '{unit}'"),
        )
    })
}

struct RelativeTimeFormat {
    locale: Locale,
    format: relative::Format,
    /// `format`, bound to the object (made on first read).
    bound: Option<V>,
}

trace!(RelativeTimeFormat { bound });

impl Object for RelativeTimeFormat {}

fn format_relative(cx: Ctx, this: Raw, value: Raw, unit: Raw) -> R<(Vec<Part>, &'static str)> {
    let (locale, format) = {
        let rtf = data::<RelativeTimeFormat>(cx, this, "RelativeTimeFormat")?;
        (rtf.locale.clone(), rtf.format)
    };
    let value = relative_time_value(cx, value)?;
    let unit = relative_time_unit(cx, unit)?;
    Ok((relative::format(value, unit, &format, &locale), unit.name()))
}

fn relative_parts_array(cx: Ctx, parts: &[Part], unit: &str) -> R<V> {
    let mut items = Vec::with_capacity(parts.len());
    for part in parts {
        let o = js::new_object(cx)?;
        js::define(cx, o.raw(), "type", js::string(cx, part.kind)?, true)?;
        js::define(cx, o.raw(), "value", js::string(cx, &part.value)?, true)?;
        if part.kind != "literal" {
            js::define(cx, o.raw(), "unit", js::string(cx, unit)?, true)?;
        }
        items.push(o);
    }
    js::new_array(cx, items)
}

native!(
    fn relative_time_format_constructor(cx, this, args) {
        let locale = resolve(cx, args.get(0))?;
        let format = relative_time_format(cx, args.get(1))?;
        instance(cx, this, Class::RelativeTimeFormat, RelativeTimeFormat { locale, format, bound: None })
    }
);

native!(
    fn relative_time_format_format(cx, this, args) {
        if let Some(bound) = &data::<RelativeTimeFormat>(cx, this, "RelativeTimeFormat")?.bound {
            return Ok(bound.clone_ref());
        }
        let f = js::closure(cx, vec![V::dup(cx, this)], |cx, captures, args| {
            let (parts, _) = format_relative(cx, captures[0].raw(), args.get(0), args.get(1))?;
            js::string(cx, &join(&parts))
        })?;
        data::<RelativeTimeFormat>(cx, this, "RelativeTimeFormat")?.bound = Some(f.clone_ref());
        Ok(f)
    }
);

native!(
    fn relative_time_format_to_parts(cx, this, args) {
        let (parts, unit) = format_relative(cx, this, args.get(0), args.get(1))?;
        relative_parts_array(cx, &parts, unit)
    }
);

native!(
    fn relative_time_format_resolved_options(cx, this, args) {
        let (locale, format) = {
            let rtf = data::<RelativeTimeFormat>(cx, this, "RelativeTimeFormat")?;
            (rtf.locale.clone(), rtf.format)
        };
        let o = js::new_object(cx)?;
        let set = |key: &str, value: V| js::define(cx, o.raw(), key, value, true);
        let text = |s: &str| js::string(cx, s);
        set("locale", text(locale.tag.as_str())?)?;
        set("style", text(format.style.name())?)?;
        set("numeric", text(format.numeric.name())?)?;
        set("numberingSystem", text("latn")?)?;
        Ok(o)
    }
);

// --- DateTimeFormat ---------------------------------------------------------

/// Which fields a format without any gets (ECMA-402's `ToDateTimeOptions`).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Defaults {
    Date,
    Time,
    All,
}

/// The local time zone's name: the zone local times are computed in
/// (`Date`'s, and so these formats'), so that a `timeZone` naming it
/// formats as local time does. The system's as the C library computing
/// them reads it ([`system_zone`]); where that is out of its sight
/// (Windows, Android), the platform's report of the same setting
/// ([`reported_zone_name`]); `None` for a zone without a name.
fn local_zone_name(cx: Ctx) -> R<Option<String>> {
    match system_zone() {
        SystemZone::Named(name) => Ok(Some(name)),
        SystemZone::Unnamed => Ok(None),
        SystemZone::Unknown => reported_zone_name(cx),
    }
}

/// What the system tells of the zone local times are computed in.
#[derive(Debug, PartialEq)]
enum SystemZone {
    /// The zone's name (`Europe/Berlin`, `GMT`), or the `TZ` local times
    /// follow by its own text (`CET-1CEST,M3.5.0,M10.5.0/3`): a POSIX rule
    /// names no zone, but a `timeZone` naming it is local time, its
    /// daylight saving time included, which no offset would be.
    Named(String),
    /// A zone without a name: a `TZ` of nothing but its `:`.
    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
    Unnamed,
    /// Nothing: the C library reads the system's setting itself (Windows,
    /// Android).
    Unknown,
}

/// The system's time zone: the zone `TZ` names, as the C library that
/// computes `Date`'s local times reads it, else the zone `/etc/localtime`
/// links to (`/var/db/timezone/zoneinfo/Europe/Berlin`).
#[cfg(not(target_arch = "wasm32"))]
fn system_zone() -> SystemZone {
    system_zone_of(std::env::var("TZ").ok().as_deref(), || {
        std::fs::read_link("/etc/localtime")
            .ok()
            .and_then(|target| TimeZone::parse(&target.to_string_lossy()))
    })
}

/// The zone `TZ` (`tz`, `None` when unset) names, read as the Linux and
/// GPUI backends read it for `localeSettings()` ([`TimeZone::posix`]), else the
/// system's (`system`, asked only then). A `TZ` naming no zone but the
/// system's own file (`:/etc/localtime`) is named by its text: a POSIX
/// rule (`JST-9`), which the C library follows, or what it cannot read,
/// which it takes for UTC.
#[cfg(not(target_arch = "wasm32"))]
fn system_zone_of(tz: Option<&str>, system: impl FnOnce() -> Option<TimeZone>) -> SystemZone {
    let mut asked = false;
    let mut known = true;
    let zone = TimeZone::posix(tz, || {
        asked = true;
        let zone = system();
        known = zone.is_some();
        zone
    });
    let text = tz.map(|tz| {
        let tz = tz.trim();
        tz.strip_prefix(':').unwrap_or(tz)
    });
    if let Some(text) = text.filter(|text| asked && *text != "/etc/localtime") {
        if text.is_empty() {
            SystemZone::Unnamed
        } else {
            SystemZone::Named(text.to_owned())
        }
    } else if known {
        SystemZone::Named(zone.as_str().to_owned())
    } else {
        SystemZone::Unknown
    }
}

/// The system's time zone: the browser's
/// (`Intl.DateTimeFormat().resolvedOptions().timeZone`, the web runtime's
/// `nsh.time_zone` import).
#[cfg(target_arch = "wasm32")]
fn system_zone() -> SystemZone {
    #[link(wasm_import_module = "nsh")]
    unsafe extern "C" {
        /// Writes the name's UTF-8 into `buf` if it fits in `cap` bytes;
        /// returns its length.
        fn time_zone(buf: *mut u8, cap: usize) -> usize;
    }
    let mut buf = [0u8; 64];
    // SAFETY: JS writes at most `buf.len()` bytes into it.
    let len = unsafe { time_zone(buf.as_mut_ptr(), buf.len()) };
    match buf
        .get(..len)
        .and_then(|name| std::str::from_utf8(name).ok())
    {
        Some(name) if !name.is_empty() => SystemZone::Named(name.to_owned()),
        _ => SystemZone::Unknown,
    }
}

/// The device's zone as the platform reports it (`LocaleSettings::time_zone`,
/// `localeSettings()`), where it can be local time's ([`may_be_local`]): a
/// test's zone (`open({ localeSettings: { timeZone } })`) names the device's zone without
/// moving local time. `None` before the platform reports one.
fn reported_zone_name(cx: Ctx) -> R<Option<String>> {
    const HALF_A_YEAR_MS: f64 = 182.0 * 86_400_000.0;
    let Some(zone) = crate::env::time_zone(cx) else {
        return Ok(None);
    };
    let now = time_value(cx, js::UNDEFINED)?;
    let offsets = [
        local_offset(cx, now)?,
        local_offset(cx, now + HALF_A_YEAR_MS)?,
    ];
    Ok(may_be_local(zone.as_str(), offsets).then(|| zone.as_str().to_owned()))
}

/// Whether the zone `name` can be the one local times are in, whose
/// offsets half a year apart are `offsets`: a zone of one offset (`UTC`,
/// `+08:00`: [`fixed_zone`]) where both are that offset, any other zone
/// (`Europe/Berlin`) always, its offsets being a zone database's.
fn may_be_local(name: &str, offsets: [i32; 2]) -> bool {
    let minutes = match fixed_zone(name) {
        Some(date::Zone::Offset(minutes)) => minutes,
        Some(_) => 0,
        None => return true,
    };
    offsets.iter().all(|offset| *offset == minutes)
}

/// The zone of one offset a `timeZone` names: UTC by one of its names, or
/// an offset (`+08:00`); `None` for any other zone's name.
fn fixed_zone(name: &str) -> Option<date::Zone> {
    let upper = name.to_ascii_uppercase();
    if matches!(
        upper.as_str(),
        "UTC" | "ETC/UTC" | "GMT" | "ETC/GMT" | "Z" | "ETC/UCT" | "UCT"
    ) {
        return Some(date::Zone::Utc);
    }
    parse_offset(name).map(date::Zone::Offset)
}

/// An offset time zone (`+08:00`, `-0530`, `+08`) in minutes east.
fn parse_offset(zone: &str) -> Option<i32> {
    let sign = match zone.as_bytes().first()? {
        b'+' => 1,
        b'-' | 0xE2 => -1,
        _ => return None,
    };
    let digits: String = zone[1..].chars().filter(|c| *c != ':').collect();
    if !digits.bytes().all(|b| b.is_ascii_digit()) || !(digits.len() == 2 || digits.len() == 4) {
        return None;
    }
    let hours: i32 = digits[..2].parse().ok()?;
    let minutes: i32 = digits
        .get(2..)
        .filter(|m| !m.is_empty())
        .map_or(Some(0), |m| m.parse().ok())?;
    (hours < 24 && minutes < 60).then_some(sign * (hours * 60 + minutes))
}

fn zone_option(cx: Ctx, o: &Option<V>) -> R<date::Zone> {
    let v = get(cx, o, "timeZone")?;
    if v.is_undefined() {
        return Ok(date::Zone::Local);
    }
    let name = js::to_string(cx, v.raw())?;
    if let Some(zone) = fixed_zone(&name) {
        return Ok(zone);
    }
    if local_zone_name(cx)?.is_some_and(|local| local.eq_ignore_ascii_case(&name)) {
        return Ok(date::Zone::Local);
    }
    if let Some(index) = super::web(cx).zones.find(&name) {
        return Ok(date::Zone::Named(index));
    }
    Err(js::range_error(
        cx,
        &format!(
            "Invalid time zone specified: {name} (nsh knows the device's zone, UTC, offsets such as +08:00 and the zones nsh.json's timeZones lists)"
        ),
    ))
}

/// `dateStyle` and `timeStyle` (`""`: not set).
type Styles = (&'static str, &'static str);

/// The fields, the zone and the styles (made into fields for a locale by
/// [`styled`]) of the options.
fn date_format(
    cx: Ctx,
    options: Raw,
    defaults: Defaults,
) -> R<(date::Format, date::Zone, Option<Styles>)> {
    use date::{Format, HourCycle, Month, Num, Text, ZoneName};
    let o = self::options(cx, options)?;
    let text = |s: Option<&str>| match s {
        Some("long") => Some(Text::Long),
        Some("short") => Some(Text::Short),
        Some("narrow") => Some(Text::Narrow),
        _ => None,
    };
    let num = |s: Option<&str>| match s {
        Some("numeric") => Some(Num::Numeric),
        Some("2-digit") => Some(Num::TwoDigit),
        _ => None,
    };
    const NUMS: &[&str] = &["2-digit", "numeric"];
    let hour12 = bool_option(cx, &o, "hour12")?;
    let hour_cycle = string_option(cx, &o, "hourCycle", &["h11", "h12", "h23", "h24"])?;
    let zone = zone_option(cx, &o)?;
    let weekday = text(string_option(
        cx,
        &o,
        "weekday",
        &["narrow", "short", "long"],
    )?);
    string_option(cx, &o, "era", &["narrow", "short", "long"])?;
    let year = num(string_option(cx, &o, "year", NUMS)?);
    let month = match string_option(
        cx,
        &o,
        "month",
        &["2-digit", "numeric", "narrow", "short", "long"],
    )? {
        Some("numeric") => Some(Month::Num(Num::Numeric)),
        Some("2-digit") => Some(Month::Num(Num::TwoDigit)),
        other => text(other).map(Month::Text),
    };
    let day = num(string_option(cx, &o, "day", NUMS)?);
    string_option(cx, &o, "dayPeriod", &["narrow", "short", "long"])?;
    let hour = num(string_option(cx, &o, "hour", NUMS)?);
    let minute = num(string_option(cx, &o, "minute", NUMS)?);
    let second = num(string_option(cx, &o, "second", NUMS)?);
    let fraction = number_option(cx, &o, "fractionalSecondDigits", 1, 3)?.unwrap_or(0);
    let zone_name = match string_option(
        cx,
        &o,
        "timeZoneName",
        &[
            "short",
            "long",
            "shortOffset",
            "longOffset",
            "shortGeneric",
            "longGeneric",
        ],
    )? {
        Some("short") => Some(ZoneName::Short),
        Some("long") => Some(ZoneName::Long),
        Some("shortOffset") => Some(ZoneName::ShortOffset),
        Some("longOffset") => Some(ZoneName::LongOffset),
        Some("shortGeneric") => Some(ZoneName::ShortGeneric),
        Some("longGeneric") => Some(ZoneName::LongGeneric),
        _ => None,
    };
    let date_style = string_option(cx, &o, "dateStyle", &["full", "long", "medium", "short"])?;
    let time_style = string_option(cx, &o, "timeStyle", &["full", "long", "medium", "short"])?;
    let hour_cycle = match (hour12, hour_cycle) {
        (Some(true), _) => Some(HourCycle::H12),
        (Some(false), _) => Some(HourCycle::H23),
        (None, Some("h11")) => Some(HourCycle::H11),
        (None, Some("h12")) => Some(HourCycle::H12),
        (None, Some("h23")) => Some(HourCycle::H23),
        (None, Some("h24")) => Some(HourCycle::H24),
        _ => None,
    };
    let mut f = Format {
        weekday,
        year,
        month,
        day,
        hour,
        minute,
        second,
        fraction,
        hour_cycle,
        zone_name,
    };
    let any_field = weekday.is_some()
        || year.is_some()
        || month.is_some()
        || day.is_some()
        || hour.is_some()
        || minute.is_some()
        || second.is_some()
        || fraction > 0
        || zone_name.is_some();
    if date_style.is_some() || time_style.is_some() {
        if any_field {
            return Err(js::type_error(
                cx,
                "Can't set option dateStyle or timeStyle with other date-time fields",
            ));
        }
        return Ok((
            f,
            zone,
            Some((date_style.unwrap_or(""), time_style.unwrap_or(""))),
        ));
    }
    let has_date = weekday.is_some() || year.is_some() || month.is_some() || day.is_some();
    let has_time = hour.is_some() || minute.is_some() || second.is_some() || fraction > 0;
    if !has_date && !has_time {
        if defaults != Defaults::Time {
            f.year = Some(Num::Numeric);
            f.month = Some(Month::Num(Num::Numeric));
            f.day = Some(Num::Numeric);
        }
        if defaults != Defaults::Date {
            f.hour = Some(Num::Numeric);
            f.minute = Some(Num::Numeric);
            f.second = Some(Num::Numeric);
        }
    }
    Ok((f, zone, None))
}

/// The fields of `dateStyle` / `timeStyle` for a locale.
fn styled(f: &mut date::Format, (date_style, time_style): Styles, locale: &Locale) {
    use date::{Month, Num, Text};
    match date_style {
        "short" => {
            f.year = Some(if locale.dates.short_year_2digit {
                Num::TwoDigit
            } else {
                Num::Numeric
            });
            f.month = Some(Month::Num(Num::Numeric));
            f.day = Some(Num::Numeric);
        }
        "medium" | "long" | "full" => {
            f.year = Some(Num::Numeric);
            f.month = Some(Month::Text(if date_style == "medium" {
                Text::Short
            } else {
                Text::Long
            }));
            f.day = Some(Num::Numeric);
            if date_style == "full" {
                f.weekday = Some(Text::Long);
            }
        }
        _ => {}
    }
    if !time_style.is_empty() {
        f.hour = Some(Num::Numeric);
        f.minute = Some(Num::Numeric);
        if time_style != "short" {
            f.second = Some(Num::Numeric);
        }
        f.zone_name = match time_style {
            "long" => Some(date::ZoneName::Short),
            "full" => Some(date::ZoneName::Long),
            _ => None,
        };
    }
}

struct DateTimeFormat {
    locale: Locale,
    format: date::Format,
    zone: date::Zone,
    styles: Option<Styles>,
    bound: Option<V>,
}

trace!(DateTimeFormat { bound });

impl Object for DateTimeFormat {}

/// The offset in minutes east of UTC that the local zone has at `ms`.
fn local_offset(cx: Ctx, ms: f64) -> R<i32> {
    // SAFETY: a new Date of this context.
    let date = V::checked(cx, unsafe { qjs::JS_NewDate(cx, ms) })?;
    let west = js::to_number(
        cx,
        js::invoke(cx, date.raw(), "getTimezoneOffset", &[])?.raw(),
    )?;
    Ok(if west.is_finite() { -(west as i32) } else { 0 })
}

/// The time `v` stands for (`undefined`: now), or a `RangeError`.
fn time_value(cx: Ctx, v: Raw) -> R<f64> {
    let ms = if js::is_undefined(v) {
        // Not std's clock: WebAssembly has none.
        nsh_core::time::unix_ms()
    } else {
        js::to_number(cx, v)?
    };
    if !ms.is_finite() || ms.abs() > 8.64e15 {
        return Err(js::range_error(cx, "Invalid time value"));
    }
    Ok(ms)
}

fn format_date(
    cx: Ctx,
    locale: &Locale,
    f: &date::Format,
    zone: date::Zone,
    ms: f64,
) -> R<Vec<Part>> {
    let (offset, abbr, long) = match zone {
        date::Zone::Local => (local_offset(cx, ms)?, None, None),
        date::Zone::Utc => (0, None, None),
        date::Zone::Offset(minutes) => (minutes, None, None),
        date::Zone::Named(index) => {
            let named = super::web(cx).zones.get(index);
            let (seconds, abbr) = named.at(ms);
            let abbr = writes_abbreviation(locale.tag.as_str(), abbr).then(|| abbr.to_owned());
            let long = abbr
                .as_deref()
                .and_then(|abbr| long_name(&named.name, abbr))
                .map(str::to_owned);
            (seconds.div_euclid(60), abbr, long)
        }
    };
    Ok(date::format(
        ms,
        offset,
        zone,
        abbr.as_deref(),
        long.as_deref(),
        f,
        &locale.dates,
    ))
}

/// Whether `locale` writes a named zone's short name as its abbreviation
/// (`EST`), as browsers do with CLDR's names: North American zones in
/// English as written in the US and Canada. Any other zone is written by
/// its offset (`GMT+5:30`).
fn writes_abbreviation(locale: &str, abbr: &str) -> bool {
    const NORTH_AMERICAN: &[&str] = &[
        "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT", "AKST", "AKDT", "HST", "HDT",
    ];
    let mut tags = locale.split(['-', '_']);
    let english = tags.next().is_some_and(|l| l.eq_ignore_ascii_case("en"));
    let region =
        tags.find(|t| t.len() == 2 || t.len() == 3 && t.bytes().all(|b| b.is_ascii_digit()));
    english
        && region.is_none_or(|r| r.eq_ignore_ascii_case("US") || r.eq_ignore_ascii_case("CA"))
        && NORTH_AMERICAN.contains(&abbr)
}

/// The long name English uses for a North American zone's abbreviation
/// (`EST`: `Eastern Standard Time`), as browsers write it. The bundled
/// language data carries no long zone names.
fn long_name(zone: &str, abbr: &str) -> Option<&'static str> {
    if !zone.starts_with("America/") && zone != "Pacific/Honolulu" {
        return None;
    }
    Some(match abbr {
        "EST" => "Eastern Standard Time",
        "EDT" => "Eastern Daylight Time",
        "CST" => "Central Standard Time",
        "CDT" => "Central Daylight Time",
        "MST" => "Mountain Standard Time",
        "MDT" => "Mountain Daylight Time",
        "PST" => "Pacific Standard Time",
        "PDT" => "Pacific Daylight Time",
        "AKST" => "Alaska Standard Time",
        "AKDT" => "Alaska Daylight Time",
        "HST" => "Hawaii Standard Time",
        "HDT" => "Hawaii Daylight Time",
        _ => return None,
    })
}

fn format_with(cx: Ctx, this: Raw, value: Raw) -> R<Vec<Part>> {
    let (locale, format, zone) = {
        let d = data::<DateTimeFormat>(cx, this, "DateTimeFormat")?;
        (d.locale.clone(), d.format, d.zone)
    };
    let ms = time_value(cx, value)?;
    format_date(cx, &locale, &format, zone, ms)
}

native!(
    fn date_time_format_constructor(cx, this, args) {
        let locale = resolve(cx, args.get(0))?;
        let (mut format, zone, styles) = date_format(cx, args.get(1), Defaults::Date)?;
        if let Some(styles) = styles {
            styled(&mut format, styles, &locale);
        }
        instance(cx, this, Class::DateTimeFormat, DateTimeFormat { locale, format, zone, styles, bound: None })
    }
);

native!(
    fn date_time_format_format(cx, this, args) {
        if let Some(bound) = &data::<DateTimeFormat>(cx, this, "DateTimeFormat")?.bound {
            return Ok(bound.clone_ref());
        }
        let f = js::closure(cx, vec![V::dup(cx, this)], |cx, captures, args| {
            let parts = format_with(cx, captures[0].raw(), args.get(0))?;
            js::string(cx, &join(&parts))
        })?;
        data::<DateTimeFormat>(cx, this, "DateTimeFormat")?.bound = Some(f.clone_ref());
        Ok(f)
    }
);

native!(
    fn date_time_format_to_parts(cx, this, args) {
        let parts = format_with(cx, this, args.get(0))?;
        parts_array(cx, &parts)
    }
);

native!(
    fn date_time_format_resolved_options(cx, this, args) {
        use date::{Month, Num, Text, Zone};
        let (locale, f, zone, styles) = {
            let d = data::<DateTimeFormat>(cx, this, "DateTimeFormat")?;
            (d.locale.clone(), d.format, d.zone, d.styles)
        };
        let o = js::new_object(cx)?;
        let set = |key: &str, value: V| js::define(cx, o.raw(), key, value, true);
        let text = |s: &str| js::string(cx, s);
        set("locale", text(locale.tag.as_str())?)?;
        set("calendar", text("gregory")?)?;
        set("numberingSystem", text("latn")?)?;
        let zone = match zone {
            Zone::Utc => "UTC".to_owned(),
            Zone::Offset(m) => format!("{}{:02}:{:02}", if m < 0 { '-' } else { '+' }, m.abs() / 60, m.abs() % 60),
            Zone::Named(index) => super::web(cx).zones.get(index).name.clone(),
            Zone::Local => match local_zone_name(cx)? {
                Some(name) => name,
                None => {
                    let m = local_offset(cx, time_value(cx, js::UNDEFINED)?)?;
                    format!("{}{:02}:{:02}", if m < 0 { '-' } else { '+' }, m.abs() / 60, m.abs() % 60)
                }
            },
        };
        set("timeZone", text(&zone)?)?;
        if f.hour.is_some() {
            let cycle = f.cycle(&locale.dates);
            set("hourCycle", text(cycle.name())?)?;
            set("hour12", V::bool(matches!(cycle, date::HourCycle::H11 | date::HourCycle::H12)))?;
        }
        if let Some((date_style, time_style)) = styles {
            if !date_style.is_empty() {
                set("dateStyle", text(date_style)?)?;
            }
            if !time_style.is_empty() {
                set("timeStyle", text(time_style)?)?;
            }
            return Ok(o);
        }
        let text_name = |t: Text| match t {
            Text::Long => "long",
            Text::Short => "short",
            Text::Narrow => "narrow",
        };
        let num_name = |n: Num| match n {
            Num::Numeric => "numeric",
            Num::TwoDigit => "2-digit",
        };
        if let Some(w) = f.weekday {
            set("weekday", text(text_name(w))?)?;
        }
        if let Some(n) = f.year {
            set("year", text(num_name(n))?)?;
        }
        if let Some(m) = f.month {
            set("month", text(match m {
                Month::Num(n) => num_name(n),
                Month::Text(t) => text_name(t),
            })?)?;
        }
        for (key, value) in [("day", f.day), ("hour", f.hour), ("minute", f.minute), ("second", f.second)] {
            if let Some(n) = value {
                // Minutes and seconds are written with two digits next to
                // the hour, as browsers report.
                let n = if (key == "minute" && f.hour.is_some()) || (key == "second" && f.minute.is_some()) {
                    Num::TwoDigit
                } else {
                    n
                };
                set(key, text(num_name(n))?)?;
            }
        }
        if f.fraction > 0 {
            set("fractionalSecondDigits", V::num(f64::from(f.fraction)))?;
        }
        if let Some(name) = f.zone_name {
            set("timeZoneName", text(name.name())?)?;
        }
        Ok(o)
    }
);

// --- The prototypes' toLocaleString -----------------------------------------

native!(
    /// `Number.prototype.toLocaleString` and `BigInt.prototype.
    /// toLocaleString`: `Intl.NumberFormat` without the object.
    fn number_to_locale_string(cx, this, args) {
        // SAFETY: an inline tag read.
        let tag = unsafe { qjs::JS_VALUE_GET_TAG(this) };
        let value = if tag == qjs::JS_TAG_BIG_INT || tag == qjs::JS_TAG_SHORT_BIG_INT {
            number_value(cx, this)?
        } else {
            // A Number object or a number (`valueOf` unwraps the object).
            number::Value::from_f64(js::to_number(cx, this)?)
        };
        let locale = resolve(cx, args.get(0))?;
        let format = number_format(cx, args.get(1))?;
        let parts = number::format(&value, &format, &locale.numbers, locale.tag.as_str());
        js::string(cx, &join(&parts))
    }
);

fn date_to_locale(cx: Ctx, this: Raw, args: js::Args<'_>, defaults: Defaults) -> R<V> {
    // SAFETY: an inline class check.
    if !unsafe { qjs::JS_IsDate(this) } {
        return Err(js::type_error(cx, "this is not a Date object."));
    }
    let ms = js::to_number(cx, this)?;
    if !ms.is_finite() {
        return js::string(cx, "Invalid Date");
    }
    let locale = resolve(cx, args.get(0))?;
    let (mut format, zone, styles) = date_format(cx, args.get(1), defaults)?;
    if let Some(styles) = styles {
        styled(&mut format, styles, &locale);
    }
    let parts = format_date(cx, &locale, &format, zone, ms)?;
    js::string(cx, &join(&parts))
}

native!(
    fn date_to_locale_string(cx, this, args) {
        date_to_locale(cx, this, args, Defaults::All)
    }
);

native!(
    fn date_to_locale_date_string(cx, this, args) {
        date_to_locale(cx, this, args, Defaults::Date)
    }
);

native!(
    fn date_to_locale_time_string(cx, this, args) {
        date_to_locale(cx, this, args, Defaults::Time)
    }
);

/// Replaces the engine's `toLocaleString`s (which ignore locales and
/// options) with these.
pub(crate) fn install(cx: Ctx) -> R<()> {
    let g = js::global(cx);
    type Methods = &'static [(&'static std::ffi::CStr, js::Native, c_int)];
    let methods: [(&str, Methods); 3] = [
        ("Number", &[(c"toLocaleString", number_to_locale_string, 0)]),
        ("BigInt", &[(c"toLocaleString", number_to_locale_string, 0)]),
        (
            "Date",
            &[
                (c"toLocaleString", date_to_locale_string, 0),
                (c"toLocaleDateString", date_to_locale_date_string, 0),
                (c"toLocaleTimeString", date_to_locale_time_string, 0),
            ],
        ),
    ];
    for (class, methods) in methods {
        let ctor = js::get(cx, g.raw(), class)?;
        let proto = js::get(cx, ctor.raw(), "prototype")?;
        for (name, f, length) in methods {
            let func = js::function(cx, name, *f, *length)?;
            // SAFETY: the property takes the function; non-enumerable, as
            // built-in methods are.
            unsafe {
                qjs::JS_DefinePropertyValueStr(
                    cx,
                    proto.raw(),
                    name.as_ptr(),
                    func.take(),
                    (qjs::JS_PROP_WRITABLE | qjs::JS_PROP_CONFIGURABLE) as c_int,
                );
            }
        }
    }
    Ok(())
}

/// The `Intl` object: the namespace of the classes.
pub(crate) fn namespace(cx: Ctx) -> R<V> {
    let global = js::new_object(cx)?;
    for (name, class) in [
        ("NumberFormat", Class::NumberFormat),
        ("DateTimeFormat", Class::DateTimeFormat),
        ("ListFormat", Class::ListFormat),
        ("RelativeTimeFormat", Class::RelativeTimeFormat),
    ] {
        let ctor = super::constructor(cx, class)?;
        js::define(cx, global.raw(), name, ctor, false)?;
    }
    let f = js::function(cx, c"getCanonicalLocales", get_canonical_locales, 1)?;
    js::define(cx, global.raw(), "getCanonicalLocales", f, false)?;
    let f = js::function(cx, c"supportedValuesOf", supported_values_of, 1)?;
    js::define(cx, global.raw(), "supportedValuesOf", f, false)?;
    let tag = js::string(cx, "Intl")?;
    // SAFETY: the property takes the string.
    unsafe {
        qjs::JS_DefinePropertyValue(
            cx,
            global.raw(),
            qjs::JS_ATOM_Symbol_toStringTag as _,
            tag.take(),
            qjs::JS_PROP_CONFIGURABLE as c_int,
        );
    }
    Ok(global)
}

pub(crate) const SPECS: &[Spec] = &[
    Spec {
        class: Class::NumberFormat,
        name: c"NumberFormat",
        parent: None,
        constructor: Some((number_format_constructor, 0)),
        methods: &[
            (Key::Name(c"formatToParts"), number_format_to_parts, 1),
            (
                Key::Name(c"resolvedOptions"),
                number_format_resolved_options,
                0,
            ),
        ],
        accessors: &[(c"format", number_format_format, None)],
        statics: &[(c"supportedLocalesOf", supported_locales_of, 1)],
        constants: &[],
        global: false,
        ts: super::ClassTs::NONE,
    },
    Spec {
        class: Class::DateTimeFormat,
        name: c"DateTimeFormat",
        parent: None,
        constructor: Some((date_time_format_constructor, 0)),
        methods: &[
            (Key::Name(c"formatToParts"), date_time_format_to_parts, 1),
            (
                Key::Name(c"resolvedOptions"),
                date_time_format_resolved_options,
                0,
            ),
        ],
        accessors: &[(c"format", date_time_format_format, None)],
        statics: &[(c"supportedLocalesOf", supported_locales_of, 1)],
        constants: &[],
        global: false,
        ts: super::ClassTs::NONE,
    },
    Spec {
        class: Class::ListFormat,
        name: c"ListFormat",
        parent: None,
        constructor: Some((list_format_constructor, 0)),
        methods: &[
            (Key::Name(c"formatToParts"), list_format_to_parts, 1),
            (
                Key::Name(c"resolvedOptions"),
                list_format_resolved_options,
                0,
            ),
        ],
        accessors: &[(c"format", list_format_format, None)],
        statics: &[(c"supportedLocalesOf", supported_locales_of, 1)],
        constants: &[],
        global: false,
        ts: super::ClassTs::NONE,
    },
    Spec {
        class: Class::RelativeTimeFormat,
        name: c"RelativeTimeFormat",
        parent: None,
        constructor: Some((relative_time_format_constructor, 0)),
        methods: &[
            (
                Key::Name(c"formatToParts"),
                relative_time_format_to_parts,
                2,
            ),
            (
                Key::Name(c"resolvedOptions"),
                relative_time_format_resolved_options,
                0,
            ),
        ],
        accessors: &[(c"format", relative_time_format_format, None)],
        statics: &[(c"supportedLocalesOf", supported_locales_of, 1)],
        constants: &[],
        global: false,
        ts: super::ClassTs::NONE,
    },
];

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;

    #[test]
    fn the_systems_zone_is_the_one_tz_names() {
        use SystemZone::{Named, Unknown, Unnamed};
        let named = |name: &str| Named(name.to_owned());
        // A system zone other than UTC, so that falling back on it shows.
        let singapore = || TimeZone::parse("Asia/Singapore");
        let zone = |tz: Option<&str>| system_zone_of(tz, singapore);
        // `TZ=GMT` is the zone `Date`'s local times follow, eight hours
        // from the system's, and the system is not asked.
        assert_eq!(zone(Some("GMT")), named("GMT"));
        assert_eq!(
            system_zone_of(Some("GMT"), || unreachable!("TZ names the zone")),
            named("GMT")
        );
        for name in ["UTC", "EST", "Japan", "Etc/GMT+5", "Europe/Berlin"] {
            assert_eq!(zone(Some(name)), named(name));
            assert_eq!(zone(Some(&format!(":{name}"))), named(name));
        }
        assert_eq!(zone(Some("")), named("UTC"));
        assert_eq!(
            zone(Some("/usr/share/zoneinfo/Asia/Tokyo")),
            named("Asia/Tokyo")
        );
        // Unset, or the system's own file: the system's zone.
        assert_eq!(zone(None), named("Asia/Singapore"));
        assert_eq!(zone(Some(":/etc/localtime")), named("Asia/Singapore"));
        // A POSIX rule is local time named by its text, not the system's
        // zone (nine hours from Singapore's), nor one offset: a `timeZone`
        // naming it keeps its daylight saving time.
        for rule in ["JST-9", "<+08>-8", "CET-1CEST,M3.5.0,M10.5.0/3"] {
            assert_eq!(zone(Some(rule)), named(rule));
            assert_eq!(zone(Some(&format!(":{rule}"))), named(rule));
        }
        // What the C library cannot read (it takes UTC) is named as set,
        // and a lone `:` is local time without a name.
        assert_eq!(zone(Some("Not a zone")), named("Not a zone"));
        assert_eq!(zone(Some(":")), Unnamed);
        // Where nothing tells (Windows, Android), nothing known: the
        // platform's report is asked instead.
        assert_eq!(system_zone_of(None, || None), Unknown);
        assert_eq!(system_zone_of(Some("GMT"), || None), named("GMT"));
    }

    #[test]
    fn a_zone_of_one_offset_is_local_time_only_with_its_offset() {
        // Singapore (+08:00), London in winter and summer.
        for (name, offsets, local) in [
            ("UTC", [480, 480], false),
            ("UTC", [0, 60], false),
            ("UTC", [0, 0], true),
            ("Etc/UTC", [0, 0], true),
            ("+08:00", [480, 480], true),
            ("+08:00", [450, 480], false),
            // A zone's name: its offsets are the database's.
            ("Asia/Singapore", [480, 480], true),
            ("Europe/London", [0, 60], true),
            ("GMT+01:00", [60, 60], true),
        ] {
            assert_eq!(may_be_local(name, offsets), local, "{name} at {offsets:?}");
        }
    }
}