daemonic_error 0.1.0

Errors that compose, predict, and leave receipts - Compose: algebraic combination (in active development) - Predict: Glass/Severity - Receipts: audit trail, position, checksum - Reflection: Runtime Reflection through TopologySegment (in active development)
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
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
use std::backtrace::Backtrace;
use crate::{DiagCtxtHandle, Subdiagnostic};
use crate::Color;
use crate::ColorSpec;
use std::borrow::Cow;
use std::cell::Cell;
use std::fmt;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use std::thread::panicking;

mod traits {
	use std::backtrace::Backtrace;
	use crate::{DiagCtxtHandle, Subdiagnostic};
	use crate::Color;
	use crate::ColorSpec;
	use std::borrow::Cow;
	use std::cell::Cell;
	use std::fmt;
	use std::fmt::Debug;
	use std::marker::PhantomData;
	use std::ops::{Deref, DerefMut};
	use std::path::{Path, PathBuf};
	use std::thread::panicking;
	use super::structures::*;
	/// Trait implemented by error types. This is rarely implemented manually. Instead, use
	/// `#[derive(Diagnostic)]` -- see [daemonic_macros::Diagnostic].
	///
	/// When implemented manually, it should be generic over the emission
	/// guarantee, i.e.:
	/// ```ignore (fragment)
	/// impl<'a, GUARANTEE: EmissionGuarantee> Diagnostic<'a, GUARANTEE> for Foo { ... }
	/// ```
	/// rather than being specific:
	/// ```ignore (fragment)
	/// impl<'a> Diagnostic<'a> for Bar { ... }  // the default type param is `ErrorGuaranteed`
	/// impl<'a> Diagnostic<'a, ()> for Baz { ... }
	/// ```
	/// There are two reasons for this.
	/// - A diagnostic like `Foo` *could* be emitted at any level -- `DiagnosticLevel` is
	///   passed in to `into_diag` from outside. Even if in practice it is
	///   always emitted at a single level, we let the diagnostic creation/emission
	///   site determine the level (by using `create_err`, `emit_warn`, etc.)
	///   rather than the `Diagnostic` impl.
	/// - Derived impls are always generic, and it's good for the hand-written
	///   impls to be consistent with them.
	#[rustc_diagnostic_item = "Diagnostic"]
	pub trait Diagnostic<'diagnostic, GUARANTEE: EmissionGuarantee = ErrorGuaranteed> {
		/// Write out as a diagnostic out of `DiagCtxt`.
		#[must_use]
		fn into_diag(
			self,
			dcx: DiagCtxtHandle<'diagnostic>,
			level: DiagnosticLevel,
		) -> Diag<'diagnostic, GUARANTEE>;
	}
	/// Trait implemented by lint types. This should not be implemented manually. Instead, use
	/// `#[derive(LintDiagnostic)]` -- see [daemonic_macros::LintDiagnostic].
	#[rustc_diagnostic_item = "LintDiagnostic"]
	pub trait LintDiagnostic<'diagnostic, GUARANTEE: EmissionGuarantee> {
		/// Decorate and emit a lint.
		fn decorate_lint<'decorate_lint>(self, diag: &'decorate_lint mut Diag<'diagnostic, GUARANTEE>);
	}
	//
	pub trait EmissionGuarantee: Sized {
		type EmitResult = Self;

		/// NEW: Can we continue after this emission?
		const CONTINUEABLE: bool = true;

		/// NEW: Recovery handler type (defaults to no-op)
		type RecoveryHandler: RecoveryHandler<Self> = NoRecovery;

		fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult;

		/// NEW: Emit with continuation support
		fn emit_continuable(diag: Diag<'_, Self>) -> crate::daemonic::daemonic_contract::daemonic_result::diagnostic::EmitOutcome<Self::EmitResult> {
			let result = Self::emit_producing_guarantee(diag);

			if Self::CONTINUEABLE {
				crate::daemonic::daemonic_contract::daemonic_result::diagnostic::EmitOutcome::Continue(result)
			} else if let Some(recovered) = Self::RecoveryHandler::attempt_recovery(&result) {
				crate::daemonic::daemonic_contract::daemonic_result::diagnostic::EmitOutcome::Recovered(recovered)
			} else {
				crate::daemonic::daemonic_contract::daemonic_result::diagnostic::EmitOutcome::MustStop(result)
			}
		}
	}
	/// Simplified version of `FluentArg` that can implement `Encodable` and `Decodable`. Collection of
	/// `DiagArg` are converted to `FluentArgs` (consuming the collection) at the start of diagnostic
	/// emission.
	// pub type DiagArg<'iter> = (&'iter DiagArgName, &'iter DiagArgValue);
	pub type DiagArgMap = FxIndexMap<DiagArgName, DiagArgValue>; // todo: FxIndexMap needs converted to generic trait bound then autobound opaquely with optional override
	/// Name of a diagnostic argument.
	pub type DiagArgName = Cow<'static, str>;
	/// Converts a value of a type into a `DiagArg` (typically a field of an `Diag` struct).
	/// Implemented as a custom trait rather than `From` so that it is implemented on the type being
	/// converted rather than on `DiagArgValue`, which enables types from other `rustc_*` crates to
	/// implement this.
	pub trait IntoDiagArg {
		/// Convert `Self` into a `DiagArgValue` suitable for rendering in a diagnostic.
		///
		/// It takes a `path` where "long values" could be written to, if the `DiagArgValue` is too big
		/// for displaying on the terminal. This path comes from the `Diag` itself. When rendering
		/// values that come from `TyCtxt`, like `Ty<'_>`, they can use `TyCtxt::short_string`. If a
		/// value has no shortening logic that could be used, the argument can be safely ignored.
		fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> DiagArgValue;
	}
}
mod structures {
	use std::backtrace::Backtrace;
	use crate::{DiagCtxtHandle, Subdiagnostic};
	use crate::Color;
	use crate::ColorSpec;
	use std::borrow::Cow;
	use std::cell::Cell;
	use std::fmt;
	use std::fmt::Debug;
	use std::marker::PhantomData;
	use std::ops::{Deref, DerefMut};
	use std::path::{Path, PathBuf};
	use std::thread::panicking;
	use crate::daemonic::daemonic_contract::daemonic_result::diagnostic::EmissionGuarantee;
	/// Useful type to use with `Result<>` indicate that an error has already
	/// been reported to the user, so no need to continue checking.
	///
	/// The `()` field is necessary: it is non-`pub`, which means values of this
	/// type cannot be constructed outside of this crate.
	///
	/// #[derive(HashStable_Generic)]
	#[derive(
		Clone,
		Copy,
		Debug,
		Hash,
		PartialEq,
		Eq,
		PartialOrd,
		Ord
	)] // This technically uses unstable traits in std lib, but presents as stable on the surface.
	pub struct ErrorGuaranteed(());
	/// This is a marker for a fatal compiler error used with `resume_unwind`.
	pub struct FatalErrorMarker;
	/// Used as a return value to signify a fatal error occurred.
	#[derive(Copy, Clone, Debug)]
	#[must_use]
	pub struct FatalError;
	pub struct FatalRecovery;
	/// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted
	/// to a `FluentValue` by the emitter to be used in diagnostic translation.
	#[derive(Clone, Debug, PartialEq, Eq, Hash)]
	pub enum DiagArgValue {
		Str(Cow<'static, str>),
		// This gets converted to a `FluentNumber`, which is an `f64`. An `i32`
		// safely fits in an `f64`. Any integers bigger than that will be converted
		// to strings in `into_diag_arg` and stored using the `Str` variant.
		Number(i32),
		StrListSepByAnd(Vec<Cow<'static, str>>),
	}
	/// Used for emitting structured error messages and other diagnostic information.
	/// Wraps a `DiagInner`, adding some useful things.
	/// - The `dcx` field, allowing it to (a) emit itself, and (b) do a drop check
	///   that it has been emitted or cancelled.
	/// - The `EmissionGuarantee`, which determines the type returned from `emit`.
	///
	/// Each constructed `Diag` must be consumed by a function such as `emit`,
	/// `cancel`, `delay_as_bug`, or `into_diag`. A panic occurs if a `Diag`
	/// is dropped without being consumed by one of these functions.
	///
	/// If there is some state in a downstream crate you would like to access in
	/// the methods of `Diag` here, consider extending `DiagCtxtFlags`.
	#[must_use]
	pub struct Diag<'a, G: EmissionGuarantee = ErrorGuaranteed> {
		pub dcx: DiagnosticContextHandle<'a>,

		/// Why the `Option`? It is always `Some` until the `Diag` is consumed via
		/// `emit`, `cancel`, etc. At that point it is consumed and replaced with
		/// `None`. Then `drop` checks that it is `None`; if not, it panics because
		/// a diagnostic was built but not used.
		///
		/// Why the Box? `DiagInner` is a large type, and `Diag` is often used as a
		/// return value, especially within the frequently-used `PResult` type. In
		/// theory, return value optimization (RVO) should avoid unnecessary
		/// copying. In practice, it does not (at the time of writing).
		/// At time of writing' statements need to be dated, fuck this guy.
		pub(crate) diag: Option<Box<DiagInner>>,

		pub(crate) _marker: PhantomData<G>,
	}
	/// The main part of a diagnostic. Note that `Diag`, which wraps this type, is
	/// used for most operations, and should be used instead whenever possible.
	/// This type should only be used when `Diag`'s lifetime causes difficulties,
	/// e.g. when storing diagnostics within `DiagCtxt`.
	#[must_use]
	#[derive(Clone, Debug)]
	pub struct DiagInner {
		// NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
		// outside of what methods in this crate themselves allow.
		pub level: crate::DaemonicCompiler::rustc::rustc_error::DiagnosticLevel,

		pub messages: Vec<(DiagMessage, Style)>,
		pub code: Option<ErrCode>,
		pub lint_id: Option<LintExpectationId>,
		pub span: MultiSpan,
		pub children: Vec<Subdiag>,
		pub suggestions: Suggestions,
		pub args: DiagArgMap,

		/// This is not used for highlighting or rendering any error message. Rather, it can be used
		/// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
		/// `span` if there is one. Otherwise, it is `DUMMY_SP`.
		pub sort_span: Span,

		pub is_lint: Option<IsLint>,

		pub long_ty_path: Option<PathBuf>,
		/// With `-Ztrack_diagnostics` enabled,
		/// we print where in rustc this error was emitted.
		pub emitted_at: DiagLocation,
	}
	/// A "sub"-diagnostic attached to a parent diagnostic.
	/// For example, a note attached to an error.
	#[derive(Clone, Debug, PartialEq, Hash)]
	pub struct Subdiag {
		pub level: crate::daemonic::daemonic_contract::daemonic_result::diagnostic::DiagnosticLevel,
		pub messages: Vec<(DiagMessage, Style)>,
		pub span: MultiSpan,
	}
	/// | Level        | is_error | EmissionGuarantee            | Top-level | Sub | Used in lints?
	/// | -----        | -------- | -----------------            | --------- | --- | --------------
	/// | Bug          | yes      | BugAbort                     | yes       | -   | -
	/// | Fatal        | yes      | FatalAbort/FatalError[^star] | yes       | -   | -
	/// | Error        | yes      | ErrorGuaranteed              | yes       | -   | yes
	/// | DelayedBug   | yes      | ErrorGuaranteed              | yes       | -   | -
	/// | ForceWarning | -        | ()                           | yes       | -   | lint-only
	/// | Warning      | -        | ()                           | yes       | yes | yes
	/// | Note         | -        | ()                           | rare      | yes | -
	/// | OnceNote     | -        | ()                           | -         | yes | lint-only
	/// | Help         | -        | ()                           | rare      | yes | -
	/// | OnceHelp     | -        | ()                           | -         | yes | lint-only
	/// | FailureNote  | -        | ()                           | rare      | -   | -
	/// | Allow        | -        | ()                           | yes       | -   | lint-only
	/// | Expect       | -        | ()                           | yes       | -   | lint-only
	///
	/// [^star]: `FatalAbort` normally, `FatalError` in the non-aborting "almost fatal" case that is
	///     occasionally used.
	///    Note for Daemonic Consumers, *DiagnosticLevel is NOT GlassState*
	///
	/// This is technically a nested trait object from the reference frame of DaemonicError.
	/// Most users/devs should never need to directly call this part of the logic solely because its compiler
	/// specific in 99% of use cases.
	///
	/// This is from and originally designed for RustC error and its internal representations for
	/// error states, GlassStates encapsulate full state in most cases (or at least should) these do not.
	/// Even with a fully constructed Diagnostic message with args and Span arent as rich as
	/// A pure Daemonic Error or GlassState derivation of the same state within shared context.
	#[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
	pub enum DiagnosticLevel {
		/// For bugs in the compiler. Manifests as an ICE (internal compiler error) panic.
		Bug,

		/// An error that causes an immediate abort. Used for things like configuration errors,
		/// internal overflows, some file operation errors.
		Fatal,

		/// An error in the code being compiled, which prevents compilation from finishing. This is the
		/// most common case.
		Error,

		/// This is a strange one: lets you register an error without emitting it. If compilation ends
		/// without any other errors occurring, this will be emitted as a bug. Otherwise, it will be
		/// silently dropped. I.e. "expect other errors are emitted" semantics. Useful on code paths
		/// that should only be reached when compiling erroneous code.
		DelayedBug,

		/// A `force-warn` lint warning about the code being compiled. Does not prevent compilation
		/// from finishing.
		///
		/// Requires a [`LintExpectationId`] for expected lint diagnostics. In all other cases this
		/// should be `None`.
		ForceWarning,

		/// A warning about the code being compiled. Does not prevent compilation from finishing.
		/// Will be skipped if `can_emit_warnings` is false.
		Warning,

		/// A message giving additional context.
		Note,

		/// A note that is only emitted once.
		OnceNote,

		/// A message suggesting how to fix something.
		Help,

		/// A help that is only emitted once.
		OnceHelp,

		/// Similar to `Note`, but used in cases where compilation has failed. When printed for human
		/// consumption, it doesn't have any kind of `note:` label.
		FailureNote,

		/// Only used for lints.
		Allow,

		/// Only used for lints. Requires a [`LintExpectationId`] for silencing the lints.
		Expect,
	}
	#[derive(Copy, Clone)]
	pub struct DiagnosticContextHandle<'a> {
		pub dcx: &'a DiagCtxt,
		/// Some contexts create `DiagCtxtHandle` with this field set, and thus all
		/// errors emitted with it will automatically taint when emitting errors.
		pub tainted_with_errors: Option<&'a Cell<Option<ErrorGuaranteed>>>,
	}


	/// A `DiagCtxt` deals with errors and other compiler output.
	/// Certain errors (fatal, bug, unimpl) may cause immediate exit,
	/// others log errors for later reporting.
	pub struct DiagCtxt {
		pub(crate) inner: Lock<DiagCtxtInner>,
	}
	// Replacement sketch provided by Ada. Love that girl <3
	pub enum EmitOutcome<R> { // todo:: this needs DaemonicRecursionManagement logic attached
		/// Error collected, continue walking
		Continue(R),
		/// Fatal intercepted, recovered to state
		Recovered(RecoveredState),
		/// Truly unrecoverable, must stop
		MustStop(R),
	}
	pub struct RecoveredState {} // todo: this is stubbed
}
mod implementations {
	use std::backtrace::Backtrace;
	use crate::{DiagCtxtHandle, DiagnosticContextHandle, Subdiagnostic};
	use crate::Color;
	use crate::ColorSpec;
	use std::borrow::Cow;
	use std::cell::Cell;
	use std::fmt;
	use std::fmt::Debug;
	use std::hash::{Hash, Hasher};
	use std::marker::PhantomData;
	use std::ops::{Deref, DerefMut};
	use std::path::{Path, PathBuf};
	use std::thread::panicking;
	use crate::daemonic::daemonic_contract::daemonic_result::diagnostic;
	use super::structures::*;
	use super::traits::*;

