tokit 0.0.0

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

use core::ops::{Add, AddAssign};

use crate::{
  error::{Unclosed, UnexpectedLexeme},
  punct::Brace,
  utils::{CharLen, Lexeme, PositionedChar, SimpleSpan, human_display::DisplayHuman},
};
use derive_more::{Display, From, IsVariant, TryUnwrap, Unwrap};

/// A zero-copy container for storing 1-4 invalid unicode hex digit characters.
///
/// This structure is designed for fixed-width unicode escapes (`\uXXXX`) which
/// require exactly 4 hexadecimal digits. When parsing fails, this container holds
/// the invalid characters encountered (up to 4) with their positions, enabling
/// precise error reporting without heap allocation.
///
/// # Design
///
/// The container uses an internal representation optimized for small sizes (1-4 items)
/// to avoid heap allocation. It implements `Deref<Target = [PositionedChar<Char>]>`
/// for convenient access to the stored characters.
///
/// # Type Parameters
///
/// * `Char` - The character type (typically `char` for UTF-8 or `u8` for bytes)
///
/// # Examples
///
/// ```
/// use tokit::error::InvalidFixedUnicodeHexDigits;
/// use tokit::utils::PositionedChar;
///
/// // Create from a single invalid character
/// let digit = InvalidFixedUnicodeHexDigits::from(
///     PositionedChar::with_position('G', 12)
/// );
/// assert_eq!(digit.len(), 1);
///
/// // Create from multiple invalid characters
/// let digits = InvalidFixedUnicodeHexDigits::from_array([
///     PositionedChar::with_position('G', 12),
///     PositionedChar::with_position('H', 13),
///     PositionedChar::with_position('I', 14),
///     PositionedChar::with_position('J', 15),
/// ]);
/// assert_eq!(digits.len(), 4);
///
/// // Access as a slice
/// for ch in digits.iter() {
///     println!("Invalid hex digit at position {}", ch.position());
/// }
/// ```
pub type InvalidFixedUnicodeHexDigits<Char = char, O = usize> =
  crate::error::InvalidHexDigits<Char, 4, O>;

/// A malformed fixed-width unicode escape sequence error.
///
/// This error occurs when a fixed-width unicode escape (`\uXXXX`) contains
/// invalid hexadecimal digits. The error captures both the invalid characters
/// encountered and the span of the malformed escape sequence.
///
/// # Type Parameters
///
/// * `Char` - The character type (typically `char` for UTF-8 or `u8` for bytes)
///
/// # Examples
///
/// ```
/// use tokit::error::{MalformedFixedUnicodeEscape, InvalidFixedUnicodeHexDigits};
/// use tokit::utils::{SimpleSpan, PositionedChar};
///
/// // Create error for malformed escape like \uGHIJ
/// let digits = InvalidFixedUnicodeHexDigits::from_array([
///     PositionedChar::with_position('G', 12),
///     PositionedChar::with_position('H', 13),
///     PositionedChar::with_position('I', 14),
///     PositionedChar::with_position('J', 15),
/// ]);
///
/// let error = MalformedFixedUnicodeEscape::new(
///     digits,
///     SimpleSpan::new(10, 16) // \uGHIJ
/// );
///
/// assert_eq!(error.span(), SimpleSpan::new(10, 16));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MalformedFixedUnicodeEscape<Char = char, O = usize> {
  digits: InvalidFixedUnicodeHexDigits<Char, O>,
  span: SimpleSpan<O>,
}

impl<Char, O> core::fmt::Display for MalformedFixedUnicodeEscape<Char, O>
where
  Char: DisplayHuman,
  O: core::fmt::Display,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "malformed hexadecimal escape sequence with invalid digits at {}, {}",
      self.span,
      self.digits_ref()
    )
  }
}

impl<Char, O> core::error::Error for MalformedFixedUnicodeEscape<Char, O>
where
  Char: DisplayHuman + core::fmt::Debug,
  O: core::fmt::Display + core::fmt::Debug,
{
}

impl<Char, O> MalformedFixedUnicodeEscape<Char, O> {
  /// Creates a new malformed fixed-width unicode escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{MalformedFixedUnicodeEscape, InvalidFixedUnicodeHexDigits};
  /// use tokit::utils::{SimpleSpan, PositionedChar};
  ///
  /// let digits = InvalidFixedUnicodeHexDigits::from(
  ///     PositionedChar::with_position('Z', 12)
  /// );
  /// let error = MalformedFixedUnicodeEscape::new(digits, SimpleSpan::new(10, 14));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(digits: InvalidFixedUnicodeHexDigits<Char, O>, span: SimpleSpan<O>) -> Self {
    Self { digits, span }
  }

  // /// Returns `true` if the sequence is also incomplete.
  // ///
  // /// A fixed-width unicode escape `\uXXXX` is 6 characters long total.
  // /// If the span is shorter, it means the escape was cut off mid-sequence.
  // ///
  // /// ## Examples
  // ///
  // /// ```
  // /// use tokit::error::{MalformedFixedUnicodeEscape, InvalidFixedUnicodeHexDigits};
  // /// use tokit::utils::SimpleSpan;
  // ///
  // /// let digits = InvalidFixedUnicodeHexDigits::<char>::from_char(12, 'G');
  // /// let error = MalformedFixedUnicodeEscape::new(digits, SimpleSpan::new(10, 14));
  // /// assert!(error.is_incomplete()); // Only 4 chars, not 6
  // /// ```
  // #[cfg_attr(not(tarpaulin), inline(always))]
  // pub const fn is_incomplete(&self) -> bool {
  //   self.span.len() < 6 // \u[0-9a-fA-F]{4} is 6 characters long
  // }

  /// Returns the invalid unicode hex digits.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{MalformedFixedUnicodeEscape, InvalidFixedUnicodeHexDigits};
  /// use tokit::utils::{SimpleSpan, PositionedChar};
  ///
  /// let digits = InvalidFixedUnicodeHexDigits::from(
  ///     PositionedChar::with_position('G', 12)
  /// );
  /// let error = MalformedFixedUnicodeEscape::new(digits, SimpleSpan::new(10, 14));
  /// assert_eq!(error.digits().len(), 1);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn digits(&self) -> InvalidFixedUnicodeHexDigits<Char, O>
  where
    Char: Clone,
    O: Clone,
  {
    self.digits.clone()
  }

  /// Returns a reference to the invalid unicode hex digits.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{MalformedFixedUnicodeEscape, InvalidFixedUnicodeHexDigits};
  /// use tokit::utils::{SimpleSpan, PositionedChar};
  ///
  /// let digits = InvalidFixedUnicodeHexDigits::from(
  ///     PositionedChar::with_position('G', 12)
  /// );
  /// let error = MalformedFixedUnicodeEscape::new(digits, SimpleSpan::new(10, 14));
  /// assert_eq!(error.digits_ref().len(), 1);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn digits_ref(&self) -> &InvalidFixedUnicodeHexDigits<Char, O> {
    &self.digits
  }

  /// Returns a mutable reference to the invalid unicode hex digits.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn digits_mut(&mut self) -> &mut InvalidFixedUnicodeHexDigits<Char, O> {
    &mut self.digits
  }

  /// Returns the span of the malformed unicode escape.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{MalformedFixedUnicodeEscape, InvalidFixedUnicodeHexDigits};
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = MalformedFixedUnicodeEscape::new(
  ///     InvalidFixedUnicodeHexDigits::<char>::from_char(12, 'G'),
  ///     SimpleSpan::new(10, 16)
  /// );
  /// assert_eq!(error.span(), SimpleSpan::new(10, 16));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span(&self) -> SimpleSpan<O>
  where
    O: Copy,
  {
    self.span
  }

  /// Returns a reference to the span of the malformed unicode escape.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_ref(&self) -> SimpleSpan<&O> {
    self.span.as_ref()
  }

  /// Returns a mutable reference to the span of the malformed unicode escape.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_mut(&mut self) -> SimpleSpan<&mut O> {
    self.span.as_mut()
  }

  /// Bumps the span and all digit positions by `n`.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{MalformedFixedUnicodeEscape, InvalidFixedUnicodeHexDigits};
  /// use tokit::utils::{SimpleSpan, PositionedChar};
  ///
  /// let mut error = MalformedFixedUnicodeEscape::new(
  ///     InvalidFixedUnicodeHexDigits::from(PositionedChar::with_position('G', 12)),
  ///     SimpleSpan::new(10, 16)
  /// );
  /// error.bump(5);
  /// assert_eq!(error.span(), SimpleSpan::new(15, 21));
  /// ```
  #[inline]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone,
  {
    self.span.bump(n);
    self.digits_mut().bump(n);
    self
  }
}

