techy 0.2.0

A fast, extensible LaTeX parser for Rust
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
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
//! Structured diagnostics, the strict/tolerant recovery policy, and the parse abort
//! error.
//!
//! Everything a parse can complain about is described by a **condition**: a small data
//! value of a concrete public type, one type per kind of problem, whose fields say what
//! went wrong. A condition reaches the caller in one of two ways: as a [`Diagnostic`],
//! which a parse records and continues past, or as a [`ParseError`], which ends the
//! parse. Both store the condition itself, the [`SourceSpan`] where it occurred, and a
//! snapshot of the parse frames that were open at that moment ([`TraceFrame`]s); code
//! processing the tree after the parse can append outer frames to a `Diagnostic` with
//! [`Diagnostic::with_outer_frames`].
//!
//! The library reports its conditions only through these two types; it never writes them
//! to a logging side channel.
//!
//! # Tolerant parsing
//!
//! The [`Recovery`] policy, chosen on the parse driver, decides which of the two a
//! problem becomes:
//!
//! - [`Recovery::Tolerant`] — the condition is recorded as an error-severity
//!   [`Diagnostic`], the parser repairs the input at the point of detection in the way
//!   that condition type documents, and parsing continues.
//! - [`Recovery::Strict`] — the condition is returned as a [`ParseError`] and the parse
//!   aborts at the first problem.
//!
//! A tolerant parse therefore succeeds and still reports problems. `parse()` returns a
//! [`ParseResult`](crate::core::ParseResult) whose
//! [`tree`](crate::core::ParseResult::tree) covers the whole input and whose
//! [`diagnostics`](crate::core::ParseResult::diagnostics) field is a [`Diagnostics`]
//! collection holding what was recorded. Call
//! [`has_errors`](Diagnostics::has_errors) before treating the tree as clean,
//! [`render_all`](Diagnostics::render_all) to print a report, and
//! [`sorted_by_position`](Diagnostics::sorted_by_position) to read the problems in
//! document order rather than in the order the parse hit them.
//!
//! [`Severity`] is a separate axis from the recovery policy: it grades a diagnostic as a
//! note, a warning, or an error, and only errors make
//! [`has_errors`](Diagnostics::has_errors) true.
//!
//! # Working with conditions
//!
//! Neither type stores a message string. The human wording is computed from the
//! condition on demand ([`Diagnostic::message`], [`ParseError::message`]), and a full
//! report with position and traceback comes from [`Diagnostic::render`].
//!
//! To act on a condition programmatically, downcast it to its concrete type — the
//! condition is reached as [`Diagnostic::data`] and downcast with
//! [`downcast_ref`](trait.DiagnosticData.html#method.downcast_ref), or, over a whole
//! collection, with [`Diagnostics::conditions`].
//!
//! Where Rust types cannot travel — log lines, wire formats, configuration — use the
//! condition's identifier string, read from the type as [`DiagnosticInfo::IDENTIFIER`]
//! rather than written as a literal.
//!
//! Conditions of your own are ordinary conditions: implement [`DiagnosticInfo`] on a data
//! struct, normally with [`#[derive(DiagnosticInfo)]`](derive@DiagnosticInfo), and it
//! travels through the same types as the library's own. Library conditions are themselves
//! plain structs with public fields, defined next to the construct that detects them.
//!
//! # Spans outlive the parse
//!
//! Diagnostics and parse errors hold `Arc`-based [`SourceSpan`]s, so they are
//! self-contained values that outlive the parse that produced them, and no source
//! lifetime appears in error signatures.
//!
//! # Related error types
//!
//! [`ParseError`] ends construct parsing, and deliberately has **no** recovery payload:
//! nothing continues past one. The token-level error that does hold a recovery token,
//! [`TokenError`](crate::core::token::TokenError), is defined with the other token types,
//! though the [`Recovery`] policy governing it is defined here.
//!
//! # See also
//!
//! - [Running the parser](crate::guide::parsing#working-with-diagnostics) — choosing a
//!   recovery policy and working with what a parse reports.
//! - [The parsing model](crate::guide::parsing_model#how-problems-flow) — where
//!   conditions are detected and how the policy is applied to them.

use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::any::Any;
use core::fmt;

use crate::source::{
    LineColProvider, LineIndexCache, Source, SourceOrigin, SourceProvenance, SourceSpan,
};
use crate::token::TokenErrorKind;

// The condition-declaration derives (ARCHITECTURE.md "Condition declaration via
// derive"), re-exported next to the traits they implement: `#[derive(DiagnosticInfo)]`
// for condition structs, `#[derive(ToDiagnosticValue)]` for field-less payload enums.
pub use techy_derive::{DiagnosticInfo, ToDiagnosticValue};

/// Makes a data struct a parse **condition**: one kind of problem a parse can report.
///
/// The implementors listed below are the conditions the library itself reports. A
/// condition defined outside the library is indistinguishable from them — it is carried,
/// rendered, matched, and serialized by exactly the same machinery.
///
/// # Writing a condition type
///
/// A condition is a plain data struct whose public fields describe the problem. Four
/// things turn it into one:
///
/// - `Clone` and `Debug`, so the carriers can store and duplicate it;
/// - a `Display` implementation producing the human wording, computed from the fields
///   rather than stored as a message string;
/// - this trait, supplying the stable [`IDENTIFIER`](DiagnosticInfo::IDENTIFIER) and,
///   optionally, [`serializable_data`](DiagnosticInfo::serializable_data);
/// - by convention `#[non_exhaustive]` plus a constructor, so that fields can be added
///   later without breaking callers.
///
/// [`#[derive(DiagnosticInfo)]`](derive@DiagnosticInfo) writes all of that except the
/// fields themselves: the trait implementation, a `Display` implementation from a message
/// format string, and the constructor.
///
/// # How a condition is carried
///
/// [`DiagnosticData`] is the dyn-compatible form of this trait and is what [`Diagnostic`]
/// and [`ParseError`] store; it is blanket-implemented for every `DiagnosticInfo` type,
/// so a condition needs no further code to be reportable. Consumers get back to the
/// concrete struct by downcasting.
///
/// Downcasting works within one process. A diagnostic read back through
/// [`techy::serialize`](crate::serialize) has lost the original Rust type and carries a
/// [`DeserializedCondition`](crate::serialize::DeserializedCondition) instead, which
/// answers the written identifier, projection, and message.
pub trait DiagnosticInfo: Any + Clone + fmt::Display + fmt::Debug + Send + Sync {
    /// The condition's identity as a string: `<crate-or-lang>.<area>.<condition>`.
    ///
    /// This is the identity to use wherever Rust types cannot travel — log lines, wire
    /// formats, configuration that names conditions. Library conditions use the
    /// `core.<area>.*` namespace; presets and downstream languages use their own.
    ///
    /// It is chosen by hand and deliberately decoupled from the type and module name.
    /// It is part of the semantic-versioning contract: renaming the struct is an
    /// internal refactor, while changing this string silently breaks every consumer
    /// matching on it.
    ///
    /// At a comparison site, read it from the type (`MyCondition::IDENTIFIER`) instead of
    /// writing the string literally.
    const IDENTIFIER: &'static str;

    /// The identity a stored condition *instance* reports.
    ///
    /// This is what [`Diagnostic::identifier`] and [`ParseError::identifier`] return.
    /// The default implementation returns [`IDENTIFIER`](DiagnosticInfo::IDENTIFIER), and
    /// every ordinary condition keeps it: one Rust type, one compile-time identifier.
    ///
    /// Override it only where a compile-time identifier is impossible — in an **adapter
    /// type** for a language binding or embedding, where a single Rust struct carries
    /// conditions defined at run time on the other side of the boundary (conditions
    /// defined in Python, say) and stores each one's identifier in a field. Such an
    /// adapter still declares its own [`IDENTIFIER`](DiagnosticInfo::IDENTIFIER), which
    /// remains the type's identity for type-keyed uses; the override changes only what
    /// stored instances report.
    ///
    /// With both this trait and [`DiagnosticData`] in scope, an unqualified
    /// `.identifier()` call on a concrete condition type is ambiguous, because both
    /// traits supply the method (error E0034). Write `DiagnosticInfo::identifier(&c)` or
    /// `DiagnosticData::identifier(&c)`.
    fn identifier(&self) -> &str {
        Self::IDENTIFIER
    }

    /// This condition's field projection for the serialization boundary.
    ///
    /// It is used when a diagnostic is written out — through
    /// [`techy::serialize`](crate::serialize), or by generic tooling that renders
    /// conditions without knowing their types. It is not an access path for program
    /// logic: a consumer in the same process downcasts to the concrete struct, which
    /// stays the authoritative description of the payload.
    ///
    /// The default returns an empty map.
    /// [`#[derive(DiagnosticInfo)]`](derive@DiagnosticInfo) generates a map of every
    /// field, each converted through [`ToDiagnosticValue`].
    fn serializable_data(&self) -> DiagnosticValue {
        DiagnosticValue::empty_map()
    }
}

mod sealed {
    /// Seals [`DiagnosticData`](super::DiagnosticData).
    ///
    /// The blanket implementation over [`DiagnosticInfo`](super::DiagnosticInfo) is the
    /// only way to obtain it, so every stored condition is a `DiagnosticInfo` type and
    /// comes with a compile-time identifier by default; the per-instance
    /// [`identifier()`](super::DiagnosticInfo::identifier) override is the exceptional
    /// case, for binding and embedding adapter types.
    pub trait Sealed {}
}

impl<T: DiagnosticInfo> sealed::Sealed for T {}

/// The condition payload as [`Diagnostic`] and [`ParseError`] store it: the
/// dyn-compatible form of [`DiagnosticInfo`].
///
/// A value of this trait renders its human message through `Display` and answers its
/// [`identifier`](DiagnosticData::identifier), but says nothing about which condition it
/// is. To read the condition's own fields, downcast it to the concrete type with
/// [`downcast_ref`](trait.DiagnosticData.html#method.downcast_ref); that concrete struct
/// is a condition's identity within one process.
///
/// **Sealed**: the blanket implementation over [`DiagnosticInfo`] is the only one, so
/// implement `DiagnosticInfo` to make a type reportable.
pub trait DiagnosticData:
    Any + fmt::Display + fmt::Debug + Send + Sync + sealed::Sealed
{
    /// The condition's wire identity ([`DiagnosticInfo::identifier`] — for every
    /// ordinary condition, the [`IDENTIFIER`](DiagnosticInfo::IDENTIFIER) const).
    fn identifier(&self) -> &str;

    /// The condition's serialization-boundary projection
    /// ([`DiagnosticInfo::serializable_data`]).
    fn serializable_data(&self) -> DiagnosticValue;

    /// Clones the payload from behind the trait object.
    ///
    /// This is what makes [`Diagnostic`] and [`ParseError`] `Clone`; it is backed by the
    /// concrete condition type's own `Clone` implementation.
    fn clone_box(&self) -> Box<dyn DiagnosticData>;
}

impl<T: DiagnosticInfo> DiagnosticData for T {
    fn identifier(&self) -> &str {
        DiagnosticInfo::identifier(self)
    }

    fn serializable_data(&self) -> DiagnosticValue {
        DiagnosticInfo::serializable_data(self)
    }

    fn clone_box(&self) -> Box<dyn DiagnosticData> {
        Box::new(self.clone())
    }
}

impl dyn DiagnosticData {
    /// Returns whether the condition payload is a `T`.
    ///
    /// Use [`downcast_ref`](trait.DiagnosticData.html#method.downcast_ref) when the
    /// payload's fields are wanted as well.
    pub fn is<T: DiagnosticInfo>(&self) -> bool {
        (self as &dyn Any).is::<T>()
    }

    /// Returns the condition payload as its concrete type, or `None` if it is not a `T`.
    ///
    /// This is the way to read a condition's fields. The
    /// [`identifier`](DiagnosticData::identifier) string exists only for boundaries where
    /// Rust types cannot travel.
    pub fn downcast_ref<T: DiagnosticInfo>(&self) -> Option<&T> {
        (self as &dyn Any).downcast_ref::<T>()
    }
}

