tabnas-json5 0.5.18

The JSON5 grammar plugin for the tabnas parsing engine, over the jsonic base grammar
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
// Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License

// The engine's error carries a code, position, hint and a formatted
// report, so it is large by design and `Result<_, TabnasError>` trips
// clippy's `result_large_err`. The engine allows the lint at its own
// crate root for the same reason; boxing here would make `parse` return
// a different shape from `Tabnas::parse` and from the other two ports.
#![allow(clippy::result_large_err)]

//! The JSON5 grammar plugin for the `tabnas` parsing engine.
//!
//! JSON5 is JSON plus comments, unquoted keys, trailing commas, single
//! quotes, hex numbers, `Infinity` and `NaN`, leading and trailing
//! decimal points, explicit `+` signs, and string line continuations.
//! The plugin layers on the relaxed-JSON base grammar of
//! [`tabnas_jsonic`] and then TIGHTENS it toward the JSON5 specification:
//! no implicit top-level `a:1` or `1,2`, no auto-close at the end of the
//! source, no unquoted text at a value position, and only ECMAScript 5.1
//! `IdentifierName`s as unquoted keys.
//!
//! ```
//! let value = tabnas_json5::parse("{ a: 1, b: [2, 3,], }")?;
//! assert_eq!(value.to_string(), r#"{"a":1,"b":[2,3]}"#);
//! # Ok::<(), tabnas_json5::Json5Error>(())
//! ```
//!
//! TypeScript is canonical: `ts/src/json5.ts` and the shared
//! `json5-grammar.jsonic` define behaviour and option defaults. The
//! shared fixtures in `test/spec/*.tsv` and the vendored
//! `test/json5-tests` corpus are the parity contract across TypeScript,
//! Go and Rust.

use std::rc::Rc;
use std::sync::OnceLock;

use indexmap::IndexMap;
use regex::Regex;
use serde_json::{json, Value as JsonValue};
use tabnas::{
    ActionError, AltSpec, Context, LexCheckResult, Lexer, Plugin, PluginError, Rule, RuleSnapshot,
    Tabnas, Tin, Token, Value, ValueDef, TIN_NR, TIN_ST, TIN_TX, TIN_ZZ,
};

/// This crate's version. It MUST equal `ts/package.json` "version": the
/// release orchestrator rewrites both, and `tests/version_test.rs` fails
/// the build if they drift. Mirrors `VERSION` in `ts/src/json5.ts` and
/// `const VERSION` in `go/json5.go`.
pub const VERSION: &str = "0.5.18";

/// The README's Rust examples run as doctests, so a stale one fails the
/// gate rather than misleading the reader. Its `toml` and `bash` fences
/// are skipped; rustdoc runs only the `rust` ones.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}

/// The error a failed parse produces, re-exported so callers need not
/// depend on the engine crate directly. The Go port returns the same
/// `*jsonic.JsonicError`.
pub use tabnas::TabnasError as Json5Error;

/// The name the plugin registers under, and so the namespace of its
/// option bag on the engine.
const PLUGIN_NAME: &str = "json5";

/// The decoration under which the resolved options are recorded on the
/// instance, so [`parse_with`] can apply the `requireValue` rule. The Go
/// port's `json5$requireValue`.
const OPTIONS_MARK: &str = "json5$options";

// ---------------------------------------------------------------------------
// The JSON5 character classes.
// ---------------------------------------------------------------------------

/// JSON5 WhiteSpace: HT, VT, FF, SP, NBSP, BOM, and the Unicode Zs
/// category characters the specification enumerates.
const JSON5_WHITESPACE: &str = "\t\u{000B}\u{000C} \u{00A0}\u{FEFF}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{202F}\u{205F}\u{3000}";

/// The JSON5 LineTerminator set is LF, CR, LS and PS. TypeScript and Go
/// write all four into `line.chars`; this port splits them in two,
/// because this engine reads the halves differently.
///
/// Both halves end a line everywhere a line can end, because the engine
/// asks `line.chars` PLUS `line.fixed` for that. The one place that asks
/// `line.chars` alone is the string lexer's unprintable test, and JSON5
/// admits an unescaped U+2028 or U+2029 inside a string literal (JSON5
/// 5.2: a `JSON5DoubleStringCharacter` is any `SourceCharacter` but a
/// quote, a backslash or a `LineTerminator`, plus `LineContinuation`,
/// plus U+2028 and U+2029). TypeScript reaches the same answer by its
/// own route: `buildStringBodySpec` in the engine's `lexer.ts` tabulates
/// the code points below 256 and falls back for the rest, and the
/// fallback treats a line character as ordinary body unless the string
/// is multi-line. Go accepts them too. Putting LS and PS in
/// `line.fixed` is what makes this engine agree with both, and the rows
/// in `../test/spec/strings.tsv` execute the agreement in all three.
const JSON5_LINE_CHARS: &str = "\r\n";
/// The other half of the JSON5 LineTerminator set: see
/// [`JSON5_LINE_CHARS`].
const JSON5_LINE_FIXED: &str = "\u{2028}\u{2029}";

/// The line terminators that bump the row counter: LF, LS, PS. CR is
/// folded into the following LF for CRLF.
const JSON5_ROW_CHARS: &str = "\n\u{2028}\u{2029}";

fn is_line_terminator(ch: char) -> bool {
    matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')
}

// ---------------------------------------------------------------------------
// Options
// ---------------------------------------------------------------------------

/// The plugin options: a strict JSON5 configuration by default, with the
/// relaxations jsonic offers beyond the specification opt-in. The
/// TypeScript `Json5Options` and the Go `Defaults()` map.
///
/// On the engine the options travel as a [`Value`] bag under the plugin
/// name, spelt with the TypeScript keys (`hashComment`, `requireValue`,
/// ...); [`Json5Options::to_value`] and [`Json5Options::from_value`]
/// convert, and a key the bag does not carry keeps its default, as the
/// Go `optBool` does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Json5Options {
    /// Accept `Infinity`, `NaN` and their signed forms as numbers.
    pub infinity: bool,
    /// Accept `0x` hexadecimal integers.
    pub hex: bool,
    /// Accept `#` line comments (not JSON5).
    pub hash_comment: bool,
    /// Accept backtick-quoted strings (not JSON5).
    pub backtick_string: bool,
    /// Accept `_` digit separators in numbers (not JSON5).
    pub number_separator: bool,
    /// Accept `0o` octal integers (not JSON5).
    pub octal: bool,
    /// Accept `0b` binary integers (not JSON5).
    pub binary: bool,
    /// Require a top-level value: an empty, whitespace-only or
    /// comments-only source is an error (`json5_empty`,
    /// `json5_no_value`) rather than a `null` result.
    pub require_value: bool,
    /// Reject unquoted text at a value position, so `foo` is an error
    /// rather than the string `"foo"`.
    pub strict_value: bool,
}

impl Default for Json5Options {
    fn default() -> Self {
        Self {
            infinity: true,
            hex: true,
            hash_comment: false,
            backtick_string: false,
            number_separator: false,
            octal: false,
            binary: false,
            require_value: true,
            strict_value: true,
        }
    }
}

impl Json5Options {
    /// The option keys as the TypeScript plugin and the Go `Defaults()`
    /// map spell them: the keys [`Json5Options::to_value`] writes and
    /// [`Json5Options::from_value`] reads.
    pub const KEYS: [&str; 9] = [
        "infinity",
        "hex",
        "hashComment",
        "backtickString",
        "numberSeparator",
        "octal",
        "binary",
        "requireValue",
        "strictValue",
    ];

    fn get(&self, key: &str) -> bool {
        match key {
            "infinity" => self.infinity,
            "hex" => self.hex,
            "hashComment" => self.hash_comment,
            "backtickString" => self.backtick_string,
            "numberSeparator" => self.number_separator,
            "octal" => self.octal,
            "binary" => self.binary,
            "requireValue" => self.require_value,
            "strictValue" => self.strict_value,
            _ => unreachable!("every option key is listed"),
        }
    }

    fn set(&mut self, key: &str, value: bool) {
        match key {
            "infinity" => self.infinity = value,
            "hex" => self.hex = value,
            "hashComment" => self.hash_comment = value,
            "backtickString" => self.backtick_string = value,
            "numberSeparator" => self.number_separator = value,
            "octal" => self.octal = value,
            "binary" => self.binary = value,
            "requireValue" => self.require_value = value,
            "strictValue" => self.strict_value = value,
            _ => unreachable!("every option key is listed"),
        }
    }

    /// The options as the engine's plugin-option bag, keyed as the
    /// TypeScript plugin spells them.
    pub fn to_value(&self) -> Value {
        let mut map = IndexMap::new();
        for key in Self::KEYS {
            map.insert(key.to_string(), Value::Bool(self.get(key)));
        }
        Value::object(map)
    }

    /// Read a plugin-option bag. A key that is absent, or not a boolean,
    /// keeps its default, as the Go port's `optBool` does.
    pub fn from_value(bag: &Value) -> Self {
        let mut options = Self::default();
        if let Value::Object(map) = bag {
            for key in Self::KEYS {
                if let Some(Value::Bool(value)) = map.get(key) {
                    options.set(key, *value);
                }
            }
        }
        options
    }

    /// Read a JSON option object, the form the shared fixtures' `opts`
    /// column and the TypeScript tests use.
    pub fn from_json(bag: &JsonValue) -> Self {
        Self::from_value(&Value::from_json(bag))
    }
}