/// The reason why a parsed value is not a valid Unicode scalar.
///
/// A valid Unicode scalar value is in the range `0x0000..=0x10FFFF`, excluding
/// the surrogate range `0xD800..=0xDFFF`.
///
/// # Examples
///
/// ```
/// use tokit::error::InvalidUnicodeScalarKind;
///
/// // Surrogate values (0xD800..=0xDFFF) are reserved for UTF-16 encoding
/// let kind = InvalidUnicodeScalarKind::Surrogate;
///
/// // Values above 0x10FFFF are beyond the Unicode codespace
/// let kind = InvalidUnicodeScalarKind::Overflow;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InvalidUnicodeScalarKind {
  /// In the UTF-16 surrogate range: `0xD800..=0xDFFF`.
  ///
  /// These values are reserved for UTF-16 surrogate pair encoding and
  /// are not valid Unicode scalar values.
  Surrogate,

  /// Above the Unicode maximum scalar value: `> 0x10FFFF`.
  ///
  /// The highest valid Unicode code point is U+10FFFF. Values above
  /// this are outside the defined Unicode codespace.
  Overflow,
}

/// An invalid unicode scalar value error.
///
/// This error occurs when a unicode escape sequence parses successfully to a
/// numeric value, but that value is not a valid Unicode scalar. There are two
/// reasons this can happen:
///
/// 1. **Surrogate**: The value is in the range `0xD800..=0xDFFF` (UTF-16 surrogates)
/// 2. **Overflow**: The value exceeds `0x10FFFF` (the maximum Unicode code point)
///
/// # Examples
///
/// ```
/// use tokit::error::{InvalidUnicodeScalarValue, InvalidUnicodeScalarKind};
/// use tokit::utils::SimpleSpan;
///
/// // Surrogate value error: \u{D800}
/// let error = InvalidUnicodeScalarValue::new(
///     0xD800,
///     SimpleSpan::new(10, 18),
///     InvalidUnicodeScalarKind::Surrogate
/// );
/// assert_eq!(error.codepoint(), 0xD800);
/// assert_eq!(error.kind(), InvalidUnicodeScalarKind::Surrogate);
///
/// // Overflow error: \u{110000}
/// let error = InvalidUnicodeScalarValue::new(
///     0x110000,
///     SimpleSpan::new(20, 30),
///     InvalidUnicodeScalarKind::Overflow
/// );
/// assert_eq!(error.codepoint(), 0x110000);
/// assert_eq!(error.kind(), InvalidUnicodeScalarKind::Overflow);
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct InvalidUnicodeScalarValue<O = usize> {
  value: u32,
  span: SimpleSpan<O>,
  kind: InvalidUnicodeScalarKind,
}

impl<O> core::fmt::Display for InvalidUnicodeScalarValue<O>
where
  O: core::fmt::Display,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    let cp = self.value;

    match self.kind {
      InvalidUnicodeScalarKind::Surrogate => write!(
        f,
        "invalid Unicode scalar value: surrogate code point U+{cp:04X} at {}",
        self.span
      ),
      InvalidUnicodeScalarKind::Overflow => write!(
        f,
        "invalid Unicode scalar value: code point U+{cp:04X} is out of range at {}",
        self.span
      ),
    }
  }
}

impl<O> core::error::Error for InvalidUnicodeScalarValue<O> where
  O: core::fmt::Display + core::fmt::Debug
{
}

impl<O> InvalidUnicodeScalarValue<O> {
  /// Creates a new invalid unicode scalar value error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{InvalidUnicodeScalarValue, InvalidUnicodeScalarKind};
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = InvalidUnicodeScalarValue::new(
  ///     0xD800,
  ///     SimpleSpan::new(10, 18),
  ///     InvalidUnicodeScalarKind::Surrogate
  /// );
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(value: u32, span: SimpleSpan<O>, kind: InvalidUnicodeScalarKind) -> Self {
    Self { value, span, kind }
  }

  /// Returns the invalid codepoint value.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{InvalidUnicodeScalarValue, InvalidUnicodeScalarKind};
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = InvalidUnicodeScalarValue::new(
  ///     0xD800,
  ///     SimpleSpan::new(10, 18),
  ///     InvalidUnicodeScalarKind::Surrogate
  /// );
  /// assert_eq!(error.codepoint(), 0xD800);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn codepoint(&self) -> u32 {
    self.value
  }

  /// Returns the span of the invalid unicode scalar value.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{InvalidUnicodeScalarValue, InvalidUnicodeScalarKind};
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = InvalidUnicodeScalarValue::new(
  ///     0x110000,
  ///     SimpleSpan::new(5, 15),
  ///     InvalidUnicodeScalarKind::Overflow
  /// );
  /// assert_eq!(error.span(), SimpleSpan::new(5, 15));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span(&self) -> SimpleSpan<O>
  where
    O: Copy,
  {
    self.span
  }

  /// Returns a reference to the span.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_ref(&self) -> SimpleSpan<&O> {
    self.span.as_ref()
  }

  /// Returns a mutable reference to the span.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_mut(&mut self) -> SimpleSpan<&mut O> {
    self.span.as_mut()
  }