	// All implementations will be moved here
	// This is a placeholder file that will contain all the impl blocks from mod.rs
	// This `impl` block contains only the public diagnostic creation/emission API.
	//
	// Functions beginning with `struct_`/`create_` create a diagnostic. Other
	// functions create and emit a diagnostic all in one go.
	impl<'a> DiagnosticContextHandle<'a> {
		// No `#[rustc_lint_diagnostics]` and no `impl Into<DiagMessage>` because bug messages aren't
		// user-facing.
		#[track_caller]
		pub fn struct_bug(self, msg: impl Into<Cow<'static, str>>) -> crate::Diag<'a, BugAbort> {
			crate::Diag::new(self, crate::DiagnosticLevel::Bug, msg.into())
		}

		// No `#[rustc_lint_diagnostics]` and no `impl Into<DiagMessage>` because bug messages aren't
		// user-facing.
		#[track_caller]
		pub fn bug(self, msg: impl Into<Cow<'static, str>>) -> ! {
			self.struct_bug(msg).emit()
		}

		// No `#[rustc_lint_diagnostics]` and no `impl Into<DiagMessage>` because bug messages aren't
		// user-facing.
		#[track_caller]
		pub fn struct_span_bug(
			self,
			span: impl Into<MultiSpan>,
			msg: impl Into<Cow<'static, str>>,
		) -> crate::Diag<'a, BugAbort> {
			self.struct_bug(msg).with_span(span)
		}

		// No `#[rustc_lint_diagnostics]` and no `impl Into<DiagMessage>` because bug messages aren't
		// user-facing.
		#[track_caller]
		pub fn span_bug(self, span: impl Into<MultiSpan>, msg: impl Into<Cow<'static, str>>) -> ! {
			self.struct_span_bug(span, msg.into()).emit()
		}