// ---------------------------------------------------------------------------
// The embedded grammar.
//
// Authored ONCE in `../json5-grammar.jsonic` and embedded into every
// runtime by `ts/embed-grammar.js`. Never hand-edit the text between the
// markers: edit the `.jsonic` file and re-run the embed. The text is
// jsonic, not JSON, and is parsed at plugin-install time by a standard
// jsonic instance, exactly as the TypeScript and Go ports parse it.
// ---------------------------------------------------------------------------

// --- BEGIN EMBEDDED json5-grammar.jsonic ---
const GRAMMAR_TEXT: &str = r#"# JSON5 Grammar Definition
# Parsed by a standard Jsonic instance and passed to jsonic.grammar()
# Function references (@ prefixed) are resolved against the refs map
# Regex references (@/pattern/flags) are resolved to RegExp instances
# Bare identifiers (UPPER_SNAKE_CASE) are placeholders overridden by the
# plugin code before the spec is applied.
#
# This file captures the strict-JSON5 baseline. The plugin layers
# option-dependent overrides (hash comments, backtick strings, octal /
# binary / separator numbers, Infinity / NaN keywords, etc.) on top.

{
  # Drop Jsonic's implicit top-level list / map alternates so `a:1` and
  # `1,2` are not accepted at the document root. JSON5 requires a single
  # value expression at top level.
  #
  # `finish: false` turns off Jsonic's auto-close of open rules at the end
  # of the source: JSON5 requires every `{` / `[` to be closed, so `{a:1`
  # is an error, not `{"a":1}`.
  options: rule: { exclude: 'imp' finish: false }

  # Restrict the token sets used by Jsonic's grammar rules:
  #   VAL drops #TX — reject bare unquoted text at value positions.
  #   KEY drops #NR — reject numeric keys like `{10: 1}`.
  options: tokenSet: {
    VAL: [ '#ST' '#NR' '#VL' ]
    KEY: [ '#TX' '#ST' '#VL' ]
  }

  # Whitespace and line-terminator sets are broadened to match the JSON5
  # spec (Unicode Zs, BOM, LS / PS). The actual character strings are
  # supplied by the plugin because they contain code points the grammar
  # parser cannot round-trip losslessly.
  options: space: { chars: JSON5_WHITESPACE }
  options: line: {
    chars: JSON5_LINE_TERMINATOR
    rowChars: JSON5_ROW_CHARS
  }

  # LexCheck hooks close the last gaps the built-in lexer has against
  # the JSON5 spec:
  #   fixed.check  reads a string literal that holds a line continuation
  #                (a backslash and a LineTerminatorSequence), which the
  #                escape map cannot express, where it stands, so every
  #                row, column and offset after it is the source's own.
  #   text.check   rejects unquoted text that cannot start a valid
  #                JSON5 IdentifierName AND is not a registered value
  #                keyword or regex-matched number.
  #   string.check rejects the escape sequences ECMAScript 5.1 forbids
  #                inside a string literal but the permissive lexer
  #                would otherwise accept (`\1`..`\9`, `\0` followed by
  #                a digit, and the ES2015-only `\u{...}` form).
  options: fixed: { check: '@fixed-check' }
  options: text:  { check: '@text-check' }

  # JSON5 numeric literals: allow hex, disallow octal / binary / digit
  # separators. Reject JS-style leading-zero integers (`010`, `-098`).
  options: number: {
    lex: true
    hex: true
    oct: false
    bin: false
    sep: ''
    exclude: '@/^[+-]?0[0-9]/'
  }

  # JSON5 comments are `//` and `/* */`. Hash comments are disabled here
  # and only enabled by the plugin when the `hashComment` option is set.
  options: comment: {
    def: {
      slash: { line: true start: '//' lex: true eatline: false }
      multi: { line: false start: '/*' end: '*/' lex: true eatline: false }
      hash:  { line: true start: '#' lex: false eatline: false }
    }
  }

  # JSON5 strings: single or double quote, with ES5.1 escapes. A line
  # continuation (backslash + LineTerminatorSequence, which produces the
  # empty string) has no entry here: an entry is keyed by one character,
  # which cannot spell CRLF, and the TypeScript and Go lexers take an
  # empty replacement as no entry at all. A string holding one is read by
  # fixed.check instead.
  options: string: {
    lex: true
    check: '@string-check'
    chars: JSON5_QUOTE_CHARS
    multiChars: JSON5_MULTI_QUOTE_CHARS
    escapeChar: '\\'
    escape: {
      b:  '\b'
      f:  '\f'
      n:  '\n'
      r:  '\r'
      t:  '\t'
      v:  '\v'
      '0': '\u0000'
      '"': '"'
      "'": "'"
      '`': '`'
      '\\': '\\'
      '/': '/'
    }
    allowUnknown: true
  }

  # Value keywords. The Infinity / NaN family is layered on by the
  # plugin (because the numeric literals cannot be round-tripped through
  # this grammar parser as actual JS numbers). The regex-matched
  # defs pick up number shapes the built-in number lexer does not
  # recognise — trailing-decimal-with-exponent (`5.e4`) and uppercase
  # `0X` hex — so both TS and Go exhibit the same behaviour on those.
  options: value: {
    lex: true
    def: {
      true:  { val: true }
      false: { val: false }
      null:  { val: null }

      trailingDecExp: {
        match:   '@/^[+-]?(?:0|[1-9][0-9]*)\\.[eE][+-]?[0-9]+/'
        val:     '@parse-trailing-dec-exp'
        consume: true
      }

      uppercaseHex: {
        match:   '@/^[+-]?0X[0-9a-fA-F]+/'
        val:     '@parse-uppercase-hex'
        consume: true
      }
    }
  }

  # JSON5 objects extend on duplicate keys (last wins); no bare-colon
  # child syntax. Lists are strict — no named properties, pairs, or
  # bare-colon children.
  options: map:  { extend: true  child: false }
  options: list: { property: false pair: false child: false }

  # Reject an entirely empty source. A comments-only source is handled
  # in code by dropping the `#ZZ jsonic` alternate from the val rule.
  options: lex: { empty: false emptyResult: null }

  options: error: {
    json5_empty:    'JSON5 input must contain a value'
    json5_no_value: 'JSON5 input must contain a value'
  }
  options: hint: {
    json5_empty: 'JSON5 requires a top-level value. An empty source is not a valid JSON5 document.'
    json5_no_value: 'JSON5 requires a top-level value. A source that consists only of whitespace and comments is not valid.'
  }
}
"#;
// --- END EMBEDDED json5-grammar.jsonic ---

// ---------------------------------------------------------------------------
// Identifier names.
// ---------------------------------------------------------------------------

/// ECMAScript 5.1 `IdentifierStart` CHARACTER: `$`, `_`, or a Unicode
/// letter (`L`) or letter number (`Nl`). The `\` that introduces a
/// `UnicodeEscapeSequence` is not included; see [`is_identifier_start`].
fn id_start(ch: char) -> bool {
    static RE: OnceLock<Regex> = OnceLock::new();
    ch == '$'
        || ch == '_'
        || RE
            .get_or_init(|| Regex::new(r"^[\p{L}\p{Nl}]$").expect("a literal pattern"))
            .is_match(ch.encode_utf8(&mut [0; 4]))
}

/// ECMAScript 5.1 `IdentifierPart`: an `IdentifierStart`, a combining
/// mark (`Mn`, `Mc`), a digit (`Nd`), a connector punctuation (`Pc`),
/// ZWNJ or ZWJ.
fn id_part(ch: char) -> bool {
    static RE: OnceLock<Regex> = OnceLock::new();
    id_start(ch)
        || ch == '\u{200C}'
        || ch == '\u{200D}'
        || RE
            .get_or_init(|| Regex::new(r"^[\p{Mn}\p{Mc}\p{Nd}\p{Pc}]$").expect("a literal pattern"))
            .is_match(ch.encode_utf8(&mut [0; 4]))
}

/// Whether `ch` may begin a JSON5 `IdentifierName` in the SOURCE text: an
/// `IdentifierStart` character, or the `\` of a `UnicodeEscapeSequence`.
fn is_identifier_start(ch: char) -> bool {
    ch == '\\' || id_start(ch)
}

/// Validate AND decode a JSON5 `IdentifierName` (used for unquoted keys).
/// `None` when the source is not a legal ECMAScript 5.1 `IdentifierName`.
///
/// An `IdentifierStart` / `IdentifierPart` may be written as a
/// `UnicodeEscapeSequence` (`\uXXXX`), and the identifier's VALUE is the
/// decoded text: `{ sigΣma: 1 }` has the key `sigΣma`. Each escape
/// contributes exactly one UTF-16 code unit, which must itself be a legal
/// identifier character: per ES5.1 7.6 an escape cannot smuggle an
/// otherwise-illegal character into an identifier, so ` `, `-`, a leading
/// `0` and escaped surrogate halves are all rejected. Mirrors the
/// TypeScript and Go `decodeIdentifierName`.
fn decode_identifier_name(source: &str) -> Option<String> {
    if source.is_empty() {
        return None;
    }
    let bytes = source.as_bytes();
    let mut out = String::with_capacity(source.len());
    let mut first = true;
    let mut i = 0;
    while i < bytes.len() {
        let ch = if bytes[i] == b'\\' {
            if i + 6 > bytes.len()
                || bytes[i + 1] != b'u'
                || !bytes[i + 2..i + 6].iter().all(u8::is_ascii_hexdigit)
            {
                return None;
            }
            let unit = u32::from_str_radix(&source[i + 2..i + 6], 16).ok()?;
            // A lone UTF-16 surrogate half is not an identifier character.
            if (0xD800..=0xDFFF).contains(&unit) {
                return None;
            }
            i += 6;
            char::from_u32(unit)?
        } else {
            let ch = source[i..].chars().next()?;
            i += ch.len_utf8();
            ch
        };
        if first {
            if !id_start(ch) {
                return None;
            }
            first = false;
        } else if !id_part(ch) {
            return None;
        }
        out.push(ch);
    }
    Some(out)
}