  /// Bumps the span by `n`.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{InvalidUnicodeScalarValue, InvalidUnicodeScalarKind};
  /// use tokit::utils::SimpleSpan;
  ///
  /// let mut error = InvalidUnicodeScalarValue::new(
  ///     0xD800,
  ///     SimpleSpan::new(10, 18),
  ///     InvalidUnicodeScalarKind::Surrogate
  /// );
  /// error.bump(5);
  /// assert_eq!(error.span(), SimpleSpan::new(15, 23));
  /// ```
  #[inline]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone,
  {
    self.span.bump(n);
    self
  }

  /// Returns the kind of invalid unicode scalar value.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{InvalidUnicodeScalarValue, InvalidUnicodeScalarKind};
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = InvalidUnicodeScalarValue::new(
  ///     0xD800,
  ///     SimpleSpan::new(10, 18),
  ///     InvalidUnicodeScalarKind::Surrogate
  /// );
  /// assert_eq!(error.kind(), InvalidUnicodeScalarKind::Surrogate);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn kind(&self) -> InvalidUnicodeScalarKind {
    self.kind
  }
}

/// An empty variable-length unicode escape error.
///
/// This error occurs when a variable-length unicode escape has no hex digits between
/// the braces: `\u{}`.
///
/// A valid variable-length unicode escape requires at least one hex digit, e.g., `\u{0}`.
///
/// # Examples
///
/// ```
/// use tokit::error::EmptyVariableUnicodeEscape;
/// use tokit::utils::SimpleSpan;
///
/// // Error for: \u{}
/// let error = EmptyVariableUnicodeEscape::new(SimpleSpan::new(10, 14));
/// assert_eq!(error.span(), SimpleSpan::new(10, 14));
/// assert_eq!(format!("{}", error), "empty variable-length unicode escape at 10..14");
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Display)]
#[display("empty variable-length unicode escape at {_0}")]
pub struct EmptyVariableUnicodeEscape<O = usize>(SimpleSpan<O>);

impl<O> EmptyVariableUnicodeEscape<O> {
  /// Creates a new empty variable-length unicode escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::EmptyVariableUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = EmptyVariableUnicodeEscape::new(SimpleSpan::new(5, 9));
  /// assert_eq!(error.span(), SimpleSpan::new(5, 9));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(span: SimpleSpan<O>) -> Self {
    Self(span)
  }

  /// Returns the span of the empty variable-length unicode escape.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::EmptyVariableUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = EmptyVariableUnicodeEscape::new(SimpleSpan::new(10, 14));
  /// assert_eq!(error.span(), SimpleSpan::new(10, 14));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span(&self) -> SimpleSpan<O>
  where
    O: Copy,
  {
    self.0
  }

  /// Returns the span of the empty variable-length unicode escape.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::EmptyVariableUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = EmptyVariableUnicodeEscape::new(SimpleSpan::new(10, 14));
  /// assert_eq!(error.span_ref(), SimpleSpan::new(&10, &14));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_ref(&self) -> SimpleSpan<&O> {
    self.0.as_ref()
  }

  /// Returns the span of the empty variable-length unicode escape.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::EmptyVariableUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = EmptyVariableUnicodeEscape::new(SimpleSpan::new(10, 14));
  /// assert_eq!(error.span_mut(), SimpleSpan::new(&mut 10, &mut 14));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_mut(&mut self) -> SimpleSpan<&mut O> {
    self.0.as_mut()
  }

  /// Bumps the span by `n`.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::EmptyVariableUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let mut error = EmptyVariableUnicodeEscape::new(SimpleSpan::new(10, 14));
  /// error.bump(5);
  /// assert_eq!(error.span(), SimpleSpan::new(15, 19));
  /// ```
  #[inline]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone,
  {
    self.0.bump(n);
    self
  }
}

impl<O> core::error::Error for EmptyVariableUnicodeEscape<O> where
  O: core::fmt::Display + core::fmt::Debug
{
}

/// A malformed variable-length unicode escape sequence error.
///
/// This error occurs when a variable-length unicode escape (`\u{...}`) contains
/// invalid characters between the braces. Valid braced escapes require
/// only hexadecimal digits (0-9, a-f, A-F).
///
/// # Type Parameters
///
/// * `Char` - The character type (typically `char` for UTF-8 or `u8` for bytes)
///
/// # Examples
///
/// ```
/// use tokit::error::MalformedVariableUnicodeSequence;
/// use tokit::utils::{Lexeme, PositionedChar};
///
/// // Error for: \u{GGGG}
/// let error = MalformedVariableUnicodeSequence::<char>::from_char(12, 'G');
/// assert_eq!(
///     format!("{}", error),
///     "invalid variable-length unicode escape character 'G' at position 12"
/// );
///
/// // Error for a span of invalid characters
/// let error: MalformedVariableUnicodeSequence<char> =
///     MalformedVariableUnicodeSequence::from_range((10, 15).into());
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct MalformedVariableUnicodeSequence<Char = char, O = usize>(Lexeme<Char, O>);

impl<Char, O> core::fmt::Display for MalformedVariableUnicodeSequence<Char, O>
where
  Char: DisplayHuman,
  O: core::fmt::Display,
{
  #[cfg_attr(not(tarpaulin), inline(always))]
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self.lexeme_ref() {
      Lexeme::Char(positioned_char) => write!(
        f,
        "invalid variable-length unicode escape character '{}' at position {}",
        positioned_char.char_ref().display(),
        positioned_char.position_ref()
      ),
      Lexeme::Range(span) => write!(
        f,
        "malformed variable-length unicode escape sequence at {}",
        span
      ),
    }
  }
}

impl<Char, O> core::error::Error for MalformedVariableUnicodeSequence<Char, O>
where
  Char: DisplayHuman + core::fmt::Debug,
  O: core::fmt::Display + core::fmt::Debug,
{
}