		#[track_caller]
		pub fn create_bug(self, bug: impl crate::Diagnostic<'a, BugAbort>) -> crate::Diag<'a, BugAbort> {
			bug.into_diag(self, crate::DiagnosticLevel::Bug)
		}

		#[track_caller]
		pub fn emit_bug(self, bug: impl crate::Diagnostic<'a, BugAbort>) -> ! {
			self.create_bug(bug).emit()
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn struct_fatal(self, msg: impl Into<DiagMessage>) -> crate::Diag<'a, FatalAbort> {
			crate::Diag::new(self, crate::DiagnosticLevel::Fatal, msg)
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn fatal(self, msg: impl Into<DiagMessage>) -> ! {
			self.struct_fatal(msg).emit()
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn struct_span_fatal(
			self,
			span: impl Into<MultiSpan>,
			msg: impl Into<DiagMessage>,
		) -> crate::Diag<'a, FatalAbort> {
			self.struct_fatal(msg).with_span(span)
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn span_fatal(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) -> ! {
			self.struct_span_fatal(span, msg).emit()
		}

		#[track_caller]
		pub fn create_fatal(self, fatal: impl crate::Diagnostic<'a, FatalAbort>) -> crate::Diag<'a, FatalAbort> {
			fatal.into_diag(self, crate::DiagnosticLevel::Fatal)
		}

		#[track_caller]
		pub fn emit_fatal(self, fatal: impl crate::Diagnostic<'a, FatalAbort>) -> ! {
			self.create_fatal(fatal).emit()
		}

		#[track_caller]
		pub fn create_almost_fatal(
			self,
			fatal: impl crate::Diagnostic<'a, crate::FatalError>,
		) -> crate::Diag<'a, crate::FatalError> {
			fatal.into_diag(self, crate::DiagnosticLevel::Fatal)
		}

		#[track_caller]
		pub fn emit_almost_fatal(self, fatal: impl crate::Diagnostic<'a, crate::FatalError>) -> crate::FatalError {
			self.create_almost_fatal(fatal).emit()
		}

		// FIXME: This method should be removed (every error should have an associated error code).
		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn struct_err(self, msg: impl Into<DiagMessage>) -> crate::Diag<'a> {
			crate::Diag::new(self, crate::DiagnosticLevel::Error, msg)
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn err(self, msg: impl Into<DiagMessage>) -> crate::ErrorGuaranteed {
			self.struct_err(msg).emit()
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn struct_span_err(
			self,
			span: impl Into<MultiSpan>,
			msg: impl Into<DiagMessage>,
		) -> crate::Diag<'a> {
			self.struct_err(msg).with_span(span)
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn span_err(
			self,
			span: impl Into<MultiSpan>,
			msg: impl Into<DiagMessage>,
		) -> crate::ErrorGuaranteed {
			self.struct_span_err(span, msg).emit()
		}

		#[track_caller]
		pub fn create_err(self, err: impl crate::Diagnostic<'a>) -> crate::Diag<'a> {
			err.into_diag(self, crate::DiagnosticLevel::Error)
		}

		#[track_caller]
		pub fn emit_err(self, err: impl crate::Diagnostic<'a>) -> crate::ErrorGuaranteed {
			self.create_err(err).emit()
		}

		/// Ensures that an error is printed. See `Level::DelayedBug`.
		//
		// No `#[rustc_lint_diagnostics]` and no `impl Into<DiagMessage>` because bug messages aren't
		// user-facing.
		#[track_caller]
		pub fn delayed_bug(self, msg: impl Into<Cow<'static, str>>) -> crate::ErrorGuaranteed {
			crate::Diag::<crate::ErrorGuaranteed>::new(self, crate::DiagnosticLevel::DelayedBug, msg.into()).emit()
		}

		/// Ensures that an error is printed. See [`Level::DelayedBug`].
		///
		/// Note: this function used to be called `delay_span_bug`. It was renamed
		/// to match similar functions like `span_err`, `span_warn`, etc.
		//
		// No `#[rustc_lint_diagnostics]` and no `impl Into<DiagMessage>` because bug messages aren't
		// user-facing.
		#[track_caller]
		pub fn span_delayed_bug(
			self,
			sp: impl Into<MultiSpan>,
			msg: impl Into<Cow<'static, str>>,
		) -> crate::ErrorGuaranteed {
			crate::Diag::<crate::ErrorGuaranteed>::new(self, crate::DiagnosticLevel::DelayedBug, msg.into()).with_span(sp).emit()
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn struct_warn(self, msg: impl Into<DiagMessage>) -> crate::Diag<'a, ()> {
			crate::Diag::new(self, crate::DiagnosticLevel::Warning, msg)
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn warn(self, msg: impl Into<DiagMessage>) {
			self.struct_warn(msg).emit()
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn struct_span_warn(
			self,
			span: impl Into<MultiSpan>,
			msg: impl Into<DiagMessage>,
		) -> crate::Diag<'a, ()> {
			self.struct_warn(msg).with_span(span)
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn span_warn(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
			self.struct_span_warn(span, msg).emit()
		}

		#[track_caller]
		pub fn create_warn(self, warning: impl crate::Diagnostic<'a, ()>) -> crate::Diag<'a, ()> {
			warning.into_diag(self, crate::DiagnosticLevel::Warning)
		}

		#[track_caller]
		pub fn emit_warn(self, warning: impl crate::Diagnostic<'a, ()>) {
			self.create_warn(warning).emit()
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn struct_note(self, msg: impl Into<DiagMessage>) -> crate::Diag<'a, ()> {
			crate::Diag::new(self, crate::DiagnosticLevel::Note, msg)
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn note(&self, msg: impl Into<DiagMessage>) {
			self.struct_note(msg).emit()
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn struct_span_note(
			self,
			span: impl Into<MultiSpan>,
			msg: impl Into<DiagMessage>,
		) -> crate::Diag<'a, ()> {
			self.struct_note(msg).with_span(span)
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn span_note(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
			self.struct_span_note(span, msg).emit()
		}

		#[track_caller]
		pub fn create_note(self, note: impl crate::Diagnostic<'a, ()>) -> crate::Diag<'a, ()> {
			note.into_diag(self, crate::DiagnosticLevel::Note)
		}

		#[track_caller]
		pub fn emit_note(self, note: impl crate::Diagnostic<'a, ()>) {
			self.create_note(note).emit()
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn struct_help(self, msg: impl Into<DiagMessage>) -> crate::Diag<'a, ()> {
			crate::Diag::new(self, crate::DiagnosticLevel::Help, msg)
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn struct_failure_note(self, msg: impl Into<DiagMessage>) -> crate::Diag<'a, ()> {
			crate::Diag::new(self, crate::DiagnosticLevel::FailureNote, msg)
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn struct_allow(self, msg: impl Into<DiagMessage>) -> crate::Diag<'a, ()> {
			crate::Diag::new(self, crate::DiagnosticLevel::Allow, msg)
		}

		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn struct_expect(self, msg: impl Into<DiagMessage>, id: LintExpectationId) -> crate::Diag<'a, ()> {
			crate::Diag::new(self, crate::DiagnosticLevel::Expect, msg).with_lint_id(id)
		}
	}
	impl<'a> DiagnosticContextHandle<'a> {
		/// Stashes a diagnostic for possible later improvement in a different,
		/// later stage of the compiler. Possible actions depend on the diagnostic
		/// level:
		/// - Level::Bug, Level:Fatal: not allowed, will trigger a panic.
		/// - Level::Error: immediately counted as an error that has occurred, because it
		///   is guaranteed to be emitted eventually. Can be later accessed with the
		///   provided `span` and `key` through
		///   [`DiagnosticContextHandle::try_steal_modify_and_emit_err`] or
		///   [`DiagnosticContextHandle::try_steal_replace_and_emit_err`]. These do not allow
		///   cancellation or downgrading of the error. Returns
		///   `Some(ErrorGuaranteed)`.
		/// - Level::DelayedBug: this does happen occasionally with errors that are
		///   downgraded to delayed bugs. It is not stashed, but immediately
		///   emitted as a delayed bug. This is because stashing it would cause it
		///   to be counted by `err_count` which we don't want. It doesn't matter
		///   that we cannot steal and improve it later, because it's not a
		///   user-facing error. Returns `Some(ErrorGuaranteed)` as is normal for
		///   delayed bugs.
		/// - Level::Warning and lower (i.e. !is_error()): can be accessed with the
		///   provided `span` and `key` through [`DiagnosticContextHandle::steal_non_err()`]. This
		///   allows cancelling and downgrading of the diagnostic. Returns `None`.
		pub fn stash_diagnostic(
			&self,
			span: Span,
			key: StashKey,
			diag: DiagInner,
		) -> Option<ErrorGuaranteed> {
			let guar = match diag.level {
				DiagnosticLevel::Bug | DiagnosticLevel::Fatal => {
					self.span_bug(
						span,
						format!("invalid level in `stash_diagnostic`: {:?}", diag.level),
					);
				}
				// We delay a bug here so that `-Ztreat-err-as-bug -Zeagerly-emit-delayed-bugs`
				// can be used to create a backtrace at the stashing site instead of whenever the
				// diagnostic context is dropped and thus delayed bugs are emitted.
				DiagnosticLevel::Error => Some(self.span_delayed_bug(span, format!("stashing {key:?}"))),
				DiagnosticLevel::DelayedBug => {
					return self.inner.borrow_mut().emit_diagnostic(diag, self.tainted_with_errors);
				}
				DiagnosticLevel::ForceWarning
				| DiagnosticLevel::Warning
				| DiagnosticLevel::Note
				| DiagnosticLevel::OnceNote
				| DiagnosticLevel::Help
				| DiagnosticLevel::OnceHelp
				| DiagnosticLevel::FailureNote
				| DiagnosticLevel::Allow
				| DiagnosticLevel::Expect => None,
			};

			// FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
			// if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
			// See the PR for a discussion.
			self.inner
				.borrow_mut()
				.stashed_diagnostics
				.entry(key)
				.or_default()
				.insert(span.with_parent(None), (diag, guar));

			guar
		}

		/// Steal a previously stashed non-error diagnostic with the given `Span`
		/// and [`StashKey`] as the key. Panics if the found diagnostic is an
		/// error.
		pub fn steal_non_err(self, span: Span, key: StashKey) -> Option<Diag<'a, ()>> {
			// FIXME(#120456) - is `swap_remove` correct?
			let (diag, guar) = self.inner.borrow_mut().stashed_diagnostics.get_mut(&key).and_then(
				|stashed_diagnostics| stashed_diagnostics.swap_remove(&span.with_parent(None)),
			)?;
			assert!(!diag.is_error());
			assert!(guar.is_none());
			Some(Diag::new_diagnostic(self, diag))
		}

		/// Steals a previously stashed error with the given `Span` and
		/// [`StashKey`] as the key, modifies it, and emits it. Returns `None` if
		/// no matching diagnostic is found. Panics if the found diagnostic's level
		/// isn't `Level::Error`.
		pub fn try_steal_modify_and_emit_err<F>(
			self,
			span: Span,
			key: StashKey,
			mut modify_err: F,
		) -> Option<ErrorGuaranteed>
		where
			F: FnMut(&mut Diag<'_>),
		{
			// FIXME(#120456) - is `swap_remove` correct?
			let err = self.inner.borrow_mut().stashed_diagnostics.get_mut(&key).and_then(
				|stashed_diagnostics| stashed_diagnostics.swap_remove(&span.with_parent(None)),
			);
			err.map(|(err, guar)| {
				// The use of `::<ErrorGuaranteed>` is safe because level is `Level::Error`.
				assert_eq!(err.level, DiagnosticLevel::Error);
				assert!(guar.is_some());
				let mut err = Diag::<ErrorGuaranteed>::new_diagnostic(self, err);
				modify_err(&mut err);
				assert_eq!(err.level, DiagnosticLevel::Error);
				err.emit()
			})
		}

		/// Steals a previously stashed error with the given `Span` and
		/// [`StashKey`] as the key, cancels it if found, and emits `new_err`.
		/// Panics if the found diagnostic's level isn't `Level::Error`.
		pub fn try_steal_replace_and_emit_err(
			self,
			span: Span,
			key: StashKey,
			new_err: Diag<'_>,
		) -> ErrorGuaranteed {
			// FIXME(#120456) - is `swap_remove` correct?
			let old_err = self.inner.borrow_mut().stashed_diagnostics.get_mut(&key).and_then(
				|stashed_diagnostics| stashed_diagnostics.swap_remove(&span.with_parent(None)),
			);
			match old_err {
				Some((old_err, guar)) => {
					assert_eq!(old_err.level, DiagnosticLevel::Error);
					assert!(guar.is_some());
					// Because `old_err` has already been counted, it can only be
					// safely cancelled because the `new_err` supplants it.
					Diag::<ErrorGuaranteed>::new_diagnostic(self, old_err).cancel();
				}
				None => {}
			};
			new_err.emit()
		}

		pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool {
			let inner = self.inner.borrow();
			if let Some(stashed_diagnostics) = inner.stashed_diagnostics.get(&key)
				&& !stashed_diagnostics.is_empty()
			{
				stashed_diagnostics.contains_key(&span.with_parent(None))
			} else {
				false
			}
		}

		/// Emit all stashed diagnostics.
		pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
			self.inner.borrow_mut().emit_stashed_diagnostics()
		}

		/// This excludes delayed bugs.
		#[inline]
		pub fn err_count(&self) -> usize {
			let inner = self.inner.borrow();
			inner.err_guars.len()
				+ inner.lint_err_guars.len()
				+ inner
				.stashed_diagnostics
				.values()
				.map(|a| a.values().filter(|(_, guar)| guar.is_some()).count())
				.sum::<usize>()
		}

		/// This excludes lint errors and delayed bugs. Unless absolutely
		/// necessary, prefer `has_errors` to this method.
		pub fn has_errors_excluding_lint_errors(&self) -> Option<ErrorGuaranteed> {
			self.inner.borrow().has_errors_excluding_lint_errors()
		}

		/// This excludes delayed bugs.
		pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
			self.inner.borrow().has_errors()
		}

		/// This excludes nothing. Unless absolutely necessary, prefer `has_errors`
		/// to this method.
		pub fn has_errors_or_delayed_bugs(&self) -> Option<ErrorGuaranteed> {
			self.inner.borrow().has_errors_or_delayed_bugs()
		}

		pub fn print_error_count(&self) {
			let mut inner = self.inner.borrow_mut();

			// Any stashed diagnostics should have been handled by
			// `emit_stashed_diagnostics` by now.
			assert!(inner.stashed_diagnostics.is_empty());

			if inner.treat_err_as_bug() {
				return;
			}

			let warnings = match inner.deduplicated_warn_count {
				0 => Cow::from(""),
				1 => Cow::from("1 warning emitted"),
				count => Cow::from(format!("{count} warnings emitted")),
			};

			let errors = match inner.deduplicated_err_count {
				0 => Cow::from(""),
				1 => Cow::from("1 error emitted"),
				count => Cow::from(format!("{count} errors emitted")),
			};

			if inner.treat_warn_as_err() && !warnings.is_empty() {
				inner.emit_diagnostic(
					DiagInner::new(DiagnosticLevel::ForceWarning, DiagMessage::Str(warnings.clone().to_owned())),
					None,
				);
			}
			if !errors.is_empty() {
				if !warnings.is_empty() {
					inner.emit_diagnostic(DiagInner::new(DiagnosticLevel::Error, format!("{errors}; {warnings}")),
										  None,
					);
				} else {
					inner.emit_diagnostic(DiagInner::new(DiagnosticLevel::Error, errors.clone().to_owned()), None);
				}
			} else if !warnings.is_empty() {
				inner.emit_diagnostic(
					DiagInner::new(DiagnosticLevel::ForceWarning, DiagMessage::Str(warnings.clone().to_owned())),
					None,
				);
			}

			match (errors.is_empty(), warnings.is_empty()) {
				(true, true) => return,
				(false, true) => {
					inner.emit_diagnostic(DiagInner::new(DiagnosticLevel::FailureNote, "aborting due to previous error"), None);
				}
				(false, false) => {
					let msg1 = "aborting due to previous error";
					let msg2 = format!("For more information about this error, try `rustc --explain E{}`.", "");
					inner.emit_diagnostic(DiagInner::new(DiagnosticLevel::FailureNote, msg1), None);
					inner.emit_diagnostic(DiagInner::new(DiagnosticLevel::FailureNote, msg2), None);
				}
				(true, false) => {
					let msg = "warnings emitted";
					inner.emit_diagnostic(DiagInner::new(DiagnosticLevel::FailureNote, msg), None);
				}
			}
		}

		/// Abort if there are errors; otherwise, return.
		pub fn abort_if_errors(&self) {
			let mut inner = self.inner.borrow_mut();
			if !inner.has_errors().is_some() {
				return;
			}

			inner.emit_stashed_diagnostics();

			FatalError.raise();
		}

		pub fn must_teach(&self, code: ErrCode) -> bool {
			self.inner.borrow().must_teach(&code)
		}

		pub fn emit_diagnostic(&self, diagnostic: DiagInner) -> Option<ErrorGuaranteed> {
			self.inner.borrow_mut().emit_diagnostic(diagnostic, self.tainted_with_errors)
		}

		pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
			self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
		}

		pub fn emit_future_breakage_report(&self) {
			let mut inner = self.inner.borrow_mut();
			if inner.emitted_diagnostics.is_empty() {
				return;
			}
		}

		pub fn emit_unused_externs(
			&self,
			lint_level: rustc_lint_defs::LintLevel,
			loud: bool,
			unused_externs: &[&str],
		) {
			let mut inner = self.inner.borrow_mut();

			if loud && lint_level.is_error() {
				inner.bump_err_count();
			}

			drop(inner);

			for unused in unused_externs {
				let unused = unused.to_string();
				self.emit_diagnostic(DiagInner::new(
					DiagnosticLevel::Allow,
					format!("unused extern crate `{unused}`"),
				));
			}
		}

		pub fn steal_fulfilled_expectation_ids(&self) -> FxIndexSet<LintExpectationId> {
			assert!(
				self.inner.borrow().unstable_expect_diagnostics.is_empty(),
				"`DiagnosticContextHandle::steal_fulfilled_expectation_ids` must be called before `DiagnosticContextHandle::drop`"
			);
			std::mem::take(&mut self.inner.borrow_mut().fulfilled_expectations)
		}

		pub fn flush_delayed(&self) {
			self.inner.borrow_mut().flush_delayed()
		}

		/// Used when trimmed_def_paths is called and we must produce a diagnostic
		/// to justify its cost.
		#[track_caller]
		pub fn set_must_produce_diag(&self) {
			assert!(
				self.inner.borrow().must_produce_diag.is_none(),
				"should only need to collect a backtrace once"
			);
			self.inner.borrow_mut().must_produce_diag = Some(Backtrace::capture());
		}
	}
	// Don't implement Send on FatalError. This makes it impossible to `panic_any!(FatalError)`.
	// We don't want to invoke the panic handler and print a backtrace for fatal errors.
	impl ! Send for FatalError {}

	impl FatalError {
		pub fn raise(self) -> ! {
			std::panic::resume_unwind(Box::new(FatalErrorMarker))
		}
	}

	impl std::fmt::Display for FatalError {
		fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
			write!(f, "fatal error")
		}
	}

	impl std::error::Error for FatalError {}
	impl ErrorGuaranteed {
		/// Don't use this outside of `DiagCtxtInner::emit_diagnostic`!
		#[deprecated = "should only be used in `DiagCtxtInner::emit_diagnostic`"]
		pub fn unchecked_error_guaranteed() -> Self {
			ErrorGuaranteed(())
		}

		pub fn raise_fatal(self) -> ! {
			FatalError.raise()
		}
	}
	// // Existing impls unchanged (backward compatible):
	//
	impl diagnostic::EmissionGuarantee for ErrorGuaranteed {
		fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
			todo!()
		}
		// CONTINUEABLE defaults to true
		// emit_producing_guarantee unchanged
	}
	// Cloning a `Diag` is a recipe for a diagnostic being emitted twice, which
	// would be bad.
	// Thank you for that very detailed explanation as to WHY. ASSHOLE.
	impl<G> ! Clone for crate::Diag<'_, G> {}

	impl<G: diagnostic::EmissionGuarantee> Deref for crate::Diag<'_, G> {
		type Target = DiagInner;

		fn deref(&self) -> &DiagInner {
			self.diag.as_ref().unwrap()
		}
	}

	impl<G: diagnostic::EmissionGuarantee> DerefMut for crate::Diag<'_, G> {
		fn deref_mut(&mut self) -> &mut DiagInner {
			self.diag.as_mut().unwrap()
		}
	}

	impl<G: diagnostic::EmissionGuarantee> Debug for crate::Diag<'_, G> {
		fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
			self.diag.fmt(f)
		}
	}