// ---------------------------------------------------------------------------
// String line continuations.
// ---------------------------------------------------------------------------

/// What a string literal holds, as [`scan_string_escapes`] reports it. A
/// string with neither is the engine's.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct StringEscapes {
    /// An escape ES5.1 refuses (`\1`..`\9`, `\0` before a digit, `\u{`), so
    /// the string is refused at its quote.
    forbidden: bool,
    /// A `LineContinuation`, so the fixed check reads the string.
    continued: bool,
}

/// What the string literal opening at the start of `remaining` holds,
/// walked the way the string check has always walked it: an escape takes
/// the character after it along, and the walk ends at the closing quote
/// or the end of the text. Mirrors `scanString` in `ts/src/json5.ts`.
/// With it, the byte just past the closing quote, or `None` where the
/// text ends first: the string is unterminated, or runs on past what the
/// lexer holds ([`scan_string_at`]).
fn scan_string_escapes(remaining: &str, quote: char) -> (StringEscapes, Option<usize>) {
    let bytes = remaining.as_bytes();
    let mut found = StringEscapes::default();
    let mut i = quote.len_utf8();
    while i < bytes.len() {
        let c = remaining[i..].chars().next().expect("inside the source");
        let size = c.len_utf8();
        if c == quote {
            return (found, Some(i + size));
        }
        if c != '\\' {
            i += size;
            continue;
        }
        if i + size >= bytes.len() {
            break;
        }
        let next = bytes[i + size];
        let after = bytes.get(i + size + 1).copied().unwrap_or(0);
        // Skip the escape lead and the character it escapes.
        let escaped = remaining[i + size..].chars().next().expect("checked above");
        if next.is_ascii_digit() && (next != b'0' || after.is_ascii_digit())
            || (next == b'u' && after == b'{')
        {
            found.forbidden = true;
        } else if is_line_terminator(escaped) {
            found.continued = true;
        }
        i += size + escaped.len_utf8();
    }
    (found, None)
}

/// Read the source on through the lexer's window until it holds more than
/// `held` characters past the cursor, twice as many where it can, so that a
/// long token costs its length to read and not its square. Answers whether
/// the window grew: it does not once the source has ended. In a whole text
/// the window is all of it, and nothing grows.
fn read_on(lexer: &mut Lexer<'_>, held: usize) -> bool {
    let before = lexer.window().len();
    lexer.fill(held.saturating_mul(2).max(held + 1));
    lexer.window().len() > before
}

/// Scan the string literal opening at the cursor through the lexer's
/// window: where the window ends before the closing quote, it is read on
/// and the string scanned again, so the scan sees what the whole source
/// holds (`lex.window`, admin ADR-30). Answers what the string holds, and
/// how many characters from the cursor it runs, through its closing quote
/// or to the end of the source.
fn scan_string_at(lexer: &mut Lexer<'_>, quote: char) -> (StringEscapes, usize) {
    loop {
        let window = lexer.window();
        let (found, closed) = scan_string_escapes(window, quote);
        if let Some(end) = closed {
            return (found, window[..end].chars().count());
        }
        let held = window.chars().count();
        if !read_on(lexer, held) {
            return (found, held);
        }
    }
}

/// The characters a number is written in: an ASCII letter (a base marker,
/// a hex digit, an exponent, or a keyword such as `Infinity`) or digit, a
/// sign, or a point. A match of a value regex the grammar declares is a run
/// of these.
fn is_number_char(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.')
}

/// Read the window on as far as the text check reads at the cursor: the
/// run of a number's characters there and the character after it, or to
/// the end of the source, so that a keyword or a value regex judged on the
/// window answers what it answers of the whole source. Every keyword the
/// check can meet (one that does not begin an `IdentifierName`, such as
/// `-Infinity`) and every match of a value regex the grammar declares is a
/// run of a number's characters
/// (`the_value_definitions_read_a_numbers_characters` in
/// `tests/reader_test.rs`).
fn hold_text(lexer: &mut Lexer<'_>) {
    loop {
        let window = lexer.window();
        let run = window
            .bytes()
            .take_while(|byte| is_number_char(*byte))
            .count();
        if run < window.len() || !read_on(lexer, run) {
            return;
        }
    }
}

/// The string options the continuation reader reads, taken from the
/// grammar document at install. A lexer check has no access to the live
/// options, so the reader carries its own copy, as the text check carries
/// its keyword list.
#[derive(Debug, Clone)]
struct StringSyntax {
    quotes: String,
    multi_line: String,
    escape: Vec<(char, String)>,
    allow_unknown: bool,
    escape_strict: bool,
    allow_control: bool,
}

impl StringSyntax {
    fn from_document(document: &JsonValue) -> Self {
        let string = &document["options"]["string"];
        let text = |key: &str| string[key].as_str().unwrap_or_default().to_string();
        let flag = |key: &str| string[key].as_bool().unwrap_or(false);
        let escape = string["escape"]
            .as_object()
            .map(|map| {
                map.iter()
                    .filter_map(|(key, replacement)| {
                        let mut chars = key.chars();
                        match (chars.next(), chars.next(), replacement.as_str()) {
                            (Some(ch), None, Some(text)) => Some((ch, text.to_string())),
                            _ => None,
                        }
                    })
                    .collect()
            })
            .unwrap_or_default();
        StringSyntax {
            quotes: text("chars"),
            multi_line: text("multiChars"),
            escape,
            allow_unknown: flag("allowUnknown"),
            escape_strict: flag("escapeStrict"),
            allow_control: flag("allowControl"),
        }
    }

    fn escape(&self, ch: char) -> Option<&str> {
        self.escape
            .iter()
            .find(|(key, _)| *key == ch)
            .map(|(_, replacement)| replacement.as_str())
    }
}

/// What [`decode_continued_string`] read, counted from the opening quote.
enum ContinuedString {
    /// The string's value, and how far it runs: in characters and in
    /// bytes, through the closing quote.
    Read {
        value: String,
        chars: usize,
        bytes: usize,
    },
    /// An error `at` characters in, its source `len` characters long.
    Bad {
        why: &'static str,
        at: usize,
        len: usize,
    },
    /// No closing quote before the end of the source.
    Unterminated,
}

/// Read the string literal at the cursor when it holds a JSON5
/// `LineContinuation`: a backslash and the `LineTerminatorSequence` after
/// it (CRLF counting as one), which adds nothing to the value.
///
/// An escape-map entry, which this engine honours even when its
/// replacement is empty, can spell a backslash before LF, CR, LS or PS,
/// but not one before CRLF, which is two characters: an entry for CR
/// takes the CR and leaves a bare LF, which is `unprintable`. Rewriting
/// the source before lexing, as this crate's `parse_with` used to, made
/// the value right and every later position wrong: it removed each
/// continuation whole, so every token and every error after one was
/// reported a row early (tabnas/json5#80), and it completed a partial
/// escape across the line break, reading `\x4`, a continuation and `b` as
/// `\x4b`.
///
/// The TypeScript and Go engines read no continuation at all, so their
/// plugins read such a string themselves, and this reads every one too,
/// not only one with a CRLF, so that the three agree on all of them:
/// entries for the other four forms would read them, but the engine ends
/// a pending surrogate pair at every escape-map hit, where the source
/// holds the pair across the continuation.
///
/// So this reads the string where it stands, the way the engine's string
/// matcher reads every other one: the same escape map, the same `\x` and
/// `\u` forms, the same surrogate pairing, the same errors on the same
/// characters. It moves the cursor with the engine's own advance, so every
/// row, column and offset after the string is the one the engine counts
/// for the source as it is. The grammar declares no `string.replace`, so
/// there is no replace step. It reads the string through the lexer's
/// window ([`scan_string_at`]), so a string the window ends inside reads as
/// the whole source has it. Mirrors `readContinuedString` in
/// `ts/src/json5.ts`.
fn read_continued_string(lexer: &mut Lexer<'_>, syntax: &StringSyntax) -> LexCheckResult {
    let Some(quote) = lexer
        .window()
        .chars()
        .next()
        .filter(|quote| syntax.quotes.contains(*quote))
    else {
        return LexCheckResult::Continue;
    };
    let (found, through) = scan_string_at(lexer, quote);
    if !found.continued {
        return LexCheckResult::Continue;
    }
    // Such a string never reaches the string check, so one that also holds
    // a forbidden escape is refused here instead, the same way and at the
    // same place: `unexpected`, on the quote.
    if found.forbidden {
        return LexCheckResult::native_token(lexer.bad("unexpected"));
    }
    // The scan held the string through its closing quote. An escape the
    // quote cuts short reads its hex digits, and an error its span, a few
    // characters past the quote: hold those too.
    lexer.fill(through + MAX_ESCAPE_CHARS);
    let start = lexer.point();
    let remaining = lexer.window();
    match decode_continued_string(remaining, quote, syntax) {
        ContinuedString::Read {
            value,
            chars,
            bytes,
        } => {
            let source = remaining[..bytes].to_string();
            lexer.advance_chars(chars);
            LexCheckResult::native_token(lexer.token(
                "#ST",
                TIN_ST,
                Value::String(value),
                source,
                start,
            ))
        }
        // Sited where it stands: on the offending character, or on the
        // backslash of a malformed escape.
        ContinuedString::Bad { why, at, len } => {
            lexer.advance_chars(at);
            let site = start.site.pos + at;
            LexCheckResult::native_token(lexer.bad_span(why, site, site + len))
        }
        // Sited on the opening quote, as the engine sites it.
        ContinuedString::Unterminated => {
            let len = remaining.chars().count();
            let site = start.site.pos;
            LexCheckResult::native_token(lexer.bad_span("unterminated_string", site, site + len))
        }
    }
}