impl<Char, O> MalformedVariableUnicodeSequence<Char, O> {
  /// Creates a new malformed variable-length unicode escape error from a lexeme.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::MalformedVariableUnicodeSequence;
  /// use tokit::utils::{Lexeme, PositionedChar};
  ///
  /// let lexeme = Lexeme::from(PositionedChar::with_position('Z', 15));
  /// let error = MalformedVariableUnicodeSequence::new(lexeme);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(lexeme: Lexeme<Char, O>) -> Self {
    Self(lexeme)
  }

  /// Creates a new malformed variable-length unicode escape error from a positioned character.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::MalformedVariableUnicodeSequence;
  ///
  /// let error = MalformedVariableUnicodeSequence::from_char(42, 'X');
  /// assert_eq!(
  ///     format!("{}", error),
  ///     "invalid variable-length unicode escape character 'X' at position 42"
  /// );
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn from_char(pos: O, ch: Char) -> Self {
    Self::from_positioned_char(PositionedChar::with_position(ch, pos))
  }

  /// Creates a new malformed variable-length unicode escape error from a positioned character.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::{error::MalformedVariableUnicodeSequence, utils::PositionedChar};
  ///
  /// let error = MalformedVariableUnicodeSequence::from_positioned_char(PositionedChar::with_position('X', 42));
  /// assert_eq!(
  ///     format!("{}", error),
  ///     "invalid variable-length unicode escape character 'X' at position 42"
  /// );
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn from_positioned_char(ch: PositionedChar<Char, O>) -> Self {
    Self(Lexeme::Char(ch))
  }

  /// Creates a new malformed variable-length unicode escape error from a span.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::MalformedVariableUnicodeSequence;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error: MalformedVariableUnicodeSequence<char> =
  ///     MalformedVariableUnicodeSequence::from_range(SimpleSpan::new(10, 15));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn from_range(span: SimpleSpan<O>) -> Self {
    Self(Lexeme::Range(span))
  }

  /// Returns the span of the malformed variable-length unicode escape.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::MalformedVariableUnicodeSequence;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = MalformedVariableUnicodeSequence::from_char(10, 'G');
  /// assert_eq!(error.span(), SimpleSpan::new(10, 11));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn span(&self) -> SimpleSpan<O>
  where
    Char: CharLen,
    O: Clone + Ord,
    for<'a> &'a O: Add<usize, Output = O>,
  {
    self.0.span()
  }

  /// Returns the lexeme of the malformed variable-length unicode escape.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::MalformedVariableUnicodeSequence;
  /// use tokit::utils::Lexeme;
  ///
  /// let error = MalformedVariableUnicodeSequence::from_char(10, 'G');
  /// assert!(error.lexeme().is_char());
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn lexeme(&self) -> Lexeme<Char, O>
  where
    Char: Copy,
    O: Copy,
  {
    self.0
  }

  /// Returns a reference to the lexeme.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn lexeme_ref(&self) -> &Lexeme<Char, O> {
    &self.0
  }

  /// Bumps the span or position by `n`.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::MalformedVariableUnicodeSequence;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let mut error = MalformedVariableUnicodeSequence::from_char(10, 'G');
  /// error.bump(5);
  /// assert_eq!(error.span(), SimpleSpan::new(15, 16));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone,
  {
    self.0.bump(n);
    self
  }
}

/// Too many digits in variable-length unicode escape error.
///
/// A valid variable-length unicode escape can have between 1 and 6 hex digits.
/// This error occurs when more than 6 hex digits are found.
///
/// # Examples
///
/// ```
/// use tokit::error::TooManyDigitsInVariableUnicodeEscape;
/// use tokit::utils::SimpleSpan;
///
/// // Error for: \u{1234567} (7 digits, limit is 6)
/// let error = TooManyDigitsInVariableUnicodeEscape::new(
///     SimpleSpan::new(10, 21),
///     7
/// );
/// assert_eq!(error.count(), 7);
/// assert_eq!(
///     format!("{}", error),
///     "too many digits (7) in variable-length unicode escape at 10..21"
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Display)]
#[display("too many digits ({_1}) in variable-length unicode escape at {_0}")]
pub struct TooManyDigitsInVariableUnicodeEscape<O = usize>(SimpleSpan<O>, usize);

impl<O> TooManyDigitsInVariableUnicodeEscape<O> {
  /// Creates a new too many digits in variable-length unicode escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::TooManyDigitsInVariableUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = TooManyDigitsInVariableUnicodeEscape::new(SimpleSpan::new(5, 15), 8);
  /// assert_eq!(error.count(), 8);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(span: SimpleSpan<O>, count: usize) -> Self {
    Self(span, count)
  }

  /// Returns the span of the too many digits error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::TooManyDigitsInVariableUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = TooManyDigitsInVariableUnicodeEscape::new(SimpleSpan::new(10, 20), 7);
  /// assert_eq!(error.span(), SimpleSpan::new(10, 20));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span(&self) -> SimpleSpan<O>
  where
    O: Copy,
  {
    self.0
  }

  /// Returns the span of the too many digits error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::TooManyDigitsInVariableUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = TooManyDigitsInVariableUnicodeEscape::new(SimpleSpan::new(10, 20), 7);
  /// assert_eq!(error.span(), SimpleSpan::new(10, 20));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_ref(&self) -> SimpleSpan<&O> {
    self.0.as_ref()
  }

  /// Returns the span of the too many digits error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::TooManyDigitsInVariableUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = TooManyDigitsInVariableUnicodeEscape::new(SimpleSpan::new(10, 20), 7);
  /// assert_eq!(error.span(), SimpleSpan::new(10, 20));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_mut(&mut self) -> SimpleSpan<&mut O> {
    self.0.as_mut()
  }

  /// Returns the count of hex digits found.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::TooManyDigitsInVariableUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = TooManyDigitsInVariableUnicodeEscape::new(SimpleSpan::new(10, 20), 7);
  /// assert_eq!(error.count(), 7);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn count(&self) -> usize {
    self.1
  }

  /// Bumps the span by `n`.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::TooManyDigitsInVariableUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let mut error = TooManyDigitsInVariableUnicodeEscape::new(SimpleSpan::new(10, 20), 7);
  /// error.bump(5);
  /// assert_eq!(error.span(), SimpleSpan::new(15, 25));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone,
  {
    self.0.bump(n);
    self
  }
}

impl<O> core::error::Error for TooManyDigitsInVariableUnicodeEscape<O> where
  O: core::fmt::Display + core::fmt::Debug + 'static
{
}

/// An error encountered during lexing for `\u{...}` (variable-length) unicode escape sequences.
///
/// Variable-length unicode escapes allow 1-6 hexadecimal digits to encode any valid Unicode
/// scalar value (U+0000 to U+10FFFF, excluding surrogates U+D800 to U+DFFF).
///
/// # Variants
///
/// - **Unclosed**: The opening brace was not closed, e.g., `\u{1234`
/// - **Empty**: The braces contained no digits, e.g., `\u{}`
/// - **TooManyDigits**: More than 6 hex digits inside the braces, e.g., `\u{1234567}`
/// - **Malformed**: Invalid characters (non-hex) inside the braces, e.g., `\u{GGGG}`
/// - **InvalidScalar**: Valid hex but invalid Unicode scalar (surrogate or overflow)
///
/// # Examples
///
/// ```
/// use tokit::error::VariableUnicodeEscapeError;
/// use tokit::utils::SimpleSpan;
///
/// // Empty braces
/// let error = VariableUnicodeEscapeError::<char>::empty(SimpleSpan::new(10, 14));
/// assert!(error.is_empty());
///
/// // Too many digits
/// let error = VariableUnicodeEscapeError::<char>::too_many_digits(SimpleSpan::new(5, 16), 7);
/// assert!(error.is_too_many_digits());
///
/// // Surrogate value
/// let error = VariableUnicodeEscapeError::<char>::surrogate(SimpleSpan::new(10, 18), 0xD800);
/// assert!(error.is_invalid_scalar());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, From, IsVariant, TryUnwrap, Unwrap)]
#[unwrap(ref, ref_mut)]
#[try_unwrap(ref, ref_mut)]
#[non_exhaustive]
pub enum VariableUnicodeEscapeError<Char = char, O = usize> {
  /// The opening brace was not closed: `\u{1234`.
  Unclosed(Unclosed<Brace, SimpleSpan<O>>),