	impl<'a, G: diagnostic::EmissionGuarantee> crate::Diag<'a, G> {
		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn new(dcx: DiagnosticContextHandle<'a>, level: diagnostic::DiagnosticLevel, message: impl Into<DiagMessage>) -> Self {
			Self::new_diagnostic(dcx, DiagInner::new(level, message))
		}

		/// Allow moving diagnostics between different error tainting contexts
		pub fn with_dcx(mut self, dcx: DiagnosticContextHandle<'_>) -> crate::Diag<'_, G> {
			crate::Diag { dcx, diag: self.diag.take(), _marker: PhantomData }
		}

		/// Creates a new `Diag` with an already constructed diagnostic.
		#[track_caller]
		pub(crate) fn new_diagnostic(dcx: DiagnosticContextHandle<'a>, diag: DiagInner) -> Self {
			debug!("Created new diagnostic");
			Self { dcx, diag: Some(Box::new(diag)), _marker: PhantomData }
		}

		/// Delay emission of this diagnostic as a bug.
		///
		/// This can be useful in contexts where an error indicates a bug but
		/// typically this only happens when other compilation errors have already
		/// happened. In those cases this can be used to defer emission of this
		/// diagnostic as a bug in the compiler only if no other errors have been
		/// emitted.
		///
		/// In the meantime, though, callsites are required to deal with the "bug"
		/// locally in whichever way makes the most sense.
		#[rustc_lint_diagnostics]
		#[track_caller]
		pub fn downgrade_to_delayed_bug(&mut self) {
			assert!(
				matches!(self.level, Level::Error | Level::DelayedBug),
				"downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
				self.level
			);
			self.level = diagnostic::DiagnosticLevel::DelayedBug;
		}

		#[doc = r" Appends a labeled span to the diagnostic."]
		#[doc = r""]
		#[doc = r" Labels are used to convey additional context for the diagnostic's primary span. They will"]
		#[doc = r" be shown together with the original diagnostic's span, *not* with spans added by"]
		#[doc = r" `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because"]
		#[doc = r" the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed"]
		#[doc = r" either."]
		#[doc = r""]
		#[doc = r" Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when"]
		#[doc = r" the diagnostic was constructed. However, the label span is *not* considered a"]
		#[doc = r#" ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is"#]
		#[doc = r" primary."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_label()`]."]
		pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagMessage>) -> &mut Self {
			let msg = self.subdiagnostic_message_to_diagnostic_message(label);
			self.span.push_span_label(span, msg);
			self
		}
		#[doc = r" Appends a labeled span to the diagnostic."]
		#[doc = r""]
		#[doc = r" Labels are used to convey additional context for the diagnostic's primary span. They will"]
		#[doc = r" be shown together with the original diagnostic's span, *not* with spans added by"]
		#[doc = r" `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because"]
		#[doc = r" the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed"]
		#[doc = r" either."]
		#[doc = r""]
		#[doc = r" Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when"]
		#[doc = r" the diagnostic was constructed. However, the label span is *not* considered a"]
		#[doc = r#" ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is"#]
		#[doc = r" primary."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_label()`]."]
		pub fn with_span_label(mut self, span: Span, label: impl Into<SubdiagMessage>) -> Self {
			self.span_label(span, label);
			self
		}

		#[doc = r" Labels all the given spans with the provided label."]
		#[doc = r" See [`Self::span_label()`] for more information."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_labels()`]."]
		pub fn span_labels(&mut self, spans: impl IntoIterator<Item=Span>, label: &str) -> &mut Self {
			for span in spans {
				self.span_label(span, label.to_string());
			}
			self
		}
		#[doc = r" Labels all the given spans with the provided label."]
		#[doc = r" See [`Self::span_label()`] for more information."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_labels()`]."]
		pub fn with_span_labels(mut self, spans: impl IntoIterator<Item=Span>, label: &str) -> Self {
			self.span_labels(spans, label);
			self
		}
		#[rustc_lint_diagnostics]
		pub fn replace_span_with(&mut self, after: Span, keep_label: bool) -> &mut Self {
			let before = self.span.clone();
			self.span(after);
			for span_label in before.span_labels() {
				if let Some(label) = span_label.label {
					if span_label.is_primary && keep_label {
						self.span.push_span_label(after, label);
					} else {
						self.span.push_span_label(span_label.span, label);
					}
				}
			}
			self
		}

		#[rustc_lint_diagnostics]
		pub fn note_expected_found(
			&mut self,
			expected_label: &str,
			expected: DiagStyledString,
			found_label: &str,
			found: DiagStyledString,
		) -> &mut Self {
			self.note_expected_found_extra(
				expected_label,
				expected,
				found_label,
				found,
				DiagStyledString::normal(""),
				DiagStyledString::normal(""),
			)
		}

		#[rustc_lint_diagnostics]
		pub fn note_expected_found_extra(
			&mut self,
			expected_label: &str,
			expected: DiagStyledString,
			found_label: &str,
			found: DiagStyledString,
			expected_extra: DiagStyledString,
			found_extra: DiagStyledString,
		) -> &mut Self {
			let expected_label = expected_label.to_string();
			let expected_label = if expected_label.is_empty() {
				"expected".to_string()
			} else {
				format!("expected {expected_label}")
			};
			let found_label = found_label.to_string();
			let found_label = if found_label.is_empty() {
				"found".to_string()
			} else {
				format!("found {found_label}")
			};
			let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
				(expected_label.len() - found_label.len(), 0)
			} else {
				(0, found_label.len() - expected_label.len())
			};
			let mut msg = vec![StringPart::normal(format!(
				"{}{} `",
				" ".repeat(expected_padding),
				expected_label
			))];
			msg.extend(expected.0);
			msg.push(StringPart::normal(format!("`")));
			msg.extend(expected_extra.0);
			msg.push(StringPart::normal(format!("\n")));
			msg.push(StringPart::normal(format!("{}{} `", " ".repeat(found_padding), found_label)));
			msg.extend(found.0);
			msg.push(StringPart::normal(format!("`")));
			msg.extend(found_extra.0);

			// For now, just attach these as notes.
			self.highlighted_note(msg);
			self
		}

		#[rustc_lint_diagnostics]
		pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
			self.highlighted_note(vec![
				StringPart::normal(format!("`{name}` from trait: `")),
				StringPart::highlighted(signature),
				StringPart::normal("`"),
			]);
			self
		}


		#[doc = r" Add a note attached to this diagnostic."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::note()`]."]
		pub fn note(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
			self.sub(diagnostic::DiagnosticLevel::Note, msg, MultiSpan::new());
			self
		}
		#[doc = r" Add a note attached to this diagnostic."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::note()`]."]
		pub fn with_note(mut self, msg: impl Into<SubdiagMessage>) -> Self {
			self.note(msg);
			self
		}
		#[rustc_lint_diagnostics]
		pub fn highlighted_note(&mut self, msg: Vec<StringPart>) -> &mut Self {
			self.sub_with_highlights(diagnostic::DiagnosticLevel::Note, msg, MultiSpan::new());
			self
		}

		#[rustc_lint_diagnostics]
		pub fn highlighted_span_note(
			&mut self,
			span: impl Into<MultiSpan>,
			msg: Vec<StringPart>,
		) -> &mut Self {
			self.sub_with_highlights(diagnostic::DiagnosticLevel::Note, msg, span.into());
			self
		}

		/// This is like [`crate::Diag::note()`], but it's only printed once.
		#[rustc_lint_diagnostics]
		pub fn note_once(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
			self.sub(diagnostic::DiagnosticLevel::OnceNote, msg, MultiSpan::new());
			self
		}


		#[doc = r" Prints the span with a note above it."]
		#[doc = r" This is like [`Diag::note()`], but it gets its own span."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_note()`]."]
		pub fn span_note(&mut self, sp: impl Into<MultiSpan>, msg: impl Into<SubdiagMessage>) -> &mut Self {
			self.sub(diagnostic::DiagnosticLevel::Note, msg, sp.into());
			self
		}
		#[doc = r" Prints the span with a note above it."]
		#[doc = r" This is like [`Diag::note()`], but it gets its own span."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_note()`]."]
		pub fn with_span_note(mut self, sp: impl Into<MultiSpan>, msg: impl Into<SubdiagMessage>) -> Self {
			self.span_note(sp, msg);
			self
		}
		/// Prints the span with a note above it.
		/// This is like [`crate::Diag::note_once()`], but it gets its own span.
		#[rustc_lint_diagnostics]
		pub fn span_note_once<S: Into<MultiSpan>>(
			&mut self,
			sp: S,
			msg: impl Into<SubdiagMessage>,
		) -> &mut Self {
			self.sub(diagnostic::DiagnosticLevel::OnceNote, msg, sp.into());
			self
		}