impl Clone for Box<dyn DiagnosticData> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

/// A small value tree: what a condition's fields project to at the serialization
/// boundary ([`DiagnosticInfo::serializable_data`]).
///
/// The set of variants is deliberately minimal. In particular there is no float variant;
/// a condition with a floating-point field projects it as a string.
///
/// A `DiagnosticValue` converts into a [`SerialValue`](crate::serialize::SerialValue)
/// (the `From` implementations are in [`techy::serialize`](crate::serialize)). With the
/// `serde` cargo feature it implements `Serialize` and `Deserialize` through that
/// conversion, so it renders exactly as the corresponding `SerialValue` does, and reading
/// back accepts only the kinds this tree can hold.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiagnosticValue {
    /// No value.
    Null,
    /// A boolean.
    Bool(bool),
    /// An integer.
    Int(i64),
    /// A string.
    Str(String),
    /// An ordered list of values.
    List(Vec<DiagnosticValue>),
    /// An ordered map of named values.
    Map(Vec<(String, DiagnosticValue)>),
}

impl DiagnosticValue {
    /// Returns an empty [`Map`](DiagnosticValue::Map).
    ///
    /// This is the default projection of a condition that serializes no fields — the
    /// value returned by the default
    /// [`serializable_data`](DiagnosticInfo::serializable_data).
    pub fn empty_map() -> DiagnosticValue {
        DiagnosticValue::Map(Vec::new())
    }
}

/// Converts one field of a condition into its [`DiagnosticValue`] projection.
///
/// This is the bridge behind the
/// [`serializable_data`](DiagnosticInfo::serializable_data) implementation that
/// [`#[derive(DiagnosticInfo)]`](derive@DiagnosticInfo) generates: the derive routes
/// every field of the condition through this trait.
///
/// Implementations are provided for the types condition payloads normally hold —
/// booleans, integers, `char`, strings, `Option`, slices and `Vec`, references, and
/// `DiagnosticValue` itself.
///
/// A field whose type does not implement this trait is rejected by the compiler at the
/// field's own declaration, so whether a payload can be serialized is decided by trait
/// bounds rather than by a check inside the macro. A field-less enum gets an
/// implementation from [`#[derive(ToDiagnosticValue)]`](derive@ToDiagnosticValue), which
/// projects the variant name in kebab case; any other type can implement the trait by
/// hand.
pub trait ToDiagnosticValue {
    /// Returns this value's projection for the serialization boundary.
    fn to_diagnostic_value(&self) -> DiagnosticValue;
}

impl ToDiagnosticValue for bool {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        DiagnosticValue::Bool(*self)
    }
}

/// Integers that fit `i64` losslessly.
macro_rules! int_to_diagnostic_value {
    ($($t:ty),*) => {$(
        impl ToDiagnosticValue for $t {
            fn to_diagnostic_value(&self) -> DiagnosticValue {
                DiagnosticValue::Int(i64::from(*self))
            }
        }
    )*};
}
int_to_diagnostic_value!(i8, i16, i32, i64, u8, u16, u32);

/// Integers that may exceed `i64`: the projection saturates at `i64::MAX` rather than
/// failing or panicking.
macro_rules! saturating_int_to_diagnostic_value {
    ($($t:ty),*) => {$(
        impl ToDiagnosticValue for $t {
            fn to_diagnostic_value(&self) -> DiagnosticValue {
                DiagnosticValue::Int(i64::try_from(*self).unwrap_or(i64::MAX))
            }
        }
    )*};
}
saturating_int_to_diagnostic_value!(u64, usize);

impl ToDiagnosticValue for isize {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        // isize is at most 64 bits on every supported target; the cast is lossless.
        DiagnosticValue::Int(*self as i64)
    }
}

impl ToDiagnosticValue for char {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        DiagnosticValue::Str(String::from(*self))
    }
}

impl ToDiagnosticValue for str {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        DiagnosticValue::Str(String::from(self))
    }
}

impl ToDiagnosticValue for String {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        DiagnosticValue::Str(self.clone())
    }
}

impl<T: ToDiagnosticValue> ToDiagnosticValue for Option<T> {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        match self {
            Some(value) => value.to_diagnostic_value(),
            None => DiagnosticValue::Null,
        }
    }
}

impl<T: ToDiagnosticValue> ToDiagnosticValue for [T] {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        DiagnosticValue::List(self.iter().map(T::to_diagnostic_value).collect())
    }
}

impl<T: ToDiagnosticValue> ToDiagnosticValue for Vec<T> {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        self.as_slice().to_diagnostic_value()
    }
}

impl<T: ToDiagnosticValue + ?Sized> ToDiagnosticValue for &T {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        (**self).to_diagnostic_value()
    }
}

impl ToDiagnosticValue for DiagnosticValue {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        self.clone()
    }
}

/// Converts a [`ResolveError`](crate::source::ResolveError) into a map with these
/// entries, in this order:
///
/// - `reference`: the reference that failed to resolve;
/// - `message`: the message of the error;
/// - `kind`: the [kind](crate::source::ResolveError::kind) of the error, in kebab case
///   (`other`, `not-found`, `include-cycle` or `include-depth-exceeded`);
/// - `cause_chain`: the `Display` texts of the underlying errors, as a list that begins
///   with the cause of the `ResolveError` and follows
///   [`Error::source`](core::error::Error::source) from there.
///
/// This map is the diagnostic value of the `error` field of the
/// [`UnresolvableSourceReference`](crate::core::constructs::UnresolvableSourceReference)
/// condition.
// The implementation is here rather than in the source module: the error module may
// depend on source types, never the reverse.
impl ToDiagnosticValue for crate::source::ResolveError {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        let mut chain: Vec<DiagnosticValue> = Vec::new();
        let mut cause = core::error::Error::source(self);
        while let Some(error) = cause {
            chain.push(DiagnosticValue::Str(error.to_string()));
            cause = error.source();
        }
        let kind = match self.kind() {
            crate::source::ResolveErrorKind::Other => "other",
            crate::source::ResolveErrorKind::NotFound => "not-found",
            crate::source::ResolveErrorKind::IncludeCycle => "include-cycle",
            crate::source::ResolveErrorKind::IncludeDepthExceeded => "include-depth-exceeded",
        };
        DiagnosticValue::Map(alloc::vec![
            ("reference".to_string(), DiagnosticValue::Str(self.reference().to_string())),
            ("message".to_string(), DiagnosticValue::Str(self.message().to_string())),
            ("kind".to_string(), DiagnosticValue::Str(kind.to_string())),
            ("cause_chain".to_string(), DiagnosticValue::List(chain)),
        ])
    }
}

/// Projects as the rendered cause chain: a list holding the error's own `Display`,
/// then that of each [`Error::source`](core::error::Error::source) hop, outermost
/// first.
///
/// `Arc<dyn Error + Send + Sync>` is the shape a condition's optional underlying-cause
/// field takes — see [`HookFailed::cause`], which follows the
/// [`ResolveError`](crate::source::ResolveError) pattern. Sharing the error through an
/// `Arc` is what keeps such a condition `Clone`.
impl ToDiagnosticValue for Arc<dyn core::error::Error + Send + Sync + 'static> {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        let mut chain: Vec<DiagnosticValue> = Vec::new();
        chain.push(DiagnosticValue::Str(self.to_string()));
        let mut cause = core::error::Error::source(&**self);
        while let Some(error) = cause {
            chain.push(DiagnosticValue::Str(error.to_string()));
            cause = error.source();
        }
        DiagnosticValue::List(chain)
    }
}

/// One frame of a traceback: what the parse, or processing after it, had descended into,
/// and where.
///
/// The [`title`](TraceFrame::title) is already rendered for display (`group ‘{’`,
/// `argument #1 of ‘\frac’`), and the [`span`](TraceFrame::span) is the source location
/// the parse descended at.
///
/// [`Diagnostic`] and [`ParseError`] store a list of these, **innermost first**, as a
/// snapshot of the frames that were open when the problem was reported. The recovery
/// entry point,
/// [`ParseContext::recover`](crate::core::constructs::ParseContext::recover), takes that
/// snapshot from the session's live frame stack. Processing after the parse appends
/// frames of its own with
/// [`Diagnostic::with_outer_frames`](Diagnostic::with_outer_frames).
///
/// Unlike the live [`Frame`](crate::core::Frame), a `TraceFrame` is not generic over the
/// language — only over the source origin — so diagnostics produced by parses of
/// different languages can be collected together.
#[derive(Debug, Clone)]
pub struct TraceFrame<O: SourceOrigin = Option<String>> {
    title: String,
    span: SourceSpan<O>,
}

impl<O: SourceOrigin> TraceFrame<O> {
    /// Creates a traceback frame from an already-rendered title and the location the
    /// parse descended at.
    pub fn new(title: impl Into<String>, span: SourceSpan<O>) -> TraceFrame<O> {
        TraceFrame { title: title.into(), span }
    }

    /// The rendered frame title.
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Where in the source the parse descended into this frame.
    pub fn span(&self) -> &SourceSpan<O> {
        &self.span
    }
}

/// How severe a [`Diagnostic`] is.
///
/// The derived ordering ranks `Note < Warning < Error`, so filtering on a threshold
/// ("warnings and above") is a comparison.
///
/// Severity is independent of the [`Recovery`] policy. Problems reported through the
/// recovery entry point are always recorded at [`Error`](Severity::Error); the library's
/// [`Warning`](Severity::Warning) and [`Note`](Severity::Note) diagnostics come from
/// places that never abort a parse, such as
/// [`DescentLimitApproaching`](crate::core::constructs::DescentLimitApproaching), or
/// from checks run outside a parse, such as
/// [`ProviderCommandsShadowedByEscape`](crate::core::specs::ProviderCommandsShadowedByEscape).
/// Presets and embedders can record diagnostics at any severity through
/// [`Diagnostic::warning`] and [`Diagnostic::note`].
///
/// Only error-severity diagnostics count toward
/// [`Diagnostics::has_errors`](Diagnostics::has_errors).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    /// Informational note.
    Note,
    /// Something suspicious that did not prevent parsing, and produced no recovery.
    Warning,
    /// A genuine error: the document is wrong, or a parse could not do what was asked.
    ///
    /// Under [`Recovery::Tolerant`] such a condition is recorded here instead of
    /// aborting the parse; under [`Recovery::Strict`] it becomes a [`ParseError`].
    Error,
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Severity::Note => "note",
            Severity::Warning => "warning",
            Severity::Error => "error",
        })
    }
}

/// One problem reported during a parse: a condition, its severity, and where it
/// occurred.
///
/// A tolerant parse collects these in a [`Diagnostics`] collection, reached as the
/// [`diagnostics`](crate::core::ParseResult::diagnostics) field of the
/// [`ParseResult`](crate::core::ParseResult). Code outside the parser creates them with
/// [`error`](Diagnostic::error), [`warning`](Diagnostic::warning),
/// [`note`](Diagnostic::note), or [`new`](Diagnostic::new).
///
/// The condition is stored as structured data rather than as a message string: read its
/// fields by downcasting [`data`](Diagnostic::data), get the human wording from
/// [`message`](Diagnostic::message), and a full report with position and traceback from
/// [`render`](Diagnostic::render).
///
/// [`frames`](Diagnostic::frames) is the traceback of parse frames that were open when
/// the problem was reported; the recovery entry point,
/// [`ParseContext::recover`](crate::core::constructs::ParseContext::recover), attaches
/// it; processing after the parse may append outer frames with
/// [`with_outer_frames`](Diagnostic::with_outer_frames).
///
/// `Diagnostic` deliberately does not implement `PartialEq`, since conditions are
/// compared through a trait object that hides their type. Compare
/// [`identifier()`](Diagnostic::identifier) and the fields of the downcast condition
/// instead.
#[derive(Debug, Clone)]
pub struct Diagnostic<O: SourceOrigin = Option<String>> {
    severity: Severity,
    data: Box<dyn DiagnosticData>,
    span: SourceSpan<O>,
    /// Traceback snapshot, innermost first.
    frames: Vec<TraceFrame<O>>,
}