  /// The braces contained **no** digits: `\u{}`.
  Empty(EmptyVariableUnicodeEscape<O>),

  /// More than 6 hex digits inside the braces.
  TooManyDigits(TooManyDigitsInVariableUnicodeEscape<O>),

  /// A malformed sequence of unicode in the braces.
  Malformed(MalformedVariableUnicodeSequence<Char, O>),

  /// Parsed number is not a Unicode scalar value (surrogate or > 0x10_FFFF).
  InvalidScalar(InvalidUnicodeScalarValue<O>),
}

impl<Char, O> core::fmt::Display for VariableUnicodeEscapeError<Char, O>
where
  Char: DisplayHuman,
  O: core::fmt::Display,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Unclosed(err) => {
        write!(
          f,
          "unclosed variable-length unicode escape at {}",
          err.span_ref()
        )
      }
      Self::Empty(err) => err.fmt(f),
      Self::TooManyDigits(err) => err.fmt(f),
      Self::Malformed(err) => err.fmt(f),
      Self::InvalidScalar(err) => err.fmt(f),
    }
  }
}

impl<Char, O> core::error::Error for VariableUnicodeEscapeError<Char, O>
where
  Char: DisplayHuman + core::fmt::Debug + 'static,
  O: core::fmt::Display + core::fmt::Debug + 'static,
{
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Unclosed(err) => Some(err),
      Self::Empty(err) => Some(err),
      Self::TooManyDigits(err) => Some(err),
      Self::Malformed(err) => Some(err),
      Self::InvalidScalar(err) => Some(err),
    }
  }
}

impl<Char, O> VariableUnicodeEscapeError<Char, O> {
  /// Creates an empty variable-length unicode escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::VariableUnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error: VariableUnicodeEscapeError<char> =
  ///     VariableUnicodeEscapeError::empty(SimpleSpan::new(10, 14));
  /// assert!(error.is_empty());
  /// ```
  #[inline]
  pub const fn empty(span: SimpleSpan<O>) -> Self {
    Self::Empty(EmptyVariableUnicodeEscape::new(span))
  }

  /// Creates a too many digits in variable-length unicode escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::VariableUnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error: VariableUnicodeEscapeError<char> =
  ///     VariableUnicodeEscapeError::too_many_digits(SimpleSpan::new(5, 15), 7);
  /// assert!(error.is_too_many_digits());
  /// ```
  #[inline]
  pub const fn too_many_digits(span: SimpleSpan<O>, count: usize) -> Self {
    Self::TooManyDigits(TooManyDigitsInVariableUnicodeEscape::new(span, count))
  }

  /// Creates an unclosed brace in variable-length unicode escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::VariableUnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error: VariableUnicodeEscapeError<char> =
  ///     VariableUnicodeEscapeError::unclosed(SimpleSpan::new(10, 15));
  /// assert!(error.is_unclosed());
  /// ```
  #[inline]
  pub const fn unclosed(span: SimpleSpan<O>) -> Self {
    Self::Unclosed(Unclosed::new(span, Brace::PHANTOM))
  }

  /// Creates an overflow error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::VariableUnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error: VariableUnicodeEscapeError<char> =
  ///     VariableUnicodeEscapeError::overflow(SimpleSpan::new(10, 20), 0x110000);
  /// assert!(error.is_invalid_scalar());
  /// ```
  #[inline]
  pub const fn overflow(span: SimpleSpan<O>, codepoint: u32) -> Self {
    Self::InvalidScalar(InvalidUnicodeScalarValue::new(
      codepoint,
      span,
      InvalidUnicodeScalarKind::Overflow,
    ))
  }

  /// Creates a surrogate error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::VariableUnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error: VariableUnicodeEscapeError<char> =
  ///     VariableUnicodeEscapeError::surrogate(SimpleSpan::new(10, 18), 0xD800);
  /// assert!(error.is_invalid_scalar());
  /// ```
  #[inline]
  pub const fn surrogate(span: SimpleSpan<O>, codepoint: u32) -> Self {
    Self::InvalidScalar(InvalidUnicodeScalarValue::new(
      codepoint,
      span,
      InvalidUnicodeScalarKind::Surrogate,
    ))
  }

  /// Bumps the span of the error by `n`.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::VariableUnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let mut error: VariableUnicodeEscapeError<char> =
  ///     VariableUnicodeEscapeError::empty(SimpleSpan::new(10, 14));
  /// error.bump(5);
  /// // Now the span would be adjusted by 5
  /// ```
  #[inline]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone + Ord + core::hash::Hash,
  {
    match self {
      Self::Unclosed(err) => {
        err.bump(n);
      }
      Self::Empty(err) => {
        err.bump(n);
      }
      Self::TooManyDigits(err) => {
        err.bump(n);
      }
      Self::Malformed(err) => {
        err.bump(n);
      }
      Self::InvalidScalar(err) => {
        err.bump(n);
      }
    }
    self
  }

  /// Returns the span of the error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::VariableUnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error: VariableUnicodeEscapeError<char> =
  ///    VariableUnicodeEscapeError::empty(SimpleSpan::new(10, 14));
  /// assert_eq!(error.span(), SimpleSpan::new(10, 14));
  /// ```
  pub fn span(&self) -> SimpleSpan<O>
  where
    Char: CharLen,
    O: Clone + Ord,
    for<'a> &'a O: Add<usize, Output = O>,
  {
    match self {
      Self::Unclosed(err) => err.span_ref().clone(),
      Self::Empty(err) => err.span_ref().cloned(),
      Self::TooManyDigits(err) => err.span_ref().cloned(),
      Self::Malformed(err) => err.span(),
      Self::InvalidScalar(err) => err.span_ref().cloned(),
    }
  }
}

/// A hint describing why a surrogate is unpaired.
///
/// In UTF-16 encoding, surrogates must come in pairs (high followed by low).
/// This hint indicates which half of the pair was found without its match.
///
/// # Examples
///
/// ```
/// use tokit::error::UnpairedSurrogateHint;
///
/// let hint = UnpairedSurrogateHint::High;
/// assert_eq!(format!("{}", hint), "high surrogate");
///
/// let hint = UnpairedSurrogateHint::Low;
/// assert_eq!(format!("{}", hint), "low surrogate");
/// ```
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Display, IsVariant)]
pub enum UnpairedSurrogateHint {
  /// An unpaired high surrogate (U+D800..U+DBFF).
  ///
  /// A high surrogate must be followed by a low surrogate to form
  /// a valid UTF-16 surrogate pair.
  #[display("high surrogate")]
  High,

  /// An unpaired low surrogate (U+DC00..U+DFFF).
  ///
  /// A low surrogate must be preceded by a high surrogate to form
  /// a valid UTF-16 surrogate pair.
  #[display("low surrogate")]
  Low,
}