/// The longest escape the decoder reads, `\uXXXX`: an escape at the end of
/// a string reads no further past its closing quote.
const MAX_ESCAPE_CHARS: usize = 6;

/// Decode the string literal opening at the start of `remaining`, without
/// moving the lexer: see [`read_continued_string`].
fn decode_continued_string(remaining: &str, quote: char, syntax: &StringSyntax) -> ContinuedString {
    let multi_line = syntax.multi_line.contains(quote);
    let next = |at: usize| remaining[at..].chars().next();
    // Up to `len` characters from byte `from`, clipped at the end of the
    // source, as the engine cuts the span of a malformed escape.
    let span = |from: usize, len: usize| remaining[from..].chars().take(len).count();

    let mut value = String::new();
    let mut pending = None;
    let mut i = quote.len_utf8();
    let mut at = 1;

    while let Some(c) = next(i) {
        if c == quote {
            flush_surrogate(&mut pending, &mut value);
            return ContinuedString::Read {
                value,
                chars: at + 1,
                bytes: i + c.len_utf8(),
            };
        }

        if c == '\\' {
            let Some(n) = next(i + 1) else {
                break;
            };
            let body = i + 1 + n.len_utf8();

            // The continuation: nothing in the value. It holds a surrogate
            // pair open, because it is no code unit.
            if is_line_terminator(n) {
                if n == '\r' && remaining[body..].starts_with('\n') {
                    i = body + 1;
                    at += 3;
                } else {
                    i = body;
                    at += 2;
                }
                continue;
            }

            if n != 'u' {
                flush_surrogate(&mut pending, &mut value);
            }

            if let Some(replacement) = syntax.escape(n) {
                value.push_str(replacement);
                i = body;
                at += 2;
                continue;
            }

            if n == 'u' {
                let Some(unit) = hex_digits(&remaining[body..], 4) else {
                    return ContinuedString::Bad {
                        why: "invalid_unicode",
                        at,
                        len: span(i, 6),
                    };
                };
                emit_code_unit(unit, &mut pending, &mut value);
                i = body + 4;
                at += 6;
                continue;
            }

            if n == 'x' && !syntax.escape_strict {
                let Some(byte) = hex_digits(&remaining[body..], 2) else {
                    return ContinuedString::Bad {
                        why: "invalid_ascii",
                        at,
                        len: span(i, 4),
                    };
                };
                value.push(char::from_u32(byte).expect("two hex digits are a scalar"));
                i = body + 2;
                at += 4;
                continue;
            }

            if !syntax.allow_unknown {
                return ContinuedString::Bad {
                    why: "unexpected",
                    at: at + 1,
                    len: 1,
                };
            }
            value.push(n);
            i = body;
            at += 2;
            continue;
        }

        // CR and LF are this engine's `line.chars` (see JSON5_LINE_CHARS):
        // string body only in a multi-line string. LS and PS are body in
        // any string, and the engine's advance counts their rows.
        let unprintable = if c == '\r' || c == '\n' {
            !multi_line
        } else {
            (c as u32) < 32 && !syntax.allow_control
        };
        if unprintable {
            return ContinuedString::Bad {
                why: "unprintable",
                at,
                len: 1,
            };
        }

        flush_surrogate(&mut pending, &mut value);
        value.push(c);
        i += c.len_utf8();
        at += 1;
    }

    ContinuedString::Unterminated
}

/// Exactly `count` hex digits at the start of `text`, or `None` when fewer
/// are there: a short or junk-terminated run is not an escape.
fn hex_digits(text: &str, count: usize) -> Option<u32> {
    let digits = text.get(..count)?;
    if !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return None;
    }
    u32::from_str_radix(digits, 16).ok()
}

/// Append one decoded UTF-16 code unit, pairing surrogates as the engine's
/// string matcher does: a high surrogate is held until the next code unit
/// decides it, and one that nothing pairs with is U+FFFD.
fn emit_code_unit(unit: u32, pending: &mut Option<u32>, out: &mut String) {
    if (0xD800..=0xDBFF).contains(&unit) {
        flush_surrogate(pending, out);
        *pending = Some(unit);
    } else if (0xDC00..=0xDFFF).contains(&unit) {
        match pending.take() {
            Some(high) => out.push(
                char::from_u32(0x10000 + ((high - 0xD800) << 10) + (unit - 0xDC00))
                    .expect("paired surrogates form a Unicode scalar"),
            ),
            None => out.push('\u{FFFD}'),
        }
    } else {
        flush_surrogate(pending, out);
        out.push(
            char::from_u32(unit).expect("four hex digits outside the surrogates are a scalar"),
        );
    }
}

/// Resolve a held high surrogate that nothing paired with.
fn flush_surrogate(pending: &mut Option<u32>, out: &mut String) {
    if pending.take().is_some() {
        out.push('\u{FFFD}');
    }
}

// ---------------------------------------------------------------------------
// The requireValue rule.
// ---------------------------------------------------------------------------

/// Does `src` contain anything that could begin a value, as opposed to
/// only whitespace and comments? JSON5 requires a top-level value, and a
/// comments-only document is exactly what `json5_no_value` names.
///
/// This deliberately does NOT lex or parse. It only has to find the FIRST
/// character that is neither whitespace nor part of a comment, and stop
/// there, which is what makes it safe. The trap in a naive "strip the
/// comments and see what is left" is a source like `"/* x */"`: a valid
/// JSON5 STRING whose contents look like a comment, which stripping would
/// wrongly report as empty. Here the leading quote is simply a non-trivia
/// character, so the scan stops on it and answers true without ever
/// looking inside.
///
/// An unterminated block comment answers TRUE on purpose. `/* x` contains
/// no value, but the engine's own `unterminated_comment` is the more
/// useful diagnostic and this declines to shadow it.
///
/// `hash_comment` says whether THIS configuration also has the `#` form.
/// It is a parameter rather than a read of the options because the two
/// callers want different answers: the `require_value` guard passes
/// `false`, so a hash-comment-only source keeps falling through to the
/// rules and the engine's own `unexpected`, and the `require_value`-off
/// short-circuit passes the option, so the same source counts as trivia
/// and resolves to the declared empty result.
///
/// It is the walk [`check_reader`] makes of a reader ([`ValueScan`]), over
/// the whole text. Mirrors `hasValue` in `ts/src/json5.ts`.
fn has_value(src: &str, hash_comment: bool) -> bool {
    ValueScan::default().scan(src.as_bytes(), true, hash_comment) != Verdict::NoValue
}

/// What the walk of a source's leading whitespace and comments answers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Verdict {
    /// What has been read does not answer: read on.
    More,
    /// A character that is neither whitespace nor part of a comment.
    Value,
    /// Only whitespace and comments, to the end of the source.
    NoValue,
}

/// Where the walk of [`ValueScan`] stands.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum Within {
    /// Outside a comment.
    #[default]
    Space,
    /// Inside a line comment.
    Line,
    /// Inside a block comment.
    Block,
}

/// The walk of a source's leading whitespace and comments, which says
/// whether anything else follows: the question [`has_value`] answers of a
/// text and [`check_reader`] of a reader. It walks the bytes it is given
/// and, when they do not answer, goes on from where it stopped once given
/// more, so a source is read only as far as its leading trivia runs.
#[derive(Debug, Clone, Copy, Default)]
struct ValueScan {
    /// The byte the walk has reached.
    at: usize,
    within: Within,
}

/// The character `bytes` starts with and its length, or `None` where the
/// bytes hold only the start of one and more may follow. A byte that is not
/// UTF-8 reads as U+FFFD, one byte long.
fn first_char(bytes: &[u8], end: bool) -> Option<(char, usize)> {
    let head = &bytes[..bytes.len().min(4)];
    let valid = match std::str::from_utf8(head) {
        Ok(text) => text,
        Err(error) if error.valid_up_to() > 0 => {
            std::str::from_utf8(&head[..error.valid_up_to()]).expect("the prefix is UTF-8")
        }
        Err(error) if error.error_len().is_none() && !end => return None,
        Err(_) => return Some(('\u{FFFD}', 1)),
    };
    let c = valid.chars().next().expect("a character");
    Some((c, c.len_utf8()))
}