impl<O: SourceOrigin> Diagnostic<O> {
    /// Creates a diagnostic from a condition, at the given severity and span.
    ///
    /// The traceback is empty; a parse attaches frames through the recovery entry point,
    /// [`ParseContext::recover`](crate::core::constructs::ParseContext::recover); code
    /// outside the parse appends frames with
    /// [`with_outer_frames`](Diagnostic::with_outer_frames).
    ///
    /// [`error`](Diagnostic::error), [`warning`](Diagnostic::warning) and
    /// [`note`](Diagnostic::note) are the shorthands for the three severities.
    pub fn new(
        severity: Severity,
        condition: impl DiagnosticInfo,
        span: SourceSpan<O>,
    ) -> Self {
        Diagnostic { severity, data: Box::new(condition), span, frames: Vec::new() }
    }

    /// Creates a diagnostic at [`Severity::Error`].
    pub fn error(condition: impl DiagnosticInfo, span: SourceSpan<O>) -> Self {
        Diagnostic::new(Severity::Error, condition, span)
    }

    /// Creates a diagnostic at [`Severity::Warning`].
    pub fn warning(condition: impl DiagnosticInfo, span: SourceSpan<O>) -> Self {
        Diagnostic::new(Severity::Warning, condition, span)
    }

    /// Creates a diagnostic at [`Severity::Note`].
    pub fn note(condition: impl DiagnosticInfo, span: SourceSpan<O>) -> Self {
        Diagnostic::new(Severity::Note, condition, span)
    }

    /// Assembles a diagnostic from parts already prepared by the recovery path: a
    /// condition boxed after the driver's refinement pass, and a frame snapshot.
    pub(crate) fn from_parts(
        severity: Severity,
        data: Box<dyn DiagnosticData>,
        span: SourceSpan<O>,
        frames: Vec<TraceFrame<O>>,
    ) -> Self {
        Diagnostic { severity, data, span, frames }
    }

    /// Appends frames that enclose the ones already stored.
    ///
    /// The appended frames are the outer ones: the activities the diagnostic's own
    /// frames were nested in, innermost first. They are stored after the frames already
    /// present, which stay first. Code that processes a parsed tree after the parse, for
    /// instance a framework transforming it, uses this to record where it was when the
    /// condition was reported, as in "while processing the copy of a heading's title
    /// shown by a reference". The diagnostic's own [`span`](Diagnostic::span) is
    /// unchanged, so the report keeps pointing to where the content was written.
    ///
    /// An empty `frames` changes nothing. The parse itself never calls this; its
    /// frames arrive through the recovery entry point,
    /// [`ParseContext::recover`](crate::core::constructs::ParseContext::recover).
    pub fn with_outer_frames(mut self, frames: Vec<TraceFrame<O>>) -> Self {
        self.frames.extend(frames);
        self
    }

    /// The severity of this diagnostic.
    pub fn severity(&self) -> Severity {
        self.severity
    }

    /// The condition that was reported.
    ///
    /// Downcast it with
    /// [`downcast_ref`](trait.DiagnosticData.html#method.downcast_ref) to read the
    /// condition's own fields.
    pub fn data(&self) -> &dyn DiagnosticData {
        &*self.data
    }

    /// The condition's identifier string, for boundaries where Rust types cannot travel.
    ///
    /// For every ordinary condition this is the type's
    /// [`IDENTIFIER`](DiagnosticInfo::IDENTIFIER) constant; see
    /// [`DiagnosticInfo::identifier`] for the adapter-type exception. Compare it against
    /// `T::IDENTIFIER` rather than against a string literal.
    pub fn identifier(&self) -> &str {
        self.data.identifier()
    }

    /// The human-readable message, rendered from the condition's `Display`.
    ///
    /// This allocates a fresh `String` on each call; the condition is the stored value,
    /// the message is derived from it.
    pub fn message(&self) -> String {
        self.data.to_string()
    }

    /// Where in the source the condition occurred.
    pub fn span(&self) -> &SourceSpan<O> {
        &self.span
    }

    /// The traceback frames, innermost first: the parse frames that were open when the
    /// condition was recorded, followed by any outer frames appended afterwards with
    /// [`with_outer_frames`](Diagnostic::with_outer_frames).
    ///
    /// Empty when the diagnostic was recorded outside a parse descent and nothing was
    /// appended. Format them with [`format_traceback`].
    pub fn frames(&self) -> &[TraceFrame<O>] {
        &self.frames
    }

    /// Renders a human-readable, multi-line report of this diagnostic.
    ///
    /// The report holds the message, the position (line and column, plus the source's
    /// origin label when it has one), the traceback ([`format_traceback`]), and the
    /// source's provenance chain, as `included from …` or `synthesized from …` lines.
    ///
    /// Line and column numbers are computed through a [`LineIndexCache`] created for this
    /// call and dropped with it. Use [`render_with`](Diagnostic::render_with) to supply a
    /// cache that persists across calls, or [`Diagnostics::render_all`] for a whole
    /// collection.
    pub fn render(&self) -> String {
        self.render_with(&mut LineIndexCache::new())
    }

    /// [`render`](Diagnostic::render) with a caller-supplied [`LineColProvider`]
    /// answering the line and column lookups.
    ///
    /// Pass a [`LineIndexCache`] kept across renders, so that each source is indexed only
    /// once however many diagnostics are rendered from it, or an editor's own incremental
    /// line table.
    pub fn render_with(&self, line_cols: &mut impl LineColProvider<O>) -> String {
        render_report(line_cols, &self.to_string(), &self.span, &self.frames)
    }
}

impl<O: SourceOrigin> fmt::Display for Diagnostic<O> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.severity, self.data)
    }
}

/// The [`Diagnostic`]s recorded during one parse, in the order the parse reported them.
///
/// This is the type of the [`diagnostics`](crate::core::ParseResult::diagnostics) field
/// of a [`ParseResult`](crate::core::ParseResult), and is where a caller looks after a
/// tolerant parse. Ask [`has_errors`](Diagnostics::has_errors) whether anything serious
/// happened, [`iter`](Diagnostics::iter) over the diagnostics, print them all with
/// [`render_all`](Diagnostics::render_all), and use
/// [`sorted_by_position`](Diagnostics::sorted_by_position) for a report that reads along
/// the document instead of following the parse.
///
/// To find specific problems, [`conditions`](Diagnostics::conditions) yields the
/// condition payloads of one concrete type, and
/// [`with_identifier`](Diagnostics::with_identifier) selects by identifier string.
///
/// # Bounded retention
///
/// At most [`limit`](Diagnostics::limit) diagnostics are stored — the
/// [`DEFAULT_LIMIT`](Diagnostics::DEFAULT_LIMIT), unless the collection was created with
/// [`with_limit`](Diagnostics::with_limit).
///
/// The cap exists because tolerant parsing of degenerate input can produce one diagnostic
/// per byte, which would otherwise mean unbounded allocation.
///
/// Diagnostics pushed beyond the cap are dropped, but not forgotten: they are counted by
/// [`suppressed`](Diagnostics::suppressed), reported by
/// [`render_all`](Diagnostics::render_all) as an "… and N more" line, and error-severity
/// ones still make [`has_errors`](Diagnostics::has_errors) true.
///
/// # Deserialized diagnostics
///
/// Diagnostics read back through [`techy::serialize`](crate::serialize), inside a
/// deserialized parse result, have lost their original Rust types and carry
/// [`DeserializedCondition`](crate::serialize::DeserializedCondition)s. Match those with
/// [`with_identifier`](Diagnostics::with_identifier); a
/// [`conditions::<T>()`](Diagnostics::conditions) call yields nothing for them.
#[derive(Debug, Clone)]
pub struct Diagnostics<O: SourceOrigin = Option<String>> {
    items: Vec<Diagnostic<O>>,
    /// Maximum number of retained diagnostics.
    limit: usize,
    /// Diagnostics pushed beyond `limit` (counted, not stored).
    suppressed: usize,
    /// Error-severity pushes, retained *and* suppressed — keeps `has_errors` truthful
    /// when errors arrive after the cap.
    error_count: usize,
}

impl<O: SourceOrigin> Diagnostics<O> {
    /// The retention cap a collection gets when none is specified.
    ///
    /// It is generous for any human- or tool-facing report, and small enough that
    /// degenerate tolerant-mode input cannot exhaust memory. Choose a different one with
    /// [`with_limit`](Diagnostics::with_limit).
    pub const DEFAULT_LIMIT: usize = 1000;

    /// Creates an empty collection with the
    /// [`DEFAULT_LIMIT`](Diagnostics::DEFAULT_LIMIT) retention cap.
    pub fn new() -> Self {
        Diagnostics::with_limit(Diagnostics::<O>::DEFAULT_LIMIT)
    }

    /// Creates an empty collection retaining at most `limit` diagnostics.
    ///
    /// Pushes beyond the cap are counted as [`suppressed`](Diagnostics::suppressed)
    /// instead of being stored. The collection a parse fills is created for you; set its
    /// cap through
    /// [`ParseDriver::diagnostics_limit`](crate::core::ParseDriver::diagnostics_limit).
    ///
    /// A limit above `i64::MAX` — `usize::MAX`, meaning "no cap" — is accepted here, but
    /// a parse result holding such a collection cannot be serialized, because the
    /// serialized form's integers are `i64`. See
    /// [`ParseResultSerialization`](crate::serialize::ParseResultSerialization).
    pub fn with_limit(limit: usize) -> Self {
        Diagnostics { items: Vec::new(), limit, suppressed: 0, error_count: 0 }
    }

    /// Assembles a collection from the parts a serialized collection recorded — the
    /// entry point for reading one back.
    ///
    /// The parts are what a collection reports about itself: `items` are the diagnostics
    /// it stored, in the order [`iter`](Diagnostics::iter) yields them; `limit` is the
    /// retention cap they were stored under ([`limit`](Diagnostics::limit));
    /// `suppressed` is the number of pushes dropped beyond that cap
    /// ([`suppressed`](Diagnostics::suppressed)); and `error_count` is the number of
    /// error-severity pushes in all, stored and suppressed together
    /// ([`error_count`](Diagnostics::error_count)).
    ///
    /// Use this to rebuild a collection from a serialized form — the one
    /// [`techy::serialize`](crate::serialize) writes, a wire format of your own, or a
    /// language binding handing the counts back. A collection filled diagnostic by
    /// diagnostic is built with [`with_limit`](Diagnostics::with_limit) and
    /// [`push`](Diagnostics::push) instead.
    ///
    /// # Errors
    ///
    /// The parts must satisfy the invariants [`push`](Diagnostics::push) maintains, and
    /// [`InconsistentDiagnosticCounts`] is returned when they do not:
    ///
    /// - `items.len() <= limit`;
    /// - `suppressed > 0` only when `items.len() == limit`;
    /// - `error_count` is at least the number of error-severity `items`, and at most that
    ///   number plus `suppressed`.
    pub fn from_parts(
        items: Vec<Diagnostic<O>>,
        limit: usize,
        suppressed: usize,
        error_count: usize,
    ) -> Result<Self, InconsistentDiagnosticCounts> {
        let retained_errors =
            items.iter().filter(|diagnostic| diagnostic.severity == Severity::Error).count();
        let consistent = items.len() <= limit
            && (suppressed == 0 || items.len() == limit)
            && retained_errors <= error_count
            && error_count <= retained_errors.saturating_add(suppressed);
        if !consistent {
            return Err(InconsistentDiagnosticCounts {
                retained: items.len(),
                retained_errors,
                limit,
                suppressed,
                error_count,
            });
        }
        Ok(Diagnostics { items, limit, suppressed, error_count })
    }

    /// Appends a diagnostic.
    ///
    /// Once [`limit`](Diagnostics::limit) diagnostics are stored, further ones are
    /// dropped and only counted: they raise [`suppressed`](Diagnostics::suppressed), and
    /// an error-severity one still makes [`has_errors`](Diagnostics::has_errors) true.
    pub fn push(&mut self, diagnostic: Diagnostic<O>) {
        if diagnostic.severity == Severity::Error {
            self.error_count += 1;
        }
        if self.items.len() < self.limit {
            self.items.push(diagnostic);
        } else {
            self.suppressed += 1;
        }
    }