/// An incomplete fixed-width unicode escape sequence error.
///
/// This error occurs when a fixed-width unicode escape (`\uXXXX`) has fewer than 4 hex digits,
/// typically due to unexpected end-of-input or a non-hex character.
///
/// # Examples
///
/// ```
/// use tokit::error::IncompleteFixedUnicodeEscape;
/// use tokit::utils::SimpleSpan;
///
/// // Incomplete: \u00A (only 3 hex digits)
/// let error = IncompleteFixedUnicodeEscape::new(
///     SimpleSpan::new(10, 13)
/// );
/// assert_eq!(error.span(), SimpleSpan::new(10, 13));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct IncompleteFixedUnicodeEscape<O = usize>(SimpleSpan<O>);

impl<O> core::fmt::Display for IncompleteFixedUnicodeEscape<O>
where
  O: core::fmt::Display,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "incomplete fixed-width unicode escape sequence at {}, fixed-width unicode escape must contains exactly four hexadecimal digits",
      self.0
    )
  }
}

impl<O> core::error::Error for IncompleteFixedUnicodeEscape<O> where
  O: core::fmt::Display + core::fmt::Debug
{
}

impl<O> IncompleteFixedUnicodeEscape<O> {
  /// Creates a new incomplete hex escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::IncompleteFixedUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = IncompleteFixedUnicodeEscape::new(SimpleSpan::new(10, 12));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(span: SimpleSpan<O>) -> Self {
    Self(span)
  }

  /// Returns the span of the incomplete hex escape.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::IncompleteFixedUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = IncompleteFixedUnicodeEscape::new(SimpleSpan::new(10, 13));
  /// assert_eq!(error.span(), SimpleSpan::new(10, 13));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span(&self) -> SimpleSpan<O>
  where
    O: Copy,
  {
    self.0
  }

  /// Returns the span of the incomplete hex escape.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::IncompleteFixedUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = IncompleteFixedUnicodeEscape::new(SimpleSpan::new(10, 13));
  /// assert_eq!(error.span_ref(), SimpleSpan::new(&10, &13));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_ref(&self) -> SimpleSpan<&O> {
    self.0.as_ref()
  }

  /// Returns the span of the incomplete hex escape.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::IncompleteFixedUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = IncompleteFixedUnicodeEscape::new(SimpleSpan::new(10, 13));
  /// assert_eq!(error.span_mut(), SimpleSpan::new(&mut 10, &mut 13));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_mut(&mut self) -> SimpleSpan<&mut O> {
    self.0.as_mut()
  }

  /// Bumps the span or position by `n`.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::IncompleteFixedUnicodeEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let mut error = IncompleteFixedUnicodeEscape::new(SimpleSpan::new(10, 12));
  /// error.bump(5);
  /// assert_eq!(error.span(), SimpleSpan::new(15, 17));
  /// ```
  #[inline]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone,
  {
    self.0.bump(n);
    self
  }
}

/// An error encountered during lexing for `\uXXXX` (fixed-width) unicode escape sequences.
///
/// Fixed-width unicode escapes require exactly 4 hexadecimal digits after `\u`.
/// They can encode values from U+0000 to U+FFFF (the Basic Multilingual Plane).
///
/// For characters beyond the BMP, UTF-16 surrogate pairs are used:
/// - High surrogate: U+D800..U+DBFF followed by
/// - Low surrogate: U+DC00..U+DFFF
///
/// # Variants
///
/// - **Incomplete**: The escape has fewer than 4 hex digits, e.g., `\uAB`
/// - **Malformed**: The 4 characters are not valid hexadecimal, e.g., `\uGGGG`
/// - **UnpairedSurrogate**: A surrogate value without its pair, e.g., `\uD800` alone
///
/// # Examples
///
/// ```
/// use tokit::error::{FixedUnicodeEscapeError, IncompleteFixedUnicodeEscape};
/// use tokit::utils::{Lexeme, SimpleSpan};
///
/// // Incomplete escape: \uAB (only 2 hex digits)
/// let error: FixedUnicodeEscapeError =
///     FixedUnicodeEscapeError::Incomplete(IncompleteFixedUnicodeEscape::new(SimpleSpan::new(10, 14)));
/// assert!(error.is_incomplete());
///
/// // Unpaired high surrogate: \uD800
/// let error = FixedUnicodeEscapeError::<char>::unpaired_high_surrogate(
///     Lexeme::Range(SimpleSpan::new(5, 11))
/// );
/// assert!(error.is_unpaired_surrogate());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, From, IsVariant, TryUnwrap, Unwrap)]
#[unwrap(ref, ref_mut)]
#[try_unwrap(ref, ref_mut)]
#[non_exhaustive]
pub enum FixedUnicodeEscapeError<Char = char, O = usize> {
  /// An incomplete fixed-width unicode escape sequence.
  ///
  /// This occurs when the escape has fewer than 4 hex digits, typically
  /// due to unexpected end-of-input or a non-hex character.
  Incomplete(IncompleteFixedUnicodeEscape<O>),

  /// A malformed fixed-width unicode escape sequence.
  ///
  /// This occurs when 4 characters follow `\u` but they are not all
  /// valid hexadecimal digits.
  Malformed(MalformedFixedUnicodeEscape<Char, O>),

  /// An unpaired surrogate in a fixed-width unicode escape sequence.
  ///
  /// This occurs when a surrogate value (U+D800..U+DFFF) appears without
  /// its required pair.
  UnpairedSurrogate(UnexpectedLexeme<Char, UnpairedSurrogateHint, O>),
}

impl<Char, O> core::fmt::Display for FixedUnicodeEscapeError<Char, O>
where
  Char: DisplayHuman + CharLen,
  O: core::fmt::Display + Clone + Ord,
  for<'a> &'a O: Add<usize, Output = O>,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Incomplete(err) => err.fmt(f),
      Self::Malformed(err) => err.fmt(f),
      Self::UnpairedSurrogate(err) => match err.hint() {
        UnpairedSurrogateHint::High => write!(
          f,
          "unpaired high surrogate in fixed-width unicode escape at {}",
          err.span(),
        ),
        UnpairedSurrogateHint::Low => write!(
          f,
          "unpaired low surrogate in fixed-width unicode escape at {}",
          err.span()
        ),
      },
    }
  }
}

impl<Char, O> core::error::Error for FixedUnicodeEscapeError<Char, O>
where
  Char: DisplayHuman + CharLen + core::fmt::Debug + 'static,
  O: core::fmt::Display + core::fmt::Debug + 'static + Clone + Ord,
  for<'a> &'a O: Add<usize, Output = O>,
{
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Incomplete(_) => None,
      Self::Malformed(err) => Some(err),
      Self::UnpairedSurrogate(err) => Some(err),
    }
  }
}