		#[doc = r" Add a warning attached to this diagnostic."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::warn()`]."]
		pub fn warn(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
			self.sub(diagnostic::DiagnosticLevel::Warning, msg, MultiSpan::new());
			self
		}
		#[doc = r" Add a warning attached to this diagnostic."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::warn()`]."]
		pub fn with_warn(mut self, msg: impl Into<SubdiagMessage>) -> Self {
			self.warn(msg);
			self
		}
		/// Prints the span with a warning above it.
		/// This is like [`crate::Diag::warn()`], but it gets its own span.
		#[rustc_lint_diagnostics]
		pub fn span_warn<S: Into<MultiSpan>>(
			&mut self,
			sp: S,
			msg: impl Into<SubdiagMessage>,
		) -> &mut Self {
			self.sub(diagnostic::DiagnosticLevel::Warning, msg, sp.into());
			self
		}


		#[doc = r" Add a help message attached to this diagnostic."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::help()`]."]
		pub fn help(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
			self.sub(diagnostic::DiagnosticLevel::Help, msg, MultiSpan::new());
			self
		}
		#[doc = r" Add a help message attached to this diagnostic."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::help()`]."]
		pub fn with_help(mut self, msg: impl Into<SubdiagMessage>) -> Self {
			self.help(msg);
			self
		}
		/// This is like [`crate::Diag::help()`], but it's only printed once.
		#[rustc_lint_diagnostics]
		pub fn help_once(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
			self.sub(diagnostic::DiagnosticLevel::OnceHelp, msg, MultiSpan::new());
			self
		}

		/// Add a help message attached to this diagnostic with a customizable highlighted message.
		#[rustc_lint_diagnostics]
		pub fn highlighted_help(&mut self, msg: Vec<StringPart>) -> &mut Self {
			self.sub_with_highlights(diagnostic::DiagnosticLevel::Help, msg, MultiSpan::new());
			self
		}

		/// Add a help message attached to this diagnostic with a customizable highlighted message.
		#[rustc_lint_diagnostics]
		pub fn highlighted_span_help(
			&mut self,
			span: impl Into<MultiSpan>,
			msg: Vec<StringPart>,
		) -> &mut Self {
			self.sub_with_highlights(diagnostic::DiagnosticLevel::Help, msg, span.into());
			self
		}

		/// Prints the span with some help above it.
		/// This is like [`crate::Diag::help()`], but it gets its own span.
		#[rustc_lint_diagnostics]
		pub fn span_help<S: Into<MultiSpan>>(
			&mut self,
			sp: S,
			msg: impl Into<SubdiagMessage>,
		) -> &mut Self {
			self.sub(diagnostic::DiagnosticLevel::Help, msg, sp.into());
			self
		}

		/// Disallow attaching suggestions to this diagnostic.
		/// Any suggestions attached e.g. with the `span_suggestion_*` methods
		/// (before and after the call to `disable_suggestions`) will be ignored.
		#[rustc_lint_diagnostics]
		pub fn disable_suggestions(&mut self) -> &mut Self {
			self.suggestions = Suggestions::Disabled;
			self
		}