    /// The number of diagnostics stored, not counting
    /// [`suppressed`](Diagnostics::suppressed) ones.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Returns whether the parse reported nothing at all — nothing stored, and nothing
    /// suppressed.
    pub fn is_empty(&self) -> bool {
        self.items.is_empty() && self.suppressed == 0
    }

    /// The retention cap this collection was created with, beyond which diagnostics are
    /// counted rather than stored.
    pub fn limit(&self) -> usize {
        self.limit
    }

    /// The number of diagnostics dropped because the retention cap was reached.
    pub fn suppressed(&self) -> usize {
        self.suppressed
    }

    /// Returns whether the parse reported any error-severity diagnostic, stored or
    /// suppressed.
    ///
    /// This is the check to make on a tolerant parse before treating its tree as a clean
    /// parse of the input.
    pub fn has_errors(&self) -> bool {
        self.error_count > 0
    }

    /// The number of error-severity diagnostics reported, stored and suppressed
    /// together — the count [`has_errors`](Diagnostics::has_errors) tests against zero.
    pub fn error_count(&self) -> usize {
        self.error_count
    }

    /// Iterates over the stored diagnostics in the order the parse recorded them.
    ///
    /// For document order, use
    /// [`sorted_by_position`](Diagnostics::sorted_by_position).
    pub fn iter(&self) -> core::slice::Iter<'_, Diagnostic<O>> {
        self.items.iter()
    }

    /// The diagnostics whose condition answers the given
    /// [`identifier`](Diagnostic::identifier), in recording order.
    ///
    /// Take the identifier from the condition type (`T::IDENTIFIER`) rather than writing
    /// it as a literal. This is the way to select
    /// [deserialized diagnostics](Diagnostics#deserialized-diagnostics), whose original
    /// types are gone; within one process, [`conditions`](Diagnostics::conditions) is the
    /// typed equivalent.
    pub fn with_identifier<'a>(
        &'a self,
        identifier: &'a str,
    ) -> impl Iterator<Item = &'a Diagnostic<O>> {
        self.items.iter().filter(move |d| d.identifier() == identifier)
    }

    /// The recorded conditions of concrete type `T`, in recording order.
    ///
    /// Each stored condition is downcast to `T` and the ones that are not a `T` are
    /// skipped. Iterate with [`iter`](Diagnostics::iter) instead when the span or
    /// severity is needed alongside the condition.
    pub fn conditions<T: DiagnosticInfo>(&self) -> impl Iterator<Item = &T> {
        self.items.iter().filter_map(|d| d.data().downcast_ref::<T>())
    }

    /// The stored diagnostics as a slice, in recording order.
    pub fn as_slice(&self) -> &[Diagnostic<O>] {
        &self.items
    }

    /// The stored diagnostics ordered by source position, for a report that reads along
    /// the document.
    ///
    /// A parse records diagnostics in the order it hits them, which nested descents and
    /// deferred recoveries can permute relative to the document. This view re-sorts them
    /// by source and then by span start, so that within each source they appear in
    /// document order.
    ///
    /// Sources themselves are ordered by first appearance in the recorded sequence, and
    /// matched by `Arc` identity. That is the only cross-source claim made: a document
    /// can be parsed from several sources at once (an `\input`-like inclusion attaches
    /// another one), and a total position order across separate sources has no meaning.
    ///
    /// The sort is stable, so diagnostics at equal positions keep their recording order.
    /// The collection itself is unchanged; the returned vector borrows from it.
    pub fn sorted_by_position(&self) -> Vec<&Diagnostic<O>> {
        let mut sources: Vec<&Arc<Source<O>>> = Vec::new();
        let mut keyed: Vec<(usize, usize, usize)> =
            Vec::with_capacity(self.items.len());
        for (arrival, diagnostic) in self.items.iter().enumerate() {
            let source = diagnostic.span().source();
            let source_index = sources
                .iter()
                .position(|known| Arc::ptr_eq(known, source))
                .unwrap_or_else(|| {
                    sources.push(source);
                    sources.len() - 1
                });
            keyed.push((source_index, diagnostic.span().start(), arrival));
        }
        // The arrival index is part of the key, so equal positions keep recovery
        // order (and the unstable sort is de-facto stable).
        keyed.sort_unstable();
        keyed.into_iter().map(|(_, _, arrival)| &self.items[arrival]).collect()
    }

    /// Renders every stored diagnostic into one human-readable report.
    ///
    /// The report holds the [`Diagnostic::render`] blocks in recording order, separated
    /// by blank lines, and ends with an "… and N more" line when diagnostics were
    /// [`suppressed`](Diagnostics::suppressed) beyond the retention cap.
    ///
    /// This is the call to use for a whole collection. All positions are resolved through
    /// one [`LineIndexCache`], created for this call, which indexes each distinct source
    /// once (sources matched by `Arc` identity); calling
    /// [`render`](Diagnostic::render) in a loop instead rebuilds the line index for every
    /// diagnostic. Provenance chains are resolved through the same cache, so each
    /// including document is also indexed once.
    ///
    /// Use [`render_all_with`](Diagnostics::render_all_with) to supply a cache that
    /// persists across reports.
    pub fn render_all(&self) -> String {
        self.render_all_with(&mut LineIndexCache::new())
    }

    /// [`render_all`](Diagnostics::render_all) with a caller-supplied
    /// [`LineColProvider`] answering the line and column lookups.
    ///
    /// Pass a [`LineIndexCache`] kept across reports, or an editor's own incremental line
    /// table.
    pub fn render_all_with(&self, line_cols: &mut impl LineColProvider<O>) -> String {
        let mut out = String::new();
        for (i, diagnostic) in self.items.iter().enumerate() {
            if i > 0 {
                out.push_str("\n\n");
            }
            out.push_str(&render_report(
                line_cols,
                &diagnostic.to_string(),
                &diagnostic.span,
                &diagnostic.frames,
            ));
        }
        if self.suppressed > 0 {
            if !out.is_empty() {
                out.push_str("\n\n");
            }
            out.push_str(&format!(
                "… and {} more {} (retention limit of {} reached)",
                self.suppressed,
                if self.suppressed == 1 { "diagnostic" } else { "diagnostics" },
                self.limit,
            ));
        }
        out
    }
}

// Deliberately no `Extend`/`FromIterator` yet (no merging consumer exists). A future
// impl must merge `suppressed` and `error_count` alongside `items` — plain item
// concatenation would silently launder suppressed errors.
impl<O: SourceOrigin> Default for Diagnostics<O> {
    fn default() -> Self {
        Diagnostics::new()
    }
}

impl<O: SourceOrigin> IntoIterator for Diagnostics<O> {
    type Item = Diagnostic<O>;
    type IntoIter = alloc::vec::IntoIter<Diagnostic<O>>;

    fn into_iter(self) -> Self::IntoIter {
        self.items.into_iter()
    }
}

impl<'a, O: SourceOrigin> IntoIterator for &'a Diagnostics<O> {
    type Item = &'a Diagnostic<O>;
    type IntoIter = core::slice::Iter<'a, Diagnostic<O>>;

    fn into_iter(self) -> Self::IntoIter {
        self.items.iter()
    }
}

/// The error that [`Diagnostics::from_parts`] returns when the parts it is given are
/// inconsistent.
///
/// The parts are inconsistent when no collection filled through [`Diagnostics::push`]
/// could have these counts, for instance when more diagnostics are supplied than the
/// retention limit allows. The rules that the parts must follow are listed on
/// [`from_parts`](Diagnostics::from_parts). The fields contain the counts of the parts
/// as they were given.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct InconsistentDiagnosticCounts {
    /// The number of diagnostics supplied.
    pub retained: usize,
    /// The number of supplied diagnostics with error severity.
    pub retained_errors: usize,
    /// The retention limit supplied.
    pub limit: usize,
    /// The number of suppressed diagnostics supplied.
    pub suppressed: usize,
    /// The error count supplied: the number of diagnostics with error severity,
    /// retained and suppressed together.
    pub error_count: usize,
}

// Hand-written wording: the message states the rule that the counts break, and the
// counts need number agreement.
impl fmt::Display for InconsistentDiagnosticCounts {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let InconsistentDiagnosticCounts {
            retained,
            retained_errors,
            limit,
            suppressed,
            error_count,
        } = *self;
        let rule = if retained > limit {
            "the supplied diagnostics may not exceed the retention limit"
        } else if suppressed > 0 && retained != limit {
            "suppressed diagnostics require the supplied diagnostics to reach the \
             retention limit"
        } else if retained_errors > error_count {
            "the error count may not be lower than the number of supplied errors"
        } else {
            "the error count may not exceed the supplied errors plus the suppressed \
             diagnostics"
        };
        write!(
            f,
            "Inconsistent diagnostic counts: {rule} ({retained} diagnostic{} supplied, \
             {retained_errors} error{} among them; {suppressed} suppressed; error count \
             {error_count}; retention limit {limit})",
            if retained == 1 { "" } else { "s" },
            if retained_errors == 1 { "" } else { "s" },
        )
    }
}

impl core::error::Error for InconsistentDiagnosticCounts {}

/// Whether a parse aborts at the first problem or records it and carries on.
///
/// This is the parse-wide policy, set on the parse driver — for the preset, as the
/// argument of [`LatexlikeDriver::new`](crate::latexlike::LatexlikeDriver::new) — and
/// applied wherever a construct parser reports a condition.
///
/// The two policies are described in full under
/// [tolerant parsing](crate::error#tolerant-parsing); the guide chapter
/// [Running the parser](crate::guide::parsing#strict-versus-tolerant) shows both in
/// action.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Recovery {
    /// Abort at the first problem: it is returned as a [`ParseError`], and no tree is
    /// produced.
    Strict,
    /// Record each problem as a [`Diagnostic`] and continue parsing.
    ///
    /// The parser repairs the input where the problem was detected, as that condition
    /// type's documentation describes — at the token level, by continuing from the
    /// recovery token the error carries. The parse succeeds and returns a best-effort
    /// tree alongside the diagnostics.
    Tolerant,
}

/// The error that ends a parse: the `Err` of
/// [`Language::parse`](crate::core::Language::parse).
///
/// It arises in two situations: a problem reported under [`Recovery::Strict`], which is
/// escalated instead of recorded, and a condition no policy can absorb — a failure in
/// consumer-supplied code ([`HookFailed`]) or a contract violation by an extension
/// ([`ImplementationError`](crate::core::constructs::ImplementationError)), both of which
/// abort even a tolerant parse.
///
/// **An `Err` always means the parse stopped.** Nothing continues past a `ParseError`: it
/// carries no recovery payload, and propagates out of every construct parser it passes
/// through. Recovery, when it happens, happens where the problem was detected, through
/// [`ParseContext::recover`](crate::core::constructs::ParseContext::recover); a sub-parse
/// that merely ended early reports that as ordinary data
/// ([`StopCause`](crate::core::constructs::StopCause)), not as an error.
///
/// A `ParseError` holds the same three things a [`Diagnostic`] does — the condition
/// ([`data`](ParseError::data)), the `Arc`-based [`SourceSpan`]
/// ([`span`](ParseError::span)), and the traceback ([`frames`](ParseError::frames)) — so
/// it is self-contained and outlives the parse. [`render`](ParseError::render) formats
/// all of it as a report.
///
/// `ParseError` deliberately does not implement `PartialEq`, since conditions are
/// compared through a trait object that hides their type. Compare
/// [`identifier()`](ParseError::identifier) and the fields of the downcast condition
/// instead.
#[derive(Debug, Clone)]
pub struct ParseError<O: SourceOrigin = Option<String>> {
    data: Box<dyn DiagnosticData>,
    span: SourceSpan<O>,
    /// Traceback snapshot, innermost first.
    frames: Vec<TraceFrame<O>>,
}