impl<Char, O> FixedUnicodeEscapeError<Char, O> {
  /// Creates an unpaired high surrogate error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::FixedUnicodeEscapeError;
  /// use tokit::utils::{Lexeme, SimpleSpan};
  ///
  /// let error = FixedUnicodeEscapeError::<char>::unpaired_high_surrogate(
  ///     Lexeme::Range(SimpleSpan::new(10, 16))
  /// );
  /// assert!(error.is_unpaired_surrogate());
  /// ```
  #[inline]
  pub const fn unpaired_high_surrogate(lexeme: Lexeme<Char, O>) -> Self {
    Self::UnpairedSurrogate(UnexpectedLexeme::new(lexeme, UnpairedSurrogateHint::High))
  }

  /// Creates an unpaired low surrogate error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::FixedUnicodeEscapeError;
  /// use tokit::utils::{Lexeme, SimpleSpan};
  ///
  /// let error = FixedUnicodeEscapeError::<char>::unpaired_low_surrogate(
  ///     Lexeme::Range(SimpleSpan::new(10, 16))
  /// );
  /// assert!(error.is_unpaired_surrogate());
  /// ```
  #[inline]
  pub const fn unpaired_low_surrogate(lexeme: Lexeme<Char, O>) -> Self {
    Self::UnpairedSurrogate(UnexpectedLexeme::new(lexeme, UnpairedSurrogateHint::Low))
  }

  /// Bumps the span or position of the error by `n`.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{FixedUnicodeEscapeError, IncompleteFixedUnicodeEscape};
  /// use tokit::utils::{Lexeme, SimpleSpan};
  ///
  /// let mut error: FixedUnicodeEscapeError =
  ///     FixedUnicodeEscapeError::Incomplete(IncompleteFixedUnicodeEscape::new(SimpleSpan::new(10, 14)));
  /// error.bump(5);
  /// // The span is now adjusted
  /// ```
  #[inline]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone,
  {
    match self {
      Self::Incomplete(lexeme) => {
        lexeme.bump(n);
      }
      Self::Malformed(seq) => {
        seq.bump(n);
      }
      Self::UnpairedSurrogate(lexeme) => {
        lexeme.bump(n);
      }
    }
    self
  }

  /// Returns the span of the error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{FixedUnicodeEscapeError, IncompleteFixedUnicodeEscape};
  /// use tokit::utils::{Lexeme, SimpleSpan};
  ///
  /// let error: FixedUnicodeEscapeError =
  ///    FixedUnicodeEscapeError::Incomplete(IncompleteFixedUnicodeEscape::new(SimpleSpan::new(
  ///       10, 14)));
  /// assert_eq!(error.span(), SimpleSpan::new(10, 14));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn span(&self) -> SimpleSpan<O>
  where
    Char: CharLen,
    O: Clone + Ord,
    for<'a> &'a O: Add<usize, Output = O>,
  {
    match self {
      Self::Incomplete(lexeme) => lexeme.span_ref().cloned(),
      Self::Malformed(seq) => seq.span_ref().cloned(),
      Self::UnpairedSurrogate(lexeme) => lexeme.span(),
    }
  }
}

/// An error encountered during lexing for unicode escape sequences.
///
/// This is the top-level error type for all unicode escape sequence failures.
/// It distinguishes between fixed-width (`\uXXXX`) and variable-length (`\u{...}`) formats.
///
/// # Variants
///
/// - **Fixed**: An error in a fixed-width unicode escape sequence (`\uXXXX`)
/// - **Variable**: An error in a variable-length unicode escape sequence (`\u{...}`)
///
/// # Examples
///
/// ## Fixed-Width Escape Errors
///
/// ```
/// use tokit::error::UnicodeEscapeError;
/// use tokit::utils::{Lexeme, SimpleSpan};
///
/// // Incomplete fixed-width escape: \uAB
/// let error = UnicodeEscapeError::<char>::incomplete_fixed_unicode_escape(
///     SimpleSpan::new(10, 14)
/// );
/// assert!(error.is_fixed());
///
/// // Unpaired high surrogate: \uD800
/// let error = UnicodeEscapeError::<char>::unpaired_high_surrogate(
///     Lexeme::Range(SimpleSpan::new(5, 11))
/// );
/// assert!(error.is_fixed());
/// ```
///
/// ## Variable-Length Escape Errors
///
/// ```
/// use tokit::error::UnicodeEscapeError;
/// use tokit::utils::SimpleSpan;
///
/// // Empty braces: \u{}
/// let error = UnicodeEscapeError::<char>::empty_variable_unicode_escape(
///     SimpleSpan::new(10, 14)
/// );
/// assert!(error.is_variable());
///
/// // Too many digits: \u{1234567}
/// let error = UnicodeEscapeError::<char>::too_many_digits_in_variable_unicode_escape(
///     SimpleSpan::new(5, 16),
///     7
/// );
/// assert!(error.is_variable());
///
/// // Surrogate value: \u{D800}
/// let error = UnicodeEscapeError::<char>::surrogate_variable_unicode_escape(
///     SimpleSpan::new(10, 18),
///     0xD800
/// );
/// assert!(error.is_variable());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, From, IsVariant, TryUnwrap, Unwrap)]
#[unwrap(ref, ref_mut)]
#[try_unwrap(ref, ref_mut)]
#[non_exhaustive]
pub enum UnicodeEscapeError<Char = char, O = usize> {
  /// An error in a fixed-width unicode escape sequence (`\uXXXX`).
  Fixed(FixedUnicodeEscapeError<Char, O>),
  /// An error in a variable-length unicode escape sequence (`\u{...}`).
  Variable(VariableUnicodeEscapeError<Char, O>),
}

impl<Char, O> core::fmt::Display for UnicodeEscapeError<Char, O>
where
  Char: DisplayHuman + CharLen,
  O: core::fmt::Display + Clone + Ord,
  for<'a> &'a O: Add<usize, Output = O>,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Fixed(err) => err.fmt(f),
      Self::Variable(err) => err.fmt(f),
    }
  }
}

impl<Char, O> core::error::Error for UnicodeEscapeError<Char, O>
where
  Char: DisplayHuman + CharLen + core::fmt::Debug + 'static,
  O: core::fmt::Display + core::fmt::Debug + Clone + Ord + 'static,
  for<'a> &'a O: Add<usize, Output = O>,
{
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Fixed(err) => Some(err),
      Self::Variable(err) => Some(err),
    }
  }
}

impl<Char, O> UnicodeEscapeError<Char, O> {
  /// Creates an unpaired high surrogate error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::UnicodeEscapeError;
  /// use tokit::utils::{Lexeme, SimpleSpan};
  ///
  /// let error = UnicodeEscapeError::<char>::unpaired_high_surrogate(
  ///     Lexeme::Range(SimpleSpan::new(10, 16))
  /// );
  /// assert!(error.is_fixed());
  /// ```
  #[inline]
  pub const fn unpaired_high_surrogate(lexeme: Lexeme<Char, O>) -> Self {
    Self::Fixed(FixedUnicodeEscapeError::unpaired_high_surrogate(lexeme))
  }