		/// Prevent new suggestions from being added to this diagnostic.
		///
		/// Suggestions added before the call to `.seal_suggestions()` will be preserved
		/// and new suggestions will be ignored.
		#[rustc_lint_diagnostics]
		pub fn seal_suggestions(&mut self) -> &mut Self {
			if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
				let suggestions_slice = std::mem::take(suggestions).into_boxed_slice();
				self.suggestions = Suggestions::Sealed(suggestions_slice);
			}
			self
		}

		/// Helper for pushing to `self.suggestions`.
		///
		/// A new suggestion is added if suggestions are enabled for this diagnostic.
		/// Otherwise, they are ignored.
		#[rustc_lint_diagnostics]
		fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
			for subst in &suggestion.substitutions {
				for part in &subst.parts {
					let span = part.span;
					let call_site = span.ctxt().outer_expn_data().call_site;
					if span.in_derive_expansion() && span.overlaps_or_adjacent(call_site) {
						// Ignore if spans is from derive macro.
						return;
					}
				}
			}

			if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
				suggestions.push(suggestion);
			}
		}


		#[doc = r" Show a suggestion that has multiple parts to it."]
		#[doc = r" In other words, multiple changes need to be applied as part of this suggestion."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::multipart_suggestion()`]."]
		pub fn multipart_suggestion(&mut self, msg: impl Into<SubdiagMessage>, suggestion: Vec<(Span, String)>, applicability: Applicability) -> &mut Self {
			self.multipart_suggestion_with_style(
				msg,
				suggestion,
				applicability,
				SuggestionStyle::ShowCode,
			)
		}
		#[doc = r" Show a suggestion that has multiple parts to it."]
		#[doc = r" In other words, multiple changes need to be applied as part of this suggestion."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::multipart_suggestion()`]."]
		pub fn with_multipart_suggestion(mut self, msg: impl Into<SubdiagMessage>, suggestion: Vec<(Span, String)>, applicability: Applicability) -> Self {
			self.multipart_suggestion(msg, suggestion, applicability);
			self
		}
		/// Show a suggestion that has multiple parts to it, always as its own subdiagnostic.
		/// In other words, multiple changes need to be applied as part of this suggestion.
		#[rustc_lint_diagnostics]
		pub fn multipart_suggestion_verbose(
			&mut self,
			msg: impl Into<SubdiagMessage>,
			suggestion: Vec<(Span, String)>,
			applicability: Applicability,
		) -> &mut Self {
			self.multipart_suggestion_with_style(
				msg,
				suggestion,
				applicability,
				SuggestionStyle::ShowAlways,
			)
		}

		/// [`crate::Diag::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
		#[rustc_lint_diagnostics]
		pub fn multipart_suggestion_with_style(
			&mut self,
			msg: impl Into<SubdiagMessage>,
			mut suggestion: Vec<(Span, String)>,
			applicability: Applicability,
			style: SuggestionStyle,
		) -> &mut Self {
			let mut seen = FxHashSet::default();
			suggestion.retain(|(span, msg)| seen.insert((span.lo(), span.hi(), msg.clone())));

			let parts = suggestion
				.into_iter()
				.map(|(span, snippet)| SubstitutionPart { snippet, span })
				.collect::<Vec<_>>();

			assert!(!parts.is_empty());
			debug_assert_eq!(
				parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
				None,
				"Span must not be empty and have no suggestion",
			);
			debug_assert_eq!(
				parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
				None,
				"suggestion must not have overlapping parts",
			);

			self.push_suggestion(CodeSuggestion {
				substitutions: vec![Substitution { parts }],
				msg: self.subdiagnostic_message_to_diagnostic_message(msg),
				style,
				applicability,
			});
			self
		}

		/// Prints out a message with for a multipart suggestion without showing the suggested code.
		///
		/// This is intended to be used for suggestions that are obvious in what the changes need to
		/// be from the message, showing the span label inline would be visually unpleasant
		/// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
		/// improve understandability.
		#[rustc_lint_diagnostics]
		pub fn tool_only_multipart_suggestion(
			&mut self,
			msg: impl Into<SubdiagMessage>,
			suggestion: Vec<(Span, String)>,
			applicability: Applicability,
		) -> &mut Self {
			self.multipart_suggestion_with_style(
				msg,
				suggestion,
				applicability,
				SuggestionStyle::CompletelyHidden,
			)
		}


		#[doc = r" Prints out a message with a suggested edit of the code."]
		#[doc = r""]
		#[doc = r" In case of short messages and a simple suggestion, rustc displays it as a label:"]
		#[doc = r""]
		#[doc = r" ```text"]
		#[doc = r" try adding parentheses: `(tup.0).1`"]
		#[doc = r" ```"]
		#[doc = r""]
		#[doc = r" The message"]
		#[doc = r""]
		#[doc = r" * should not end in any punctuation (a `:` is added automatically)"]
		#[doc = r#" * should not be a question (avoid language like "did you mean")"#]
		#[doc = r#" * should not contain any phrases like "the following", "as shown", etc."#]
		#[doc = r#" * may look like "to do xyz, use" or "to do xyz, use abc""#]
		#[doc = r" * may contain a name of a function, variable, or type, but not whole expressions"]
		#[doc = r""]
		#[doc = r" See `CodeSuggestion` for more information."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_suggestion()`]."]
		pub fn span_suggestion(&mut self, sp: Span, msg: impl Into<SubdiagMessage>, suggestion: impl ToString, applicability: Applicability) -> &mut Self {
			self.span_suggestion_with_style(
				sp,
				msg,
				suggestion,
				applicability,
				SuggestionStyle::ShowCode,
			);
			self
		}
		#[doc = r" Prints out a message with a suggested edit of the code."]
		#[doc = r""]
		#[doc = r" In case of short messages and a simple suggestion, rustc displays it as a label:"]
		#[doc = r""]
		#[doc = r" ```text"]
		#[doc = r" try adding parentheses: `(tup.0).1`"]
		#[doc = r" ```"]
		#[doc = r""]
		#[doc = r" The message"]
		#[doc = r""]
		#[doc = r" * should not end in any punctuation (a `:` is added automatically)"]
		#[doc = r#" * should not be a question (avoid language like "did you mean")"#]
		#[doc = r#" * should not contain any phrases like "the following", "as shown", etc."#]
		#[doc = r#" * may look like "to do xyz, use" or "to do xyz, use abc""#]
		#[doc = r" * may contain a name of a function, variable, or type, but not whole expressions"]
		#[doc = r""]
		#[doc = r" See `CodeSuggestion` for more information."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_suggestion()`]."]
		pub fn with_span_suggestion(mut self, sp: Span, msg: impl Into<SubdiagMessage>, suggestion: impl ToString, applicability: Applicability) -> Self {
			self.span_suggestion(sp, msg, suggestion, applicability);
			self
		}
		/// [`crate::Diag::span_suggestion()`] but you can set the [`SuggestionStyle`].
		#[rustc_lint_diagnostics]
		pub fn span_suggestion_with_style(
			&mut self,
			sp: Span,
			msg: impl Into<SubdiagMessage>,
			suggestion: impl ToString,
			applicability: Applicability,
			style: SuggestionStyle,
		) -> &mut Self {
			debug_assert!(
				!(sp.is_empty() && suggestion.to_string().is_empty()),
				"Span must not be empty and have no suggestion"
			);
			self.push_suggestion(CodeSuggestion {
				substitutions: vec![Substitution {
					parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
				}],
				msg: self.subdiagnostic_message_to_diagnostic_message(msg),
				style,
				applicability,
			});
			self
		}


		#[doc = r" Always show the suggested change."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_suggestion_verbose()`]."]
		pub fn span_suggestion_verbose(&mut self, sp: Span, msg: impl Into<SubdiagMessage>, suggestion: impl ToString, applicability: Applicability) -> &mut Self {
			self.span_suggestion_with_style(
				sp,
				msg,
				suggestion,
				applicability,
				SuggestionStyle::ShowAlways,
			);
			self
		}
		#[doc = r" Always show the suggested change."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_suggestion_verbose()`]."]
		pub fn with_span_suggestion_verbose(mut self, sp: Span, msg: impl Into<SubdiagMessage>, suggestion: impl ToString, applicability: Applicability) -> Self {
			self.span_suggestion_verbose(sp, msg, suggestion, applicability);
			self
		}

		#[doc = r" Prints out a message with multiple suggested edits of the code."]
		#[doc = r" See also [`Diag::span_suggestion()`]."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_suggestions()`]."]
		pub fn span_suggestions(&mut self, sp: Span, msg: impl Into<SubdiagMessage>, suggestions: impl IntoIterator<Item=String>, applicability: Applicability) -> &mut Self {
			self.span_suggestions_with_style(
				sp,
				msg,
				suggestions,
				applicability,
				SuggestionStyle::ShowCode,
			)
		}
		#[doc = r" Prints out a message with multiple suggested edits of the code."]
		#[doc = r" See also [`Diag::span_suggestion()`]."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_suggestions()`]."]
		pub fn with_span_suggestions(mut self, sp: Span, msg: impl Into<SubdiagMessage>, suggestions: impl IntoIterator<Item=String>, applicability: Applicability) -> Self {
			self.span_suggestions(sp, msg, suggestions, applicability);
			self
		}
		#[rustc_lint_diagnostics]
		pub fn span_suggestions_with_style(
			&mut self,
			sp: Span,
			msg: impl Into<SubdiagMessage>,
			suggestions: impl IntoIterator<Item=String>,
			applicability: Applicability,
			style: SuggestionStyle,
		) -> &mut Self {
			let substitutions = suggestions
				.into_iter()
				.map(|snippet| {
					debug_assert!(
						!(sp.is_empty() && snippet.is_empty()),
						"Span must not be empty and have no suggestion"
					);
					Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] }
				})
				.collect();
			self.push_suggestion(CodeSuggestion {
				substitutions,
				msg: self.subdiagnostic_message_to_diagnostic_message(msg),
				style,
				applicability,
			});
			self
		}

		/// Prints out a message with multiple suggested edits of the code, where each edit consists of
		/// multiple parts.
		/// See also [`crate::Diag::multipart_suggestion()`].
		#[rustc_lint_diagnostics]
		pub fn multipart_suggestions(
			&mut self,
			msg: impl Into<SubdiagMessage>,
			suggestions: impl IntoIterator<Item=Vec<(Span, String)>>,
			applicability: Applicability,
		) -> &mut Self {
			let substitutions = suggestions
				.into_iter()
				.map(|sugg| {
					let mut parts = sugg
						.into_iter()
						.map(|(span, snippet)| SubstitutionPart { snippet, span })
						.collect::<Vec<_>>();

					parts.sort_unstable_by_key(|part| part.span);

					assert!(!parts.is_empty());
					debug_assert_eq!(
						parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
						None,
						"Span must not be empty and have no suggestion",
					);
					debug_assert_eq!(
						parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
						None,
						"suggestion must not have overlapping parts",
					);

					Substitution { parts }
				})
				.collect();

			self.push_suggestion(CodeSuggestion {
				substitutions,
				msg: self.subdiagnostic_message_to_diagnostic_message(msg),
				style: SuggestionStyle::ShowCode,
				applicability,
			});
			self
		}


		#[doc = r" Prints out a message with a suggested edit of the code. If the suggestion is presented"]
		#[doc = r" inline, it will only show the message and not the suggestion."]
		#[doc = r""]
		#[doc = r" See `CodeSuggestion` for more information."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_suggestion_short()`]."]
		pub fn span_suggestion_short(&mut self, sp: Span, msg: impl Into<SubdiagMessage>, suggestion: impl ToString, applicability: Applicability) -> &mut Self {
			self.span_suggestion_with_style(
				sp,
				msg,
				suggestion,
				applicability,
				SuggestionStyle::HideCodeInline,
			);
			self
		}
		#[doc = r" Prints out a message with a suggested edit of the code. If the suggestion is presented"]
		#[doc = r" inline, it will only show the message and not the suggestion."]
		#[doc = r""]
		#[doc = r" See `CodeSuggestion` for more information."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span_suggestion_short()`]."]
		pub fn with_span_suggestion_short(mut self, sp: Span, msg: impl Into<SubdiagMessage>, suggestion: impl ToString, applicability: Applicability) -> Self {
			self.span_suggestion_short(sp, msg, suggestion, applicability);
			self
		}
		/// Prints out a message for a suggestion without showing the suggested code.
		///
		/// This is intended to be used for suggestions that are obvious in what the changes need to
		/// be from the message, showing the span label inline would be visually unpleasant
		/// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
		/// improve understandability.
		#[rustc_lint_diagnostics]
		pub fn span_suggestion_hidden(
			&mut self,
			sp: Span,
			msg: impl Into<SubdiagMessage>,
			suggestion: impl ToString,
			applicability: Applicability,
		) -> &mut Self {
			self.span_suggestion_with_style(
				sp,
				msg,
				suggestion,
				applicability,
				SuggestionStyle::HideCodeAlways,
			);
			self
		}


		#[doc = r" Adds a suggestion to the JSON output that will not be shown in the CLI."]
		#[doc = r""]
		#[doc = r" This is intended to be used for suggestions that are *very* obvious in what the changes"]
		#[doc = r" need to be from the message, but we still want other tools to be able to apply them."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::tool_only_span_suggestion()`]."]
		pub fn tool_only_span_suggestion(&mut self, sp: Span, msg: impl Into<SubdiagMessage>, suggestion: impl ToString, applicability: Applicability) -> &mut Self {
			self.span_suggestion_with_style(
				sp,
				msg,
				suggestion,
				applicability,
				SuggestionStyle::CompletelyHidden,
			);
			self
		}
		#[doc = r" Adds a suggestion to the JSON output that will not be shown in the CLI."]
		#[doc = r""]
		#[doc = r" This is intended to be used for suggestions that are *very* obvious in what the changes"]
		#[doc = r" need to be from the message, but we still want other tools to be able to apply them."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::tool_only_span_suggestion()`]."]
		pub fn with_tool_only_span_suggestion(mut self, sp: Span, msg: impl Into<SubdiagMessage>, suggestion: impl ToString, applicability: Applicability) -> Self {
			self.tool_only_span_suggestion(sp, msg, suggestion, applicability);
			self
		}
		/// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
		/// [rustc_macros::Subdiagnostic]). Performs eager translation of any translatable messages
		/// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
		/// interpolated variables).
		#[rustc_lint_diagnostics]
		pub fn subdiagnostic(&mut self, subdiagnostic: impl Subdiagnostic) -> &mut Self {
			subdiagnostic.add_to_diag(self);
			self
		}

		/// Fluent (Deprecated in DaemonicCompiler) variables are not namespaced from each other, so when
		/// `Diagnostic`s and `Subdiagnostic`s use the same variable name,
		/// one value will clobber the other. Eagerly translating the
		/// diagnostic uses the variables defined right then, before the
		/// clobbering occurs.
		pub fn eagerly_translate(&self, msg: impl Into<SubdiagMessage>) -> SubdiagMessage {
			let args = self.args.iter();
			let msg = self.subdiagnostic_message_to_diagnostic_message(msg.into());
			self.dcx.eagerly_translate(msg, args)
		}


		#[doc = r" Add a span."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span()`]."]
		pub fn span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self {
			self.span = sp.into();
			if let Some(span) = self.span.primary_span() {
				self.sort_span = span;
			}
			self
		}
		#[doc = r" Add a span."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::span()`]."]
		pub fn with_span(mut self, sp: impl Into<MultiSpan>) -> Self {
			self.span(sp);
			self
		}
		#[rustc_lint_diagnostics]
		pub fn is_lint(&mut self, name: String, has_future_breakage: bool) -> &mut Self {
			self.is_lint = Some(IsLint { name, has_future_breakage });
			self
		}

		#[doc = r" Add an error code."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::code()`]."]
		pub fn code(&mut self, code: ErrCode) -> &mut Self {
			self.code = Some(code);
			self
		}
		#[doc = r" Add an error code."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::code()`]."]
		pub fn with_code(mut self, code: ErrCode) -> Self {
			self.code(code);
			self
		}

		#[doc = r" Add an argument."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::lint_id()`]."]
		pub fn lint_id(&mut self, id: LintExpectationId) -> &mut Self {
			self.lint_id = Some(id);
			self
		}
		#[doc = r" Add an argument."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::lint_id()`]."]
		pub fn with_lint_id(mut self, id: LintExpectationId) -> Self {
			self.lint_id(id);
			self
		}

		#[doc = r" Add a primary message."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::primary_message()`]."]
		pub fn primary_message(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
			self.messages[0] = (msg.into(), Style::NoStyle);
			self
		}
		#[doc = r" Add a primary message."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::primary_message()`]."]
		pub fn with_primary_message(mut self, msg: impl Into<DiagMessage>) -> Self {
			self.primary_message(msg);
			self
		}

		#[doc = r" Add an argument."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::arg()`]."]
		pub fn arg(&mut self, name: impl Into<diagnostic::DiagArgName>, arg: impl crate::IntoDiagArg) -> &mut Self {
			self.deref_mut().arg(name, arg);
			self
		}
		#[doc = r" Add an argument."]
		#[rustc_lint_diagnostics]
		#[doc = "See [`Diag::arg()`]."]
		pub fn with_arg(mut self, name: impl Into<diagnostic::DiagArgName>, arg: impl crate::IntoDiagArg) -> Self {
			self.arg(name, arg);
			self
		}
		/// Helper function that takes a `SubdiagMessage` and returns a `DiagMessage` by
		/// combining it with the primary message of the diagnostic (if translatable, otherwise it just
		/// passes the user's string along).
		pub(crate) fn subdiagnostic_message_to_diagnostic_message(
			&self,
			attr: impl Into<SubdiagMessage>,
		) -> DiagMessage {
			self.deref().subdiagnostic_message_to_diagnostic_message(attr)
		}

		/// Convenience function for internal use, clients should use one of the
		/// public methods above.
		///
		/// Used by `proc_macro_server` for implementing `server::Diagnostic`.
		pub fn sub(&mut self, level: diagnostic::DiagnosticLevel, message: impl Into<SubdiagMessage>, span: MultiSpan) {
			self.deref_mut().sub(level, message, span);
		}

		/// Convenience function for internal use, clients should use one of the
		/// public methods above.
		fn sub_with_highlights(&mut self, level: diagnostic::DiagnosticLevel, messages: Vec<StringPart>, span: MultiSpan) {
			let messages = messages
				.into_iter()
				.map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.content), m.style))
				.collect();
			let sub = crate::Subdiag { level, messages, span };
			self.children.push(sub);
		}

		/// Takes the diagnostic. For use by methods that consume the Diag: `emit`,
		/// `cancel`, etc. Afterwards, `drop` is the only code that will be run on
		/// `self`.
		fn take_diag(&mut self) -> DiagInner {
			if let Some(path) = &self.long_ty_path {
				self.note(format!(
					"the full name for the type has been written to '{}'",
					path.display()
				));
				self.note("consider using `--verbose` to print the full type name to the console");
			}
			Box::into_inner(self.diag.take().unwrap())
		}

		/// This method allows us to access the path of the file where "long types" are written to.
		///
		/// When calling `Diag::emit`, as part of that we will check if a `long_ty_path` has been set,
		/// and if it has been then we add a note mentioning the file where the "long types" were
		/// written to.
		///
		/// When calling `tcx.short_string()` after a `Diag` is constructed, the preferred way of doing
		/// so is `tcx.short_string(ty, diag.long_ty_path())`. The diagnostic itself is the one that
		/// keeps the existence of a "long type" anywhere in the diagnostic, so the note telling the
		/// user where we wrote the file to is only printed once at most, *and* it makes it much harder
		/// to forget to set it.
		///
		/// If the diagnostic hasn't been created before a "short ty string" is created, then you should
		/// ensure that this method is called to set it `*diag.long_ty_path() = path`.
		///
		/// As a rule of thumb, if you see or add at least one `tcx.short_string()` call anywhere, in a
		/// scope, `diag.long_ty_path()` should be called once somewhere close by.
		pub fn long_ty_path(&mut self) -> &mut Option<PathBuf> {
			&mut self.long_ty_path
		}

		/// Most `emit_producing_guarantee` functions use this as a starting point.
		pub fn emit_producing_nothing(mut self) {
			let diag = self.take_diag();
			self.dcx.emit_diagnostic(diag);
		}

		/// `ErrorGuaranteed::emit_producing_guarantee` uses this.
		pub fn emit_producing_error_guaranteed(mut self) -> ErrorGuaranteed {
			let diag = self.take_diag();

			// The only error levels that produce `ErrorGuaranteed` are
			// `Error` and `DelayedBug`. But `DelayedBug` should never occur here
			// because delayed bugs have their level changed to `Bug` when they are
			// actually printed, so they produce an ICE.
			//
			// (Also, even though `level` isn't `pub`, the whole `DiagInner` could
			// be overwritten with a new one thanks to `DerefMut`. So this assert
			// protects against that, too.)
			assert!(
				matches!(diag.level, Level::Error | Level::DelayedBug),
				"invalid diagnostic level ({:?})",
				diag.level,
			);

			let guar = self.dcx.emit_diagnostic(diag);
			guar.unwrap()
		}

		/// Emit and consume the diagnostic.
		#[track_caller]
		pub fn emit(self) -> G::EmitResult {
			G::emit_producing_guarantee(self)
		}

		/// Emit the diagnostic unless `delay` is true,
		/// in which case the emission will be delayed as a bug.
		///
		/// See `emit` and `delay_as_bug` for details.
		#[track_caller]
		pub fn emit_unless(mut self, delay: bool) -> G::EmitResult {
			if delay {
				self.downgrade_to_delayed_bug();
			}
			self.emit()
		}

		/// Cancel and consume the diagnostic. (A diagnostic must either be emitted or
		/// cancelled or it will panic when dropped).
		pub fn cancel(mut self) {
			self.diag = None;
			drop(self);
		}

		/// See `DiagCtxt::stash_diagnostic` for details.
		pub fn stash(mut self, span: Span, key: StashKey) -> Option<ErrorGuaranteed> {
			let diag = self.take_diag();
			self.dcx.stash_diagnostic(span, key, diag)
		}

		/// Delay emission of this diagnostic as a bug.
		///
		/// This can be useful in contexts where an error indicates a bug but
		/// typically this only happens when other compilation errors have already
		/// happened. In those cases this can be used to defer emission of this
		/// diagnostic as a bug in the compiler only if no other errors have been
		/// emitted.
		///
		/// In the meantime, though, callsites are required to deal with the "bug"
		/// locally in whichever way makes the most sense.
		#[track_caller]
		pub fn delay_as_bug(mut self) -> G::EmitResult {
			self.downgrade_to_delayed_bug();
			self.emit()
		}
	}

	/// Destructor bomb: every `Diag` must be consumed (emitted, cancelled, etc.)
	/// or we emit a bug.
	impl<G: diagnostic::EmissionGuarantee> Drop for crate::Diag<'_, G> {
		fn drop(&mut self) {
			match self.diag.take() {
				Some(diag) if !panicking() => {
					self.dcx.emit_diagnostic(DiagInner::new(
						diagnostic::DiagnosticLevel::Bug,
						DiagMessage::from("the following error was constructed but not emitted"),
					));
					self.dcx.emit_diagnostic(*diag);
					panic!("error was constructed but not emitted");
				}
				_ => {}
			}
		}
	}
	impl fmt::Display for crate::DiagnosticLevel {
		fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
			self.to_str().fmt(f)
		}
	}
	impl crate::DiagnosticLevel {
		pub fn color(self) -> ColorSpec {
			let mut spec = ColorSpec::new();
			match self {
				crate::DiagnosticLevel::Bug | crate::DiagnosticLevel::Fatal | crate::DiagnosticLevel::Error | crate::DiagnosticLevel::DelayedBug => {
					spec.set_fg(Some(Color::Red)).set_intense(true);
				}
				crate::DiagnosticLevel::ForceWarning | crate::DiagnosticLevel::Warning => {
					spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
				}
				crate::DiagnosticLevel::Note | crate::DiagnosticLevel::OnceNote => {
					spec.set_fg(Some(Color::Green)).set_intense(true);
				}
				crate::DiagnosticLevel::Help | crate::DiagnosticLevel::OnceHelp => {
					spec.set_fg(Some(Color::Cyan)).set_intense(true);
				}
				crate::DiagnosticLevel::FailureNote => {}
				crate::DiagnosticLevel::Allow | crate::DiagnosticLevel::Expect => unreachable!(),
			}
			spec
		}

		pub fn to_str(self) -> &'static str {
			match self {
				crate::DiagnosticLevel::Bug | crate::DiagnosticLevel::DelayedBug => "error: internal compiler error",
				crate::DiagnosticLevel::Fatal | crate::DiagnosticLevel::Error => "error",
				crate::DiagnosticLevel::ForceWarning | crate::DiagnosticLevel::Warning => "warning",
				crate::DiagnosticLevel::Note | crate::DiagnosticLevel::OnceNote => "note",
				crate::DiagnosticLevel::Help | crate::DiagnosticLevel::OnceHelp => "help",
				crate::DiagnosticLevel::FailureNote => "failure-note",
				crate::DiagnosticLevel::Allow | crate::DiagnosticLevel::Expect => unreachable!(),
			}
		}

		pub fn is_failure_note(&self) -> bool {
			matches!(*self, DiagnosticLevel::FailureNote)
		}

		// Can this level be used in a subdiagnostic message?
		fn can_be_subdiag(&self) -> bool {
			match self {
				crate::DiagnosticLevel::Bug |
				crate::DiagnosticLevel::DelayedBug |
				crate::DiagnosticLevel::Fatal |
				crate::DiagnosticLevel::Error |
				crate::DiagnosticLevel::ForceWarning |
				crate::DiagnosticLevel::FailureNote |
				crate::DiagnosticLevel::Allow |
				crate::DiagnosticLevel::Expect => false,

				crate::DiagnosticLevel::Warning |
				crate::DiagnosticLevel::Note |
				crate::DiagnosticLevel::Help |
				crate::DiagnosticLevel::OnceNote |
				crate::DiagnosticLevel::OnceHelp => true,
			}
		}
	}
	/// Converts a value of a type into a `DiagArg` (typically a field of an `Diag` struct).
	/// Implemented as a custom trait rather than `From` so that it is implemented on the type being
	/// converted rather than on `DiagArgValue`, which enables types from other `rustc_*` crates to
	/// implement this.

	impl diagnostic::EmissionGuarantee for () {
		fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
			todo!()
		}
		// Warnings, continue
	}

	// // NEW: Fatal no longer FORCES diverge
	impl diagnostic::EmissionGuarantee for FatalGuarantee {
		const CONTINUEABLE: bool = false;  // Not by default
		type RecoveryHandler = diagnostic::FatalRecovery;  // But CAN recover

		fn emit_producing_guarantee(diag: crate::Diag<'_, Self>) -> Self::EmitResult {
			// Original fatal logic
		}
	}
	impl RecoveryHandler<FatalGuarantee> for FatalRecovery {
		fn attempt_recovery(result: &FatalGuarantee) -> Option<RecoveredState> {
			// Check if this specific fatal is recoverable
			if result.kind.is_structurally_broken() {
				None  // Truly must stop
			} else {
				Some(RecoveredState::from_fatal(result))
			}
		}
	}
	// // NEW: Fatal no longer FORCES diverge
	impl EmissionGuarantee for FatalGuarantee {
		const CONTINUEABLE: bool = false;
		// Not by default
		type RecoveryHandler = FatalRecovery;  // But CAN recover

		fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
			// todo: Original fatal logic stub
		}
	}
	impl DiagInner {
		#[track_caller]
		pub fn new<M: Into<DiagMessage>>(level: crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel, message: M) -> Self {
			DiagInner::new_with_messages(level, vec![(message.into(), Style::NoStyle)])
		}

		#[track_caller]
		pub fn new_with_messages(level: crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel, messages: Vec<(DiagMessage, Style)>) -> Self {
			DiagInner {
				level,
				lint_id: None,
				messages,
				code: None,
				span: MultiSpan::new(),
				children: vec![],
				suggestions: Suggestions::Enabled(vec![]),
				args: Default::default(),
				sort_span: DUMMY_SP,
				is_lint: None,
				long_ty_path: None,
				emitted_at: DiagLocation::caller(),
			}
		}

		#[inline(always)]
		pub fn level(&self) -> crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel {
			self.level
		}

		pub fn is_error(&self) -> bool {
			match self.level {
				crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::Bug | crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::Fatal | crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::Error | crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::DelayedBug => true,

				crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::ForceWarning
				| crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::Warning
				| crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::Note
				| crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::OnceNote
				| crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::Help
				| crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::OnceHelp
				| crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::FailureNote
				| crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::Allow
				| crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::Expect => false,
			}
		}

		/// Indicates whether this diagnostic should show up in cargo's future breakage report.
		pub(crate) fn has_future_breakage(&self) -> bool {
			matches!(self.is_lint, Some(IsLint { has_future_breakage: true, .. }))
		}

		pub(crate) fn is_force_warn(&self) -> bool {
			match self.level {
				crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel::ForceWarning => {
					assert!(self.is_lint.is_some());
					true
				}
				_ => false,
			}
		}

		// See comment on `Diag::subdiagnostic_message_to_diagnostic_message`.
		pub fn subdiagnostic_message_to_diagnostic_message(
			&self,
			attr: impl Into<SubdiagMessage>,
		) -> DiagMessage {
			let msg =
				self.messages.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
			msg.with_subdiagnostic_message(attr.into())
		}

		pub(crate) fn sub(
			&mut self,
			level: crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel,
			message: impl Into<SubdiagMessage>,
			span: MultiSpan,
		) {
			let sub = Subdiag {
				level,
				messages: vec![(
					self.subdiagnostic_message_to_diagnostic_message(message),
					Style::NoStyle,
				)],
				span,
			};
			self.children.push(sub);
		}

		pub(crate) fn arg(&mut self, name: impl Into<DiagArgName>, arg: impl IntoDiagArg) {
			self.args.insert(name.into(), arg.into_diag_arg(&mut self.long_ty_path));
		}

		/// Fields used for DaemonicHashable, and PartialEq trait.
		fn keys(
			&self,
		) -> (
			&crate::daemonic::daemonic_contract::daemonic_result::diagnostic::structures::DiagnosticLevel,
			&[(DiagMessage, Style)],
			&Option<ErrCode>,
			&MultiSpan,
			&[Subdiag],
			&Suggestions,
			Vec<(&DiagArgName, &DiagArgValue)>,
			&Option<IsLint>,
		) {
			(
				&self.level,
				&self.messages,
				&self.code,
				&self.span,
				&self.children,
				&self.suggestions,
				self.args.iter().collect(),
				// omit self.sort_span
				&self.is_lint,
				// omit self.emitted_at
			)
		}
	}

	impl Hash for DiagInner {
		fn hash<H>(&self, state: &mut H)
		where
			H: Hasher,
		{
			self.keys().hash(state);
		}
	}

	impl PartialEq for DiagInner {
		fn eq(&self, other: &Self) -> bool {
			self.keys() == other.keys()
		}
	}
	impl IntoDiagArg for DiagArgValue {
		fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
			self
		}
	}
	impl<'a> std::ops::Deref for DiagCtxtHandle<'a> {
		type Target = &'a DiagCtxt;

		fn deref(&self) -> &Self::Target {
			&self.dcx
		}
	}
}