impl ValueScan {
    /// Walk `src`, the source's bytes read so far, from where the walk
    /// stopped; `end` says whether they are all of it.
    fn scan(&mut self, src: &[u8], end: bool, hash_comment: bool) -> Verdict {
        let n = src.len();
        let more = if end { Verdict::NoValue } else { Verdict::More };
        loop {
            match self.within {
                Within::Line => {
                    // A line comment runs to the next line terminator, or
                    // the end.
                    while self.at < n {
                        let Some((c, size)) = first_char(&src[self.at..], end) else {
                            return Verdict::More;
                        };
                        if is_line_terminator(c) {
                            break;
                        }
                        self.at += size;
                    }
                    if self.at >= n {
                        return more;
                    }
                    self.within = Within::Space;
                }
                Within::Block => {
                    // A block comment runs to the first `*/` after its
                    // opening.
                    match src[self.at..].windows(2).position(|pair| pair == b"*/") {
                        Some(k) => {
                            self.at += k + 2;
                            self.within = Within::Space;
                        }
                        None if end => return Verdict::Value, // unterminated: leave it to unterminated_comment
                        None => {
                            // A `*` the bytes end on may begin the `*/`.
                            self.at = self.at.max(n.saturating_sub(1));
                            return Verdict::More;
                        }
                    }
                }
                Within::Space => {
                    if self.at >= n {
                        return more;
                    }
                    let Some((c, size)) = first_char(&src[self.at..], end) else {
                        return Verdict::More;
                    };
                    if is_json5_space(c) {
                        self.at += size;
                        continue;
                    }
                    if hash_comment && c == '#' {
                        self.at += 1;
                        self.within = Within::Line;
                        continue;
                    }
                    if c == '/' {
                        match src.get(self.at + 1) {
                            None if !end => return Verdict::More,
                            Some(b'/') => {
                                self.at += 2;
                                self.within = Within::Line;
                                continue;
                            }
                            Some(b'*') => {
                                self.at += 2;
                                self.within = Within::Block;
                                continue;
                            }
                            _ => {}
                        }
                    }
                    // Anything else begins something. Whether it is a VALID
                    // value is the parser's question, not this one.
                    return Verdict::Value;
                }
            }
        }
    }
}

/// The ECMAScript `\s` class, which is the JSON5 whitespace and line
/// terminator set: `White_Space` minus NEL, plus the BOM. Named here
/// rather than borrowed from `char::is_whitespace`, which includes U+0085
/// and excludes U+FEFF, so the intent survives the difference.
fn is_json5_space(c: char) -> bool {
    c == '\u{FEFF}' || (c.is_whitespace() && c != '\u{0085}')
}

// ---------------------------------------------------------------------------
// Grammar alternate helpers.
// ---------------------------------------------------------------------------

fn tag_contains(tags: &str, want: &str) -> bool {
    tags.split(',').any(|tag| tag.trim() == want)
}

/// Remove `tin` from every slot of every alternate tagged `required_tag`.
fn filter_tin_from_alts(alts: &mut [AltSpec], tin: Tin, required_tag: &str) {
    for alt in alts.iter_mut() {
        if !tag_contains(&alt.g, required_tag) {
            continue;
        }
        for slot in alt.s.iter_mut() {
            slot.retain(|t| *t != tin);
        }
    }
}

/// jsonic's `#ZZ` end-of-source alternate: the one that lets a source
/// holding no value succeed.
fn is_zz_jsonic_alt(alt: &AltSpec) -> bool {
    tag_contains(&alt.g, "jsonic")
        && alt.s.len() == 1
        && alt.s[0].len() == 1
        && alt.s[0][0] == TIN_ZZ
}

/// The pattern inside a serialized `@/pattern/flags` regular expression
/// (the flags are not used by this grammar), or `None` for any other
/// string.
fn bare_regex_source(source: &str) -> Option<&str> {
    let body = source.strip_prefix("@/")?;
    let slash = body.rfind('/')?;
    Some(&body[..slash])
}

/// A serialized regular expression, compiled for the `regex` crate.
fn compile_serialized_regex(source: &str) -> Option<Regex> {
    Regex::new(bare_regex_source(source)?).ok()
}

// ---------------------------------------------------------------------------
// Base-prefixed integer literals.
//
// `0x`, `0o` and `0b` literals are read as an EXACT integer and rounded
// to a double ONCE. The obvious fold -- `value = value * base + digit`
// in `f64` -- rounds at every digit, and past the 53-bit exact integer
// range those roundings accumulate: `0Xa6f2f78f4f9bf44` came out as
// `43a4de5ef1e9f37e` where canonical TypeScript's `parseInt` answers
// `43a4de5ef1e9f37f`, one unit in the last place low. That is silently
// altered data, not a formatting difference.
//
// `parseInt` on a base-prefixed digit string is correctly rounded from
// the exact integer, half to even, so that is what these reproduce. The
// zon port solves the same problem over general bases in
// `zon/rs/src/number.rs`; the bases here are all powers of two, so a
// `u128` head plus a sticky bit replaces its limb arithmetic.
// ---------------------------------------------------------------------------

/// `2^k` for a non-negative `k`, exactly, saturating to infinity above
/// the double range. A repeated multiply would round on the way up.
/// Mirrors `pow2` in the zon port.
fn pow2(k: i64) -> f64 {
    debug_assert!(k >= 0, "only non-negative exponents arise here");
    if k > 1023 {
        f64::INFINITY
    } else {
        f64::from_bits(((k + 1023) as u64) << 52)
    }
}

/// The exact integer the digit values denote, as the NEAREST double,
/// rounding half to even. `bits` is the width of one digit, so the base
/// is a power of two: 1 for binary, 3 for octal, 4 for hexadecimal.
fn digits_to_f64(digits: &[u32], bits: u32) -> f64 {
    // Leading zeros carry no value, and dropping them is what makes the
    // head below wider than the 54 significant bits the rounding needs.
    let start = digits.iter().position(|digit| *digit != 0);
    let Some(start) = start else {
        return 0.0;
    };
    let digits = &digits[start..];

    // A u128 holds exactly this many digits of the base.
    let head_len = (128 / bits) as usize;
    let pack = |run: &[u32]| {
        run.iter()
            .fold(0u128, |value, digit| (value << bits) | u128::from(*digit))
    };
    if digits.len() <= head_len {
        // A `u128` to `f64` cast rounds to nearest, ties to even, which
        // is the rule `parseInt` follows.
        return pack(digits) as f64;
    }

    // Longer than a u128: keep the top `head_len` digits, and remember
    // whether anything below them was set. Those two are all the
    // rounding can depend on. The leading digit is non-zero, so the head
    // is at least 121 bits wide in every base here and `shift` is
    // comfortably positive.
    let head = pack(&digits[..head_len]);
    let tail = &digits[head_len..];
    let dropped = i64::from(bits) * tail.len() as i64;
    let shift = 128 - head.leading_zeros() - 53;

    let mut mantissa = (head >> shift) as u64;
    let half = (head >> (shift - 1)) & 1 == 1;
    let sticky = head & ((1u128 << (shift - 1)) - 1) != 0 || tail.iter().any(|digit| *digit != 0);
    if half && (sticky || mantissa & 1 == 1) {
        // At most 2^53, which is still an exact double.
        mantissa += 1;
    }
    mantissa as f64 * pow2(dropped + i64::from(shift))
}

/// The value of a base-prefixed integer literal -- `0x1F`, `-0o17`,
/// `+0b1010`, with an optional `separator` between digits -- or `None`
/// when `src` is not one.
///
/// This is deliberately tolerant about which prefixes it reads: whether
/// a literal is ACCEPTED is settled by the lexer and by the `hex` /
/// `octal` / `binary` options long before this runs, and re-deciding it
/// here would be a second copy of that rule.
fn radix_literal_value(src: &str, separator: Option<char>) -> Option<f64> {
    let (negative, rest) = match src.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, src.strip_prefix('+').unwrap_or(src)),
    };
    let rest = rest.strip_prefix('0')?;
    let mut characters = rest.chars();
    let bits = match characters.next()? {
        'x' | 'X' => 4,
        'o' | 'O' => 3,
        'b' | 'B' => 1,
        _ => return None,
    };
    let base = 1u32 << bits;

    let mut digits = Vec::new();
    for character in characters {
        if Some(character) == separator {
            continue;
        }
        digits.push(character.to_digit(base)?);
    }
    if digits.is_empty() {
        return None;
    }

    let magnitude = digits_to_f64(&digits, bits);
    Some(if negative { -magnitude } else { magnitude })
}

// ---------------------------------------------------------------------------
// The plugin.
// ---------------------------------------------------------------------------

/// The names the grammar document binds.
const FIXED_CHECK: &str = "@fixed-check";
const TEXT_CHECK: &str = "@text-check";
const STRING_CHECK: &str = "@string-check";
const PARSE_TRAILING_DEC_EXP: &str = "@parse-trailing-dec-exp";
const PARSE_UPPERCASE_HEX: &str = "@parse-uppercase-hex";
/// The `pair` after-open validator this plugin adds in code.
const PAIR_KEY_CHECK: &str = "@json5-pair-key";

/// The `pair` after-open action: reject a `#TX` key whose source is not a
/// JSON5 `IdentifierName`, and rewrite one written with `\uXXXX` escapes
/// to its decoded text. jsonic's `@pairkey` alternate action has already
/// copied the raw token value into `u.key`, so both are updated.
fn pair_key_check(
    rule: &mut Rule,
    _context: &mut Context,
    _next: Option<&RuleSnapshot>,
    out: Option<Token>,
) -> Result<Option<Token>, ActionError> {
    let Some(token) = rule.o0().filter(|token| token.tin == TIN_TX) else {
        return Ok(out);
    };
    let Some(name) = decode_identifier_name(token.src.as_str()) else {
        let mut bad = token.clone();
        bad.bad("unexpected");
        return Ok(Some(bad));
    };
    if token.val != Value::String(name.clone()) {
        Rc::make_mut(&mut rule.o)[0].val = Value::String(name.clone());
        rule.u_mut().insert("key".to_string(), Value::String(name));
    }
    Ok(out)
}