  /// Creates an unpaired low surrogate error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::UnicodeEscapeError;
  /// use tokit::utils::{Lexeme, SimpleSpan};
  ///
  /// let error = UnicodeEscapeError::<char>::unpaired_low_surrogate(
  ///     Lexeme::Range(SimpleSpan::new(10, 16))
  /// );
  /// assert!(error.is_fixed());
  /// ```
  #[inline]
  pub const fn unpaired_low_surrogate(lexeme: Lexeme<Char, O>) -> Self {
    Self::Fixed(FixedUnicodeEscapeError::unpaired_low_surrogate(lexeme))
  }

  /// Creates an incomplete fixed-width unicode escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::UnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = UnicodeEscapeError::<char>::incomplete_fixed_unicode_escape(
  ///     SimpleSpan::new(10, 14)
  /// );
  /// assert!(error.is_fixed());
  /// ```
  #[inline]
  pub const fn incomplete_fixed_unicode_escape(span: SimpleSpan<O>) -> Self {
    Self::Fixed(FixedUnicodeEscapeError::Incomplete(
      IncompleteFixedUnicodeEscape::new(span),
    ))
  }

  /// Creates a malformed fixed-width unicode escape sequence error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{UnicodeEscapeError, InvalidFixedUnicodeHexDigits};
  /// use tokit::utils::{SimpleSpan, PositionedChar};
  ///
  /// let digits = InvalidFixedUnicodeHexDigits::from(
  ///     PositionedChar::with_position('G', 12)
  /// );
  /// let error = UnicodeEscapeError::malformed_fixed_unicode_escape(
  ///     digits,
  ///     SimpleSpan::new(10, 16)
  /// );
  /// assert!(error.is_fixed());
  /// ```
  #[inline]
  pub const fn malformed_fixed_unicode_escape(
    digits: InvalidFixedUnicodeHexDigits<Char, O>,
    span: SimpleSpan<O>,
  ) -> Self {
    Self::Fixed(FixedUnicodeEscapeError::Malformed(
      MalformedFixedUnicodeEscape::new(digits, span),
    ))
  }

  /// Creates an empty variable-length unicode escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::UnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = UnicodeEscapeError::<char>::empty_variable_unicode_escape(
  ///     SimpleSpan::new(10, 14)
  /// );
  /// assert!(error.is_variable());
  /// ```
  #[inline]
  pub const fn empty_variable_unicode_escape(span: SimpleSpan<O>) -> Self {
    Self::Variable(VariableUnicodeEscapeError::empty(span))
  }

  /// Creates a too many digits in variable-length unicode escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::UnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = UnicodeEscapeError::<char>::too_many_digits_in_variable_unicode_escape(
  ///     SimpleSpan::new(5, 16),
  ///     7
  /// );
  /// assert!(error.is_variable());
  /// ```
  #[inline]
  pub const fn too_many_digits_in_variable_unicode_escape(
    span: SimpleSpan<O>,
    count: usize,
  ) -> Self {
    Self::Variable(VariableUnicodeEscapeError::too_many_digits(span, count))
  }

  /// Creates an unclosed brace in variable-length unicode escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::UnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = UnicodeEscapeError::<char>::unclosed_variable_unicode_escape(
  ///     SimpleSpan::new(10, 15)
  /// );
  /// assert!(error.is_variable());
  /// ```
  #[inline]
  pub const fn unclosed_variable_unicode_escape(span: SimpleSpan<O>) -> Self {
    Self::Variable(VariableUnicodeEscapeError::unclosed(span))
  }

  /// Creates a surrogate in variable-length unicode escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::UnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = UnicodeEscapeError::<char>::surrogate_variable_unicode_escape(
  ///     SimpleSpan::new(10, 18),
  ///     0xD800
  /// );
  /// assert!(error.is_variable());
  /// ```
  #[inline]
  pub const fn surrogate_variable_unicode_escape(span: SimpleSpan<O>, codepoint: u32) -> Self {
    Self::Variable(VariableUnicodeEscapeError::surrogate(span, codepoint))
  }

  /// Creates an overflow in variable-length unicode escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::UnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = UnicodeEscapeError::<char>::overflow_variable_unicode_escape(
  ///     SimpleSpan::new(10, 20),
  ///     0x110000
  /// );
  /// assert!(error.is_variable());
  /// ```
  #[inline]
  pub const fn overflow_variable_unicode_escape(span: SimpleSpan<O>, codepoint: u32) -> Self {
    Self::Variable(VariableUnicodeEscapeError::overflow(span, codepoint))
  }

  /// Creates a malformed variable-length unicode escape error from a character.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::UnicodeEscapeError;
  ///
  /// let error = UnicodeEscapeError::<char>::invalid_variable_unicode_escape_char(12, 'G');
  /// assert!(error.is_variable());
  /// ```
  #[inline]
  pub const fn invalid_variable_unicode_escape_char(pos: O, ch: Char) -> Self {
    Self::Variable(VariableUnicodeEscapeError::Malformed(
      MalformedVariableUnicodeSequence::from_char(pos, ch),
    ))
  }

  /// Creates a malformed variable-length unicode escape error from a span.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::UnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error: UnicodeEscapeError =
  ///     UnicodeEscapeError::<char>::invalid_variable_unicode_escape_sequence(
  ///         SimpleSpan::new(10, 15)
  ///     );
  /// assert!(error.is_variable());
  /// ```
  #[inline]
  pub const fn invalid_variable_unicode_escape_sequence(span: SimpleSpan<O>) -> Self {
    Self::Variable(VariableUnicodeEscapeError::Malformed(
      MalformedVariableUnicodeSequence::from_range(span),
    ))
  }

  /// Bumps the span or position of the error by `n`.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::UnicodeEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let mut error = UnicodeEscapeError::<char>::empty_variable_unicode_escape(
  ///     SimpleSpan::new(10, 14)
  /// );
  /// error.bump(5);
  /// // The span is now adjusted by 5
  /// ```
  #[inline]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone + Ord + core::hash::Hash,
  {
    match self {
      Self::Fixed(err) => {
        err.bump(n);
      }
      Self::Variable(err) => {
        err.bump(n);
      }
    }
    self
  }

  /// Returns the span of the error.
  ///
  /// ## Examples
  ///
  /// ```
  ///
  /// use tokit::error::UnicodeEscapeError;
  ///
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = UnicodeEscapeError::<char>::empty_variable_unicode_escape(
  ///    SimpleSpan::new(10, 14)
  /// );
  /// assert_eq!(error.span(), SimpleSpan::new(10, 14));
  /// ```
  #[inline]
  pub fn span(&self) -> SimpleSpan<O>
  where
    Char: CharLen,
    O: Clone + Ord,
    for<'a> &'a O: Add<usize, Output = O>,
  {
    match self {
      Self::Fixed(err) => err.span(),
      Self::Variable(err) => err.span(),
    }
  }
}