impl<O: SourceOrigin> ParseError<O> {
    /// Creates a parse error from a condition and the span it occurred at.
    ///
    /// The traceback is empty. A parse attaches frames through the recovery entry point,
    /// [`ParseContext::recover`](crate::core::constructs::ParseContext::recover), or
    /// explicitly with [`with_frames`](ParseError::with_frames).
    pub fn new(condition: impl DiagnosticInfo, span: SourceSpan<O>) -> ParseError<O> {
        ParseError { data: Box::new(condition), span, frames: Vec::new() }
    }

    /// Creates a parse error from a token error's kind — how a tokenization failure
    /// becomes a parse abort.
    ///
    /// A built-in token condition is stored as the parse error's condition; a
    /// [`TokenErrorKind::Custom`] payload is
    /// unwrapped and stored directly, rather than boxed a second time, so downcasting
    /// finds the original condition type either way.
    pub fn from_token_error(kind: TokenErrorKind, span: SourceSpan<O>) -> ParseError<O> {
        ParseError { data: kind.into_condition(), span, frames: Vec::new() }
    }

    /// Assembles a parse error from parts already prepared by the recovery path: a
    /// condition boxed after the driver's refinement pass, and a frame snapshot.
    pub(crate) fn from_parts(
        data: Box<dyn DiagnosticData>,
        span: SourceSpan<O>,
        frames: Vec<TraceFrame<O>>,
    ) -> ParseError<O> {
        ParseError { data, span, frames }
    }

    /// Attaches a traceback snapshot, replacing any frames already stored.
    ///
    /// This is for the sites that abort directly instead of going through the recovery
    /// entry point; the frames normally come from
    /// [`ParserSession::snapshot_frames`](crate::core::ParserSession::snapshot_frames).
    /// Inside a construct parser, use
    /// [`ParseContext::attach_hook_frames`](crate::core::constructs::ParseContext::attach_hook_frames)
    /// instead: it snapshots and attaches a hook-returned error's frames in one call.
    pub fn with_frames(mut self, frames: Vec<TraceFrame<O>>) -> ParseError<O> {
        self.frames = frames;
        self
    }

    /// The condition that was reported.
    ///
    /// Downcast it with
    /// [`downcast_ref`](trait.DiagnosticData.html#method.downcast_ref) to read the
    /// condition's own fields.
    pub fn data(&self) -> &dyn DiagnosticData {
        &*self.data
    }

    /// The condition's identifier string, for boundaries where Rust types cannot travel.
    ///
    /// For every ordinary condition this is the type's
    /// [`IDENTIFIER`](DiagnosticInfo::IDENTIFIER) constant; see
    /// [`DiagnosticInfo::identifier`] for the adapter-type exception. Compare it against
    /// `T::IDENTIFIER` rather than against a string literal.
    pub fn identifier(&self) -> &str {
        self.data.identifier()
    }

    /// The human-readable message, rendered from the condition's `Display`.
    ///
    /// This allocates a fresh `String` on each call; the condition is the stored value,
    /// the message is derived from it.
    pub fn message(&self) -> String {
        self.data.to_string()
    }

    /// Where in the source the condition occurred.
    pub fn span(&self) -> &SourceSpan<O> {
        &self.span
    }

    /// The parse frames that were open at the moment of the abort, innermost first.
    ///
    /// Empty when the abort happened outside a parse descent. Format them with
    /// [`format_traceback`].
    pub fn frames(&self) -> &[TraceFrame<O>] {
        &self.frames
    }

    /// Renders a human-readable, multi-line report of this error: message, position,
    /// traceback, and provenance chain, as [`Diagnostic::render`] does.
    ///
    /// Line and column numbers are computed through a [`LineIndexCache`] created for this
    /// call and dropped with it; [`render_with`](ParseError::render_with) takes a
    /// persistent one.
    pub fn render(&self) -> String {
        self.render_with(&mut LineIndexCache::new())
    }

    /// [`render`](ParseError::render) with a caller-supplied [`LineColProvider`]
    /// answering the line and column lookups, like [`Diagnostic::render_with`].
    pub fn render_with(&self, line_cols: &mut impl LineColProvider<O>) -> String {
        render_report(line_cols, &format!("error: {}", self.data), &self.span, &self.frames)
    }
}

impl<O: SourceOrigin> fmt::Display for ParseError<O> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.data, f)
    }
}

impl<O: SourceOrigin> core::error::Error for ParseError<O> {}

/// The error that is reported when a hook fails to do its work (id
/// `core.hooks.hook-failed`).
///
/// A *hook* is code that a language or an embedding provides and that the library calls
/// during a parse: a [`ParseDriver`](crate::core::ParseDriver) method, a
/// [`Lang`](crate::core::Lang) hook, or a descent-state callback such as
/// [`GroupChildState::Compute`](crate::core::constructs::GroupChildState::Compute). This
/// condition reports an operational failure of the hook's own code, for instance an
/// input/output failure, or an exception raised by code behind a language binding.
///
/// The hook returns the condition inside a [`ParseError`], and the parse aborts under
/// every recovery policy. The library itself reports this condition when
/// [`Lang::make_node_ext`](crate::core::Lang::make_node_ext) fails while the parser
/// builds a node.
///
/// # Choosing this condition
///
/// A hook that fails reports one of three kinds of condition:
///
/// - `HookFailed`, when the hook's own code fails. The failure concerns neither the
///   document nor a contract of the library.
/// - [`ImplementationError`](crate::core::constructs::ImplementationError), when the
///   hook violates a contract of the library. Such an error is a bug in the hook.
/// - Any other condition, when the parsed document contains a problem. Report it through
///   [`ParseContext::recover`](crate::core::constructs::ParseContext::recover) wherever
///   the signature of the hook allows, so that a tolerant parse records the problem and
///   continues.
///
/// # The underlying error
///
/// The field [`cause`](HookFailed::cause) can contain the error that caused the failure.
/// This error is shared behind an `Arc`, so that the condition stays `Clone`, as
/// [`ResolveError`](crate::source::ResolveError) does. You can walk the chain of causes
/// from this field with [`Error::source`](core::error::Error::source), or downcast the
/// error to its concrete type. The serialized form of the condition contains the
/// `detail` string and the chain of causes as text.
#[derive(Debug, Clone, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "core.hooks.hook-failed",
    message = "Hook failed: {detail}"
)]
pub struct HookFailed {
    /// The description of the failure, as a complete message that begins with a capital
    /// letter, for instance `"Failed to read the definition file ‘defs.json’"`.
    pub detail: String,
    /// The underlying error, if the hook has one.
    ///
    /// Pass it as the second argument of [`new`](HookFailed::new), or attach it with
    /// [`with_cause`](HookFailed::with_cause).
    pub cause: Option<Arc<dyn core::error::Error + Send + Sync + 'static>>,
}

impl HookFailed {
    /// Attaches the underlying error, storing it in the
    /// [`cause`](HookFailed::cause) field.
    ///
    /// This method takes the error by value and wraps it in an `Arc`. The second
    /// argument of [`new`](HookFailed::new) takes an error that is already shared.
    pub fn with_cause(
        mut self,
        cause: impl core::error::Error + Send + Sync + 'static,
    ) -> Self {
        self.cause = Some(Arc::new(cause));
        self
    }
}

/// The shared body of the `render`/`render_with` family: headline, position, traceback,
/// and provenance chain, with every line/column lookup answered by `line_cols`.
///
/// Routing all lookups through one provider is what makes
/// [`Diagnostics::render_all`] cost O(N + k) rather than O(k·N): one line-starts table
/// per distinct source, however many positions ask for one.
fn render_report<O: SourceOrigin>(
    line_cols: &mut impl LineColProvider<O>,
    headline: &str,
    span: &SourceSpan<O>,
    frames: &[TraceFrame<O>],
) -> String {
    let mut msg = String::from(headline);
    msg.push_str("\n  at: ");
    msg.push_str(&format_position_with(span, line_cols));

    let traceback = format_traceback_with(frames, line_cols);
    if !traceback.is_empty() {
        msg.push('\n');
        msg.push_str(&traceback);
    }

    for provenance in span.source().provenance_chain() {
        match provenance {
            SourceProvenance::Primary => {}
            SourceProvenance::Resolved { reference, triggered_at } => {
                msg.push_str(&format!(
                    "\n  included from {} ({})",
                    format_position_with(triggered_at, line_cols),
                    reference,
                ));
            }
            SourceProvenance::Synthesized { description, triggered_at } => {
                msg.push_str(&format!(
                    "\n  synthesized from {} ({})",
                    format_position_with(triggered_at, line_cols),
                    description,
                ));
            }
        }
    }

    msg
}

/// Formats the start of a span for display, as `@ (line 2, col 5) [origin]`.
///
/// The `[origin]` part is omitted when the source's origin has no label.
///
/// When line and column information is unavailable for the position — the content lies
/// past the [`LineIndexCache`] scan cap, for instance — the result falls back to the raw
/// byte position, as `@ byte 42 (no line information)`.
///
/// This builds a [`LineIndexCache`] for the call and drops it again. Pass a persistent one
/// to [`format_position_with`], or render a whole collection with
/// [`Diagnostics::render_all`], which shares a single cache across all positions.
pub fn format_position<O: SourceOrigin>(span: &SourceSpan<O>) -> String {
    format_position_with(span, &mut LineIndexCache::new())
}

/// [`format_position`] with a caller-supplied [`LineColProvider`] answering the line and
/// column lookup — a persistent [`LineIndexCache`], or an editor's own incremental line
/// table.
pub fn format_position_with<O: SourceOrigin>(
    span: &SourceSpan<O>,
    line_cols: &mut impl LineColProvider<O>,
) -> String {
    let source = span.source();
    let pos_str = match line_cols.line_col(source, span.start()) {
        Some((line, col)) => format!("@ (line {}, col {})", line, col),
        None => format!("@ byte {} (no line information)", span.start()),
    };

    match source.origin().label() {
        Some(label) => format!("{} [{}]", pos_str, label),
        None => pos_str,
    }
}

/// Formats a traceback — the [`TraceFrame`]s of [`Diagnostic::frames`] or
/// [`ParseError::frames`], innermost first — as one line per frame.
///
/// Each frame's position and origin label come from its own source, so a traceback that
/// crosses an included document reads correctly. Returns an empty string when `frames` is
/// empty.
///
/// [`Diagnostic::render`] and [`ParseError::render`] already append this to their
/// reports; call it directly to format a traceback on its own. It builds a
/// [`LineIndexCache`] for the call and drops it again;
/// [`format_traceback_with`] takes a persistent one.
///
/// # Example output
///
/// ```text
/// Inside:
///   @ (line 5, col 9): group ‘{’
///   @ (line 5, col 9): argument #1 of macro ‘\section’
///   @ (line 5, col 1): macro ‘\section’
///   @ (line 2, col 1): environment ‘document’
///   @ (line 2, col 1): macro ‘\begin’
/// ```
pub fn format_traceback<O: SourceOrigin>(frames: &[TraceFrame<O>]) -> String {
    format_traceback_with(frames, &mut LineIndexCache::new())
}