/// Parse the embedded grammar with a standard jsonic instance and patch
/// the placeholders and the option-dependent overrides, exactly as the
/// TypeScript and Go plugins do before `grammar()`.
fn grammar_document(options: &Json5Options) -> Result<JsonValue, PluginError> {
    let parsed = tabnas_jsonic::make().parse(GRAMMAR_TEXT).map_err(|error| {
        PluginError(format!(
            "json5: the embedded grammar does not parse: {error}"
        ))
    })?;
    let mut document = parsed.to_json();
    if !document.get("options").is_some_and(JsonValue::is_object) {
        return Err(PluginError(
            "json5: the embedded grammar has no `options` table".into(),
        ));
    }
    let opts = &mut document["options"];

    // Substitute the placeholder bare-identifier strings with the real
    // character sets. (The grammar parser cannot round-trip some of these
    // code points safely as string literals.)
    opts["space"]["chars"] = json!(JSON5_WHITESPACE);
    // LS and PS travel in `line.fixed` rather than `line.chars`: see the
    // note on `JSON5_LINE_CHARS`. Together the two are the JSON5
    // LineTerminator set, which TypeScript and Go write into
    // `line.chars` whole.
    opts["line"]["chars"] = json!(JSON5_LINE_CHARS);
    opts["line"]["fixed"] = json!(JSON5_LINE_FIXED);
    opts["line"]["rowChars"] = json!(JSON5_ROW_CHARS);
    if options.backtick_string {
        opts["string"]["chars"] = json!("'\"`");
        opts["string"]["multiChars"] = json!("`");
    } else {
        opts["string"]["chars"] = json!("'\"");
        opts["string"]["multiChars"] = json!("");
    }

    // Option-dependent overrides applied on top of the strict baseline.
    opts["number"]["hex"] = json!(options.hex);
    opts["number"]["oct"] = json!(options.octal);
    opts["number"]["bin"] = json!(options.binary);
    opts["number"]["sep"] = if options.number_separator {
        json!("_")
    } else {
        JsonValue::Null
    };
    opts["comment"]["def"]["hash"]["lex"] = json!(options.hash_comment);
    opts["lex"]["empty"] = json!(!options.require_value);

    // `options.number.exclude` is a bare pattern on this engine, where a
    // `value.def.match` is the serialized `@/pattern/` form; the loader
    // stores the string as it is, so the wrapper is taken off here.
    if let Some(exclude) = opts["number"]["exclude"].as_str() {
        if let Some(bare) = bare_regex_source(exclude) {
            opts["number"]["exclude"] = json!(bare);
        }
    }

    if !options.strict_value {
        if let Some(sets) = opts["tokenSet"].as_object_mut() {
            sets.shift_remove("VAL");
        }
    }
    Ok(document)
}

/// The `Infinity` / `NaN` family the plugin layers on in code: the
/// values cannot be round-tripped through the grammar parser as numbers.
const INFINITY_DEFINITIONS: [(&str, f64); 6] = [
    ("Infinity", f64::INFINITY),
    ("+Infinity", f64::INFINITY),
    ("-Infinity", f64::NEG_INFINITY),
    ("NaN", f64::NAN),
    ("+NaN", f64::NAN),
    ("-NaN", f64::NAN),
];

/// The value keywords and value regexes in force, so the text check can
/// let them through: the ones the document declares, plus the
/// `Infinity` family when the option is on.
fn value_definitions(document: &JsonValue, options: &Json5Options) -> (Vec<String>, Vec<Regex>) {
    let mut names = Vec::new();
    let mut regexes = Vec::new();
    if let Some(defs) = document["options"]["value"]["def"].as_object() {
        for (name, def) in defs {
            match def.get("match").and_then(JsonValue::as_str) {
                Some(source) => regexes.extend(compile_serialized_regex(source)),
                None => names.push(name.clone()),
            }
        }
    }
    if options.infinity {
        names.extend(
            INFINITY_DEFINITIONS
                .iter()
                .map(|(name, _)| name.to_string()),
        );
    }
    (names, regexes)
}

/// The keywords the document declares with `val: null`. The JSON loader
/// reads a null `val` as "no value" and the keyword would come back as
/// its own text, so these are put back as [`Value::Null`] after install.
fn null_keywords(document: &JsonValue) -> Vec<String> {
    document["options"]["value"]["def"]
        .as_object()
        .map(|defs| {
            defs.iter()
                .filter(|(_, def)| def.get("val").is_some_and(JsonValue::is_null))
                .map(|(name, _)| name.clone())
                .collect()
        })
        .unwrap_or_default()
}

/// Install JSON5 on `parser`, which must already carry the jsonic grammar
/// (from [`tabnas_jsonic::make`], or [`tabnas_jsonic::jsonic`] on a bare
/// engine). The counterpart of the TypeScript `Json5` plugin function and
/// the Go `Json5(j, opts)`.
///
/// Most callers want [`make`] / [`make_with`], or [`plugin`] with
/// [`Tabnas::use_plugin`], which record the options on the instance the
/// same way this does.
///
/// ```
/// let mut parser = tabnas_jsonic::make();
/// tabnas_json5::json5(&mut parser, &tabnas_json5::Json5Options::default())?;
/// let value = tabnas_json5::parse_with(&parser, "{ a: 0x1F, b: [+Infinity, NaN] }")?;
/// assert_eq!(value.to_json()["a"], 31.0);
/// assert_eq!(value.to_json()["b"], serde_json::json!([null, null]));
/// let tabnas::Value::Object(map) = &value else { panic!("not an object") };
/// let tabnas::Value::Array(numbers) = &map["b"] else { panic!("not an array") };
/// assert_eq!(numbers[0], tabnas::Value::Number(f64::INFINITY));
/// assert!(matches!(numbers[1], tabnas::Value::Number(n) if n.is_nan()));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn json5(parser: &mut Tabnas, options: &Json5Options) -> Result<(), PluginError> {
    let options = *options;

    let document = grammar_document(&options)?;
    let (value_names, value_regexes) = value_definitions(&document, &options);
    let null_keywords = null_keywords(&document);

    // The refs the document names, registered before it is installed.
    //
    // `@fixed-check` runs before every lexer step, ahead of every matcher.
    // A string that holds a line continuation is its own: at the string's
    // opening quote it reads it (`read_continued_string`) and returns the
    // finished token, or refuses it, as the string check would, when it
    // also holds a forbidden escape. Anywhere else it makes no token, and
    // every other string is the engine's.
    //
    // In a parse from a reader it also reads the window on, first, as far
    // as any check of this crate reads at this token: a string to its
    // closing quote (the scan), and where the text check may judge the
    // token, what it reads ([`hold_text`]). The engine cuts a token again
    // over a wider window when a matcher's read reached the window's end,
    // unless the source has ended; a check that read on in the middle of
    // the cut, to the end of the source, would keep the answer a matcher
    // before it gave over the shorter window. Read on first, every matcher
    // of the cut reads the same window.
    let syntax = StringSyntax::from_document(&document);
    parser.imperative_lex_check_ref(FIXED_CHECK, move |lexer: &mut Lexer<'_>| {
        match lexer.window().chars().next() {
            Some(first) if !syntax.quotes.contains(first) && !is_identifier_start(first) => {
                hold_text(lexer);
                LexCheckResult::Continue
            }
            _ => read_continued_string(lexer, &syntax),
        }
    });

    // Reject unquoted text that cannot start a valid JSON5 IdentifierName
    // AND is not a value keyword or a value regex match. Skipping the text
    // matcher leaves the character unclaimed, so the lexer raises
    // `unexpected` there, the same outcome as the TypeScript
    // `{ done: true, token: undefined }`.
    //
    // It reads through the lexer's window as far as its answer needs
    // ([`hold_text`]): the first character, and the run of a number's
    // characters at the cursor and the character after it, which holds any
    // keyword and any value regex match it can meet. The fixed check has
    // read that far already.
    parser.imperative_lex_check_ref(TEXT_CHECK, move |lexer: &mut Lexer<'_>| {
        let Some(first) = lexer.window().chars().next() else {
            return LexCheckResult::Continue;
        };
        if is_identifier_start(first) {
            return LexCheckResult::Continue;
        }
        hold_text(lexer);
        let remaining = lexer.window();
        if value_names
            .iter()
            .any(|name| remaining.starts_with(name.as_str()))
            || value_regexes.iter().any(|regex| regex.is_match(remaining))
        {
            LexCheckResult::Continue
        } else {
            LexCheckResult::Skip
        }
    });

    // Reject the escape sequences ECMAScript 5.1, and hence JSON5, forbids
    // inside a string literal but the engine's permissive escape handling
    // (allowUnknown, non-strict `\u{...}`) would otherwise accept:
    //   \1 .. \9    a DecimalDigit is an EscapeCharacter, so it is not a
    //               NonEscapeCharacter: legacy octal escapes are not JSON5.
    //   \0<digit>   `0` is an escape only when NOT followed by a DecimalDigit.
    //   \u{XXXX}    the ES2015 code-point form; JSON5 has only `\uXXXX`.
    let quotes = document["options"]["string"]["chars"]
        .as_str()
        .unwrap_or("'\"")
        .to_string();
    // The scan reads the string through the lexer's window, to its closing
    // quote or the end of the source ([`scan_string_at`]).
    parser.imperative_lex_check_ref(STRING_CHECK, move |lexer: &mut Lexer<'_>| {
        match lexer
            .window()
            .chars()
            .next()
            .filter(|quote| quotes.contains(*quote))
        {
            Some(quote) if scan_string_at(lexer, quote).0.forbidden => LexCheckResult::Skip,
            _ => LexCheckResult::Continue,
        }
    });

    // Trailing-decimal-with-exponent (`5.e4`) and uppercase `0X` hex: the
    // number shapes the built-in lexer misses, matched by regex value
    // definitions so every runtime agrees on them.
    parser.value_transform_ref(PARSE_TRAILING_DEC_EXP, |groups: &[String]| {
        let literal = groups.first().map(String::as_str).unwrap_or_default();
        let (mantissa, exponent) = literal.split_once(['e', 'E']).unwrap_or((literal, "0"));
        Value::Number(
            format!("{}e{exponent}", mantissa.trim_end_matches('.'))
                .parse()
                .unwrap_or(f64::NAN),
        )
    });
    parser.value_transform_ref(PARSE_UPPERCASE_HEX, |groups: &[String]| {
        // The regex admits no digit separator, so none is passed.
        let literal = groups.first().map(String::as_str).unwrap_or_default();
        Value::Number(radix_literal_value(literal, None).unwrap_or(f64::NAN))
    });

    parser.state_action_with_next_ref(PAIR_KEY_CHECK, pair_key_check);

    let spec = tabnas::GrammarSpec::from_value(document).map_err(|error| PluginError(error.0))?;
    parser
        .grammar(&spec)
        .map_err(|error| PluginError(error.0))?;

    // Infinity / NaN cannot be round-tripped through the grammar parser as
    // actual numbers, so layer them on here; and the `null` keyword's
    // value cannot travel as JSON null, so it is put back the same way.
    parser
        .set_options(|o| {
            for name in &null_keywords {
                if let Some(def) = o.value.definitions.get_mut(name) {
                    def.val = Some(Value::Null);
                }
            }
            if options.infinity {
                for (name, value) in INFINITY_DEFINITIONS {
                    o.value.definitions.insert(
                        name.to_string(),
                        ValueDef {
                            val: Some(Value::Number(value)),
                            matcher: None,
                            transform: None,
                            consume: false,
                        },
                    );
                }
            }
        })
        .map_err(|error| PluginError(error.0))?;

    // Grammar alternates resolve token sets when they are installed, so
    // the `tokenSet` the document declares does not reach jsonic's
    // pre-built `val` and `pair` alternates. Filter `#TX` from the
    // val-tagged alternates and `#NR` from the pair-tagged ones directly,
    // as the Go port does, to make the restriction effective at parse
    // time.
    for name in parser.rule_names() {
        parser.define_rule(name, |spec| {
            if options.strict_value {
                filter_tin_from_alts(&mut spec.open, TIN_TX, "val");
                filter_tin_from_alts(&mut spec.close, TIN_TX, "val");
            }
            filter_tin_from_alts(&mut spec.open, TIN_NR, "pair");
            filter_tin_from_alts(&mut spec.close, TIN_NR, "pair");
        });
    }

    // Rule-level trims the grammar file cannot express declaratively:
    //   - pair.open loses its leading-comma `jsonic` alt so `{,}` fails.
    //   - pair gains an after-open validator that rejects #TX keys whose
    //     source text is not a valid JSON5 IdentifierName.
    //   - val.open loses its `#ZZ jsonic` alt (when requireValue is set)
    //     so a source containing only whitespace / comments errors out.
    parser.define_rule("pair", |spec| {
        spec.open
            .retain(|alt| !(tag_contains(&alt.g, "comma") && tag_contains(&alt.g, "jsonic")));
        if !spec.ao.iter().any(|action| action == PAIR_KEY_CHECK) {
            spec.ao.push(PAIR_KEY_CHECK.to_string());
        }
    });
    if options.require_value {
        parser.define_rule("val", |spec| {
            spec.open.retain(|alt| !is_zz_jsonic_alt(alt));
        });
    }

    // Record the resolved options on the instance so `parse_with` and
    // `check_reader` can apply the requireValue rule. The TypeScript plugin
    // wraps the instance's own `parse` and `parseReader` for this; the
    // engine here runs a `parser.start` hook INSTEAD of the parse rather
    // than before it, and a method cannot be wrapped on an instance, so
    // the guard lives in the package-level entry points, as in Go.
    parser.decorate(OPTIONS_MARK, options);
    Ok(())
}