pub use traits::*;
pub use structures::*;
pub use implementations::*;


// Trait for types that `Diag::emit` can return as a "guarantee" (or "proof")
// token that the emission happened.
// pub trait EmissionGuarantee: Sized {
// 	/// This exists so that bugs and fatal errors can both result in `!` (an
// 	/// abort) when emitted, but have different aborting behaviour.
// 	/// But.. fuckin why? Bugs and Fatals should be handled better than
// 	/// just blanketing all as `!` bails. They should emit states that allow
// 	/// caller to define behavior, if no behavior defined or trait unbound at
// 	/// callsite -> then trigger `!`
// 	/// `!` should not be the sole promise EmissionGuarantee provides.
// 	type EmitResult = Self;
//
// 	/// Implementation of `Diag::emit`, fully controlled by each `impl` of
// 	/// `EmissionGuarantee`, to make it impossible to create a value of
// 	/// `Self::EmitResult` without actually performing the emission.
// 	/// Logic still 'works' and compiles, but is semantically incorrect.
// 	/// emit result is an alias for Self, Self::EmitResult -> returns Self::Self under the hood.
// 	///
// 	///    2024 edition (current logic) semantics state this should be a dynamic trait
// 	///    But dyn Self::Self doesnt compile, throws type error "Expected Trait, found Type Alias"
// 	///    this makes sense because Types define what and how to store.
// 	///    Trait defines behavior given context, emitting Type Self::EmitResult in this context
// 	/// propagates self up to a Sized EmissionGuaranteed trait, which can be employed elsewhere.
// 	/// Why the fuck does this work and compile?
// 	/// Whoever originally wrote this had to work within constraints, i get it.
// 	/// But also, Fuck You. Sincerely, Meph.
// 	#[track_caller]
// 	fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult; // todo: This was written pre 2018 edition.
//
//
//
// 	//
//
// 	const CONTINUEABLE: bool;
// 	// Not by default
// 	type RecoveryHandler;
// }