/// [`format_traceback`] with a caller-supplied [`LineColProvider`] answering the line and
/// column lookups — a persistent [`LineIndexCache`], or an editor's own incremental line
/// table.
pub fn format_traceback_with<O: SourceOrigin>(
    frames: &[TraceFrame<O>],
    line_cols: &mut impl LineColProvider<O>,
) -> String {
    if frames.is_empty() {
        return String::new();
    }

    let mut result = String::from("Inside:");
    for frame in frames {
        result.push_str("\n  ");
        result.push_str(&format_position_with(&frame.span, line_cols));
        result.push_str(": ");
        result.push_str(&frame.title);
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::source::Source;
    use std::sync::Arc;

    /// A third-party-style condition — the extension surface demonstration: a plain
    /// data struct, a `Display` for the wording, and a `DiagnosticInfo` impl.
    /// Deliberately hand-written (no derive): this exercises the manual trait path and
    /// the defaulted `serializable_data()` (see
    /// `serializable_data_defaults_to_an_empty_map`).
    #[derive(Debug, Clone, PartialEq, Eq)]
    struct TestCondition {
        detail: String,
    }

    impl TestCondition {
        fn new(detail: &str) -> TestCondition {
            TestCondition { detail: detail.to_string() }
        }
    }

    impl fmt::Display for TestCondition {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str(&self.detail)
        }
    }

    impl DiagnosticInfo for TestCondition {
        const IDENTIFIER: &'static str = "test.error.test-condition";
    }

    /// A second condition type, for filtering/downcast tests.
    #[derive(Debug, Clone, PartialEq, Eq, crate::error::DiagnosticInfo)]
    #[diagnostic(
        id = "test.error.other-condition",
        message = "other condition",
        no_constructor
    )]
    struct OtherCondition;

    /// A binding-adapter-shaped condition: one Rust type carrying conditions defined
    /// at runtime on the other side of an embedding boundary, overriding
    /// `identifier()` per instance — the exceptional case the method exists for.
    #[derive(Debug, Clone)]
    struct AdapterCondition {
        identifier: String,
        detail: String,
    }

    impl fmt::Display for AdapterCondition {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str(&self.detail)
        }
    }

    impl DiagnosticInfo for AdapterCondition {
        const IDENTIFIER: &'static str = "test.error.adapter";
        fn identifier(&self) -> &str {
            &self.identifier
        }
    }

    #[test]
    fn an_adapter_condition_reports_its_per_instance_identifier() {
        let source = arc_source("Hello");
        let diagnostic = Diagnostic::error(
            AdapterCondition {
                identifier: "pylang.custom.my-condition".to_string(),
                detail: "adapter-carried condition".to_string(),
            },
            SourceSpan::new(&source, 0..1),
        );
        // The stored instance answers its runtime identifier…
        assert_eq!(diagnostic.identifier(), "pylang.custom.my-condition");
        // …preserved across the dyn clone path…
        assert_eq!(diagnostic.clone().identifier(), "pylang.custom.my-condition");
        // …while the adapter type keeps its const and the in-process type identity.
        assert_eq!(AdapterCondition::IDENTIFIER, "test.error.adapter");
        let condition = diagnostic.data().downcast_ref::<AdapterCondition>().unwrap();
        assert_eq!(condition.detail, "adapter-carried condition");
    }

    #[test]
    fn ordinary_conditions_still_answer_their_const_identifier() {
        // The default `identifier()` body answers the const — shipped conditions and
        // `T::IDENTIFIER`-keyed matching are unaffected by the method's existence.
        let ordinary = TestCondition::new("x");
        assert_eq!(DiagnosticInfo::identifier(&ordinary), TestCondition::IDENTIFIER);
        let source = arc_source("Hello");
        let diagnostic =
            Diagnostic::error(TestCondition::new("x"), SourceSpan::new(&source, 0..1));
        assert_eq!(diagnostic.identifier(), TestCondition::IDENTIFIER);
    }

    fn origin(url: &str) -> Option<String> {
        Some(url.to_string())
    }

    fn arc_source(content: &str) -> Arc<Source> {
        Arc::new(Source::new(content))
    }

    /// The decimal numbers of `text`, in order: the line and column (or byte) numbers
    /// that a formatted position shows, read without the words around them.
    fn numbers_in(text: &str) -> Vec<usize> {
        text.split(|c: char| !c.is_ascii_digit())
            .filter(|run| !run.is_empty())
            .map(|run| run.parse().unwrap())
            .collect()
    }

    /// Checks that `line` shows `frame`: the frame's position, then its title at the end.
    fn assert_frame_line(line: &str, frame: &TraceFrame) {
        let position = format_position(frame.span());
        let at = line.find(&position).unwrap_or_else(|| panic!("no position in {line:?}"));
        assert!(line.ends_with(frame.title()), "{line:?}");
        assert!(at + position.len() <= line.len() - frame.title().len(), "{line:?}");
    }

    /// Checks the structure of a traceback: one heading line, then one line per frame,
    /// in the order of `frames`.
    fn assert_traceback(traceback: &str, frames: &[TraceFrame]) {
        let lines: Vec<&str> = traceback.lines().collect();
        assert_eq!(lines.len(), frames.len() + 1, "{traceback}");
        assert!(!lines[0].is_empty());
        for (line, frame) in lines[1..].iter().zip(frames) {
            assert_frame_line(line, frame);
        }
    }

    /// Checks the structure of a report: `headline`, then a line that ends with the
    /// position of `span`, then the traceback of `frames`. Returns the lines after the
    /// traceback (the provenance lines).
    fn assert_report<'a>(
        rendered: &'a str,
        headline: &str,
        span: &SourceSpan,
        frames: &[TraceFrame],
    ) -> Vec<&'a str> {
        let lines: Vec<&str> = rendered.lines().collect();
        assert_eq!(lines[0], headline, "{rendered}");
        assert!(lines[1].ends_with(&format_position(span)), "{rendered}");
        let traceback = format_traceback(frames);
        let traceback_lines: Vec<&str> = traceback.lines().collect();
        let end = 2 + traceback_lines.len();
        assert_eq!(lines[2..end], traceback_lines[..], "{rendered}");
        lines[end..].to_vec()
    }

    #[test]
    fn diagnostic_render_includes_line_info() {
        let source = arc_source("Hello\n\\unknown\nworld");
        let span = SourceSpan::new(&source, 6..14);
        let diagnostic = Diagnostic::error(TestCondition::new("unknown macro"), span.clone());

        // The headline is the diagnostic's `Display`: the severity, then the message.
        let headline = diagnostic.to_string();
        assert!(headline.starts_with(&Severity::Error.to_string()), "{headline}");
        assert!(headline.ends_with("unknown macro"), "{headline}");

        let rendered = diagnostic.render();
        let rest = assert_report(&rendered, &headline, &span, &[]);
        assert!(rest.is_empty(), "{rendered}");
        // The position is line 2, column 1.
        assert_eq!(numbers_in(&format_position(&span)), [2, 1]);
    }

    #[test]
    fn sorted_by_position_is_source_major_span_start_minor_and_stable() {
        let first = arc_source("first source content");
        let second = arc_source("second source content");
        let mut diagnostics: Diagnostics = Diagnostics::new();
        // Recovery order deliberately scrambled: positions out of order within
        // each source, sources interleaved.
        for (source, range, tag) in [
            (&first, 10..12, "f10"),
            (&second, 5..6, "s5"),
            (&first, 0..2, "f0"),
            (&first, 10..11, "f10-later"), // equal start: keeps recovery order
            (&second, 0..1, "s0"),
        ] {
            diagnostics.push(Diagnostic::error(
                TestCondition::new(tag),
                SourceSpan::new(source, range),
            ));
        }

        let tags: Vec<String> = diagnostics
            .sorted_by_position()
            .into_iter()
            .map(|diagnostic| diagnostic.message())
            .collect();
        // `first` appeared first: its diagnostics lead, in span order; the equal
        // starts keep their recovery order (stable).
        assert_eq!(tags, ["f0", "f10", "f10-later", "s0", "s5"]);

        // The view borrows: the collection itself keeps recovery order.
        assert_eq!(diagnostics.iter().next().unwrap().message(), "f10");
    }

    #[test]
    fn diagnostic_accessors() {
        let source = arc_source("Hello\nWorld\nTest");
        let span = SourceSpan::new(&source, 10..15);
        let diagnostic = Diagnostic::error(TestCondition::new("test"), span);

        assert_eq!(diagnostic.span().start(), 10);
        assert_eq!(diagnostic.span().end(), 15);
        assert_eq!(diagnostic.severity(), Severity::Error);
        assert_eq!(diagnostic.message(), "test");
        assert!(diagnostic.frames().is_empty());
        // The two identities ([§dd-dr:errors]): the identifier string on the wire…
        assert_eq!(diagnostic.identifier(), TestCondition::IDENTIFIER);
        // …and the concrete type in-process, reached by downcast.
        assert!(diagnostic.data().is::<TestCondition>());
        let condition = diagnostic.data().downcast_ref::<TestCondition>().unwrap();
        assert_eq!(condition.detail, "test");
        assert!(diagnostic.data().downcast_ref::<OtherCondition>().is_none());
    }

    #[test]
    fn diagnostic_clone_preserves_the_payload() {
        let source = arc_source("Hello");
        let diagnostic =
            Diagnostic::error(TestCondition::new("boom"), SourceSpan::new(&source, 0..1));
        let clone = diagnostic.clone();
        assert_eq!(clone.identifier(), TestCondition::IDENTIFIER);
        assert_eq!(clone.data().downcast_ref::<TestCondition>().unwrap().detail, "boom");
    }

    #[test]
    fn serializable_data_defaults_to_an_empty_map() {
        let condition = TestCondition::new("x");
        assert_eq!(
            DiagnosticInfo::serializable_data(&condition),
            DiagnosticValue::empty_map()
        );
        let data: Box<dyn DiagnosticData> = Box::new(condition);
        assert_eq!(data.serializable_data(), DiagnosticValue::Map(Vec::new()));
    }

    #[test]
    fn diagnostic_render_with_origin() {
        let source: Arc<Source> = Arc::new(
            Source::new("Hello\n\\unknown\nworld").with_origin(origin("test.tex")),
        );
        let span = SourceSpan::new(&source, 6..14);
        let diagnostic = Diagnostic::error(TestCondition::new("unknown macro"), span.clone());

        let rendered = diagnostic.render();
        assert_report(&rendered, &diagnostic.to_string(), &span, &[]);
        // The position shows line 2, column 1, followed by the origin label.
        let position = format_position(&span);
        let unlabeled = arc_source("Hello\n\\unknown\nworld");
        let unlabeled_position = format_position(&SourceSpan::new(&unlabeled, 6..14));
        assert_eq!(numbers_in(&unlabeled_position), [2, 1]);
        assert!(position.starts_with(&unlabeled_position), "{position}");
        assert!(position[unlabeled_position.len()..].contains("test.tex"), "{position}");
    }

    #[test]
    fn diagnostic_render_walks_provenance_chain() {
        let document: Arc<Source> = Arc::new(
            Source::new(r"\input{main.tex}").with_origin(origin("document.tex")),
        );
        let main: Arc<Source> = Arc::new(Source::resolved(
            "\\mycommand\n",
            "main.tex",
            SourceSpan::entire(&document),
        ));
        let expanded: Arc<Source> = Arc::new(Source::synthesized(
            "expansion text",
            "macro expansion",
            SourceSpan::new(&main, 0..10),
        ));

        let span = SourceSpan::new(&expanded, 0..9);
        let diagnostic = Diagnostic::error(TestCondition::new("boom"), span.clone());
        let rendered = diagnostic.render();

        // One provenance line per hop, innermost first: each shows the position that
        // triggered the hop, then the hop's description or reference.
        let hops = assert_report(&rendered, &diagnostic.to_string(), &span, &[]);
        assert_eq!(hops.len(), 2, "{rendered}");
        let hop_layout = |line: &str, trigger: &SourceSpan, text: &str| -> String {
            let position = format_position(trigger);
            let at = line.find(&position).unwrap_or_else(|| panic!("no position in {line:?}"));
            assert!(line[at + position.len()..].contains(text), "{line:?}");
            line[..at].to_string()
        };
        let synthesized = hop_layout(hops[0], &SourceSpan::new(&main, 0..10), "macro expansion");
        let included = hop_layout(hops[1], &SourceSpan::entire(&document), "main.tex");
        assert!(format_position(&SourceSpan::entire(&document)).contains("document.tex"));
        // The two kinds of hop read differently.
        assert_ne!(synthesized, included);
    }

    #[test]
    fn diagnostics_collection() {
        let source = arc_source("Hello");
        let mut diagnostics: Diagnostics = Diagnostics::new();
        assert!(diagnostics.is_empty());
        assert!(!diagnostics.has_errors());

        diagnostics.push(Diagnostic::warning(
            TestCondition::new("odd"),
            SourceSpan::new(&source, 0..1),
        ));
        assert!(!diagnostics.has_errors());

        diagnostics.push(Diagnostic::error(
            TestCondition::new("bad"),
            SourceSpan::new(&source, 1..2),
        ));
        assert_eq!(diagnostics.len(), 2);
        assert!(diagnostics.has_errors());

        let severities: Vec<Severity> = diagnostics.iter().map(|d| d.severity()).collect();
        assert_eq!(severities, vec![Severity::Warning, Severity::Error]);
    }

    #[test]
    fn diagnostics_identifier_filtering_and_typed_access() {
        let source = arc_source("Hello");
        let mut diagnostics: Diagnostics = Diagnostics::new();
        diagnostics
            .push(Diagnostic::error(TestCondition::new("a"), SourceSpan::new(&source, 0..1)));
        diagnostics.push(Diagnostic::error(OtherCondition, SourceSpan::new(&source, 1..2)));
        diagnostics
            .push(Diagnostic::error(TestCondition::new("b"), SourceSpan::new(&source, 2..3)));

        assert_eq!(diagnostics.with_identifier(TestCondition::IDENTIFIER).count(), 2);
        assert_eq!(diagnostics.with_identifier(OtherCondition::IDENTIFIER).count(), 1);
        assert_eq!(diagnostics.with_identifier("test.error.nope").count(), 0);

        let details: Vec<&str> = diagnostics
            .conditions::<TestCondition>()
            .map(|c| c.detail.as_str())
            .collect();
        assert_eq!(details, ["a", "b"]);
    }

    #[test]
    fn diagnostics_default_limit_applies() {
        let diagnostics: Diagnostics = Diagnostics::new();
        assert_eq!(diagnostics.limit(), Diagnostics::<Option<String>>::DEFAULT_LIMIT);
        assert_eq!(diagnostics.suppressed(), 0);
    }

    #[test]
    fn diagnostics_limit_counts_suppressed_pushes() {
        let source = arc_source("abcde");
        let mut diagnostics: Diagnostics = Diagnostics::with_limit(2);
        for i in 0..5 {
            diagnostics.push(Diagnostic::error(
                TestCondition::new("boom"),
                SourceSpan::new(&source, i..i + 1),
            ));
        }

        // Two retained, three counted; the collection is decidedly not empty.
        assert_eq!(diagnostics.len(), 2);
        assert_eq!(diagnostics.suppressed(), 3);
        assert!(!diagnostics.is_empty());
        assert!(diagnostics.has_errors());
        assert_eq!(diagnostics.iter().count(), 2);

        // The retained reports, then one closing block that gives the number of
        // suppressed diagnostics and the retention limit, in this order.
        let rendered = diagnostics.render_all();
        let blocks: Vec<&str> = rendered.split("\n\n").collect();
        assert_eq!(blocks.len(), 3, "{rendered}");
        let reports: Vec<String> = diagnostics.iter().map(|d| d.render()).collect();
        assert_eq!(blocks[..2], [reports[0].as_str(), reports[1].as_str()]);
        assert_eq!(blocks[2].lines().count(), 1, "{rendered}");
        assert_eq!(numbers_in(blocks[2]), [3, 2], "{rendered}");
    }

    #[test]
    fn has_errors_sees_errors_beyond_the_limit() {
        let source = arc_source("ab");
        let mut diagnostics: Diagnostics = Diagnostics::with_limit(1);
        diagnostics.push(Diagnostic::warning(
            TestCondition::new("odd"),
            SourceSpan::new(&source, 0..1),
        ));
        assert!(!diagnostics.has_errors());

        // The error lands beyond the cap: dropped from storage, not from the verdict.
        diagnostics.push(Diagnostic::error(
            TestCondition::new("bad"),
            SourceSpan::new(&source, 1..2),
        ));
        assert_eq!(diagnostics.len(), 1);
        assert!(diagnostics.has_errors());
    }

    #[test]
    fn from_parts_restores_a_collection_whose_diagnostics_were_dropped() {
        let source = arc_source("abcd");
        let mut original: Diagnostics = Diagnostics::with_limit(2);
        for i in 0..4 {
            original.push(Diagnostic::error(
                TestCondition::new("boom"),
                SourceSpan::new(&source, i..i + 1),
            ));
        }

        // The parts a serialized form records, handed straight back.
        let items: Vec<Diagnostic> = original.iter().cloned().collect();
        let rebuilt = Diagnostics::from_parts(
            items,
            original.limit(),
            original.suppressed(),
            original.error_count(),
        )
        .unwrap();

        assert_eq!(rebuilt.len(), original.len());
        assert_eq!(rebuilt.limit(), 2);
        assert_eq!(rebuilt.suppressed(), 2);
        assert_eq!(rebuilt.error_count(), 4);
        assert!(rebuilt.has_errors());
        assert_eq!(rebuilt.render_all(), original.render_all());
    }

    #[test]
    fn from_parts_rejects_counts_that_contradict_one_another() {
        let source = arc_source("ab");
        // Two diagnostics, one of them an error.
        let items: Vec<Diagnostic> = vec![
            Diagnostic::error(TestCondition::new("bad"), SourceSpan::new(&source, 0..1)),
            Diagnostic::warning(TestCondition::new("odd"), SourceSpan::new(&source, 1..2)),
        ];
        let refuse = |limit, suppressed, error_count| {
            Diagnostics::from_parts(items.clone(), limit, suppressed, error_count).unwrap_err()
        };

        // More diagnostics than the retention cap allows.
        assert_eq!(
            refuse(1, 0, 1),
            InconsistentDiagnosticCounts {
                retained: 2,
                retained_errors: 1,
                limit: 1,
                suppressed: 0,
                error_count: 1,
            }
        );
        // Suppressed pushes although the cap was not reached.
        assert_eq!(
            refuse(5, 1, 1),
            InconsistentDiagnosticCounts {
                retained: 2,
                retained_errors: 1,
                limit: 5,
                suppressed: 1,
                error_count: 1,
            }
        );
        // Fewer errors in all than there are error-severity diagnostics.
        assert_eq!(
            refuse(5, 0, 0),
            InconsistentDiagnosticCounts {
                retained: 2,
                retained_errors: 1,
                limit: 5,
                suppressed: 0,
                error_count: 0,
            }
        );
        // More errors in all than the retained errors plus the suppressed pushes.
        assert_eq!(
            refuse(2, 1, 3),
            InconsistentDiagnosticCounts {
                retained: 2,
                retained_errors: 1,
                limit: 2,
                suppressed: 1,
                error_count: 3,
            }
        );

        // A single diagnostic over a zero limit is refused as well.
        let one = vec![Diagnostic::error(TestCondition::new("bad"), SourceSpan::new(&source, 0..1))];
        assert_eq!(
            Diagnostics::from_parts(one, 0, 0, 1).unwrap_err(),
            InconsistentDiagnosticCounts {
                retained: 1,
                retained_errors: 1,
                limit: 0,
                suppressed: 0,
                error_count: 1,
            }
        );

        // And the consistent parts are accepted.
        assert!(Diagnostics::from_parts(items, 2, 1, 2).is_ok());
    }

    #[test]
    fn render_all_matches_the_per_diagnostic_renders() {
        // Two sources — one reached through a provenance hop — so the shared index
        // cache is exercised across sources; sharing must not change the output.
        let document: Arc<Source> = Arc::new(
            Source::new("Hello\n\\input{main.tex}").with_origin(origin("document.tex")),
        );
        let main: Arc<Source> = Arc::new(Source::resolved(
            "\\bad\nmore\n",
            "main.tex",
            SourceSpan::new(&document, 6..22),
        ));

        let mut diagnostics: Diagnostics = Diagnostics::new();
        diagnostics.push(Diagnostic::error(
            TestCondition::new("first"),
            SourceSpan::new(&main, 0..4),
        ));
        diagnostics.push(Diagnostic::warning(
            TestCondition::new("second"),
            SourceSpan::new(&main, 5..9),
        ));
        diagnostics.push(Diagnostic::error(
            TestCondition::new("third"),
            SourceSpan::new(&document, 0..5),
        ));

        let separate: Vec<String> = diagnostics.iter().map(|d| d.render()).collect();
        // The joined reports and nothing else: no closing block when nothing was
        // suppressed.
        assert_eq!(diagnostics.render_all(), separate.join("\n\n"));
    }

    #[test]
    fn format_traceback_single_frame() {
        let source = arc_source("Hello\nWorld\nTest");

        let frames =
            vec![TraceFrame::new("environment ‘document’", SourceSpan::new(&source, 6..11))];

        let traceback = format_traceback(&frames);
        assert_traceback(&traceback, &frames);
        assert_eq!(numbers_in(traceback.lines().nth(1).unwrap()), [2, 1]);
    }

    #[test]
    fn format_traceback_multiple_frames_innermost_first() {
        let source = arc_source("Hello\nWorld\nTest\nMore");

        let frames = vec![
            TraceFrame::new("callable ‘\\textbf’", SourceSpan::new(&source, 12..16)),
            TraceFrame::new("environment ‘document’", SourceSpan::new(&source, 6..11)),
            TraceFrame::new("callable ‘\\section’", SourceSpan::new(&source, 0..5)),
        ];

        let traceback = format_traceback(&frames);
        assert_traceback(&traceback, &frames);
        let positions: Vec<Vec<usize>> =
            traceback.lines().skip(1).map(numbers_in).collect();
        assert_eq!(positions, [[3, 1], [2, 1], [1, 1]]);
    }

    #[test]
    fn format_traceback_empty_frames() {
        let frames: Vec<TraceFrame> = vec![];
        assert_eq!(format_traceback(&frames), "");
    }

    #[test]
    fn format_traceback_with_origin() {
        let source: Arc<Source> = Arc::new(
            Source::new("Hello\nWorld\nTest").with_origin(origin("test.tex")),
        );

        let frames =
            vec![TraceFrame::new("environment ‘document’", SourceSpan::new(&source, 6..11))];

        let traceback = format_traceback(&frames);
        assert_traceback(&traceback, &frames);
        // The frame's position carries its source's origin label.
        assert!(format_position(frames[0].span()).contains("test.tex"));
        assert_eq!(numbers_in(traceback.lines().nth(1).unwrap()), [2, 1]);
    }

    #[test]
    fn render_appends_the_traceback() {
        let source = arc_source("Hello\nWorld");
        let span = SourceSpan::new(&source, 6..7);
        let diagnostic = Diagnostic::from_parts(
            Severity::Error,
            Box::new(TestCondition::new("boom")),
            span.clone(),
            vec![TraceFrame::new("group ‘{’", SourceSpan::new(&source, 0..1))],
        );
        let rendered = diagnostic.render();
        let rest = assert_report(&rendered, &diagnostic.to_string(), &span, diagnostic.frames());
        assert!(rest.is_empty(), "{rendered}");
        assert_traceback(&format_traceback(diagnostic.frames()), diagnostic.frames());
        assert_eq!(rendered.lines().count(), 4, "{rendered}");
    }

    #[test]
    fn with_outer_frames_on_an_empty_traceback_stores_them_in_order() {
        let source = arc_source("Hello\nWorld");
        let diagnostic =
            Diagnostic::error(TestCondition::new("boom"), SourceSpan::new(&source, 6..7))
                .with_outer_frames(vec![
                    TraceFrame::new("copy of a title", SourceSpan::new(&source, 0..5)),
                    TraceFrame::new("reference", SourceSpan::new(&source, 6..11)),
                ]);
        let titles: Vec<&str> = diagnostic.frames().iter().map(|f| f.title()).collect();
        assert_eq!(titles, ["copy of a title", "reference"]);
    }

    #[test]
    fn with_outer_frames_keeps_existing_frames_first() {
        let source = arc_source("Hello\nWorld");
        let diagnostic = Diagnostic::from_parts(
            Severity::Error,
            Box::new(TestCondition::new("boom")),
            SourceSpan::new(&source, 6..7),
            vec![TraceFrame::new("group ‘{’", SourceSpan::new(&source, 0..1))],
        )
        .with_outer_frames(vec![TraceFrame::new(
            "appended",
            SourceSpan::new(&source, 6..11),
        )]);
        let titles: Vec<&str> = diagnostic.frames().iter().map(|f| f.title()).collect();
        assert_eq!(titles, ["group ‘{’", "appended"]);

        let diagnostic = diagnostic.with_outer_frames(vec![TraceFrame::new(
            "appended later",
            SourceSpan::new(&source, 0..5),
        )]);
        let titles: Vec<&str> = diagnostic.frames().iter().map(|f| f.title()).collect();
        assert_eq!(titles, ["group ‘{’", "appended", "appended later"]);
    }

    #[test]
    fn with_outer_frames_with_no_frames_changes_nothing() {
        let source = arc_source("Hello\nWorld");
        let diagnostic = Diagnostic::from_parts(
            Severity::Error,
            Box::new(TestCondition::new("boom")),
            SourceSpan::new(&source, 6..7),
            vec![TraceFrame::new("group ‘{’", SourceSpan::new(&source, 0..1))],
        );
        let rendered_before = diagnostic.render();
        let spans_before: Vec<_> =
            diagnostic.frames().iter().map(|f| (f.title().to_string(), f.span().span())).collect();

        let diagnostic = diagnostic.with_outer_frames(Vec::new());
        let spans_after: Vec<_> =
            diagnostic.frames().iter().map(|f| (f.title().to_string(), f.span().span())).collect();
        assert_eq!(spans_after, spans_before);
        assert_eq!(diagnostic.render(), rendered_before);
    }

    #[test]
    fn render_shows_outer_frames_after_parse_frames() {
        let source = arc_source("Hello\nWorld");
        let diagnostic = Diagnostic::from_parts(
            Severity::Error,
            Box::new(TestCondition::new("boom")),
            SourceSpan::new(&source, 6..7),
            vec![TraceFrame::new("group ‘{’", SourceSpan::new(&source, 0..1))],
        )
        .with_outer_frames(vec![TraceFrame::new(
            "copy shown by a reference",
            SourceSpan::new(&source, 7..8),
        )]);
        let rendered = diagnostic.render();
        // The diagnostic's own position is unchanged, and the outer frame follows the
        // parse frame.
        let span = SourceSpan::new(&source, 6..7);
        assert_report(&rendered, &diagnostic.to_string(), &span, diagnostic.frames());
        assert_eq!(numbers_in(rendered.lines().nth(1).unwrap()), [2, 1]);
        let lines: Vec<&str> = rendered.lines().collect();
        assert_frame_line(lines[3], &TraceFrame::new("group ‘{’", SourceSpan::new(&source, 0..1)));
        assert_frame_line(
            lines[4],
            &TraceFrame::new("copy shown by a reference", SourceSpan::new(&source, 7..8)),
        );
        assert_eq!(numbers_in(lines[4]), [2, 2]);
    }

    #[test]
    fn with_outer_frames_accepts_frames_from_another_source() {
        let source = arc_source("Hello\nWorld");
        let other: Arc<Source> =
            Arc::new(Source::new("one\ntwo\nthree").with_origin(origin("other.tex")));
        let diagnostic =
            Diagnostic::error(TestCondition::new("boom"), SourceSpan::new(&source, 6..7))
                .with_outer_frames(vec![TraceFrame::new(
                    "reference",
                    SourceSpan::new(&other, 8..13),
                )]);
        let rendered = diagnostic.render();
        let span = SourceSpan::new(&source, 6..7);
        assert_report(&rendered, &diagnostic.to_string(), &span, diagnostic.frames());
        // The frame line shows the position in the other source, with its label.
        let frame_line = rendered.lines().nth(3).unwrap();
        assert_frame_line(frame_line, &TraceFrame::new("reference", SourceSpan::new(&other, 8..13)));
        assert!(format_position(&SourceSpan::new(&other, 8..13)).contains("other.tex"));
        assert_eq!(numbers_in(frame_line), [3, 1]);
    }

    #[test]
    fn parse_error_carries_the_condition() {
        let source = arc_source("Hello");
        let err: ParseError =
            ParseError::new(TestCondition::new("boom"), SourceSpan::new(&source, 0..2));
        assert_eq!(err.identifier(), TestCondition::IDENTIFIER);
        assert_eq!(err.message(), "boom");
        assert_eq!(err.data().downcast_ref::<TestCondition>().unwrap().detail, "boom");
        assert_eq!(err.to_string(), "boom");
        assert!(err.frames().is_empty());
        // A fatal error renders like an error diagnostic of the same condition.
        let span = SourceSpan::new(&source, 0..2);
        let as_diagnostic = Diagnostic::error(TestCondition::new("boom"), span.clone());
        assert_eq!(err.render(), as_diagnostic.render());
        assert_report(&err.render(), &as_diagnostic.to_string(), &span, &[]);
        assert_eq!(numbers_in(err.render().lines().nth(1).unwrap()), [1, 1]);
    }

    // --- HookFailed: the general operational hook-failure condition ------------------

    /// The innermost hop of the test cause chain.
    #[derive(Debug)]
    struct UnderlyingIo;

    impl fmt::Display for UnderlyingIo {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("disk unavailable")
        }
    }

    impl core::error::Error for UnderlyingIo {}

    /// A two-hop cause chain: the embedding's failure, caused by `UnderlyingIo`.
    #[derive(Debug)]
    struct EmbeddingFailure {
        source: UnderlyingIo,
    }

    impl fmt::Display for EmbeddingFailure {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("embedding call failed")
        }
    }

    impl core::error::Error for EmbeddingFailure {
        fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
            Some(&self.source)
        }
    }

    #[test]
    fn hook_failed_constructs_and_renders() {
        let plain = HookFailed::new("state seed unavailable", None);
        assert_eq!(HookFailed::IDENTIFIER, "core.hooks.hook-failed");
        assert_eq!(DiagnosticInfo::identifier(&plain), HookFailed::IDENTIFIER);
        assert_eq!(plain.detail, "state seed unavailable");
        // The message carries the hook's detail.
        assert!(plain.to_string().contains("state seed unavailable"));
        assert!(plain.cause.is_none());

        // The derive's constructor also takes the cause positionally (an
        // already-shared `Arc`); `with_cause` is the by-value sugar.
        let arc: Arc<dyn core::error::Error + Send + Sync> = Arc::new(UnderlyingIo);
        let positional = HookFailed::new("boom", Some(arc));
        assert_eq!(positional.cause.as_ref().unwrap().to_string(), "disk unavailable");
    }

    #[test]
    fn hook_failed_cause_chain_is_reachable_through_a_parse_error() {
        let source = arc_source("Hello");
        let condition = HookFailed::new("embedding call failed", None)
            .with_cause(EmbeddingFailure { source: UnderlyingIo });
        let err: ParseError =
            ParseError::new(condition, SourceSpan::new(&source, 0..1));
        assert_eq!(err.identifier(), "core.hooks.hook-failed");

        // Downcast to the concrete condition, then walk the chain off the field.
        let condition = err.data().downcast_ref::<HookFailed>().unwrap();
        let cause = condition.cause.as_ref().unwrap();
        assert_eq!(cause.to_string(), "embedding call failed");
        let hop = core::error::Error::source(&**cause).unwrap();
        assert_eq!(hop.to_string(), "disk unavailable");
        assert!(hop.source().is_none());

        // Clones share the cause by reference count (the `Arc` pattern).
        let clone = condition.clone();
        assert!(Arc::ptr_eq(cause, clone.cause.as_ref().unwrap()));
    }

    #[test]
    fn hook_failed_serializable_data_projects_the_cause_chain() {
        let plain = HookFailed::new("boom", None);
        assert_eq!(
            DiagnosticInfo::serializable_data(&plain),
            DiagnosticValue::Map(vec![
                ("detail".to_string(), DiagnosticValue::Str("boom".to_string())),
                ("cause".to_string(), DiagnosticValue::Null),
            ])
        );

        let chained =
            HookFailed::new("boom", None).with_cause(EmbeddingFailure { source: UnderlyingIo });
        assert_eq!(
            DiagnosticInfo::serializable_data(&chained),
            DiagnosticValue::Map(vec![
                ("detail".to_string(), DiagnosticValue::Str("boom".to_string())),
                (
                    "cause".to_string(),
                    DiagnosticValue::List(vec![
                        DiagnosticValue::Str("embedding call failed".to_string()),
                        DiagnosticValue::Str("disk unavailable".to_string()),
                    ])
                ),
            ])
        );
    }

    #[test]
    fn the_with_variants_match_their_transient_shorthands() {
        // The shorthand-not-second-path contract: a caller-held persistent cache
        // produces byte-identical reports, across repeated renders (entries are
        // reused, never rebuilt — content is immutable).
        let document: Arc<Source> = Arc::new(
            Source::new("Hello\n\\input{main.tex}").with_origin(origin("document.tex")),
        );
        let main: Arc<Source> = Arc::new(Source::resolved(
            "\\bad\nmore\n",
            "main.tex",
            SourceSpan::new(&document, 6..22),
        ));
        let mut diagnostics: Diagnostics = Diagnostics::new();
        diagnostics.push(Diagnostic::from_parts(
            Severity::Error,
            Box::new(TestCondition::new("boom")),
            SourceSpan::new(&main, 0..4),
            vec![TraceFrame::new("group ‘{’", SourceSpan::new(&document, 6..7))],
        ));
        let error: ParseError =
            ParseError::new(TestCondition::new("halt"), SourceSpan::new(&main, 5..9));

        let mut cache = crate::source::LineIndexCache::new();
        for _ in 0..2 {
            assert_eq!(diagnostics.render_all_with(&mut cache), diagnostics.render_all());
            let diagnostic = diagnostics.iter().next().unwrap();
            assert_eq!(diagnostic.render_with(&mut cache), diagnostic.render());
            assert_eq!(error.render_with(&mut cache), error.render());
            assert_eq!(
                format_position_with(diagnostic.span(), &mut cache),
                format_position(diagnostic.span())
            );
            assert_eq!(
                format_traceback_with(diagnostic.frames(), &mut cache),
                format_traceback(diagnostic.frames())
            );
        }
    }

    #[test]
    fn format_position_char_pos_fallback() {
        // A source too large for line indexing has no line and column: the position
        // falls back to the raw byte position, and shows no other number.
        let content = "a\n".repeat(DEFAULT_MAX_TEST_LEN);
        let source = arc_source(&content);
        let span = SourceSpan::new(&source, 42..43);
        assert_eq!(LineIndexCache::new().line_col(&source, 42), None);

        let formatted = format_position(&span);
        assert_eq!(numbers_in(&formatted), [42]);
        // It reads differently from a line-and-column position.
        let small = arc_source("a\n".repeat(30).as_str());
        let line_col = format_position(&SourceSpan::new(&small, 42..43));
        assert_eq!(numbers_in(&line_col), [22, 1]);
        assert_ne!(
            formatted.replace(char::is_numeric, ""),
            line_col.replace(char::is_numeric, "")
        );
    }

    // Exceeds the default max scan length of 500_000 bytes ("a\n" is 2 bytes).
    const DEFAULT_MAX_TEST_LEN: usize = 300_000;

    /// The derive works *inside* the defining crate too (via `extern crate self as
    /// techy` in lib.rs) — the in-crate migration of the built-in conditions relies on
    /// this. The full derive surface is exercised from the consumer side in
    /// tests/derive_conditions.rs.
    #[derive(Debug, Clone, PartialEq, Eq, crate::error::DiagnosticInfo)]
    #[non_exhaustive]
    #[diagnostic(id = "test.error.derived-condition", message = "derived: {detail}")]
    struct DerivedCondition {
        detail: String,
    }

    #[test]
    fn derive_works_in_crate() {
        let condition = DerivedCondition::new("boom");
        assert_eq!(DerivedCondition::IDENTIFIER, "test.error.derived-condition");
        assert_eq!(condition.to_string(), "derived: boom");
        assert_eq!(
            DiagnosticInfo::serializable_data(&condition),
            DiagnosticValue::Map(vec![(
                "detail".to_string(),
                DiagnosticValue::Str("boom".to_string())
            )])
        );
    }
}