/// The plugin form of [`json5`], for [`Tabnas::use_plugin`]. Its defaults
/// are [`Json5Options::default`], and the bag it receives is read with
/// [`Json5Options::from_value`], so a caller passes only the keys to
/// change:
///
/// ```
/// let mut parser = tabnas_jsonic::make();
/// let overrides = tabnas_json5::Json5Options { hash_comment: true, ..Default::default() };
/// parser.use_plugin(tabnas_json5::plugin(), Some(overrides.to_value()))?;
/// assert_eq!(tabnas_json5::parse_with(&parser, "# c\n42")?.to_string(), "42");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn plugin() -> Plugin {
    Plugin::new(PLUGIN_NAME, |parser, options| {
        json5(parser, &Json5Options::from_value(options))
    })
    .with_defaults(Json5Options::default().to_value())
}

/// Build a JSON5 parser with caller options: `Make(opts)` in Go, which is
/// `jsonic.Make()` followed by `UseDefaults(Json5, Defaults(), opts)`, or
/// `make(opts)` in TypeScript, which is
/// `new Tabnas().use(jsonic).use(Json5, opts)`.
///
/// It declares `lex.window`, so that [`Tabnas::parse_reader`] (and
/// [`parse_reader_with`]) reads a reader a window at a time rather than
/// whole (admin ADR-30): the checks this crate installs read the source
/// only through the lexer's window, and jsonic's base is the engine's own
/// matchers. The window is declared here, on the parser this crate makes
/// whole, and not in [`json5`] or [`plugin`], which a host may install
/// beneath matchers of its own.
///
/// Infallible by design: the grammar is a fixed literal, so a failure
/// here is a bug in this crate rather than anything a caller did.
///
/// ```
/// let options = tabnas_json5::Json5Options { strict_value: false, ..Default::default() };
/// let parser = tabnas_json5::make_with(options);
/// assert_eq!(tabnas_json5::parse_with(&parser, "foo")?.to_string(), r#""foo""#);
/// # Ok::<(), tabnas_json5::Json5Error>(())
/// ```
pub fn make_with(options: Json5Options) -> Tabnas {
    let mut parser = tabnas_jsonic::make();
    parser
        .use_plugin(plugin(), Some(options.to_value()))
        .expect("the json5 grammar is fixed and valid");
    parser
        .set_options(|options| options.lex.window = true)
        .expect("lex.window sets");
    parser
}

/// Build a JSON5 parser with the default (strict JSON5) options.
///
/// ```
/// let parser = tabnas_json5::make();
/// let value = tabnas_json5::parse_with(&parser, "[1, 2, 3,]")?;
/// assert_eq!(value.to_string(), "[1,2,3]");
/// assert!(tabnas_json5::parse_with(&parser, "[1, 2").is_err());
/// # Ok::<(), tabnas_json5::Json5Error>(())
/// ```
pub fn make() -> Tabnas {
    make_with(Json5Options::default())
}

/// A `json5_empty` or `json5_no_value` error, worded from the message and
/// hint templates the grammar registers on the instance, so the wording
/// has one source.
fn value_error(parser: &Tabnas, code: &str, src: &str) -> Json5Error {
    let mut error = Json5Error::new(code, "", src, 0, 1, 1);
    let config = parser.config();
    error.detail = config
        .error
        .get(code)
        .cloned()
        .unwrap_or_else(|| "JSON5 input must contain a value".to_string());
    error.hint = config.hint.get(code).cloned().unwrap_or_default();
    error
}

/// Parse a JSON5 source with a parser that carries the plugin: the
/// counterpart of the Go `Parse(j, src)` and of the `parse` the
/// TypeScript plugin wraps.
///
/// This is the entry point the plugin's behaviour is specified against.
/// It applies the one thing the engine's own [`Tabnas::parse`] cannot do
/// from inside a plugin, the `requireValue` rule: with the option on (the
/// default) an empty source is `json5_empty` and a whitespace-only or
/// comments-only one is `json5_no_value`; with it off, every such source
/// is the grammar's declared empty result, `null`. Everything else,
/// string line continuations included, is the instance's own, so
/// [`Tabnas::parse`] reads it the same way and reports the same
/// positions.
///
/// A parser that does not carry the plugin is parsed as it is.
///
/// ```
/// let parser = tabnas_json5::make();
/// let error = tabnas_json5::parse_with(&parser, "// only a comment").unwrap_err();
/// assert_eq!(error.code, "json5_no_value");
/// # Ok::<(), tabnas_json5::Json5Error>(())
/// ```
pub fn parse_with(parser: &Tabnas, src: &str) -> Result<Value, Json5Error> {
    let Some(options) = parser.decoration::<Json5Options>(OPTIONS_MARK).copied() else {
        return parser.parse(src);
    };
    if options.require_value {
        if src.is_empty() {
            return Err(value_error(parser, "json5_empty", src));
        }
        // Slash forms ONLY, deliberately, and the `false` says so at the
        // call rather than in a comment on the scan. A hash-comment-only
        // source is not `json5_no_value` here: it reaches the rules and
        // fails on the comment with the engine's own `unexpected`, which
        // is what all three runtimes do and what the `# comment` row of
        // `test/spec/options.tsv` pins.
        if !has_value(src, false) {
            return Err(value_error(parser, "json5_no_value", src));
        }
    } else if !src.is_empty() && !has_value(src, options.hash_comment) {
        // Without requireValue, a source holding no value resolves to the
        // SAME declared empty result that `""` already resolves to.
        // Delegating to the engine's own empty-source path keeps the
        // grammar's `emptyResult` the one place that value is written.
        //
        // With `hash_comment` on, `#` is trivia exactly as `//` is, so a
        // hash-comment-only source takes this path too. The result is the
        // same `null` the rules already fell out with here, measured both
        // ways; what changes is that it now arrives by the SAME route as
        // in the canonical, which took the rules path and answered
        // `undefined` until 2026-09-21.
        return parser.parse("");
    }
    parser.parse(src)
}