/// Constructs an event at the debug level.
/// i hate this macro.
/// this is legacy macro.
/// fuck this macro.
/// replace with proper constructor at some point
///
/// This functions similarly to the [`event!`] macro. See [the top-level
/// documentation][lib] for details on the syntax accepted by
/// this macro.
///
/// [`event!`]: crate::event!
/// [lib]: crate#using-the-macros
///
/// # Examples
///
/// ```rust
/// use tracing::debug;
/// # fn main() {
/// # #[derive(Debug)] struct Position { x: f32, y: f32 }
///
/// let pos = Position { x: 3.234, y: -1.223 };
///
/// debug!(?pos.x, ?pos.y);
/// debug!(target: "app_events", position = ?pos, "New position");
/// debug!(name: "completed", position = ?pos);
/// # }
/// ```
#[macro_export]
macro_rules! debug {
// Name / target / parent.
(name: $name:expr, target: $target:expr, parent: $parent:expr, { $($field:tt)* }, $($arg:tt)* ) => (
$crate::event!(name: $name, target: $target, parent: $parent, $crate::Level::DEBUG, { $($field)* }, $($arg)*)
);
(name: $name:expr, target: $target:expr, parent: $parent:expr, $($k:ident).+ $($field:tt)* ) => (
$crate::event!(name: $name, target: $target, parent: $parent, $crate::Level::DEBUG, { $($k).+ $($field)* })
);
(name: $name:expr, target: $target:expr, parent: $parent:expr, ?$($k:ident).+ $($field:tt)* ) => (
$crate::event!(name: $name, target: $target, parent: $parent, $crate::Level::DEBUG, { ?$($k).+ $($field)* })
);
(name: $name:expr, target: $target:expr, parent: $parent:expr, %$($k:ident).+ $($field:tt)* ) => (
$crate::event!(name: $name, target: $target, parent: $parent, $crate::Level::DEBUG, { %$($k).+ $($field)* })
);
(name: $name:expr, target: $target:expr, parent: $parent:expr, $($arg:tt)+ ) => (
$crate::event!(name: $name, target: $target, parent: $parent, $crate::Level::DEBUG, {}, $($arg)+)
);

// Name / target.
(name: $name:expr, target: $target:expr, { $($field:tt)* }, $($arg:tt)* ) => (
$crate::event!(name: $name, target: $target, $crate::Level::DEBUG, { $($field)* }, $($arg)*)
);
(name: $name:expr, target: $target:expr, $($k:ident).+ $($field:tt)* ) => (
$crate::event!(name: $name, target: $target, $crate::Level::DEBUG, { $($k).+ $($field)* })
);
(name: $name:expr, target: $target:expr, ?$($k:ident).+ $($field:tt)* ) => (
$crate::event!(name: $name, target: $target, $crate::Level::DEBUG, { ?$($k).+ $($field)* })
);
(name: $name:expr, target: $target:expr, %$($k:ident).+ $($field:tt)* ) => (
$crate::event!(name: $name, target: $target, $crate::Level::DEBUG, { %$($k).+ $($field)* })
);
(name: $name:expr, target: $target:expr, $($arg:tt)+ ) => (
$crate::event!(name: $name, target: $target, $crate::Level::DEBUG, {}, $($arg)+)
);

// Target / parent.
(target: $target:expr, parent: $parent:expr, { $($field:tt)* }, $($arg:tt)* ) => (
$crate::event!(target: $target, parent: $parent, $crate::Level::DEBUG, { $($field)* }, $($arg)*)
);
(target: $target:expr, parent: $parent:expr, $($k:ident).+ $($field:tt)* ) => (
$crate::event!(target: $target, parent: $parent, $crate::Level::DEBUG, { $($k).+ $($field)* })
);
(target: $target:expr, parent: $parent:expr, ?$($k:ident).+ $($field:tt)* ) => (
$crate::event!(target: $target, parent: $parent, $crate::Level::DEBUG, { ?$($k).+ $($field)* })
);
(target: $target:expr, parent: $parent:expr, %$($k:ident).+ $($field:tt)* ) => (
$crate::event!(target: $target, parent: $parent, $crate::Level::DEBUG, { %$($k).+ $($field)* })
);
(target: $target:expr, parent: $parent:expr, $($arg:tt)+ ) => (
$crate::event!(target: $target, parent: $parent, $crate::Level::DEBUG, {}, $($arg)+)
);

// Name / parent.
(name: $name:expr, parent: $parent:expr, { $($field:tt)* }, $($arg:tt)* ) => (
$crate::event!(name: $name, parent: $parent, $crate::Level::DEBUG, { $($field)* }, $($arg)*)
);
(name: $name:expr, parent: $parent:expr, $($k:ident).+ $($field:tt)* ) => (
$crate::event!(name: $name, parent: $parent, $crate::Level::DEBUG, { $($k).+ $($field)* })
);
(name: $name:expr, parent: $parent:expr, ?$($k:ident).+ $($field:tt)* ) => (
$crate::event!(name: $name, parent: $parent, $crate::Level::DEBUG, { ?$($k).+ $($field)* })
);
(name: $name:expr, parent: $parent:expr, %$($k:ident).+ $($field:tt)* ) => (
$crate::event!(name: $name, parent: $parent, $crate::Level::DEBUG, { %$($k).+ $($field)* })
);
(name: $name:expr, parent: $parent:expr, $($arg:tt)+ ) => (
$crate::event!(name: $name, parent: $parent, $crate::Level::DEBUG, {}, $($arg)+)
);

// Name.
(name: $name:expr, { $($field:tt)* }, $($arg:tt)* ) => (
$crate::event!(name: $name, $crate::Level::DEBUG, { $($field)* }, $($arg)*)
);
(name: $name:expr, $($k:ident).+ $($field:tt)* ) => (
$crate::event!(name: $name, $crate::Level::DEBUG, { $($k).+ $($field)* })
);
(name: $name:expr, ?$($k:ident).+ $($field:tt)* ) => (
$crate::event!(name: $name, $crate::Level::DEBUG, { ?$($k).+ $($field)* })
);
(name: $name:expr, %$($k:ident).+ $($field:tt)* ) => (
$crate::event!(name: $name, $crate::Level::DEBUG, { %$($k).+ $($field)* })
);
(name: $name:expr, $($arg:tt)+ ) => (
$crate::event!(name: $name, $crate::Level::DEBUG, {}, $($arg)+)
);

// Target.
(target: $target:expr, { $($field:tt)* }, $($arg:tt)* ) => (
$crate::event!(target: $target, $crate::Level::DEBUG, { $($field)* }, $($arg)*)
);
(target: $target:expr, $($k:ident).+ $($field:tt)* ) => (
$crate::event!(target: $target, $crate::Level::DEBUG, { $($k).+ $($field)* })
);
(target: $target:expr, ?$($k:ident).+ $($field:tt)* ) => (
$crate::event!(target: $target, $crate::Level::DEBUG, { ?$($k).+ $($field)* })
);
(target: $target:expr, %$($k:ident).+ $($field:tt)* ) => (
$crate::event!(target: $target, $crate::Level::DEBUG, { %$($k).+ $($field)* })
);
(target: $target:expr, $($arg:tt)+ ) => (
$crate::event!(target: $target, $crate::Level::DEBUG, {}, $($arg)+)
);

// Parent.
(parent: $parent:expr, { $($field:tt)+ }, $($arg:tt)+ ) => (
$crate::event!(
target: module_path!(),
parent: $parent,
$crate::Level::DEBUG,
{ $($field)+ },
$($arg)+
)
);
(parent: $parent:expr, $($k:ident).+ = $($field:tt)*) => (
$crate::event!(
target: module_path!(),
parent: $parent,
$crate::Level::DEBUG,
{ $($k).+ = $($field)*}
)
);
(parent: $parent:expr, ?$($k:ident).+ = $($field:tt)*) => (
$crate::event!(
target: module_path!(),
parent: $parent,
$crate::Level::DEBUG,
{ ?$($k).+ = $($field)*}
)
);
(parent: $parent:expr, %$($k:ident).+ = $($field:tt)*) => (
$crate::event!(
target: module_path!(),
parent: $parent,
$crate::Level::DEBUG,
{ %$($k).+ = $($field)*}
)
);
(parent: $parent:expr, $($k:ident).+, $($field:tt)*) => (
$crate::event!(
target: module_path!(),
parent: $parent,
$crate::Level::DEBUG,
{ $($k).+, $($field)*}
)
);
(parent: $parent:expr, ?$($k:ident).+, $($field:tt)*) => (
$crate::event!(
target: module_path!(),
parent: $parent,
$crate::Level::DEBUG,
{ ?$($k).+, $($field)*}
)
);
(parent: $parent:expr, %$($k:ident).+, $($field:tt)*) => (
$crate::event!(
target: module_path!(),
parent: $parent,
$crate::Level::DEBUG,
{ %$($k).+, $($field)*}
)
);
(parent: $parent:expr, $($arg:tt)+) => (
$crate::event!(
target: module_path!(),
parent: $parent,
$crate::Level::DEBUG,
{},
$($arg)+
)
);

// ...
({ $($field:tt)+ }, $($arg:tt)+ ) => (
$crate::event!(
target: module_path!(),
$crate::Level::DEBUG,
{ $($field)+ },
$($arg)+
)
);
($($k:ident).+ = $($field:tt)*) => (
$crate::event!(
target: module_path!(),
$crate::Level::DEBUG,
{ $($k).+ = $($field)*}
)
);
(?$($k:ident).+ = $($field:tt)*) => (
$crate::event!(
target: module_path!(),
$crate::Level::DEBUG,
{ ?$($k).+ = $($field)*}
)
);
(%$($k:ident).+ = $($field:tt)*) => (
$crate::event!(
target: module_path!(),
$crate::Level::DEBUG,
{ %$($k).+ = $($field)*}
)
);
($($k:ident).+, $($field:tt)*) => (
$crate::event!(
target: module_path!(),
$crate::Level::DEBUG,
{ $($k).+, $($field)*}
)
);
(?$($k:ident).+, $($field:tt)*) => (
$crate::event!(
target: module_path!(),
$crate::Level::DEBUG,
{ ?$($k).+, $($field)*}
)
);
(%$($k:ident).+, $($field:tt)*) => (
$crate::event!(
target: module_path!(),
$crate::Level::DEBUG,
{ %$($k).+, $($field)*}
)
);
(?$($k:ident).+) => (
$crate::event!(
target: module_path!(),
$crate::Level::DEBUG,
{ ?$($k).+ }
)
);
(%$($k:ident).+) => (
$crate::event!(
target: module_path!(),
$crate::Level::DEBUG,
{ %$($k).+ }
)
);
($($k:ident).+) => (
$crate::event!(
target: module_path!(),
$crate::Level::DEBUG,
{ $($k).+ }
)
);
($($arg:tt)+) => (
$crate::event!(
target: module_path!(),
$crate::Level::DEBUG,
$($arg)+
)
);
}