/// The reader [`check_reader`] gives back: every byte the reader it read
/// from gives, the ones it read first, and a read that failed there,
/// where it failed.
pub struct Checked<R> {
    read: std::io::Cursor<Vec<u8>>,
    failure: Option<std::io::Error>,
    rest: Option<R>,
}

impl<R: std::io::Read> std::io::Read for Checked<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let n = self.read.read(buf)?;
        if n > 0 || buf.is_empty() {
            return Ok(n);
        }
        if let Some(failure) = self.failure.take() {
            return Err(failure);
        }
        match &mut self.rest {
            Some(rest) => rest.read(buf),
            None => Ok(0),
        }
    }
}

/// Apply the `requireValue` rule [`parse_with`] applies to a source read
/// from `reader`, reading only as far as the answer needs: the leading
/// whitespace and comments, and the first character after them. With the
/// option on (the default), an empty source is `json5_empty` and one of
/// only whitespace and comments `json5_no_value`, as [`parse_with`] has
/// them; any other source comes back as a reader that gives every byte
/// `reader` gives, the ones read here first, for the parse. A read that
/// fails, or bytes that are not UTF-8, are the parse's to report (the
/// engine's `unreadable`): the reader gives them as `reader` did. A parser
/// without the option, or without the plugin, reads `reader` as it is.
///
/// A host that parses through a reader source of its own, as dmog does
/// through transduce's, calls this first in place of reading the document
/// whole for the rule.
///
/// ```
/// let parser = tabnas_json5::make();
/// let error = tabnas_json5::check_reader(&parser, &b"  // only a comment"[..]).err();
/// assert_eq!(error.map(|e| e.code), Some("json5_no_value".to_string()));
/// let checked = tabnas_json5::check_reader(&parser, &b"[1, 2,]"[..])?;
/// assert_eq!(parser.parse_reader(checked)?.to_string(), "[1,2]");
/// # Ok::<(), tabnas_json5::Json5Error>(())
/// ```
pub fn check_reader<R: std::io::Read>(
    parser: &Tabnas,
    mut reader: R,
) -> Result<Checked<R>, Json5Error> {
    let checked = |read: Vec<u8>, failure, rest| Checked {
        read: std::io::Cursor::new(read),
        failure,
        rest,
    };
    let require_value = parser
        .decoration::<Json5Options>(OPTIONS_MARK)
        .is_some_and(|options| options.require_value);
    if !require_value {
        return Ok(checked(Vec::new(), None, Some(reader)));
    }
    let mut read = Vec::new();
    let mut scan = ValueScan::default();
    let mut buf = [0u8; 512];
    loop {
        let n = match reader.read(&mut buf) {
            Ok(n) => n,
            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(error) => return Ok(checked(read, Some(error), None)),
        };
        read.extend_from_slice(&buf[..n]);
        let end = n == 0;
        match scan.scan(&read, end, false) {
            Verdict::More => {}
            Verdict::Value => return Ok(checked(read, None, (!end).then_some(reader))),
            Verdict::NoValue => {
                let Ok(text) = std::str::from_utf8(&read) else {
                    return Ok(checked(read, None, None));
                };
                let code = if text.is_empty() {
                    "json5_empty"
                } else {
                    "json5_no_value"
                };
                return Err(value_error(parser, code, text));
            }
        }
    }
}

/// Parse a JSON5 source read from `reader` with a parser that carries the
/// plugin: the counterpart of [`parse_with`] for a reader, and of the Go
/// `ParseReader(j, r)` and the TypeScript plugin's `tn.parseReader`. The
/// `requireValue` rule reads `reader` only as far as its answer needs
/// ([`check_reader`]), and the parser then reads the rest through
/// [`Tabnas::parse_reader`]: a window at a time where it declares
/// `lex.window`, as [`make`]'s does, so a long document is never held
/// whole. It gives the value and the errors [`parse_with`] gives of the
/// same text, but for an error's excerpt of a very long line
/// (tabnas/parser `DIVERGENCE.md`).
///
/// ```
/// let parser = tabnas_json5::make();
/// let value = tabnas_json5::parse_reader_with(&parser, &b"{ a: 0x1F, b: [2,], }"[..])?;
/// assert_eq!(value.to_string(), r#"{"a":31,"b":[2]}"#);
/// let error = tabnas_json5::parse_reader_with(&parser, &b""[..]).unwrap_err();
/// assert_eq!(error.code, "json5_empty");
/// # Ok::<(), tabnas_json5::Json5Error>(())
/// ```
pub fn parse_reader_with(parser: &Tabnas, reader: impl std::io::Read) -> Result<Value, Json5Error> {
    let checked = check_reader(parser, reader)?;
    parser.parse_reader(checked)
}

/// Parse a JSON5 source string with the shared default parser.
///
/// The parser is built once, on first use, and reused after that. Reuse
/// is safe: [`Tabnas::parse`] takes `&self` and builds a fresh parse
/// context per call, and `Tabnas` is `Send + Sync`, so concurrent callers
/// share one installed grammar instead of each rebuilding it, which is
/// what dominates a small parse.
///
/// Use [`make_with`] and [`parse_with`] instead when the parser needs
/// configuring: that returns a fresh instance and leaves this one alone.
///
/// ```
/// let value = tabnas_json5::parse("{ a: 1, b: [2, 3,], }")?;
/// assert_eq!(value.to_string(), r#"{"a":1,"b":[2,3]}"#);
/// assert_eq!(tabnas_json5::parse("").unwrap_err().code, "json5_empty");
/// # Ok::<(), tabnas_json5::Json5Error>(())
/// ```
pub fn parse(src: &str) -> Result<Value, Json5Error> {
    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
    parse_with(DEFAULT.get_or_init(make), src)
}

/// One optional alchemy source and the entry point a host calls.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationPart {
    /// The entry point a host calls.
    pub entry: &'static str,
    /// The source text, or `None` for an entry supplied by alchemy.
    pub source: Option<&'static str>,
}

/// The package-local structural translation interface.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationParts {
    /// The complete `tabnas.plugin.json` text.
    pub manifest: &'static str,
    /// An optional lift from the grammar's events to its first read shape.
    pub lift: Option<TranslationPart>,
    /// An optional embedding of a plain tree in the format's schema, with its reverse.
    pub embed: Option<TranslationPart>,
    /// An optional render from the write shape to text.
    pub render: Option<TranslationPart>,
    /// An optional transducer: the format's JSON events from its parser's
    /// rule passes, for a host that reads parser events.
    pub transduce: Option<TranslationPart>,
}

const TRANSLATION: TranslationParts = TranslationParts {
    manifest: include_str!("../translate/manifest.json"),
    lift: None,
    embed: None,
    render: Some(TranslationPart {
        entry: "json5-render",
        source: Some(include_str!("../translate/render.alc")),
    }),
    transduce: Some(TranslationPart {
        entry: "json5-transduce",
        source: Some(include_str!("../translate/transduce.alc")),
    }),
};

/// Return JSON5's immutable translation parts.
#[must_use]
pub const fn translate() -> Option<TranslationParts> {
    Some(TRANSLATION)
}

/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
/// it. Its `translate` object is what a host that translates reads: the
/// shape JSON5 is read as and written from (`tree`), the root its render
/// takes (`any`), the file that holds the render, and the sentences that
/// say what the render does not keep. It also names the transducer part,
/// `alchemy/transduce.alc`, the document's JSON events from the grammar's
/// rule passes, through which a host that reads parser events reads a
/// document. The crate embeds its own copies, `translate/manifest.json`
/// and `translate/transduce.alc`, since a packaged crate holds nothing
/// outside `rs/`; `tests/translate_test.rs` holds each copy to its file.
///
/// ```
/// assert!(tabnas_json5::manifest_text().contains("\"translate\""));
/// ```
pub fn manifest_text() -> &'static str {
    TRANSLATION.manifest
}

/// JSON5's render, `alchemy/render.alc`, the file the manifest's
/// `translate.render` names: a library of alchemy definitions, with no
/// `export`, whose entry point `json5-render` writes a tree's events as
/// one compact JSON5 document, a number that is not finite as `Infinity`,
/// `-Infinity` or `NaN`. A host links it with its own program. The crate
/// embeds its own copy, `translate/render.alc`, held to the file as the
/// manifest's is.
///
/// ```
/// assert!(tabnas_json5::render_text().contains("def json5-render [input]"));
/// ```
pub fn render_text() -> &'static str {
    match TRANSLATION.render {
        Some(part) => part.source.unwrap_or_default(),
        None => "",
    }
}