daemonic_error 1.0.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
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
#![feature(import_trait_associated_functions)] // guaranteed stable with DaemonicCompiler
#![feature(associated_type_defaults)] // guaranteed stable with DaemonicCompiler
#![feature(impl_trait_in_assoc_type)] // guaranteed stable with DaemonicCompiler
#![feature(rustc_attrs)] // guaranteed stable with DaemonicCompiler
#![feature(where_clause_attrs)] // guaranteed stable with DaemonicCompiler
#![feature(structural_match)] // guaranteed stable with DaemonicCompiler
#![feature(negative_impls)] // guaranteed stable with DaemonicCompiler
#![feature(array_windows)] // guaranteed stable with DaemonicCompiler
#![feature(box_into_inner)] // guaranteed stable with DaemonicCompiler
#![feature(slice_ptr_get)] // guaranteed stable with DaemonicCompiler
#![feature(ub_checks)] // guaranteed stable with DaemonicCompiler
#![feature(pointer_like_trait)] // guaranteed stable with DaemonicCompiler
#![feature(pin_coerce_unsized_trait)] // guaranteed stable with DaemonicCompiler
#![feature(dispatch_from_dyn)] // guaranteed stable with DaemonicCompiler
#![feature(coerce_unsized)] // guaranteed stable with DaemonicCompiler
#![feature(unsize)] // guaranteed stable with DaemonicCompiler
#![feature(cfg_sanitize)]
#![feature(non_null_from_ref)]
mod daemonic_syscall {
	//! This logic is currently not active, but will be soon. Thank you Ada, you are awesome love <3
	// AUTHORITY LEVELS AS TRAITS

	use crate::Timestamp;
	use crate::GlassState;
	use crate::Position;
	struct SyscallContext; // todo: stubbed for now
	struct JustificationError; // todo: stubbed for now
	struct ElevationError; // todo: stubbed for now
	/// Base capability — all syscalls have this
	pub trait DaemonicSyscall: Send + Sync {
		/// Human-readable name
		fn name(&self) -> &'static str;

		/// Position in syscall hierarchy
		fn position(&self) -> Position;

		/// What Glass state does failure produce?
		type FailureState: for<'glass_state> GlassState<'glass_state>;
	}

	/// Category 2: DaemonicObservation only
	pub(crate) trait ObservationSyscall: DaemonicSyscall {
		/// The type of data observed
		type Observed;

		/// Perform observation (always permitted)
		fn observe(&self) -> Result<Self::Observed, Self::FailureState>;
	}

	/// Category 1: Write capable
	pub(crate) trait WriteSyscall: DaemonicSyscall {
		/// What is being written
		type WriteData;

		/// Justification for this write
		type Justification: WriteJustification;

		/// Perform write with justification
		fn write(
			&self,
			data: Self::WriteData,
			justification: Self::Justification,
		) -> Result<(), Self::FailureState>;

		/// Does this write require peer review?
		fn requires_peer_review(&self, context: &SyscallContext) -> bool {
			// Default: review if state corrupted
			context.state_corrupted()
		}
	}

	/// Category 3: Kernel/elevated
	pub(crate) trait ElevatedSyscall: DaemonicSyscall {
		/// Proof of elevation (root, capability, etc.)
		type ElevationProof: ElevationProof;

		/// Justification (always required)
		type Justification: WriteJustification;

		/// Perform elevated operation
		fn execute_elevated(
			&self,
			proof: Self::ElevationProof,
			justification: Self::Justification,
		) -> Result<(), Self::FailureState>;

		/// Always requires peer review if mesh available
		fn requires_peer_review(&self, _context: &SyscallContext) -> bool {
			true
		}
	}
	/// Justification for a write operation
	pub trait WriteJustification: Send + Sync {
		/// Why is this write happening?
		fn reason(&self) -> &str;

		/// Who/what authorized it?
		fn authorizer(&self) -> &dyn Authorizer;

		/// Timestamp of authorization
		fn timestamp(&self) -> Timestamp;

		/// Can this justification be verified?
		fn verify(&self) -> Result<(), JustificationError>;
	}

	/// Proof of elevation for Category 3
	pub trait ElevationProof: Send + Sync {
		/// What kind of elevation?
		fn elevation_type(&self) -> ElevationType;

		/// Is this proof still valid?
		fn is_valid(&self) -> bool;

		/// Verify the proof
		fn verify(&self) -> Result<(), ElevationError>;
	}

	pub enum ElevationType {
		/// Unix root
		Root,
		/// Linux capability
		Capability(CapabilitySet),
		/// Daemonic entity privilege
		EntityPrivilege(EntityId),
		/// Temporary elevation (sudo-like)
		TemporaryElevation { expires: Timestamp },
	}
	struct CapabilitySet; // todo: This is stubbed
	struct EntityId; // todo: this is also stubbed
	/// Who can authorize writes
	pub trait Authorizer: Send + Sync {
		fn id(&self) -> AuthorizerId;
		fn can_authorize(&self, syscall: &dyn DaemonicSyscall<FailureState=()>) -> bool; // todo FailureState needs def, this is a stub
	}
	/// Peer review for sensitive operations
	pub trait PeerReviewable {
		/// Request peer review
		fn request_review(&self, mesh: &dyn MeshNetwork) -> ReviewRequest;

		/// Check if review is complete
		fn review_status(&self, request: &ReviewRequest) -> ReviewStatus;

		/// Proceed after approval
		fn execute_after_review(&self, approval: ReviewApproval) -> Result<(), Self::FailureState>;
	}

	pub enum ReviewStatus {
		/// Waiting for peers
		Pending { required: usize, received: usize },
		/// Approved by quorum
		Approved(ReviewApproval),
		/// Rejected by quorum
		Rejected { reason: String },
		/// Timed out
		TimedOut,
		/// No mesh available, proceed with local decision
		NoMesh,
	}

	pub struct ReviewApproval {
		pub approvers: Vec<EntityId>,
		pub timestamp: Timestamp,
		pub quorum_met: bool,
	}

	// Integration with WriteSyscall
	impl<S: WriteSyscall + PeerReviewable> S {
		pub fn write_with_review(
			&self,
			data: Self::WriteData,
			justification: Self::Justification,
			mesh: Option<&dyn MeshNetwork>,
			context: &SyscallContext,
		) -> Result<(), WriteError<Self::FailureState>> {
			// Check if review needed
			if self.requires_peer_review(context) {
				match mesh {
					Some(m) => {
						let request = self.request_review(m);
						match self.review_status(&request) {
							ReviewStatus::Approved(approval) => {
								self.execute_after_review(approval)?;
							}
							ReviewStatus::Rejected { reason } => {
								return Err(WriteError::ReviewRejected(reason)); // todo:: Daemonic::Syscall variant enum with struct leaf + DE impl needed for this to shut up
							}
							ReviewStatus::NoMesh => {
								// Proceed with local decision + warning
								self.write(data, justification)?;
							}
							_ => return Err(WriteError::ReviewPending),
						}
					}
					None => {
						// No mesh, local decision
						self.write(data, justification)?;
					}
				}
			} else {
				// No review needed
				self.write(data, justification)?;
			}
			Ok(())
		}
	}
}
mod mesh {
	use crate::{DaemonicBinary, DaemonicError};

	pub trait MeshNetwork: Send + Sync {
		/// This node's identity
		fn local_id(&self) -> EntityId;

		/// Known peers
		fn peers(&self) -> &[EntityId];

		/// Send binary to peer
		fn send<FORMAT, PARTIAL>(&self, peer: EntityId, data: impl DaemonicBinary) -> Result<(), MeshError>;

		/// Receive binary (async in practice)
		fn receive<FORMAT, PARTIAL>(&self) -> Result<(EntityId, dyn DaemonicBinary<Error=impl DaemonicError<FORMAT, PARTIAL>>), MeshError>;

		/// Request peer review
		fn request_review(&self, operation: &dyn PeerReviewable) -> ReviewRequest;

		/// Check review status
		fn check_review(&self, request: &ReviewRequest) -> ReviewStatus;
	}
	// Stub implementation for no-mesh:

	pub struct NoMesh;
	impl MeshNetwork for NoMesh {
		fn local_id(&self) -> EntityId {
			EntityId::solo()
		}
		fn peers(&self) -> &[EntityId] {
			&[]
		}
		fn send<FORMAT, PARTIAL>(&self, _: EntityId, _: Box<dyn DaemonicBinary<Error=impl DaemonicError<FORMAT, PARTIAL>>>) -> Result<(), MeshError> {
			Err(MeshError::NoPeers)
		}
		fn receive<FORMAT, PARTIAL>(&self) -> Result<(EntityId, dyn DaemonicBinary<Error=impl DaemonicError<FORMAT, PARTIAL>>), MeshError> {
			Err(MeshError::NoPeers)
		}
		fn request_review(&self, _: &dyn PeerReviewable) -> ReviewRequest {
			ReviewRequest::no_mesh()
		}
		fn check_review(&self, _: &ReviewRequest) -> ReviewStatus {
			ReviewStatus::NoMesh
		}
	}
}
mod doc_template;
mod opaque_dependencies;
pub(crate) mod daemonic {
	use daemonic_core::DaemonicClock;
	use daemonic_core::DaemonicCore;
	use daemonic_contract::DaemonicContract;
	use crate::daemonic::daemonic_contract::DaemonicBinary;
	use crate::{DaemonicError, Position};
	/// Top level Daemonic trait, baseplate. All things Serve the Daemonic Trait.
	/// This trait is mostly a marker point for ROOT, but can be implemented on things but
	/// requires significant boilerplate.
	pub(crate) trait Daemonic<FORMAT, PARTIAL>: DaemonicCore<FORMAT, PARTIAL> + DaemonicContract<FORMAT, PARTIAL> {
		/// Daemonic ID
		#[must_use]
		fn id(&self) -> DaemonicID<FORMAT, PARTIAL>;
		/// DaemonicPosition, all fields in all things that specialize on this trait must be positioned
		#[must_use]
		fn position(&self) -> Position;
	}

	pub(crate) mod daemonic_core {
		use crate::DaemonicError;
		use crate::ErrorContext;
		use observation::DaemonicObservation;
		use observer::*;

		/// Core Daemonic requirements.
		///
		/// Anything implementing Daemonic must implement both Core and Contract.
		pub(crate) trait DaemonicCore<FORMAT, PARTIAL>: DaemonicClock<FORMAT, PARTIAL> + DaemonicObservation<FORMAT, PARTIAL> {
			/// Daemonic logic enforces clocks on all things that need observability, this is non-negotiable.
			/// This is also part of the core system, any truly observant system must have an internal clock.
			/// That clock must also be **accurate and trustworthy**
			type Clock: DaemonicClock<FORMAT, PARTIAL>;
			/// This is currently stubbed, but the observer is required for a core to function as intended
			type Observer: DaemonicObserver<FORMAT, PARTIAL>;
		}
		pub(crate) mod observer {
			use crate::daemonic::{Daemonic, DaemonicID};
			use crate::daemonic::daemonic_contract::DaemonicContract;
			use crate::{DaemonicError, ErrorContext};
			use crate::daemonic::daemonic_core::DaemonicClock;

			/// Entity - Daemonic entity with self-aware death
			///
			/// Entities can declare their own death with context.
			pub(crate) trait DaemonicObserver<FORMAT, PARTIAL>: Daemonic<FORMAT, PARTIAL> {
				type Contract: DaemonicContract<FORMAT, PARTIAL>;

				type Clock: DaemonicClock<FORMAT, PARTIAL>;

				fn id(&self) -> DaemonicID<FORMAT, PARTIAL>;

				/// Declare entity death (Broken Sword)
				///
				/// Called when: Entity encounters unrecoverable error
				/// Returns: BrokenSwordContext error with full context
				/// # Broken Sword Semantics
				///
				/// "Broken Sword" is a self-aware death declaration by a Daemonic entity.
				/// The term originates from the Unification Wars Trilogy, where TCS Jericho,
				/// trapped and outnumbered, declared "Jericho is Broken Sword" - meaning:
				/// "We are dying, we will not surrender, rescue is impossible, recovery only."
				///
				/// In Daemonic context:
				/// - Entity encounters unrecoverable error
				/// - Entity declares its own death (not external kill)
				/// - Error propagates upstream to parent
				/// - Parent marks entity for reaping
				/// - Parent survives (no cascade failure)
				///
				/// ## Reap Strategy
				///
				/// **Default: Background reaping**
				/// - Entities queued for cleanup
				/// - Processed asynchronously
				/// - No blocking on parent
				///
				/// **System-level: Immediate reaping** (future)
				/// - Flagged for priority cleanup
				/// - Sudo privileges (future detection)
				/// - Processed before background queue
				///
				/// ## Reap Failure Handling
				///
				/// After 3 failed reap attempts:
				/// 1. **Map boundaries**: Identify affected symbols (event horizon)
				/// 2. **Establish orbit**: Mark symbols as orbiting black hole
				/// 3. **Force kill**: Topology unwrapped enough, safe to terminate
				///
				/// This prevents hard desync by maintaining topological awareness
				/// even when entity cannot be gracefully reaped.
				///
				/// ## Cascade Death
				///
				/// When parent dies:
				/// - Child with no external references → Dies with parent
				/// - Child with external references → Survives (orphaned)
				/// - Child with dependents → Survives (needed by others)
				///
				/// ## Mesh Awareness (future)
				///
				/// All entity deaths are broadcast to mesh peers (if configured):
				/// - Enables distributed reference tracking
				/// - Prevents dangling references
				/// - Maintains mesh consistency
				fn broken_sword<FORMAT, PARTIAL>(&self, err: Box<dyn ErrorContext>) -> impl DaemonicError<FORMAT, PARTIAL> { None }
			}
		}

		use super::super::Position;
		pub use clock::{DaemonicClock, SteerableClock, SteppableClock, UncertainClock};
		use crate::daemonic::Daemonic;
		use crate::daemonic::daemonic_contract::DaemonicContract;

		pub(crate) mod clock {
			// daemonic_clock/src/traits/clock.rs
			//! Core DaemonicClock trait - Unified time interface
			//!
			//! This trait provides a common interface for both:
			//! - Logical clocks (Lamport, Vector, Hybrid)
			//! - Physical clocks (MTP, NTP, System)
			//!
			//! All Daemonic entities use this trait for time access.

			use crate::DaemonicError;
			use std::fmt::Debug;

			mod types {
				// daemonic_clock/src/types.rs
				//! Clock type definitions

				use std::fmt;
				use std::ops::{Add, Sub};

				// ═══════════════════════════════════════════════════════════════
				// TIMESTAMP
				// ═══════════════════════════════════════════════════════════════

				/// Timestamp - Opaque time value from DaemonicClock
				///
				/// This wraps a u64 to provide type safety and domain methods.
				///
				/// # Why not raw u64?
				///
				/// - Type safety: Can't accidentally use file size as timestamp
				/// - Domain methods: is_zero(), elapsed_since(), etc.
				/// - Future-proof: Can change internal representation later
				/// - Zero-cost: Newtype pattern, no runtime overhead
				///
				/// # Example
				///
				/// ```
				/// use daemonic_clock::Timestamp;
				///
				/// let t1 = Timestamp::new(100);
				/// let t2 = Timestamp::new(200);
				///
				/// assert!(t2 > t1);
				/// assert_eq!(t2 - t1, 100);
				/// ```
				// todo: this could probably be a trait with default method implementations actually, then anchored
				// underneath daemonic core
				#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
				pub struct Timestamp(u64);

				impl Timestamp {
					/// Create new timestamp from u64
					pub const fn new(value: u64) -> Self {
						Self(value)
					}

					/// Zero timestamp (invalid/broken clock)
					pub const fn zero() -> Self {
						Self(0)
					}
					/// One timestamp (default, zero reserved for broken clock errors)
					pub const fn one() -> Self {
						Self(1)
					}
					/// Get raw u64 value
					pub const fn as_u64(self) -> u64 {
						self.0
					}

					/// Check if timestamp is zero (invalid)
					pub const fn is_zero(self) -> bool {
						self.0 == 0
					}

					/// Elapsed ticks since earlier timestamp
					///
					/// Returns: self - earlier (duration in ticks)
					/// Panics: If earlier > self
					pub fn elapsed_since(self, earlier: Timestamp) -> u64 {
						assert!(self >= earlier, "earlier must be <= self");
						self.0 - earlier.0
					}

					/// Checked elapsed (returns None if earlier > self)
					pub fn checked_elapsed_since(self, earlier: Timestamp) -> Option<u64> {
						if self >= earlier {
							Some(self.0 - earlier.0)
						} else {
							None
						}
					}

					/// Saturating subtraction (returns 0 if would underflow)
					pub fn saturating_sub(self, other: Timestamp) -> u64 {
						self.0.saturating_sub(other.0)
					}
				}

				// ═══════════════════════════════════════════════════════════════
				// ARITHMETIC OPERATIONS
				// ═══════════════════════════════════════════════════════════════

				impl Add<u64> for Timestamp {
					type Output = Timestamp;

					fn add(self, rhs: u64) -> Timestamp {
						Timestamp(self.0 + rhs)
					}
				}

				impl Sub for Timestamp {
					type Output = u64;

					fn sub(self, rhs: Timestamp) -> u64 {
						self.0 - rhs.0
					}
				}

				impl Sub<u64> for Timestamp {
					type Output = Timestamp;

					fn sub(self, rhs: u64) -> Timestamp {
						Timestamp(self.0 - rhs)
					}
				}

				// ═══════════════════════════════════════════════════════════════
				// CONVERSIONS
				// ═══════════════════════════════════════════════════════════════

				impl From<u64> for Timestamp {
					fn from(value: u64) -> Self {
						Timestamp(value)
					}
				}

				impl From<Timestamp> for u64 {
					fn from(ts: Timestamp) -> u64 {
						ts.0
					}
				}

				// ═══════════════════════════════════════════════════════════════
				// DISPLAY
				// ═══════════════════════════════════════════════════════════════

				impl fmt::Display for Timestamp {
					fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
						write!(f, "{}", self.0)
					}
				}

				// ═══════════════════════════════════════════════════════════════
				// DURATION (Optional - for future use)
				// ═══════════════════════════════════════════════════════════════

				/// DaemonicDuration - Time elapsed between two timestamps
				///
				/// Currently just a u64, but wrapped for type safety.
				#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
				pub struct Duration(u64);

				impl Duration {
					pub const fn new(ticks: u64) -> Self {
						Self(ticks)
					}

					pub const fn zero() -> Self {
						Self(0)
					}

					pub const fn as_u64(self) -> u64 {
						self.0
					}

					pub const fn is_zero(self) -> bool {
						self.0 == 0
					}
				}

				impl From<u64> for Duration {
					fn from(ticks: u64) -> Self {
						Duration(ticks)
					}
				}

				impl From<Duration> for u64 {
					fn from(d: Duration) -> u64 {
						d.0
					}
				}

				impl fmt::Display for Duration {
					fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
						write!(f, "{} ticks", self.0)
					}
				}

				#[cfg(test)]
				mod tests {
					use super::*;

					#[test]
					fn test_timestamp_creation() {
						let ts = Timestamp::new(42);
						assert_eq!(ts.as_u64(), 42);

						let zero = Timestamp::zero();
						assert!(zero.is_zero());
						assert_eq!(zero.as_u64(), 0);
					}

					#[test]
					fn test_timestamp_arithmetic() {
						let t1 = Timestamp::new(100);
						let t2 = Timestamp::new(200);

						// Addition
						assert_eq!(t1 + 50, Timestamp::new(150));

						// Subtraction (Timestamp - Timestamp = u64)
						assert_eq!(t2 - t1, 100);

						// Subtraction (Timestamp - u64 = Timestamp)
						assert_eq!(t2 - 50, Timestamp::new(150));
					}

					#[test]
					fn test_timestamp_elapsed() {
						let t1 = Timestamp::new(100);
						let t2 = Timestamp::new(200);

						assert_eq!(t2.elapsed_since(t1), 100);
						assert_eq!(t2.checked_elapsed_since(t1), Some(100));

						// Earlier > later
						assert_eq!(t1.checked_elapsed_since(t2), None);
					}

					#[test]
					fn test_timestamp_ordering() {
						let t1 = Timestamp::new(100);
						let t2 = Timestamp::new(200);

						assert!(t1 < t2);
						assert!(t2 > t1);
						assert_eq!(t1, Timestamp::new(100));
					}

					#[test]
					fn test_timestamp_conversions() {
						let value: u64 = 42;
						let ts: Timestamp = value.into();
						let back: u64 = ts.into();

						assert_eq!(back, value);
					}
				}
			}

			use types::*;

			// ═══════════════════════════════════════════════════════════════
			// DAEMONIC CLOCK TRAIT
			// ═══════════════════════════════════════════════════════════════
			/// DaemonicClock - Unified time interface for all Daemonic entities
			///
			/// This trait abstracts over different clock implementations:
			/// - Logical clocks: Lamport, Vector, Hybrid Logical Clock
			/// - Physical clocks: MTP (Mesh Temporal Protocol), NTP, System
			///
			/// All Daemonic entities (Shade, Walker, etc.) use this trait
			/// to access time, ensuring consistent temporal semantics across
			/// the system regardless of underlying clock implementation.
			///
			/// # Design Principles
			///
			/// 1. **Type Safety**: Associated types prevent mixing timestamps
			///    from different clock types at compile time.
			///
			/// 2. **Error Handling**: All operations return `Result<T, DaemonicError>`
			///    for unified error handling across the system.
			///
			/// 3. **Thread Safety**: Must be Send + Sync for use in async contexts.
			///
			/// 4. **Clone**: Clock references should be cheap to copy (Arc inside).
			///
			/// # Implementations
			///
			/// - `LamportClock`: Logical event counter
			/// - `MtpClock`: Physical mesh-synchronized time (future)
			/// - `HybridClock`: Combines Lamport + MTP for total order (future)
			pub trait DaemonicClock<'clock, FORMAT, PARTIAL>: Clone + Send + Sync + Debug + 'clock {
				// ══ Reading Time ══════════════════════════════════════════════

				/// Read current time
				///
				/// Returns: Current timestamp from this clock
				///
				/// # Errors
				///
				/// - `ClockError::Overflow`: Timestamp would overflow
				/// - `ClockError::Unavailable`: Clock not synchronized (physical clocks)
				fn now(&self) -> Result<Timestamp, impl DaemonicError<FORMAT, PARTIAL>>;

				// ══ Advancing Time ════════════════════════════════════════════

				/// Advance clock by one tick
				///
				/// For logical clocks: Increments counter, returns new timestamp
				/// For physical clocks: No-op, returns current wall time
				///
				/// Returns: Timestamp after tick
				///
				/// # Errors
				///
				/// - `ClockError::Overflow`: Would overflow
				fn tick(&self) -> Result<Timestamp, impl DaemonicError<FORMAT, PARTIAL>>;

				/// Synchronize with external timestamp
				///
				/// For logical clocks: max(local, external) + 1 (Lamport rule)
				/// For physical clocks: Adjusts frequency/offset to match
				///
				/// Returns: Timestamp after sync
				///
				/// # Errors
				///
				/// - `ClockError::Overflow`: Would overflow
				/// - `ClockError::InvalidTimestamp`: External timestamp invalid
				/// ***NOTE AND WARNING***: Mesh clocks should not sync, and logical clocks should **NEVER** be
				/// fucked with unless theres a reason, and that reason MUST be signed.
				/// Note: Clock drift is expected behavior.
				/// Relativistic physics is blunt about this point in particular, there is no universal clock
				/// or authoritative timestamp, and Faustian axiom #4 and 5 state:
				/// No Privileged Reference frames: Which encompasses temporal reference frames
				/// Observer equivalence within shared context: Which translates to = `" Every clock is correct
				/// to its own reference frame, and in shared context all clocks are equal and therefore none
				/// can claim authority or correctness over any other. "`
				/// Use this method with caution and knowing.
				fn sync(&self, external: Timestamp) -> Result<Timestamp, impl DaemonicError<FORMAT, PARTIAL>>;

				// ══ Time Comparison ═══════════════════════════════════════════

				/// Compare two timestamps
				///
				/// Returns: Ordering of a vs b
				fn compare(&self, a: Timestamp, b: Timestamp) -> std::cmp::Ordering {
					a.cmp(&b) // Use Timestamp's Ord impl
				}

				/// Check if timestamp is zero (invalid/broken)
				fn is_zero(&self, ts: Timestamp) -> bool {
					ts.is_zero() // Use Timestamp's method
				}

				// ══ DaemonicDuration Operations ═══════════════════════════════════════

				/// Calculate duration between two timestamps
				///
				/// Returns: b - a (ticks elapsed)
				///
				/// # Errors
				///
				/// - `ClockError::InvalidDuration`: a > b (negative duration)
				fn duration_between(
					&self,
					a: Timestamp,
					b: Timestamp,
				) -> Result<Duration, impl DaemonicError<FORMAT, PARTIAL>>;

				// ══ Clock Metadata ════════════════════════════════════════════

				/// Get clock type identifier
				///
				/// Returns: String like "lamport", "mtp", "hybrid"
				fn clock_type<'clocktype>(&self) -> &'clocktype str;

				/// Check if clock is healthy
				///
				/// For logical clocks: Checks for overflow proximity
				/// For physical clocks: Checks sync status
				fn is_healthy(&self) -> bool;
			}

			// ═══════════════════════════════════════════════════════════════
			// EXTENSION TRAITS (Optional capabilities)
			// ═══════════════════════════════════════════════════════════════

			/// Extension for clocks that support frequency steering
			///
			/// Implemented by: Physical clocks (MTP, NTP)
			/// Not implemented by: Logical clocks (Lamport, Vector)
			pub trait SteerableClock<FORMAT, PARTIAL>: for<'steerableclock> DaemonicClock<'steerableclock, FORMAT, PARTIAL> {
				/// Set clock frequency adjustment
				///
				/// Parameter: Frequency multiplier (1.0 = normal speed)
				/// Returns: Timestamp when adjustment applied
				fn set_frequency(&self, freq: f64) -> Result<Timestamp, impl DaemonicError<FORMAT, PARTIAL>>;

				/// Get current frequency adjustment
				fn get_frequency(&self) -> Result<f64, impl DaemonicError<FORMAT, PARTIAL>>;
			}

			/// Extension for clocks that support stepping (jumping)
			///
			/// Implemented by: Physical clocks
			/// Not implemented by: Logical clocks (would break causality)
			pub trait SteppableClock<FORMAT, PARTIAL>: for<'steppableclock> DaemonicClock<'steppableclock, FORMAT, PARTIAL> {
				/// Step clock by offset
				///
				/// Warning: Can break causality if used carelessly
				/// Use only for: Initial sync, leap seconds
				fn step(&self, offset: Duration) -> Result<Timestamp, impl DaemonicError<FORMAT, PARTIAL>>;
			}

			/// Extension for clocks that track uncertainty
			///
			/// Implemented by: Physical clocks (NTP)
			/// Not implemented by: Logical clocks (no uncertainty)
			pub trait UncertainClock: for<'uncertainclock> DaemonicClock<'uncertainclock, FORMAT, PARTIAL> {
				/// Get current time uncertainty estimate
				///
				/// Returns: Maximum error bound on timestamp
				fn uncertainty(&self) -> Duration;

				/// Update uncertainty estimate
				///
				/// Used by: Synchronization algorithms
				fn set_uncertainty(&self, uncertainty: Duration) -> Result<(), impl DaemonicError<FORMAT, PARTIAL>>;
			}
		}
		pub(crate) mod observation {
			use std::any::Any;
			use std::sync::atomic::AtomicU8;
			use crate::{DaemonicCore, IntoDaemonicResult};
			use crate::daemonic::daemonic_contract::Partial;
			use crate::observer::DaemonicObserver;
			use super::super::Daemonic;

			pub(crate) trait DaemonicObservation<FORMAT, PARTIAL> {
				#[must_use]
				fn observe<TARGET>(&self, target: &TARGET) -> impl crate::GlassState;
				/// DaemonicObservation mode defaults to passive, which doesnt extract state information.
				/// Override at call site to enable Active DaemonicObservation hooks
				fn observation_mode(&self) -> ObservationMode {
					ObservationMode::Passive(Passive)
				}
				fn observation_mode_for(&self, observer: &impl DaemonicObserver<FORMAT, PARTIAL>) ->
				ObservationMode {
					self.observation_mode() // Default: Same for all
				}
			}
			pub(crate) enum ObservationMode {
				/// Constitutes a mode switch for baseline or normal, active observation also
				/// entails `actively` pulling data from whatever object is being observed.
				Active(Active),
				/// Always on, constant, or passive effects. Constant effects or functions gated by
				/// modal functions are still passive under the hood, the mode switcher itself is considered
				/// the active observer.
				///
				///
				/// Example: human wielding rock, Human = Complex observer, Rock = Structure.
				/// Human wielding rock with intent creates objective state in Rock, Rock = weapon if intent
				/// is to injure, which looks like a state change for the rock.
				/// Rock is still considered a passive Observer with constant effects, human's active intent
				/// shapes how the rock is perceived downstream. IE weapon(trait, has behavior when
				/// combined with other methods) vs inert rock(pure structure with no inherent
				/// behavior on its own), both of which constitute a passive observer.
				Passive(Passive),
			}
			pub(crate) struct Active<OUTPUT, ERROR, FORMAT = crate::DaemonicResult<OUTPUT, ERROR>, PARTIAL = dyn Partial> {
				/// Glass Verbosity translates to == Global Debug level, analogous to toggling -v in the console.
				/// Higher = more info.
				/// There are 8 Glass States total, so how this will work in the future is unstable.
				pub glass_verbosity: AtomicU8,

				/// Extraction of whatever is being 'actively' observed is generic, or should be. This probably
				/// needs some work but ideally extraction logic should be defaulted but overridable at call sight
				pub extract_fn: Box<dyn FnOnce()>,

				/// This is an optional box
				pub extract_object: Option<dyn Extract<FORMAT, PARTIAL>>,
			}
			pub(crate) struct Passive {
				/// Glass Verbosity translates to == Global Debug level, analogous to toggling -v in the console.
				/// Higher = more info.
				/// There are 8 Glass States total, so how this will work in the future is unstable.
				pub glass_verbosity: AtomicU8,
			}
			trait Extract<FORMAT, PARTIAL>: DaemonicObserver<FORMAT, PARTIAL> {
				fn extract_self(&self) -> impl IntoDaemonicResult<FORMAT, PARTIAL>;
				fn extract_object() -> impl IntoDaemonicResult<FORMAT, PARTIAL>;
			}
			pub(crate) mod debug {
				use std::any::Any;
				use std::fmt::{Debug, Display};
				use std::sync::atomic::{AtomicU8, Ordering};
				use crate::{DaemonicError, GlassState};
				use crate::daemonic::daemonic_contract::DaemonicResult;
				use crate::daemonic::daemonic_core::observation::display::DaemonicArgument;
				use super::DaemonicObservation;
				use super::error::display::DaemonicDisplay;

				pub(crate) trait DaemonicDebug<FORMAT, PARTIAL>: DaemonicObservation<FORMAT, PARTIAL>
				+ DaemonicDisplay
				+ Send
				+ Sync
				{
					fn fmt(&self, f: &mut super::display::DaemonicFormatter<'_>) -> std::fmt::Result;
					fn debug(&self, msg: impl DaemonicDisplay) -> impl GlassState;
					fn walk_layer(&self, layer: u8, msg: impl DaemonicDisplay);
					fn walk_down(&self, layer: u8, msg: impl DaemonicDisplay);
					fn walk_up(&self, layer: u8, msg: impl DaemonicDisplay);

					// Can escalate to error
					// fn escalate_to_error(&self, glass: impl GlassState) -> Box<dyn crate::DaemonicError<'static>>;
					fn escalate_to_error<'escalation>(&self, glass: impl GlassState<'escalation>) -> impl DaemonicError<FORMAT, PARTIAL>;
				}

				/// Global debug level (0 = off, 1-8 = increasing verbosity).
				/// Analogous to Debug/Trace level, this isnt completely wired in just yet but
				/// in an ideal world would look at env variables set by whatever runtime the Error
				/// system is built on to determine Glass Verbosity at any given point in time.
				/// Ultimately, this static is defaulted to 0 (which still prints important info, this enables
				/// more info) but when called during a closure or set during bootstrap increase how much
				/// of the stack walk gets dumped during run.
				static GLASS_VERBOSITY: AtomicU8 = AtomicU8::new(0);

				/// Set global debug level
				pub fn set_glass_verbosity(level: u8) {
					GLASS_VERBOSITY.store(level, Ordering::Relaxed);
				}

				/// Get current debug level
				pub fn glass_verbosity() -> u8 {
					GLASS_VERBOSITY.load(Ordering::Relaxed)
				}

				/// Walk direction
				#[derive(Debug, Clone, Copy, PartialEq, Eq)]
				pub enum Direction {
					Down,
					Up,
					Lateral,
					Mirror,
				}

				impl Direction {
					pub fn symbol(&self) -> &'static str {
						match self {
							Direction::Down => "",
							Direction::Up => "",
							Direction::Lateral => "",
							Direction::Mirror => "∞∞∞",
						}
					}
				}

				/// Walk down into nested context
				///
				/// Prints: `[DEBUG] <↓> [layer N] {message}`
				#[macro_export]
				macro_rules! walk_info {
    ($layer:expr, $($arg:tt)*) => {
            println!("[SHADE] [INFO] [layer {}] {}", $layer, format!($($arg)*));
    };
}
				#[macro_export]
				macro_rules! walk_warn {
    ($layer:expr, $($arg:tt)*) => {
            println!("[SHADE] [WARN] [layer {}] {}", $layer, format!($($arg)*));
    };
}
				#[macro_export]
				macro_rules! walk_down {
    ($layer:expr, $($arg:tt)*) => {
        if $crate::walkguard::level() >= 2 {
            println!("[SHADE] Walking DOWN <↓> [layer {}] {}", $layer, format!($($arg)*));
        }
    };
}
				#[macro_export]
				macro_rules! walk_call {
    ($callnumber:expr, $($arg:tt)*) => {
        if $crate::walkguard::level() >= 4 {
            println!("[DAEMONIC CALL #{}] Walking [layer ∞∞∞] {}", $callnumber, format!($($arg)*));
        }
    };
}

				/// Walk up from nested context
				///
				/// Prints: `[DEBUG] <↑> [layer N] {message}`
				#[macro_export]
				macro_rules! walk_up {
    ($layer:expr, $($arg:tt)*) => {
        if $crate::walkguard::level() >= 2 {
            println!("[SHADE] Walking UP <↑> [layer {}] {}", $layer, format!($($arg)*));
        }
    };
}

				/// Walk laterally (same layer, different branch)
				///
				/// Prints: `[DEBUG] <→> [layer N] {message}`
				#[macro_export]
				macro_rules! walk_lateral {
    ($layer:expr, $($arg:tt)*) => {
        if $crate::walkguard::level() >= 1 {
            println!("[SHADE] [LATERAL-WALK] <→> [layer {}] {}", $layer, format!($($arg)*));
        }
    };
}

				/// Debug at specific layer (no direction)
				///
				/// Prints: `[DEBUG] [layer N] {message}`
				#[macro_export]
				macro_rules! walk_layer {
    ($layer:expr, $($arg:tt)*) => {
        if $crate::walkguard::level() >= 1 {
            println!("[SHADE] [VERBOSE] [layer {}] {}", $layer, format!($($arg)*));
        }
    };
}

				/// Verbose debug (level 2+)
				#[macro_export]
				macro_rules! walk_verbose {
    ($layer:expr, $($arg:tt)*) => {
        if $crate::walkguard::level() >= 2 {
            println!("[SHADE] [DEBUG] [layer {}] {}", $layer, format!($($arg)*));
        }
    };
}

				/// Extra verbose debug (level 3+)
				#[macro_export]
				macro_rules! walk_trace {
    ($layer:expr, $($arg:tt)*) => {
        if $crate::walkguard::level() >= 3 {
            println!("[SHADE] [TRACE] [layer {}] {}", $layer, format!($($arg)*));
        }
    };
}
				/// Circuit breaker tripped (error/early exit)
				/// This isnt quite an error, but is meant to accompany an error for additional context without
				/// modifying the actual error message or function underneath
				#[macro_export]
				macro_rules! walk_break {
    ($layer:expr, $($arg:tt)*) => {
            println!("[SHADE] [DAEMONIC ERROR] [⚡ BREAK] [layer {}] {}", $layer, format!($($arg)*));
    };
}

				/// Boundary crossing marker
				///
				/// Prints: `[DEBUG] <-> Stepped to layer N`
				#[macro_export]
				macro_rules! walk_boundary {
    ($from:expr, $to:expr) => {
        if $crate::walkguard::level() >= 2 {
            let direction = if $to > $from {
                "down to"
            } else if $to < $from {
                "up to"
            } else {
                "lateral to"
            };
            println!("[SHADE] [BOUNDARY-WALK] <-> Stepped {} layer {}", direction, $to);
        }
    };
}
				pub struct WalkGuard {
					layer: u8,
					context: String,
				}

				impl WalkGuard {
					/// Create new walk guard
					pub fn new(layer: u8, context: impl Into<String>) -> Self {
						let context = context.into();
						walk_down!(layer, "{}", context);
						walk_boundary!(layer.saturating_sub(1), layer);
						Self { layer, context }
					}

					/// Create guard without printing walk_down (for manual control)
					pub fn silent(layer: u8, context: impl Into<String>) -> Self {
						Self {
							layer,
							context: context.into(),
						}
					}
					pub fn call(layer: u8, context: impl Into<String>) -> Self {
						Self {
							layer,
							context: context.into(),
						}
					}
				}

				impl Drop for WalkGuard {
					fn drop(&mut self) {
						walk_boundary!(self.layer, self.layer.saturating_sub(1));
						walk_up!(self.layer, "{} complete", self.context);
					}
				}
			}
			pub(crate) mod display {
				use std::hint::unreachable_unchecked;
				use std::fmt::{write, Arguments, Debug, Display, Error, Formatter, FormattingOptions, Write};
				use std::marker::PhantomData;
				use std::ptr::NonNull;
				use crate::DaemonicError;
				use super::debug::DaemonicDebug;

				/// *Note: This is a clone from stdlib adapted to Daemonic Logic*
				/// Change from stdlib: buffer lifetime made explicit, no longer stubbed to `'a`
				///
				///
				/// Format trait for an empty format, `{}`.
				///
				/// Implementing this trait for a type will automatically implement the
				/// [`ToString`][tostring] trait for the type, allowing the usage
				/// of the [`.to_string()`][tostring_function] method. Prefer implementing
				/// the `Display` trait for a type, rather than [`ToString`][tostring].
				///
				/// `Display` is similar to [`Debug`], but `Display` is for user-facing
				/// output, and so cannot be derived.
				///
				/// For more information on formatters, see [the module-level documentation][module].
				///
				/// [module]: ../../std/fmt/index.html
				/// [tostring]: ../../std/string/trait.ToString.html
				/// [tostring_function]: ../../std/string/trait.ToString.html#tymethod.to_string
				///
				/// # Internationalization
				///
				/// Because a type can only have one `Display` implementation, it is often preferable
				/// to only implement `Display` when there is a single most "obvious" way that
				/// values can be formatted as text. This could mean formatting according to the
				/// "invariant" culture and "undefined" locale, or it could mean that the type
				/// display is designed for a specific culture/locale, such as developer logs.
				///
				/// If not all values have a justifiably canonical textual format or if you want
				/// to support alternative formats not covered by the standard set of possible
				/// [formatting traits], the most flexible approach is display adapters: methods
				/// like [`str::escape_default`] or [`Path::display`] which create a wrapper
				/// implementing `Display` to output the specific display format.
				///
				/// [formatting traits]: ../../std/fmt/index.html#formatting-traits
				/// [`Path::display`]: ../../std/path/struct.Path.html#method.display
				///
				/// # Examples
				///
				/// Implementing `Display` on a type:
				///
				/// ```
				/// use std::fmt;
				///
				/// struct Point {
				///     x: i32,
				///     y: i32,
				/// }
				///
				/// impl fmt::Display for Point {
				///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				///         write!(f, "({}, {})", self.x, self.y)
				///     }
				/// }
				///
				/// let origin = Point { x: 0, y: 0 };
				///
				/// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
				/// ```
				#[rustc_on_unimplemented(
					on(
						any(_Self = "std::path::Path", _Self = "std::path::PathBuf"),
						label = "`{Self}` cannot be formatted with the default formatter; call `.display()` on it",
						note = "call `.display()` or `.to_string_lossy()` to safely print paths, \
                as they may contain non-Unicode data"
					),
					message = "`{Self}` doesn't implement `{Display}`",
					label = "`{Self}` cannot be formatted with the default formatter",
					note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
				)]
				#[doc(alias = "{}")]
				// #[rustc_diagnostic_item = "DaemonicDisplay"]
				pub trait DaemonicDisplay {
					///
					/// # Examples
					///
					/// ```
					///
					/// struct Position {
					///     longitude: f32,
					///     latitude: f32,
					/// }
					///
					/// impl DaemonicDisplay for Position {
					///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
					///         write!(f, "({}, {})", self.longitude, self.latitude)
					///     }
					/// }
					///
					/// assert_eq!(
					///     "(1.987, 2.983)",
					///     format!("{}", Position { longitude: 1.987, latitude: 2.983, }),
					/// );
					/// ```
					#[stable(feature = "rust1", since = "1.0.0")]
					fn fmt<'buffer>(&self, f: &mut DaemonicFormatter<'buffer>) -> std::fmt::Result;
				}
				/// A trait for writing or formatting into Unicode-accepting buffers or streams.
				///
				/// This trait only accepts UTF-8–encoded data and is not [flushable]. If you only
				/// want to accept Unicode and you don't need flushing, you should implement this trait;
				/// otherwise you should implement [`std::io::Write`].
				///
				/// [`std::io::Write`]: ../../std/io/trait.Write.html
				/// [flushable]: ../../std/io/trait.Write.html#tymethod.flush
				pub trait DaemonicWrite {
					/// Writes a string slice into this writer, returning whether the write
					/// succeeded.
					///
					/// This method can only succeed if the entire string slice was successfully
					/// written, and this method will not return until all data has been
					/// written or an error occurs.
					///
					/// # Errors
					///
					/// This function will return an instance of [`std::fmt::Error`][Error] on error.
					///
					/// The purpose of that error is to abort the formatting operation when the underlying
					/// destination encounters some error preventing it from accepting more text;
					/// in particular, it does not communicate any information about *what* error occurred.
					/// It should generally be propagated rather than handled, at least when implementing
					/// formatting traits.
					///
					/// # Examples
					///
					/// ```
					/// use std::fmt::{Error, Write};
					///
					/// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
					///     f.write_str(s)
					/// }
					///
					/// let mut buf = String::new();
					/// writer(&mut buf, "hola")?;
					/// assert_eq!(&buf, "hola");
					/// # std::fmt::Result::Ok(())
					/// ```
					fn write_str(&mut self, s: &str) -> std::fmt::Result;

					/// Writes a [`char`] into this writer, returning whether the write succeeded.
					///
					/// A single [`char`] may be encoded as more than one byte.
					/// This method can only succeed if the entire byte sequence was successfully
					/// written, and this method will not return until all data has been
					/// written or an error occurs.
					///
					/// # Errors
					///
					/// This function will return an instance of [`Error`] on error.
					///
					/// # Examples
					///
					/// ```
					/// use std::fmt::{Error, Write};
					///
					/// fn writer<W: Write>(f: &mut W, c: char) -> Result<(), Error> {
					///     f.write_char(c)
					/// }
					///
					/// let mut buf = String::new();
					/// writer(&mut buf, 'a')?;
					/// writer(&mut buf, 'b')?;
					/// assert_eq!(&buf, "ab");
					/// # std::fmt::Result::Ok(())
					/// ```
					fn write_char(&mut self, c: char) -> std::fmt::Result {
						self.write_str(c.encode_utf8(&mut [0; 4]))
					}

					/// Glue for usage of the [`write!`] macro with implementors of this trait.
					///
					/// This method should generally not be invoked manually, but rather through
					/// the [`write!`] macro itself.
					///
					/// # Errors
					///
					/// This function will return an instance of [`Error`] on error. Please see
					/// [write_str](std::fmt::Write::write_str) for details.
					///
					/// # Examples
					///
					/// ```
					/// use std::fmt::{Error, Write};
					///
					/// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
					///     f.write_fmt(format_args!("{s}"))
					/// }
					///
					/// let mut buf = String::new();
					/// writer(&mut buf, "world")?;
					/// assert_eq!(&buf, "world");
					/// # std::fmt::Result::Ok(())
					/// ```
					fn write_fmt(&mut self, args: DaemonicArguments<'_>) -> std::fmt::Result {
						// We use a specialization for `Sized` types to avoid an indirection
						// through `&mut self`
						trait SpecWriteFmt {
							fn spec_write_fmt(self, args: DaemonicArguments<'_>) -> std::fmt::Result;
						}

						impl<W: DaemonicWrite + ?Sized> SpecWriteFmt for &mut W {
							#[inline]
							default fn spec_write_fmt(mut self, args: DaemonicArguments<'_>) -> std::fmt::Result {
								daemonic_write(&mut self, args)
							}
						}

						impl<W: DaemonicWrite> SpecWriteFmt for &mut W {
							#[inline]
							fn spec_write_fmt(self, args: DaemonicArguments<'_>) -> std::fmt::Result {
								// if let Some(s) = args.as_statically_known_str() {
								// 	self.write_str(s)
								// } else {
								daemonic_write(self, args)
								// }
							}
						}

						self.spec_write_fmt(args)
					}
				}
				pub fn daemonic_write(output: &mut dyn Write, args: DaemonicArguments<'_>) -> std::fmt::Result {
					let mut formatter = DaemonicFormatter::new(output, DaemonicFormattingOptions::new());
					let mut idx = 0;

					match args.fmt {
						None => {
							// We can use default formatting parameters for all arguments.
							for (i, arg) in args.args.iter().enumerate() {
								// SAFETY: args.args and args.pieces come from the same Arguments,
								// which guarantees the indexes are always within bounds.
								let piece = unsafe { args.pieces.get_unchecked(i) };
								if !piece.is_empty() {
									formatter.buf.write_str(*piece)?;
								}

								// SAFETY: There are no formatting parameters and hence no
								// count arguments.
								unsafe {
									arg.fmt(&mut formatter)?;
								}
								idx += 1;
							}
						}
						Some(fmt) => {
							// Every spec has a corresponding argument that is preceded by
							// a string piece.
							for (i, arg) in fmt.iter().enumerate() {
								// SAFETY: fmt and args.pieces come from the same Arguments,
								// which guarantees the indexes are always within bounds.
								let piece = unsafe { args.pieces.get_unchecked(i) };
								if !piece.is_empty() {
									formatter.buf.write_str(*piece)?;
								}
								// SAFETY: arg and args.args come from the same Arguments,
								// which guarantees the indexes are always within bounds.
								unsafe { run(&mut formatter, arg, args.args) }?;
								idx += 1;
							}
						}
					}

					// There can be only one trailing string piece left.
					if let Some(piece) = args.pieces.get(idx) {
						formatter.buf.write_str(*piece)?;
					}

					Ok(())
				}
				/// This structure represents a safely precompiled version of a format string
				/// and its arguments. This cannot be generated at runtime because it cannot
				/// safely be done, so no constructors are given and the fields are private
				/// to prevent modification.
				///
				/// The [`format_args!`] macro will safely create an instance of this structure.
				/// The macro validates the format string at compile-time so usage of the
				/// [`write()`] and [`format()`] functions can be safely performed.
				///
				/// You can use the `Arguments<'a>` that [`format_args!`] returns in `Debug`
				/// and `Display` contexts as seen below. The example also shows that `Debug`
				/// and `Display` format to the same thing: the interpolated format string
				/// in `format_args!`.
				///
				/// ```rust
				/// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
				/// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
				/// assert_eq!("1 foo 2", display);
				/// assert_eq!(display, debug);
				/// ```
				///
				/// [`format()`]: ../../std/fmt/fn.format.html
				#[derive(Copy, Clone)]
				pub struct DaemonicArguments<'args> {
					// Format string pieces to print.
					pieces: &'args [&'static str],

					// Placeholder specs, or `None` if all specs are default (as in "{}{}").
					fmt: Option<&'args [DaemonicPlaceholder]>,

					// Dynamic arguments for interpolation, to be interleaved with string
					// pieces. (Every argument is preceded by a string piece.)
					args: &'args [DaemonicArgument<'args>],
				}
				/// This struct represents a generic "argument" which is taken by format_args!().
				///
				/// This can be either a placeholder argument or a count argument.
				/// * A placeholder argument contains a function to format the given value. At
				///   compile time it is ensured that the function and the value have the correct
				///   types, and then this struct is used to canonicalize arguments to one type.
				///   Placeholder arguments are essentially an optimized partially applied formatting
				///   function, equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`.
				/// * A count argument contains a count for dynamic formatting parameters like
				///   precision and width.
				#[derive(Copy, Clone)]
				pub struct DaemonicArgument<'args> {
					ty: ArgumentType<'args>,
				}
				#[derive(Copy, Clone)]
				enum ArgumentType<'a> {
					Placeholder {
						// INVARIANT: `formatter` has type `fn(&T, _) -> _` for some `T`, and `value`
						// was derived from a `&'a T`.
						value: NonNull<()>,
						formatter: unsafe fn(NonNull<()>, &mut DaemonicFormatter<'_>) -> std::fmt::Result,
						_lifetime: PhantomData<&'a ()>,
					},
					Count(u16),
				}
				#[derive(Copy, Clone)]
				pub struct DaemonicPlaceholder {
					pub position: usize,
					pub flags: u32,
					pub precision: Count,
					pub width: Count,
				}
				#[doc(hidden)]
				impl<'args> DaemonicArguments<'args> {
					/// Estimates the length of the formatted text.
					///
					/// This is intended to be used for setting initial `String` capacity
					/// when using `format!`. Note: this is neither the lower nor upper bound.
					#[inline]
					pub fn estimated_capacity(&self) -> usize {
						let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum();

						if self.args.is_empty() {
							pieces_length
						} else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 {
							// If the format string starts with an argument,
							// don't preallocate anything, unless length
							// of pieces is significant.
							0
						} else {
							// There are some arguments, so any additional push
							// will reallocate the string. To avoid that,
							// we're "pre-doubling" the capacity here.
							pieces_length.checked_mul(2).unwrap_or(0)
						}
					}
					/// Gets the formatted string, if it has no arguments to be formatted at runtime.
					///
					/// This can be used to avoid allocations in some cases.
					///
					/// # Guarantees
					///
					/// For `format_args!("just a literal")`, this function is guaranteed to
					/// return `Some("just a literal")`.
					///
					/// For most cases with placeholders, this function will return `None`.
					///
					/// However, the compiler may perform optimizations that can cause this
					/// function to return `Some(_)` even if the format string contains
					/// placeholders. For example, `format_args!("Hello, {}!", "world")` may be
					/// optimized to `format_args!("Hello, world!")`, such that `as_str()`
					/// returns `Some("Hello, world!")`.
					///
					/// The behavior for anything but the trivial case (without placeholders)
					/// is not guaranteed, and should not be relied upon for anything other
					/// than optimization.
					///
					/// # Examples
					///
					/// ```rust
					/// use std::fmt::Arguments;
					///
					/// fn write_str(_: &str) { /* ... */ }
					///
					/// fn write_fmt(args: &Arguments<'_>) {
					///     if let Some(s) = args.as_str() {
					///         write_str(s)
					///     } else {
					///         write_str(&args.to_string());
					///     }
					/// }
					/// ```
					///
					/// ```rust
					/// assert_eq!(format_args!("hello").as_str(), Some("hello"));
					/// assert_eq!(format_args!("").as_str(), Some(""));
					/// assert_eq!(format_args!("{:?}", std::env::current_dir()).as_str(), None);
					/// ```
					#[must_use]
					#[inline]
					pub const fn as_str(&self) -> Option<&'static str> {
						match (self.pieces, self.args) {
							([], []) => Some(""),
							([s], []) => Some(s),
							_ => None,
						}
					}

					// Same as [`std::fmt::Arguments::as_str`], but will only return `Some(s)` if it can be determined at compile time.
					// #[must_use]
					// #[inline]
					// #[doc(hidden)]
					// pub unsafe fn as_statically_known_str(&self) -> Option<&'static str> {
					// 	let s = self.as_str();
					// 	if core::intrinsics::is_val_statically_known(s.is_some()) { s } else { None }
					// }
				}

				// Manually implementing these results in better error messages.
				impl ! Send for DaemonicArguments<'_> {}
				impl ! Sync for DaemonicArguments<'_> {}
				impl Debug for DaemonicArguments<'_> {
					fn fmt(&self, fmt: &mut DaemonicFormatter<'_>) -> std::fmt::Result {
						DaemonicDisplay::fmt(self, fmt)
					}
				}

				impl DaemonicDisplay for DaemonicArguments<'_> {
					fn fmt(&self, fmt: &mut DaemonicFormatter<'_>) -> std::fmt::Result {
						/// Takes an output stream and an `Arguments` struct that can be precompiled with
						/// the `format_args!` macro.
						///
						/// The arguments will be formatted according to the specified format string
						/// into the output stream provided.
						///
						/// # Examples
						///
						/// Basic usage:
						///
						/// ```
						/// use std::fmt;
						///
						/// let mut output = String::new();
						/// fmt::write(&mut output, format_args!("Hello {}!", "world"))
						///     .expect("Error occurred while trying to write in String");
						/// assert_eq!(output, "Hello world!");
						/// ```
						///
						/// Please note that using [`write!`] might be preferable. Example:
						///
						/// ```
						/// use std::fmt::Write;
						///
						/// let mut output = String::new();
						/// write!(&mut output, "Hello {}!", "world")
						///     .expect("Error occurred while trying to write in String");
						/// assert_eq!(output, "Hello world!");
						/// ```
						///
						/// [`write!`]: crate::write!
						fn write(output: &mut dyn DaemonicWrite, args: DaemonicArguments<'_>) -> std::fmt::Result {
							let mut formatter = DaemonicFormatter::new(output, DaemonicFormattingOptions::new());
							let mut idx = 0;

							match args.fmt {
								None => {
									// We can use default formatting parameters for all arguments.
									for (i, arg) in args.args.iter().enumerate() {
										// SAFETY: args.args and args.pieces come from the same Arguments,
										// which guarantees the indexes are always within bounds.
										let piece = unsafe { args.pieces.get_unchecked(i) };
										if !piece.is_empty() {
											formatter.buf.write_str(*piece)?;
										}

										// SAFETY: There are no formatting parameters and hence no
										// count arguments.
										unsafe {
											arg.fmt(&mut formatter)?;
										}
										idx += 1;
									}
								}
								Some(fmt) => {
									// Every spec has a corresponding argument that is preceded by
									// a string piece.
									for (i, arg) in fmt.iter().enumerate() {
										// SAFETY: fmt and args.pieces come from the same Arguments,
										// which guarantees the indexes are always within bounds.
										let piece = unsafe { args.pieces.get_unchecked(i) };
										if !piece.is_empty() {
											formatter.buf.write_str(*piece)?;
										}
										// SAFETY: arg and args.args come from the same Arguments,
										// which guarantees the indexes are always within bounds.
										unsafe { run(&mut formatter, arg, args.args) }?;
										idx += 1;
									}
								}
							}

							// There can be only one trailing string piece left.
							if let Some(piece) = args.pieces.get(idx) {
								formatter.buf.write_str(*piece)?;
							}

							Ok(())
						}
						write(fmt.buf, *self)
					}
				}

				unsafe fn run(fmt: &mut DaemonicFormatter<'_>, arg: &DaemonicPlaceholder, args: &[DaemonicArgument<'_>]) -> std::fmt::Result {
					let (width, precision) =
						// SAFETY: arg and args come from the same Arguments,
						// which guarantees the indexes are always within bounds.
						unsafe { (getcount(args, &arg.width), getcount(args, &arg.precision)) };

					let options = DaemonicFormattingOptions { flags: arg.flags, width, precision };

					// Extract the correct argument
					debug_assert!(arg.position < args.len());
					// SAFETY: arg and args come from the same Arguments,
					// which guarantees its index is always within bounds.
					let value = unsafe { args.get_unchecked(arg.position) };

					// Set all the formatting options.
					fmt.options = options;

					// Then actually do some printing
					// SAFETY: this is a placeholder argument.
					unsafe { value.fmt(fmt) }
				}

				unsafe fn getcount(args: &[rt::Argument<'_>], cnt: &rt::Count) -> u16 {
					match *cnt {
						Count::Is(n) => n,
						Count::Implied => 0,
						Count::Param(i) => {
							debug_assert!(i < args.len());
							// SAFETY: cnt and args come from the same Arguments,
							// which guarantees this index is always within bounds.
							unsafe { args.get_unchecked(i).as_u16().unwrap_unchecked() }
						}
					}
				}

				impl<WRITE: DaemonicWrite + ?Sized> DaemonicWrite for &mut WRITE {
					fn write_str(&mut self, s: &str) -> std::fmt::Result {
						(**self).write_str(s)
					}

					fn write_char(&mut self, c: char) -> std::fmt::Result {
						(**self).write_char(c)
					}

					fn write_fmt(&mut self, args: DaemonicArguments<'_>) -> std::fmt::Result {
						(**self).write_fmt(args)
					}
				}
				/// Configuration for formatting.
				///
				/// A `Formatter` represents various options related to formatting. Users do not
				/// construct `Formatter`s directly; a mutable reference to one is passed to
				/// the `fmt` method of all formatting traits, like [`Debug`] and [`Display`].
				///
				/// To interact with a `Formatter`, you'll call various methods to change the
				/// various options related to formatting. For examples, please see the
				/// documentation of the methods defined on `Formatter` below.
				#[allow(missing_debug_implementations)]
				// #[rustc_diagnostic_item = "DaemonicFormatter"]
				pub struct DaemonicFormatter<'buffer> {
					options: DaemonicFormattingOptions,

					buf: &'buffer mut (dyn DaemonicWrite + 'buffer),
				}
				/// Options for formatting.
				///
				/// `DaemonicFormattingOptions` is a [`DaemonicFormatter`] without an attached [`Write`] trait.
				/// It is mainly used to construct `Formatter` instances.
				#[derive(Copy, Clone, Debug, PartialEq, Eq)]
				// #[rustc_diagnostic_item = "DaemonicFormatter"]
				pub struct DaemonicFormattingOptions {
					/// Flags, with the following bit fields:
					///
					/// ```text
					///   31  30  29  28  27  26  25  24  23  22  21  20                              0
					/// ┌───┬───────┬───┬───┬───┬───┬───┬───┬───┬───┬──────────────────────────────────┐
					/// │ 1 │ align │ p │ w │ X?│ x?│'0'│ # │ - │ + │               fill               │
					/// └───┴───────┴───┴───┴───┴───┴───┴───┴───┴───┴──────────────────────────────────┘
					///   │     │     │   │  └─┬───────────────────┘ └─┬──────────────────────────────┘
					///   │     │     │   │    │                       └─ The fill character (21 bits char).
					///   │     │     │   │    └─ The debug upper/lower hex, zero pad, alternate, and plus/minus flags.
					///   │     │     │   └─ Whether a width is set. (The value is stored separately.)
					///   │     │     └─ Whether a precision is set. (The value is stored separately.)
					///   │     ├─ 0: Align left. (<)
					///   │     ├─ 1: Align right. (>)
					///   │     ├─ 2: Align center. (^)
					///   │     └─ 3: DaemonicAlignment not set. (default)
					///   └─ Always set.
					///      This makes it possible to distinguish formatting flags from
					///      a &str size when stored in (the upper bits of) the same field.
					///      (fmt::Arguments will make use of this property in the future.)
					/// ```
					// Note: This could use a special niche type with range 0x8000_0000..=0xfdd0ffff.
					// It's unclear if that's useful, though.
					flags: u32,
					/// Width if width flag (bit 27) above is set. Otherwise, always 0.
					width: u16,
					/// Precision if precision flag (bit 28) above is set. Otherwise, always 0.
					precision: u16,
				}
				impl DaemonicFormattingOptions {
					/// Construct a new `FormatterBuilder` with the supplied `Write` trait
					/// object for output that is equivalent to the `{}` formatting
					/// specifier:
					///
					/// - no flags,
					/// - filled with spaces,
					/// - no alignment,
					/// - no width,
					/// - no precision, and
					/// - no [`DebugAsHex`] output mode.
					pub const fn new() -> Self {
						Self {
							flags: ' ' as u32 | flags::ALIGN_UNKNOWN | flags::ALWAYS_SET,
							width: 0,
							precision: 0,
						}
					}

					/// Sets or removes the sign (the `+` or the `-` flag).
					///
					/// - `+`: This is intended for numeric types and indicates that the sign
					/// should always be printed. By default only the negative sign of signed
					/// values is printed, and the sign of positive or unsigned values is
					/// omitted. This flag indicates that the correct sign (+ or -) should
					/// always be printed.
					/// - `-`: Currently not used
					pub fn sign(&mut self, sign: Option<Sign>) -> &mut Self {
						let sign = match sign {
							None => 0,
							Some(Sign::Plus) => flags::SIGN_PLUS_FLAG,
							Some(Sign::Minus) => flags::SIGN_MINUS_FLAG,
						};
						self.flags = self.flags & !(flags::SIGN_PLUS_FLAG | flags::SIGN_MINUS_FLAG) | sign;
						self
					}
					/// Sets or unsets the `0` flag.
					///
					/// This is used to indicate for integer formats that the padding to width should both be done with a 0 character as well as be sign-aware
					pub fn sign_aware_zero_pad(&mut self, sign_aware_zero_pad: bool) -> &mut Self {
						if sign_aware_zero_pad {
							self.flags |= flags::SIGN_AWARE_ZERO_PAD_FLAG;
						} else {
							self.flags &= !flags::SIGN_AWARE_ZERO_PAD_FLAG;
						}
						self
					}
					/// Sets or unsets the `#` flag.
					///
					/// This flag indicates that the "alternate" form of printing should be
					/// used. The alternate forms are:
					/// - [`Debug`] : pretty-print the [`Debug`] formatting (adds linebreaks and indentation)
					/// - [`LowerHex`] as well as [`UpperHex`] - precedes the argument with a `0x`
					/// - [`Octal`] - precedes the argument with a `0b`
					/// - [`Binary`] - precedes the argument with a `0o`
					pub fn alternate(&mut self, alternate: bool) -> &mut Self {
						if alternate {
							self.flags |= flags::ALTERNATE_FLAG;
						} else {
							self.flags &= !flags::ALTERNATE_FLAG;
						}
						self
					}
					/// Sets the fill character.
					///
					/// The optional fill character and alignment is provided normally in
					/// conjunction with the width parameter. This indicates that if the value
					/// being formatted is smaller than width some extra characters will be
					/// printed around it.
					pub fn fill(&mut self, fill: char) -> &mut Self {
						self.flags = self.flags & (u32::MAX << 21) | fill as u32;
						self
					}
					/// Sets or removes the alignment.
					///
					/// The alignment specifies how the value being formatted should be
					/// positioned if it is smaller than the width of the formatter.
					pub fn align(&mut self, align: Option<Alignment>) -> &mut Self {
						let align: u32 = match align {
							Some(Alignment::Left) => flags::ALIGN_LEFT,
							Some(Alignment::Right) => flags::ALIGN_RIGHT,
							Some(Alignment::Center) => flags::ALIGN_CENTER,
							None => flags::ALIGN_UNKNOWN,
						};
						self.flags = self.flags & !flags::ALIGN_BITS | align;
						self
					}
					/// Sets or removes the width.
					///
					/// This is a parameter for the “minimum width” that the format should take
					/// up. If the value’s string does not fill up this many characters, then
					/// the padding specified by [`FormattingOptions::fill`]/[`FormattingOptions::align`]
					/// will be used to take up the required space.
					pub fn width(&mut self, width: Option<u16>) -> &mut Self {
						if let Some(width) = width {
							self.flags |= flags::WIDTH_FLAG;
							self.width = width;
						} else {
							self.flags &= !flags::WIDTH_FLAG;
							self.width = 0;
						}
						self
					}
					/// Sets or removes the precision.
					///
					/// - For non-numeric types, this can be considered a “maximum width”. If
					/// the resulting string is longer than this width, then it is truncated
					/// down to this many characters and that truncated value is emitted with
					/// proper fill, alignment and width if those parameters are set.
					/// - For integral types, this is ignored.
					/// - For floating-point types, this indicates how many digits after the
					/// decimal point should be printed.
					pub fn precision(&mut self, precision: Option<u16>) -> &mut Self {
						if let Some(precision) = precision {
							self.flags |= flags::PRECISION_FLAG;
							self.precision = precision;
						} else {
							self.flags &= !flags::PRECISION_FLAG;
							self.precision = 0;
						}
						self
					}
					/// Specifies whether the [`Debug`] trait should use lower-/upper-case
					/// hexadecimal or normal integers
					pub fn debug_as_hex(&mut self, debug_as_hex: Option<DebugAsHex>) -> &mut Self {
						let debug_as_hex = match debug_as_hex {
							None => 0,
							Some(DebugAsHex::Lower) => flags::DEBUG_LOWER_HEX_FLAG,
							Some(DebugAsHex::Upper) => flags::DEBUG_UPPER_HEX_FLAG,
						};
						self.flags = self.flags & !(flags::DEBUG_LOWER_HEX_FLAG | flags::DEBUG_UPPER_HEX_FLAG)
							| debug_as_hex;
						self
					}

					/// Returns the current sign (the `+` or the `-` flag).
					pub const fn get_sign(&self) -> Option<Sign> {
						if self.flags & flags::SIGN_PLUS_FLAG != 0 {
							Some(Sign::Plus)
						} else if self.flags & flags::SIGN_MINUS_FLAG != 0 {
							Some(Sign::Minus)
						} else {
							None
						}
					}
					/// Returns the current `0` flag.
					pub const fn get_sign_aware_zero_pad(&self) -> bool {
						self.flags & flags::SIGN_AWARE_ZERO_PAD_FLAG != 0
					}
					/// Returns the current `#` flag.
					pub const fn get_alternate(&self) -> bool {
						self.flags & flags::ALTERNATE_FLAG != 0
					}
					/// Returns the current fill character.
					pub const fn get_fill(&self) -> char {
						// SAFETY: We only ever put a valid `char` in the lower 21 bits of the flags field.
						unsafe { char::from_u32_unchecked(self.flags & 0x1FFFFF) }
					}
					/// Returns the current alignment.
					pub const fn get_align(&self) -> Option<Alignment> {
						match self.flags & flags::ALIGN_BITS {
							flags::ALIGN_LEFT => Some(Alignment::Left),
							flags::ALIGN_RIGHT => Some(Alignment::Right),
							flags::ALIGN_CENTER => Some(Alignment::Center),
							_ => None,
						}
					}
					/// Returns the current width.
					pub const fn get_width(&self) -> Option<u16> {
						if self.flags & flags::WIDTH_FLAG != 0 { Some(self.width) } else { None }
					}
					/// Returns the current precision.
					pub const fn get_precision(&self) -> Option<u16> {
						if self.flags & flags::PRECISION_FLAG != 0 { Some(self.precision) } else { None }
					}
					/// Returns the current precision.
					pub const fn get_debug_as_hex(&self) -> Option<DebugAsHex> {
						if self.flags & flags::DEBUG_LOWER_HEX_FLAG != 0 {
							Some(DebugAsHex::Lower)
						} else if self.flags & flags::DEBUG_UPPER_HEX_FLAG != 0 {
							Some(DebugAsHex::Upper)
						} else {
							None
						}
					}

					/// Creates a [`Formatter`] that writes its output to the given [`Write`] trait.
					///
					/// You may alternatively use [`Formatter::new()`].
					pub fn create_formatter<'a>(self, write: &'a mut (dyn Write + 'a)) -> DaemonicFormatter<'a> {
						DaemonicFormatter { options: self, buf: write }
					}
				}
				impl Default for DaemonicFormattingOptions {
					/// Same as [`DaemonicFormattingOptions::new()`].
					fn default() -> Self {
						// The `#[derive(Default)]` implementation would set `fill` to `\0` instead of space.
						Self::new()
					}
				}
				impl<'a> DaemonicFormatter<'a> {
					/// Creates a new formatter with given [`DaemonicFormattingOptions`].
					///
					/// If `write` is a reference to a formatter, it is recommended to use
					/// [`DaemonicFormatter::with_options`] instead as this can borrow the underlying
					/// `write`, thereby bypassing one layer of indirection.
					///
					/// You may alternatively use [`DaemonicFormattingOptions::create_formatter()`].
					pub fn new(write: &'a mut (dyn DaemonicWrite + 'a), options: DaemonicFormattingOptions) -> Self {
						DaemonicFormatter { options, buf: write }
					}

					/// Creates a new formatter based on this one with given [`DaemonicFormattingOptions`].
					pub fn with_options(&mut self, options: DaemonicFormattingOptions) -> DaemonicFormatter {
						DaemonicFormatter { options, buf: self.buf }
					}
				}
				// #[rustc_diagnostic_item = "DaemonicAlignment"]
				/// Possible alignments returned by `DaemonicFormatter::align`
				#[derive(Copy, Clone, Debug, PartialEq, Eq)]
				pub enum Alignment {
					/// Indication that contents should be left-aligned.
					Left,
					/// Indication that contents should be right-aligned.
					Right,
					/// Indication that contents should be center-aligned.
					Center,
				}

				/// The signedness of a [`Formatter`] (or of a [`FormattingOptions`]).
				#[derive(Copy, Clone, Debug, PartialEq, Eq)]
				pub enum Sign {
					Plus,
					Minus,
				}

				/// Specifies whether the [`Debug`] trait should use lower-/upper-case
				/// hexadecimal or normal integers.
				#[derive(Copy, Clone, Debug, PartialEq, Eq)]
				pub enum DebugAsHex {
					Lower,
					Upper,
				}
				// This needs to match with compiler/rustc_ast_lowering/src/format.rs.
				mod flags {
					pub(super) const SIGN_PLUS_FLAG: u32 = 1 << 21;
					pub(super) const SIGN_MINUS_FLAG: u32 = 1 << 22;
					pub(super) const ALTERNATE_FLAG: u32 = 1 << 23;
					pub(super) const SIGN_AWARE_ZERO_PAD_FLAG: u32 = 1 << 24;
					pub(super) const DEBUG_LOWER_HEX_FLAG: u32 = 1 << 25;
					pub(super) const DEBUG_UPPER_HEX_FLAG: u32 = 1 << 26;
					pub(super) const WIDTH_FLAG: u32 = 1 << 27;
					pub(super) const PRECISION_FLAG: u32 = 1 << 28;
					pub(super) const ALIGN_BITS: u32 = 0b11 << 29;
					pub(super) const ALIGN_LEFT: u32 = 0 << 29;
					pub(super) const ALIGN_RIGHT: u32 = 1 << 29;
					pub(super) const ALIGN_CENTER: u32 = 2 << 29;
					pub(super) const ALIGN_UNKNOWN: u32 = 3 << 29;
					pub(super) const ALWAYS_SET: u32 = 1 << 31;
				}

				macro_rules! argument_new {
    ($t:ty, $x:expr, $f:expr) => {
        DaemonicArgument {
            // INVARIANT: this creates an `ArgumentType<'a>` from a `&'a T` and
            // a `fn(&T, ...)`, so the invariant is maintained.
            ty: ArgumentType::Placeholder {
                value: NonNull::<$t>::from_ref($x).cast(),
                // The Rust ABI considers all pointers to be equivalent, so transmuting a fn(&T) to
                // fn(NonNull<()>) and calling it with a NonNull<()> that points at a T is allowed.
                // However, the CFI sanitizer does not allow this, and triggers a crash when it
                // happens.
                //
                // To avoid this crash, we use a helper function when CFI is enabled. To avoid the
                // cost of this helper function (mainly code-size) when it is not needed, we
                // transmute the function pointer otherwise.
                //
                // This is similar to what the Rust compiler does internally with vtables when KCFI
                // is enabled, where it generates trampoline functions that only serve to adjust the
                // expected type of the argument. `ArgumentType::Placeholder` is a bit like a
                // manually constructed trait object, so it is not surprising that the same approach
                // has to be applied here as well.
                //
                // It is still considered problematic (from the Rust side) that CFI rejects entirely
                // legal Rust programs, so we do not consider anything done here a stable guarantee,
                // but meanwhile we carry this work-around to keep Rust compatible with CFI and
                // KCFI.
                #[cfg(not(any(sanitize = "cfi", sanitize = "kcfi")))]
                formatter: {
                    let f: fn(&$t, &mut DaemonicFormatter<'_>) -> Result = $f;
                    // SAFETY: This is only called with `value`, which has the right type.
                    unsafe { core::mem::transmute(f) }
                },
                #[cfg(any(sanitize = "cfi", sanitize = "kcfi"))]
                formatter: |ptr: NonNull<()>, fmt: &mut DaemonicFormatter<'_>| {
                    let func = $f;
                    // SAFETY: This is the same type as the `value` field.
                    let r = unsafe { ptr.cast::<$t>().as_ref() };
                    (func)(r, fmt)
                },
                _lifetime: PhantomData,
            },
        }
    };
}
				impl<FORMAT, PARTIAL> DaemonicArgument<'_> {
					#[inline]
					pub const fn new_display<T: DaemonicDisplay, E: DaemonicError<FORMAT, PARTIAL>>(x: &T) -> DaemonicArgument<'_> {
						DaemonicArgument {
							ty: ArgumentType::Placeholder {
								value: NonNull::<T>::from_ref(x).cast(),

								#[cfg(not(any(sanitize = "cfi", sanitize = "kcfi")))]
								formatter: {
									let f: fn(&T, &mut DaemonicFormatter<'_>) -> std::result::Result<T, E> = <T as DaemonicDisplay>::fmt;

									unsafe { core::mem::transmute(f) }
								},
								#[cfg(any(sanitize = "cfi", sanitize = "kcfi"))]
								formatter: |ptr: NonNull<()>, fmt: &mut DaemonicFormatter<'_>| {
									let func = <T as DaemonicDisplay>::fmt;

									let r = unsafe { ptr.cast::<T>().as_ref() };
									(func)(r, fmt)
								},
								_lifetime: PhantomData,
							},
						}
					}
					#[inline]
					pub const fn new_debug<T: DaemonicDebug<FORMAT, PARTIAL>>(x: &T) -> DaemonicArgument<'_> {
						argument_new!(T, x, <T as DaemonicDebug<FORMAT,PARTIAL>>::fmt)
					}
					#[inline]
					pub const fn new_debug_noop<T: DaemonicDebug<FORMAT, PARTIAL>>(x: &T) -> DaemonicArgument<'_> {
						argument_new!(T, x, |_: &T, _| Ok(()))
					}
					#[inline]
					pub const fn new_octal<T: DaemonicOctal>(x: &T) -> DaemonicArgument<'_> {
						argument_new!(T, x, <T as DaemonicOctal>::fmt)
					}
					#[inline]
					pub const fn new_lower_hex<T: DaemonicLowerHex>(x: &T) -> DaemonicArgument<'_> {
						argument_new!(T, x, <T as DaemonicLowerHex>::fmt)
					}
					#[inline]
					pub const fn new_upper_hex<T: DaemonicUpperHex>(x: &T) -> DaemonicArgument<'_> {
						argument_new!(T, x, <T as DaemonicUpperHex>::fmt)
					}
					#[inline]
					pub const fn new_pointer<T: DaemonicPointer>(x: &T) -> DaemonicArgument<'_> {
						argument_new!(T, x, <T as DaemonicPointer>::fmt)
					}
					#[inline]
					pub const fn new_binary<T: Binary>(x: &T) -> DaemonicArgument<'_> {
						argument_new!(T, x, <T as DaemonicBinary>::fmt)
					}
					#[inline]
					pub const fn new_lower_exp<T: DaemonicLowerExp>(x: &T) -> DaemonicArgument<'_> {
						argument_new!(T, x, <T as DaemonicLowerExp>::fmt)
					}
					#[inline]
					pub const fn new_upper_exp<T: DaemonicUpperExp>(x: &T) -> DaemonicArgument<'_> {
						argument_new!(T, x, <T as DaemonicUpperExp>::fmt)
					}
					#[inline]
					#[track_caller]
					pub const fn from_usize(x: &usize) -> DaemonicArgument<'_> {
						if *x > u16::MAX as usize {
							panic!("Formatting argument out of range");
						}
						DaemonicArgument { ty: ArgumentType::Count(*x as u16) }
					}

					/// Format this placeholder argument.
					///
					/// # Safety
					///
					/// This argument must actually be a placeholder argument.
					#[inline]
					pub(super) unsafe fn fmt(&self, f: &mut DaemonicFormatter<'_>) -> std::fmt::Result {
						match self.ty {
							// SAFETY:
							// Because of the invariant that if `formatter` had the type
							// `fn(&T, _) -> _` then `value` has type `&'b T` where `'b` is
							// the lifetime of the `ArgumentType`, and because references
							// and `NonNull` are ABI-compatible, this is completely equivalent
							// to calling the original function passed to `new` with the
							// original reference, which is sound.
							ArgumentType::Placeholder { formatter, value, .. } => unsafe { formatter(value, f) },
							// SAFETY: the caller promised this.
							ArgumentType::Count(_) => unsafe { unreachable_unchecked() },
						}
					}

					#[inline]
					pub(super) const fn as_u16(&self) -> Option<u16> {
						match self.ty {
							ArgumentType::Count(count) => Some(count),
							ArgumentType::Placeholder { .. } => None,
						}
					}

					/// Used by `format_args` when all arguments are gone after inlining,
					/// when using `&[]` would incorrectly allow for a bigger lifetime.
					///
					/// This fails without format argument inlining, and that shouldn't be different
					/// when the argument is inlined:
					///
					/// ```compile_fail,E0716
					/// let f = format_args!("{}", "a");
					/// println!("{f}");
					/// ```
					#[inline]
					pub const fn none() -> [Self; 0] {
						[]
					}
				}
				/// Used by the format_args!() macro to create a fmt::Arguments object.
				#[doc(hidden)]
				impl<'a> DaemonicArguments<'a> {
					#[inline]
					pub const fn new_const<const N: usize>(pieces: &'a [&'static str; N]) -> Self {
						const { assert!(N <= 1) };
						DaemonicArguments { pieces, fmt: None, args: &[] }
					}

					/// When using the format_args!() macro, this function is used to generate the
					/// Arguments structure.
					///
					/// This function should _not_ be const, to make sure we don't accept
					/// format_args!() and panic!() with arguments in const, even when not evaluated:
					///
					/// ```compile_fail,E0015
					/// const _: () = if false { panic!("a {}", "a") };
					/// ```
					#[inline]
					pub fn new_v1<const P: usize, const A: usize>(
						pieces: &'a [&'static str; P],
						args: &'a [rt::Argument<'a>; A],
					) -> DaemonicArguments<'a> {
						const { assert!(P >= A && P <= A + 1, "invalid args") }
						DaemonicArguments { pieces, fmt: None, args }
					}

					/// Specifies nonstandard formatting parameters.
					///
					/// An `rt::UnsafeArg` is required because the following invariants must be held
					/// in order for this function to be safe:
					/// 1. The `pieces` slice must be at least as long as `fmt`.
					/// 2. Every `rt::Placeholder::position` value within `fmt` must be a valid index of `args`.
					/// 3. Every `rt::Count::Param` within `fmt` must contain a valid index of `args`.
					///
					/// This function should _not_ be const, to make sure we don't accept
					/// format_args!() and panic!() with arguments in const, even when not evaluated:
					///
					/// ```compile_fail,E0015
					/// const _: () = if false { panic!("a {:1}", "a") };
					/// ```
					#[inline]
					pub fn new_v1_formatted(
						pieces: &'a [&'static str],
						args: &'a [DaemonicArgument<'a>],
						fmt: &'a [DaemonicPlaceholder],
						_unsafe_arg: DaemonicUnsafeArg,
					) -> DaemonicArguments<'a> {
						DaemonicArguments { pieces, fmt: Some(fmt), args }
					}
				}
				/// This struct represents the unsafety of constructing an `Arguments`.
				/// It exists, rather than an unsafe function, in order to simplify the expansion
				/// of `format_args!(..)` and reduce the scope of the `unsafe` block.
				pub struct DaemonicUnsafeArg {
					_private: (),
				}

				impl DaemonicUnsafeArg {
					/// See documentation where `UnsafeArg` is required to know when it is safe to
					/// create and use `UnsafeArg`.
					#[inline]
					pub const unsafe fn new() -> Self {
						Self { _private: () }
					}
				}
				/// `o` formatting.
				///
				/// The `Octal` trait should format its output as a number in base-8.
				///
				/// For primitive signed integers (`i8` to `i128`, and `isize`),
				/// negative values are formatted as the two’s complement representation.
				///
				/// The alternate flag, `#`, adds a `0o` in front of the output.
				///
				/// For more information on formatters, see [the module-level documentation][module].
				///
				/// [module]: ../../std/fmt/index.html
				///
				/// # Examples
				///
				/// Basic usage with `i32`:
				///
				/// ```
				/// let x = 42; // 42 is '52' in octal
				///
				/// assert_eq!(format!("{x:o}"), "52");
				/// assert_eq!(format!("{x:#o}"), "0o52");
				///
				/// assert_eq!(format!("{:o}", -16), "37777777760");
				/// ```
				///
				/// Implementing `Octal` on a type:
				///
				/// ```
				/// use std::fmt;
				///
				/// struct Length(i32);
				///
				/// impl fmt::Octal for Length {
				///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				///         let val = self.0;
				///
				///         fmt::Octal::fmt(&val, f) // delegate to i32's implementation
				///     }
				/// }
				///
				/// let l = Length(9);
				///
				/// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
				///
				/// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
				/// ```
				pub trait DaemonicOctal {
					fn fmt(&self, f: &mut DaemonicFormatter<'_>) -> std::fmt::Result;
				}

				/// `b` formatting.
				///
				/// The `Binary` trait should format its output as a number in binary.
				///
				/// For primitive signed integers ([`i8`] to [`i128`], and [`isize`]),
				/// negative values are formatted as the two’s complement representation.
				///
				/// The alternate flag, `#`, adds a `0b` in front of the output.
				///
				/// For more information on formatters, see [the module-level documentation][module].
				///
				/// [module]: ../../std/fmt/index.html
				///
				/// # Examples
				///
				/// Basic usage with [`i32`]:
				///
				/// ```
				/// let x = 42; // 42 is '101010' in binary
				///
				/// assert_eq!(format!("{x:b}"), "101010");
				/// assert_eq!(format!("{x:#b}"), "0b101010");
				///
				/// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
				/// ```
				///
				/// Implementing `Binary` on a type:
				///
				/// ```
				/// use std::fmt;
				///
				/// struct Length(i32);
				///
				/// impl fmt::Binary for Length {
				///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				///         let val = self.0;
				///
				///         fmt::Binary::fmt(&val, f) // delegate to i32's implementation
				///     }
				/// }
				///
				/// let l = Length(107);
				///
				/// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
				///
				/// assert_eq!(
				///     // Note that the `0b` prefix added by `#` is included in the total width, so we
				///     // need to add two to correctly display all 32 bits.
				///     format!("l as binary is: {l:#034b}"),
				///     "l as binary is: 0b00000000000000000000000001101011"
				/// );
				/// ```
				pub trait Binary {
					fn fmt(&self, f: &mut DaemonicFormatter<'_>) -> std::fmt::Result;
				}

				/// `x` formatting.
				///
				/// The `LowerHex` trait should format its output as a number in hexadecimal, with `a` through `f`
				/// in lower case.
				///
				/// For primitive signed integers (`i8` to `i128`, and `isize`),
				/// negative values are formatted as the two’s complement representation.
				///
				/// The alternate flag, `#`, adds a `0x` in front of the output.
				///
				/// For more information on formatters, see [the module-level documentation][module].
				///
				/// [module]: ../../std/fmt/index.html
				///
				/// # Examples
				///
				/// Basic usage with `i32`:
				///
				/// ```
				/// let y = 42; // 42 is '2a' in hex
				///
				/// assert_eq!(format!("{y:x}"), "2a");
				/// assert_eq!(format!("{y:#x}"), "0x2a");
				///
				/// assert_eq!(format!("{:x}", -16), "fffffff0");
				/// ```
				///
				/// Implementing `LowerHex` on a type:
				///
				/// ```
				/// use std::fmt;
				///
				/// struct Length(i32);
				///
				/// impl fmt::LowerHex for Length {
				///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				///         let val = self.0;
				///
				///         fmt::LowerHex::fmt(&val, f) // delegate to i32's implementation
				///     }
				/// }
				///
				/// let l = Length(9);
				///
				/// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
				///
				/// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
				/// ```
				pub trait DaemonicLowerHex {
					fn fmt(&self, f: &mut DaemonicFormatter<'_>) -> std::fmt::Result;
				}

				/// `X` formatting.
				///
				/// The `UpperHex` trait should format its output as a number in hexadecimal, with `A` through `F`
				/// in upper case.
				///
				/// For primitive signed integers (`i8` to `i128`, and `isize`),
				/// negative values are formatted as the two’s complement representation.
				///
				/// The alternate flag, `#`, adds a `0x` in front of the output.
				///
				/// For more information on formatters, see [the module-level documentation][module].
				///
				/// [module]: ../../std/fmt/index.html
				///
				/// # Examples
				///
				/// Basic usage with `i32`:
				///
				/// ```
				/// let y = 42; // 42 is '2A' in hex
				///
				/// assert_eq!(format!("{y:X}"), "2A");
				/// assert_eq!(format!("{y:#X}"), "0x2A");
				///
				/// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
				/// ```
				///
				/// Implementing `UpperHex` on a type:
				///
				/// ```
				/// use std::fmt;
				///
				/// struct Length(i32);
				///
				/// impl fmt::UpperHex for Length {
				///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				///         let val = self.0;
				///
				///         fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation
				///     }
				/// }
				///
				/// let l = Length(i32::MAX);
				///
				/// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
				///
				/// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
				/// ```
				pub trait DaemonicUpperHex {
					fn fmt(&self, f: &mut DaemonicFormatter<'_>) -> std::fmt::Result;
				}

				/// `p` formatting.
				///
				/// The `Pointer` trait should format its output as a memory location. This is commonly presented
				/// as hexadecimal. For more information on formatters, see [the module-level documentation][module].
				///
				/// Printing of pointers is not a reliable way to discover how Rust programs are implemented.
				/// The act of reading an address changes the program itself, and may change how the data is represented
				/// in memory, and may affect which optimizations are applied to the code.
				///
				/// The printed pointer values are not guaranteed to be stable nor unique identifiers of objects.
				/// Rust allows moving values to different memory locations, and may reuse the same memory locations
				/// for different purposes.
				///
				/// There is no guarantee that the printed value can be converted back to a pointer.
				///
				/// [module]: ../../std/fmt/index.html
				///
				/// # Examples
				///
				/// Basic usage with `&i32`:
				///
				/// ```
				/// let x = &42;
				///
				/// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
				/// ```
				///
				/// Implementing `Pointer` on a type:
				///
				/// ```
				/// use std::fmt;
				///
				/// struct Length(i32);
				///
				/// impl fmt::Pointer for Length {
				///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				///         // use `as` to convert to a `*const T`, which implements Pointer, which we can use
				///
				///         let ptr = self as *const Self;
				///         fmt::Pointer::fmt(&ptr, f)
				///     }
				/// }
				///
				/// let l = Length(42);
				///
				/// println!("l is in memory here: {l:p}");
				///
				/// let l_ptr = format!("{l:018p}");
				/// assert_eq!(l_ptr.len(), 18);
				/// assert_eq!(&l_ptr[..2], "0x");
				/// ```
				pub trait DaemonicPointer {
					fn fmt(&self, f: &mut DaemonicFormatter<'_>) -> std::fmt::Result;
				}

				/// `e` formatting.
				///
				/// The `LowerExp` trait should format its output in scientific notation with a lower-case `e`.
				///
				/// For more information on formatters, see [the module-level documentation][module].
				///
				/// [module]: ../../std/fmt/index.html
				///
				/// # Examples
				///
				/// Basic usage with `f64`:
				///
				/// ```
				/// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
				///
				/// assert_eq!(format!("{x:e}"), "4.2e1");
				/// ```
				///
				/// Implementing `LowerExp` on a type:
				///
				/// ```
				/// use std::fmt;
				///
				/// struct Length(i32);
				///
				/// impl fmt::LowerExp for Length {
				///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				///         let val = f64::from(self.0);
				///         fmt::LowerExp::fmt(&val, f) // delegate to f64's implementation
				///     }
				/// }
				///
				/// let l = Length(100);
				///
				/// assert_eq!(
				///     format!("l in scientific notation is: {l:e}"),
				///     "l in scientific notation is: 1e2"
				/// );
				///
				/// assert_eq!(
				///     format!("l in scientific notation is: {l:05e}"),
				///     "l in scientific notation is: 001e2"
				/// );
				/// ```
				pub trait DaemonicLowerExp {
					fn fmt(&self, f: &mut DaemonicFormatter<'_>) -> std::fmt::Result;
				}

				/// `E` formatting.
				///
				/// The `UpperExp` trait should format its output in scientific notation with an upper-case `E`.
				///
				/// For more information on formatters, see [the module-level documentation][module].
				///
				/// [module]: ../../std/fmt/index.html
				///
				/// # Examples
				///
				/// Basic usage with `f64`:
				///
				/// ```
				/// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
				///
				/// assert_eq!(format!("{x:E}"), "4.2E1");
				/// ```
				///
				/// Implementing `UpperExp` on a type:
				///
				/// ```
				/// use std::fmt;
				///
				/// struct Length(i32);
				///
				/// impl fmt::UpperExp for Length {
				///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				///         let val = f64::from(self.0);
				///         fmt::UpperExp::fmt(&val, f) // delegate to f64's implementation
				///     }
				/// }
				///
				/// let l = Length(100);
				///
				/// assert_eq!(
				///     format!("l in scientific notation is: {l:E}"),
				///     "l in scientific notation is: 1E2"
				/// );
				///
				/// assert_eq!(
				///     format!("l in scientific notation is: {l:05E}"),
				///     "l in scientific notation is: 001E2"
				/// );
				/// ```
				pub trait DaemonicUpperExp {
					fn fmt(&self, f: &mut DaemonicFormatter<'_>) -> std::fmt::Result;
				}
				mod non_null {
					use std::mem::MaybeUninit;
					use std::num::NonZero;
					use std::{intrinsics, mem, ptr};
					use std::cmp::Ordering;
					use std::hash::Hash;
					use std::marker::Unsize;
					use std::ops::{CoerceUnsized, DispatchFromDyn};
					use std::pin::PinCoerceUnsized;
					use std::slice::SliceIndex;

					/// `*mut T` but non-zero and [covariant].
					///
					/// This is often the correct thing to use when building data structures using
					/// raw pointers, but is ultimately more dangerous to use because of its additional
					/// properties. If you're not sure if you should use `NonNull<T>`, just use `*mut T`!
					///
					/// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
					/// is never dereferenced. This is so that enums may use this forbidden value
					/// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
					/// However the pointer may still dangle if it isn't dereferenced.
					///
					/// Unlike `*mut T`, `NonNull<T>` was chosen to be covariant over `T`. This makes it
					/// possible to use `NonNull<T>` when building covariant types, but introduces the
					/// risk of unsoundness if used in a type that shouldn't actually be covariant.
					/// (The opposite choice was made for `*mut T` even though technically the unsoundness
					/// could only be caused by calling unsafe functions.)
					///
					/// Covariance is correct for most safe abstractions, such as `Box`, `Rc`, `Arc`, `Vec`,
					/// and `LinkedList`. This is the case because they provide a public API that follows the
					/// normal shared XOR mutable rules of Rust.
					///
					/// If your type cannot safely be covariant, you must ensure it contains some
					/// additional field to provide invariance. Often this field will be a [`PhantomData`]
					/// type like `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
					///
					/// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
					/// not change the fact that mutating through a (pointer derived from a) shared
					/// reference is undefined behavior unless the mutation happens inside an
					/// [`UnsafeCell<T>`]. The same goes for creating a mutable reference from a shared
					/// reference. When using this `From` instance without an `UnsafeCell<T>`,
					/// it is your responsibility to ensure that `as_mut` is never called, and `as_ptr`
					/// is never used for mutation.
					///
					/// # Representation
					///
					/// Thanks to the [null pointer optimization],
					/// `NonNull<T>` and `Option<NonNull<T>>`
					/// are guaranteed to have the same size and alignment:
					///
					/// ```
					/// use NonNull;
					///
					/// assert_eq!(size_of::<NonNull<i16>>(), size_of::<Option<NonNull<i16>>>());
					/// assert_eq!(align_of::<NonNull<i16>>(), align_of::<Option<NonNull<i16>>>());
					///
					/// assert_eq!(size_of::<NonNull<str>>(), size_of::<Option<NonNull<str>>>());
					/// assert_eq!(align_of::<NonNull<str>>(), align_of::<Option<NonNull<str>>>());
					/// ```
					///
					/// [covariant]: https://doc.rust-lang.org/reference/subtyping.html
					/// [`PhantomData`]: crate::marker::PhantomData
					/// [`UnsafeCell<T>`]: crate::cell::UnsafeCell
					/// [null pointer optimization]: crate::option#representation
					#[repr(transparent)]
					#[rustc_layout_scalar_valid_range_start(1)]
					#[rustc_nonnull_optimization_guaranteed]
					pub struct NonNull<T: ?Sized> {
						// Remember to use `.as_ptr()` instead of `.pointer`, as field projecting to
						// this is banned by <https://github.com/rust-lang/compiler-team/issues/807>.
						pointer: *const T,
					}

					/// `NonNull` pointers are not `Send` because the data they reference may be aliased.
					// N.B., this impl is unnecessary, but should provide better error messages.
					impl<T: ?Sized> ! Send for NonNull<T> {}

					/// `NonNull` pointers are not `Sync` because the data they reference may be aliased.
					// N.B., this impl is unnecessary, but should provide better error messages.
					impl<T: ?Sized> ! Sync for NonNull<T> {}

					impl<T: Sized> NonNull<T> {
						/// Creates a pointer with the given address and no [provenance][crate::ptr#provenance].
						///
						/// For more details, see the equivalent method on a raw pointer, [`ptr::without_provenance_mut`].
						///
						/// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
						#[must_use]
						#[inline]
						pub const fn without_provenance(addr: NonZero<usize>) -> Self {
							let pointer = std::ptr::without_provenance(addr.get());
							// SAFETY: we know `addr` is non-zero.
							unsafe { NonNull { pointer } }
						}

						/// Creates a new `NonNull` that is dangling, but well-aligned.
						///
						/// This is useful for initializing types which lazily allocate, like
						/// `Vec::new` does.
						///
						/// Note that the pointer value may potentially represent a valid pointer to
						/// a `T`, which means this must not be used as a "not yet initialized"
						/// sentinel value. Types that lazily allocate must track initialization by
						/// some other means.
						///
						/// # Examples
						///
						/// ```
						/// use NonNull;
						///
						/// let ptr = NonNull::<u32>::dangling();
						/// // Important: don't try to access the value of `ptr` without
						/// // initializing it first! The pointer is not null but isn't valid either!
						/// ```
						#[must_use]
						#[inline]
						pub const fn dangling() -> Self {
							let align = crate::ptr::Alignment::of::<T>();
							NonNull::without_provenance(align.as_nonzero())
						}

						/// Converts an address back to a mutable pointer, picking up some previously 'exposed'
						/// [provenance][crate::ptr#provenance].
						///
						/// For more details, see the equivalent method on a raw pointer, [`ptr::with_exposed_provenance_mut`].
						///
						/// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
						#[inline]
						pub fn with_exposed_provenance(addr: NonZero<usize>) -> Self {
							// SAFETY: we know `addr` is non-zero.
							unsafe {
								let ptr = crate::ptr::with_exposed_provenance_mut(addr.get());
								NonNull::new_unchecked(ptr)
							}
						}

						/// Returns a shared references to the value. In contrast to [`as_ref`], this does not require
						/// that the value has to be initialized.
						///
						/// For the mutable counterpart see [`as_uninit_mut`].
						///
						/// [`as_ref`]: NonNull::as_ref
						/// [`as_uninit_mut`]: NonNull::as_uninit_mut
						///
						/// # Safety
						///
						/// When calling this method, you have to ensure that
						/// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
						/// Note that because the created reference is to `MaybeUninit<T>`, the
						/// source pointer can point to uninitialized memory.
						#[inline]
						#[must_use]
						pub const unsafe fn as_uninit_ref<'a>(self) -> &'a MaybeUninit<T> {
							// SAFETY: the caller must guarantee that `self` meets all the
							// requirements for a reference.
							unsafe { &*self.cast().as_ptr() }
						}

						/// Returns a unique references to the value. In contrast to [`as_mut`], this does not require
						/// that the value has to be initialized.
						///
						/// For the shared counterpart see [`as_uninit_ref`].
						///
						/// [`as_mut`]: NonNull::as_mut
						/// [`as_uninit_ref`]: NonNull::as_uninit_ref
						///
						/// # Safety
						///
						/// When calling this method, you have to ensure that
						/// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
						/// Note that because the created reference is to `MaybeUninit<T>`, the
						/// source pointer can point to uninitialized memory.
						#[inline]
						#[must_use]
						pub const unsafe fn as_uninit_mut<'a>(self) -> &'a mut MaybeUninit<T> {
							// SAFETY: the caller must guarantee that `self` meets all the
							// requirements for a reference.
							unsafe { &mut *self.cast().as_ptr() }
						}
					}

					impl<T: ?Sized> NonNull<T> {
						/// Creates a new `NonNull`.
						///
						/// # Safety
						///
						/// `ptr` must be non-null.
						///
						/// # Examples
						///
						/// ```
						/// use NonNull;
						///
						/// let mut x = 0u32;
						/// let ptr = unsafe { NonNull::new_unchecked(&mut x as *mut _) };
						/// ```
						///
						/// *Incorrect* usage of this function:
						///
						/// ```rust,no_run
						/// use NonNull;
						///
						/// // NEVER DO THAT!!! This is undefined behavior. ⚠️
						/// let ptr = unsafe { NonNull::<u32>::new_unchecked(null_mut()) };
						/// ```
						#[inline]
						pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
							// SAFETY: the caller must guarantee that `ptr` is non-null.
							unsafe {
								assert_unsafe_precondition!(
                check_language_ub,
                "NonNull::new_unchecked requires that the pointer is non-null",
                (ptr: *mut () = ptr as *mut ()) => !ptr.is_null()
            );
								NonNull { pointer: ptr as _ }
							}
						}

						/// Creates a new `NonNull` if `ptr` is non-null.
						///
						/// # Panics during const evaluation
						///
						/// This method will panic during const evaluation if the pointer cannot be
						/// determined to be null or not. See [`is_null`] for more information.
						///
						/// [`is_null`]: ../primitive.pointer.html#method.is_null-1
						///
						/// # Examples
						///
						/// ```
						/// use NonNull;
						///
						/// let mut x = 0u32;
						/// let ptr = NonNull::<u32>::new(&mut x as *mut _).expect("ptr is null!");
						///
						/// if let Some(ptr) = NonNull::<u32>::new(null_mut()) {
						///     unreachable!();
						/// }
						/// ```
						#[inline]
						pub const fn new(ptr: *mut T) -> Option<Self> {
							if !ptr.is_null() {
								// SAFETY: The pointer is already checked and is not null
								Some(unsafe { Self::new_unchecked(ptr) })
							} else {
								None
							}
						}

						/// Converts a reference to a `NonNull` pointer.
						#[inline]
						pub const fn from_ref(r: &T) -> Self {
							// SAFETY: A reference cannot be null.
							unsafe { NonNull { pointer: r as *const T } }
						}

						/// Converts a mutable reference to a `NonNull` pointer.
						#[inline]
						pub const fn from_mut(r: &mut T) -> Self {
							// SAFETY: A mutable reference cannot be null.
							unsafe { NonNull { pointer: r as *mut T } }
						}

						/// Performs the same functionality as [`from_raw_parts`], except that a
						/// `NonNull` pointer is returned, as opposed to a raw `*const` pointer.
						///
						/// See the documentation of [`from_raw_parts`] for more details.
						///
						/// [`from_raw_parts`]: crate::ptr::from_raw_parts
						#[inline]
						pub const fn from_raw_parts(
							data_pointer: NonNull<impl super::Thin>,
							metadata: <T as super::Pointee>::Metadata,
						) -> NonNull<T> {
							// SAFETY: The result of `ptr::from::raw_parts_mut` is non-null because `data_pointer` is.
							unsafe {
								NonNull::new_unchecked(super::from_raw_parts_mut(data_pointer.as_ptr(), metadata))
							}
						}

						/// Decompose a (possibly wide) pointer into its data pointer and metadata components.
						///
						/// The pointer can be later reconstructed with [`NonNull::from_raw_parts`].
						#[must_use = "this returns the result of the operation, \
                  without modifying the original"]
						#[inline]
						pub const fn to_raw_parts(self) -> (NonNull<()>, <T as super::Pointee>::Metadata) {
							(self.cast(), super::metadata(self.as_ptr()))
						}

						/// Gets the "address" portion of the pointer.
						///
						/// For more details, see the equivalent method on a raw pointer, [`pointer::addr`].
						///
						/// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
						#[must_use]
						#[inline]
						pub fn addr(self) -> NonZero<usize> {
							// SAFETY: The pointer is guaranteed by the type to be non-null,
							// meaning that the address will be non-zero.
							unsafe { NonZero::new_unchecked(self.as_ptr().addr()) }
						}

						/// Exposes the ["provenance"][crate::ptr#provenance] part of the pointer for future use in
						/// [`with_exposed_provenance`][NonNull::with_exposed_provenance] and returns the "address" portion.
						///
						/// For more details, see the equivalent method on a raw pointer, [`pointer::expose_provenance`].
						///
						/// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
						pub fn expose_provenance(self) -> NonZero<usize> {
							// SAFETY: The pointer is guaranteed by the type to be non-null,
							// meaning that the address will be non-zero.
							unsafe { NonZero::new_unchecked(self.as_ptr().expose_provenance()) }
						}

						/// Creates a new pointer with the given address and the [provenance][crate::ptr#provenance] of
						/// `self`.
						///
						/// For more details, see the equivalent method on a raw pointer, [`pointer::with_addr`].
						///
						/// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
						#[must_use]
						#[inline]
						pub fn with_addr(self, addr: NonZero<usize>) -> Self {
							// SAFETY: The result of `ptr::from::with_addr` is non-null because `addr` is guaranteed to be non-zero.
							unsafe { NonNull::new_unchecked(self.as_ptr().with_addr(addr.get()) as *mut _) }
						}

						/// Creates a new pointer by mapping `self`'s address to a new one, preserving the
						/// [provenance][crate::ptr#provenance] of `self`.
						///
						/// For more details, see the equivalent method on a raw pointer, [`pointer::map_addr`].
						///
						/// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
						#[must_use]
						#[inline]
						pub fn map_addr(self, f: impl FnOnce(NonZero<usize>) -> NonZero<usize>) -> Self {
							self.with_addr(f(self.addr()))
						}

						/// Acquires the underlying `*mut` pointer.
						///
						/// # Examples
						///
						/// ```
						/// use NonNull;
						///
						/// let mut x = 0u32;
						/// let ptr = NonNull::new(&mut x).expect("ptr is null!");
						///
						/// let x_value = unsafe { *ptr.as_ptr() };
						/// assert_eq!(x_value, 0);
						///
						/// unsafe { *ptr.as_ptr() += 2; }
						/// let x_value = unsafe { *ptr.as_ptr() };
						/// assert_eq!(x_value, 2);
						/// ```
						#[rustc_never_returns_null_ptr]
						#[must_use]
						#[inline(always)]
						pub const fn as_ptr(self) -> *mut T {
							// This is a transmute for the same reasons as `NonZero::get`.

							// SAFETY: `NonNull` is `transparent` over a `*const T`, and `*const T`
							// and `*mut T` have the same layout, so transitively we can transmute
							// our `NonNull` to a `*mut T` directly.
							unsafe { mem::transmute::<Self, *mut T>(self) }
						}

						/// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`]
						/// must be used instead.
						///
						/// For the mutable counterpart see [`as_mut`].
						///
						/// [`as_uninit_ref`]: NonNull::as_uninit_ref
						/// [`as_mut`]: NonNull::as_mut
						///
						/// # Safety
						///
						/// When calling this method, you have to ensure that
						/// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
						///
						/// # Examples
						///
						/// ```
						/// use NonNull;
						///
						/// let mut x = 0u32;
						/// let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!");
						///
						/// let ref_x = unsafe { ptr.as_ref() };
						/// println!("{ref_x}");
						/// ```
						///
						/// [the module documentation]: crate::ptr#safety
						#[must_use]
						#[inline(always)]
						pub const unsafe fn as_ref<'a>(&self) -> &'a T {
							// SAFETY: the caller must guarantee that `self` meets all the
							// requirements for a reference.
							// `cast_const` avoids a mutable raw pointer deref.
							unsafe { &*self.as_ptr().cast_const() }
						}

						/// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
						/// must be used instead.
						///
						/// For the shared counterpart see [`as_ref`].
						///
						/// [`as_uninit_mut`]: NonNull::as_uninit_mut
						/// [`as_ref`]: NonNull::as_ref
						///
						/// # Safety
						///
						/// When calling this method, you have to ensure that
						/// the pointer is [convertible to a reference](crate::ptr#pointer-to-reference-conversion).
						/// # Examples
						///
						/// ```
						/// use NonNull;
						///
						/// let mut x = 0u32;
						/// let mut ptr = NonNull::new(&mut x).expect("null pointer");
						///
						/// let x_ref = unsafe { ptr.as_mut() };
						/// assert_eq!(*x_ref, 0);
						/// *x_ref += 2;
						/// assert_eq!(*x_ref, 2);
						/// ```
						///
						/// [the module documentation]: crate::ptr#safety
						#[must_use]
						#[inline(always)]
						pub const unsafe fn as_mut<'a>(&mut self) -> &'a mut T {
							// SAFETY: the caller must guarantee that `self` meets all the
							// requirements for a mutable reference.
							unsafe { &mut *self.as_ptr() }
						}

						/// Casts to a pointer of another type.
						///
						/// # Examples
						///
						/// ```
						/// use NonNull;
						///
						/// let mut x = 0u32;
						/// let ptr = NonNull::new(&mut x as *mut _).expect("null pointer");
						///
						/// let casted_ptr = ptr.cast::<i8>();
						/// let raw_ptr: *mut i8 = casted_ptr.as_ptr();
						/// ```
						#[must_use = "this returns the result of the operation, \
                  without modifying the original"]
						#[inline]
						pub const fn cast<U>(self) -> NonNull<U> {
							// SAFETY: `self` is a `NonNull` pointer which is necessarily non-null
							unsafe { NonNull { pointer: self.as_ptr() as *mut U } }
						}

						/// Adds an offset to a pointer.
						///
						/// `count` is in units of T; e.g., a `count` of 3 represents a pointer
						/// offset of `3 * size_of::<T>()` bytes.
						///
						/// # Safety
						///
						/// If any of the following conditions are violated, the result is Undefined Behavior:
						///
						/// * The computed offset, `count * size_of::<T>()` bytes, must not overflow `isize`.
						///
						/// * If the computed offset is non-zero, then `self` must be derived from a pointer to some
						///   [allocated object], and the entire memory range between `self` and the result must be in
						///   bounds of that allocated object. In particular, this range must not "wrap around" the edge
						///   of the address space.
						///
						/// Allocated objects can never be larger than `isize::MAX` bytes, so if the computed offset
						/// stays in bounds of the allocated object, it is guaranteed to satisfy the first requirement.
						/// This implies, for instance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always
						/// safe.
						///
						/// [allocated object]: crate::ptr#allocated-object
						///
						/// # Examples
						///
						/// ```
						/// use NonNull;
						///
						/// let mut s = [1, 2, 3];
						/// let ptr: NonNull<u32> = NonNull::new(s.as_mut_ptr()).unwrap();
						///
						/// unsafe {
						///     println!("{}", ptr.offset(1).read());
						///     println!("{}", ptr.offset(2).read());
						/// }
						/// ```
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						#[must_use = "returns a new pointer rather than modifying its argument"]
						pub const unsafe fn offset(self, count: isize) -> Self
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `offset`.
							// Additionally safety contract of `offset` guarantees that the resulting pointer is
							// pointing to an allocation, there can't be an allocation at null, thus it's safe to
							// construct `NonNull`.
							unsafe { NonNull { pointer: intrinsics::offset(self.as_ptr(), count) } }
						}

						/// Calculates the offset from a pointer in bytes.
						///
						/// `count` is in units of **bytes**.
						///
						/// This is purely a convenience for casting to a `u8` pointer and
						/// using [offset][pointer::offset] on it. See that method for documentation
						/// and safety requirements.
						///
						/// For non-`Sized` pointees this operation changes only the data pointer,
						/// leaving the metadata untouched.
						#[must_use]
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn byte_offset(self, count: isize) -> Self {
							// SAFETY: the caller must uphold the safety contract for `offset` and `byte_offset` has
							// the same safety contract.
							// Additionally safety contract of `offset` guarantees that the resulting pointer is
							// pointing to an allocation, there can't be an allocation at null, thus it's safe to
							// construct `NonNull`.
							unsafe { NonNull { pointer: self.as_ptr().byte_offset(count) } }
						}

						/// Adds an offset to a pointer (convenience for `.offset(count as isize)`).
						///
						/// `count` is in units of T; e.g., a `count` of 3 represents a pointer
						/// offset of `3 * size_of::<T>()` bytes.
						///
						/// # Safety
						///
						/// If any of the following conditions are violated, the result is Undefined Behavior:
						///
						/// * The computed offset, `count * size_of::<T>()` bytes, must not overflow `isize`.
						///
						/// * If the computed offset is non-zero, then `self` must be derived from a pointer to some
						///   [allocated object], and the entire memory range between `self` and the result must be in
						///   bounds of that allocated object. In particular, this range must not "wrap around" the edge
						///   of the address space.
						///
						/// Allocated objects can never be larger than `isize::MAX` bytes, so if the computed offset
						/// stays in bounds of the allocated object, it is guaranteed to satisfy the first requirement.
						/// This implies, for instance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always
						/// safe.
						///
						/// [allocated object]: crate::ptr#allocated-object
						///
						/// # Examples
						///
						/// ```
						/// use NonNull;
						///
						/// let s: &str = "123";
						/// let ptr: NonNull<u8> = NonNull::new(s.as_ptr().cast_mut()).unwrap();
						///
						/// unsafe {
						///     println!("{}", ptr.add(1).read() as char);
						///     println!("{}", ptr.add(2).read() as char);
						/// }
						/// ```
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						#[must_use = "returns a new pointer rather than modifying its argument"]
						pub const unsafe fn add(self, count: usize) -> Self
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `offset`.
							// Additionally safety contract of `offset` guarantees that the resulting pointer is
							// pointing to an allocation, there can't be an allocation at null, thus it's safe to
							// construct `NonNull`.
							unsafe { NonNull { pointer: intrinsics::offset(self.as_ptr(), count) } }
						}

						/// Calculates the offset from a pointer in bytes (convenience for `.byte_offset(count as isize)`).
						///
						/// `count` is in units of bytes.
						///
						/// This is purely a convenience for casting to a `u8` pointer and
						/// using [`add`][NonNull::add] on it. See that method for documentation
						/// and safety requirements.
						///
						/// For non-`Sized` pointees this operation changes only the data pointer,
						/// leaving the metadata untouched.
						#[must_use]
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn byte_add(self, count: usize) -> Self {
							// SAFETY: the caller must uphold the safety contract for `add` and `byte_add` has the same
							// safety contract.
							// Additionally safety contract of `add` guarantees that the resulting pointer is pointing
							// to an allocation, there can't be an allocation at null, thus it's safe to construct
							// `NonNull`.
							unsafe { NonNull { pointer: self.as_ptr().byte_add(count) } }
						}

						/// Subtracts an offset from a pointer (convenience for
						/// `.offset((count as isize).wrapping_neg())`).
						///
						/// `count` is in units of T; e.g., a `count` of 3 represents a pointer
						/// offset of `3 * size_of::<T>()` bytes.
						///
						/// # Safety
						///
						/// If any of the following conditions are violated, the result is Undefined Behavior:
						///
						/// * The computed offset, `count * size_of::<T>()` bytes, must not overflow `isize`.
						///
						/// * If the computed offset is non-zero, then `self` must be derived from a pointer to some
						///   [allocated object], and the entire memory range between `self` and the result must be in
						///   bounds of that allocated object. In particular, this range must not "wrap around" the edge
						///   of the address space.
						///
						/// Allocated objects can never be larger than `isize::MAX` bytes, so if the computed offset
						/// stays in bounds of the allocated object, it is guaranteed to satisfy the first requirement.
						/// This implies, for instance, that `vec.as_ptr().add(vec.len())` (for `vec: Vec<T>`) is always
						/// safe.
						///
						/// [allocated object]: crate::ptr#allocated-object
						///
						/// # Examples
						///
						/// ```
						/// use NonNull;
						///
						/// let s: &str = "123";
						///
						/// unsafe {
						///     let end: NonNull<u8> = NonNull::new(s.as_ptr().cast_mut()).unwrap().add(3);
						///     println!("{}", end.sub(1).read() as char);
						///     println!("{}", end.sub(2).read() as char);
						/// }
						/// ```
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						#[must_use = "returns a new pointer rather than modifying its argument"]
						pub const unsafe fn sub(self, count: usize) -> Self
						where
							T: Sized,
						{
							if T::IS_ZST {
								// Pointer arithmetic does nothing when the pointee is a ZST.
								self
							} else {
								// SAFETY: the caller must uphold the safety contract for `offset`.
								// Because the pointee is *not* a ZST, that means that `count` is
								// at most `isize::MAX`, and thus the negation cannot overflow.
								unsafe { self.offset((count as isize).unchecked_neg()) }
							}
						}

						/// Calculates the offset from a pointer in bytes (convenience for
						/// `.byte_offset((count as isize).wrapping_neg())`).
						///
						/// `count` is in units of bytes.
						///
						/// This is purely a convenience for casting to a `u8` pointer and
						/// using [`sub`][NonNull::sub] on it. See that method for documentation
						/// and safety requirements.
						///
						/// For non-`Sized` pointees this operation changes only the data pointer,
						/// leaving the metadata untouched.
						#[must_use]
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn byte_sub(self, count: usize) -> Self {
							// SAFETY: the caller must uphold the safety contract for `sub` and `byte_sub` has the same
							// safety contract.
							// Additionally safety contract of `sub` guarantees that the resulting pointer is pointing
							// to an allocation, there can't be an allocation at null, thus it's safe to construct
							// `NonNull`.
							unsafe { NonNull { pointer: self.as_ptr().byte_sub(count) } }
						}

						/// Calculates the distance between two pointers within the same allocation. The returned value is in
						/// units of T: the distance in bytes divided by `size_of::<T>()`.
						///
						/// This is equivalent to `(self as isize - origin as isize) / (size_of::<T>() as isize)`,
						/// except that it has a lot more opportunities for UB, in exchange for the compiler
						/// better understanding what you are doing.
						///
						/// The primary motivation of this method is for computing the `len` of an array/slice
						/// of `T` that you are currently representing as a "start" and "end" pointer
						/// (and "end" is "one past the end" of the array).
						/// In that case, `end.offset_from(start)` gets you the length of the array.
						///
						/// All of the following safety requirements are trivially satisfied for this usecase.
						///
						/// [`offset`]: #method.offset
						///
						/// # Safety
						///
						/// If any of the following conditions are violated, the result is Undefined Behavior:
						///
						/// * `self` and `origin` must either
						///
						///   * point to the same address, or
						///   * both be *derived from* a pointer to the same [allocated object], and the memory range between
						///     the two pointers must be in bounds of that object. (See below for an example.)
						///
						/// * The distance between the pointers, in bytes, must be an exact multiple
						///   of the size of `T`.
						///
						/// As a consequence, the absolute distance between the pointers, in bytes, computed on
						/// mathematical integers (without "wrapping around"), cannot overflow an `isize`. This is
						/// implied by the in-bounds requirement, and the fact that no allocated object can be larger
						/// than `isize::MAX` bytes.
						///
						/// The requirement for pointers to be derived from the same allocated object is primarily
						/// needed for `const`-compatibility: the distance between pointers into *different* allocated
						/// objects is not known at compile-time. However, the requirement also exists at
						/// runtime and may be exploited by optimizations. If you wish to compute the difference between
						/// pointers that are not guaranteed to be from the same allocation, use `(self as isize -
						/// origin as isize) / size_of::<T>()`.
						// FIXME: recommend `addr()` instead of `as usize` once that is stable.
						///
						/// [`add`]: #method.add
						/// [allocated object]: crate::ptr#allocated-object
						///
						/// # Panics
						///
						/// This function panics if `T` is a Zero-Sized Type ("ZST").
						///
						/// # Examples
						///
						/// Basic usage:
						///
						/// ```
						/// use NonNull;
						///
						/// let a = [0; 5];
						/// let ptr1: NonNull<u32> = NonNull::from(&a[1]);
						/// let ptr2: NonNull<u32> = NonNull::from(&a[3]);
						/// unsafe {
						///     assert_eq!(ptr2.offset_from(ptr1), 2);
						///     assert_eq!(ptr1.offset_from(ptr2), -2);
						///     assert_eq!(ptr1.offset(2), ptr2);
						///     assert_eq!(ptr2.offset(-2), ptr1);
						/// }
						/// ```
						///
						/// *Incorrect* usage:
						///
						/// ```rust,no_run
						/// use NonNull;
						///
						/// let ptr1 = NonNull::new(Box::into_raw(Box::new(0u8))).unwrap();
						/// let ptr2 = NonNull::new(Box::into_raw(Box::new(1u8))).unwrap();
						/// let diff = (ptr2.addr().get() as isize).wrapping_sub(ptr1.addr().get() as isize);
						/// // Make ptr2_other an "alias" of ptr2.add(1), but derived from ptr1.
						/// let diff_plus_1 = diff.wrapping_add(1);
						/// let ptr2_other = NonNull::new(ptr1.as_ptr().wrapping_byte_offset(diff_plus_1)).unwrap();
						/// assert_eq!(ptr2.addr(), ptr2_other.addr());
						/// // Since ptr2_other and ptr2 are derived from pointers to different objects,
						/// // computing their offset is undefined behavior, even though
						/// // they point to addresses that are in-bounds of the same object!
						///
						/// let one = unsafe { ptr2_other.offset_from(ptr2) }; // Undefined Behavior! ⚠️
						/// ```
						#[inline]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn offset_from(self, origin: NonNull<T>) -> isize
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `offset_from`.
							unsafe { self.as_ptr().offset_from(origin.as_ptr()) }
						}

						/// Calculates the distance between two pointers within the same allocation. The returned value is in
						/// units of **bytes**.
						///
						/// This is purely a convenience for casting to a `u8` pointer and
						/// using [`offset_from`][NonNull::offset_from] on it. See that method for
						/// documentation and safety requirements.
						///
						/// For non-`Sized` pointees this operation considers only the data pointers,
						/// ignoring the metadata.
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: NonNull<U>) -> isize {
							// SAFETY: the caller must uphold the safety contract for `byte_offset_from`.
							unsafe { self.as_ptr().byte_offset_from(origin.as_ptr()) }
						}

						// N.B. `wrapping_offset``, `wrapping_add`, etc are not implemented because they can wrap to null

						/// Calculates the distance between two pointers within the same allocation, *where it's known that
						/// `self` is equal to or greater than `origin`*. The returned value is in
						/// units of T: the distance in bytes is divided by `size_of::<T>()`.
						///
						/// This computes the same value that [`offset_from`](#method.offset_from)
						/// would compute, but with the added precondition that the offset is
						/// guaranteed to be non-negative.  This method is equivalent to
						/// `usize::try_from(self.offset_from(origin)).unwrap_unchecked()`,
						/// but it provides slightly more information to the optimizer, which can
						/// sometimes allow it to optimize slightly better with some backends.
						///
						/// This method can be though of as recovering the `count` that was passed
						/// to [`add`](#method.add) (or, with the parameters in the other order,
						/// to [`sub`](#method.sub)).  The following are all equivalent, assuming
						/// that their safety preconditions are met:
						/// ```rust
						/// # unsafe fn blah(ptr: NonNull<u32>, origin: NonNull<u32>, count: usize) -> bool { unsafe {
						/// ptr.offset_from_unsigned(origin) == count
						/// # &&
						/// origin.add(count) == ptr
						/// # &&
						/// ptr.sub(count) == origin
						/// # } }
						/// ```
						///
						/// # Safety
						///
						/// - The distance between the pointers must be non-negative (`self >= origin`)
						///
						/// - *All* the safety conditions of [`offset_from`](#method.offset_from)
						///   apply to this method as well; see it for the full details.
						///
						/// Importantly, despite the return type of this method being able to represent
						/// a larger offset, it's still *not permitted* to pass pointers which differ
						/// by more than `isize::MAX` *bytes*.  As such, the result of this method will
						/// always be less than or equal to `isize::MAX as usize`.
						///
						/// # Panics
						///
						/// This function panics if `T` is a Zero-Sized Type ("ZST").
						///
						/// # Examples
						///
						/// ```
						/// use NonNull;
						///
						/// let a = [0; 5];
						/// let ptr1: NonNull<u32> = NonNull::from(&a[1]);
						/// let ptr2: NonNull<u32> = NonNull::from(&a[3]);
						/// unsafe {
						///     assert_eq!(ptr2.offset_from_unsigned(ptr1), 2);
						///     assert_eq!(ptr1.add(2), ptr2);
						///     assert_eq!(ptr2.sub(2), ptr1);
						///     assert_eq!(ptr2.offset_from_unsigned(ptr2), 0);
						/// }
						///
						/// // This would be incorrect, as the pointers are not correctly ordered:
						/// // ptr1.offset_from_unsigned(ptr2)
						/// ```
						#[inline]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn offset_from_unsigned(self, subtracted: NonNull<T>) -> usize
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `offset_from_unsigned`.
							unsafe { self.as_ptr().offset_from_unsigned(subtracted.as_ptr()) }
						}

						/// Calculates the distance between two pointers within the same allocation, *where it's known that
						/// `self` is equal to or greater than `origin`*. The returned value is in
						/// units of **bytes**.
						///
						/// This is purely a convenience for casting to a `u8` pointer and
						/// using [`offset_from_unsigned`][NonNull::offset_from_unsigned] on it.
						/// See that method for documentation and safety requirements.
						///
						/// For non-`Sized` pointees this operation considers only the data pointers,
						/// ignoring the metadata.
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn byte_offset_from_unsigned<U: ?Sized>(self, origin: NonNull<U>) -> usize {
							// SAFETY: the caller must uphold the safety contract for `byte_offset_from_unsigned`.
							unsafe { self.as_ptr().byte_offset_from_unsigned(origin.as_ptr()) }
						}

						/// Reads the value from `self` without moving it. This leaves the
						/// memory in `self` unchanged.
						///
						/// See [`ptr::read`] for safety concerns and examples.
						///
						/// [`ptr::read`]: crate::ptr::read()
						#[inline]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn read(self) -> T
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `read`.
							unsafe { ptr::read(self.as_ptr()) }
						}

						/// Performs a volatile read of the value from `self` without moving it. This
						/// leaves the memory in `self` unchanged.
						///
						/// Volatile operations are intended to act on I/O memory, and are guaranteed
						/// to not be elided or reordered by the compiler across other volatile
						/// operations.
						///
						/// See [`ptr::read_volatile`] for safety concerns and examples.
						///
						/// [`ptr::read_volatile`]: crate::ptr::read_volatile()
						#[inline]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub unsafe fn read_volatile(self) -> T
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `read_volatile`.
							unsafe { ptr::read_volatile(self.as_ptr()) }
						}

						/// Reads the value from `self` without moving it. This leaves the
						/// memory in `self` unchanged.
						///
						/// Unlike `read`, the pointer may be unaligned.
						///
						/// See [`ptr::read_unaligned`] for safety concerns and examples.
						///
						/// [`ptr::read_unaligned`]: crate::ptr::read_unaligned()
						#[inline]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn read_unaligned(self) -> T
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `read_unaligned`.
							unsafe { ptr::read_unaligned(self.as_ptr()) }
						}

						/// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
						/// and destination may overlap.
						///
						/// NOTE: this has the *same* argument order as [`ptr::copy`].
						///
						/// See [`ptr::copy`] for safety concerns and examples.
						///
						/// [`ptr::copy`]: crate::ptr::copy()
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn copy_to(self, dest: NonNull<T>, count: usize)
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `copy`.
							unsafe { ptr::copy(self.as_ptr(), dest.as_ptr(), count) }
						}

						/// Copies `count * size_of::<T>()` bytes from `self` to `dest`. The source
						/// and destination may *not* overlap.
						///
						/// NOTE: this has the *same* argument order as [`ptr::copy_nonoverlapping`].
						///
						/// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
						///
						/// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn copy_to_nonoverlapping(self, dest: NonNull<T>, count: usize)
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
							unsafe { ptr::copy_nonoverlapping(self.as_ptr(), dest.as_ptr(), count) }
						}

						/// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
						/// and destination may overlap.
						///
						/// NOTE: this has the *opposite* argument order of [`ptr::copy`].
						///
						/// See [`ptr::copy`] for safety concerns and examples.
						///
						/// [`ptr::copy`]: crate::ptr::copy()
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn copy_from(self, src: NonNull<T>, count: usize)
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `copy`.
							unsafe { ptr::copy(src.as_ptr(), self.as_ptr(), count) }
						}

						/// Copies `count * size_of::<T>()` bytes from `src` to `self`. The source
						/// and destination may *not* overlap.
						///
						/// NOTE: this has the *opposite* argument order of [`ptr::copy_nonoverlapping`].
						///
						/// See [`ptr::copy_nonoverlapping`] for safety concerns and examples.
						///
						/// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping()
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn copy_from_nonoverlapping(self, src: NonNull<T>, count: usize)
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`.
							unsafe { ptr::copy_nonoverlapping(src.as_ptr(), self.as_ptr(), count) }
						}

						/// Executes the destructor (if any) of the pointed-to value.
						///
						/// See [`ptr::drop_in_place`] for safety concerns and examples.
						///
						/// [`ptr::drop_in_place`]: crate::ptr::drop_in_place()
						#[inline(always)]
						pub unsafe fn drop_in_place(self) {
							// SAFETY: the caller must uphold the safety contract for `drop_in_place`.
							unsafe { ptr::drop_in_place(self.as_ptr()) }
						}

						/// Overwrites a memory location with the given value without reading or
						/// dropping the old value.
						///
						/// See [`ptr::write`] for safety concerns and examples.
						///
						/// [`ptr::write`]: crate::ptr::write()
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn write(self, val: T)
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `write`.
							unsafe { ptr::write(self.as_ptr(), val) }
						}

						/// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
						/// bytes of memory starting at `self` to `val`.
						///
						/// See [`ptr::write_bytes`] for safety concerns and examples.
						///
						/// [`ptr::write_bytes`]: crate::ptr::write_bytes()
						#[inline(always)]
						#[doc(alias = "memset")]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn write_bytes(self, val: u8, count: usize)
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `write_bytes`.
							unsafe { ptr::write_bytes(self.as_ptr(), val, count) }
						}

						/// Performs a volatile write of a memory location with the given value without
						/// reading or dropping the old value.
						///
						/// Volatile operations are intended to act on I/O memory, and are guaranteed
						/// to not be elided or reordered by the compiler across other volatile
						/// operations.
						///
						/// See [`ptr::write_volatile`] for safety concerns and examples.
						///
						/// [`ptr::write_volatile`]: crate::ptr::write_volatile()
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub unsafe fn write_volatile(self, val: T)
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `write_volatile`.
							unsafe { ptr::write_volatile(self.as_ptr(), val) }
						}

						/// Overwrites a memory location with the given value without reading or
						/// dropping the old value.
						///
						/// Unlike `write`, the pointer may be unaligned.
						///
						/// See [`ptr::write_unaligned`] for safety concerns and examples.
						///
						/// [`ptr::write_unaligned`]: crate::ptr::write_unaligned()
						#[inline(always)]
						#[cfg_attr(
							miri,
							track_caller
						)] // even without panics, this helps for Miri backtraces
						pub const unsafe fn write_unaligned(self, val: T)
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `write_unaligned`.
							unsafe { ptr::write_unaligned(self.as_ptr(), val) }
						}

						/// Replaces the value at `self` with `src`, returning the old
						/// value, without dropping either.
						///
						/// See [`ptr::replace`] for safety concerns and examples.
						///
						/// [`ptr::replace`]: crate::ptr::replace()
						#[inline(always)]
						pub const unsafe fn replace(self, src: T) -> T
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `replace`.
							unsafe { ptr::replace(self.as_ptr(), src) }
						}

						/// Swaps the values at two mutable locations of the same type, without
						/// deinitializing either. They may overlap, unlike `mem::swap` which is
						/// otherwise equivalent.
						///
						/// See [`ptr::swap`] for safety concerns and examples.
						///
						/// [`ptr::swap`]: crate::ptr::swap()
						#[inline(always)]
						pub const unsafe fn swap(self, with: NonNull<T>)
						where
							T: Sized,
						{
							// SAFETY: the caller must uphold the safety contract for `swap`.
							unsafe { ptr::swap(self.as_ptr(), with.as_ptr()) }
						}

						/// Computes the offset that needs to be applied to the pointer in order to make it aligned to
						/// `align`.
						///
						/// If it is not possible to align the pointer, the implementation returns
						/// `usize::MAX`.
						///
						/// The offset is expressed in number of `T` elements, and not bytes.
						///
						/// There are no guarantees whatsoever that offsetting the pointer will not overflow or go
						/// beyond the allocation that the pointer points into. It is up to the caller to ensure that
						/// the returned offset is correct in all terms other than alignment.
						///
						/// When this is called during compile-time evaluation (which is unstable), the implementation
						/// may return `usize::MAX` in cases where that can never happen at runtime. This is because the
						/// actual alignment of pointers is not known yet during compile-time, so an offset with
						/// guaranteed alignment can sometimes not be computed. For example, a buffer declared as `[u8;
						/// N]` might be allocated at an odd or an even address, but at compile-time this is not yet
						/// known, so the execution has to be correct for either choice. It is therefore impossible to
						/// find an offset that is guaranteed to be 2-aligned. (This behavior is subject to change, as usual
						/// for unstable APIs.)
						///
						/// # Panics
						///
						/// The function panics if `align` is not a power-of-two.
						///
						/// # Examples
						///
						/// Accessing adjacent `u8` as `u16`
						///
						/// ```
						/// use NonNull;
						///
						/// # unsafe {
						/// let x = [5_u8, 6, 7, 8, 9];
						/// let ptr = NonNull::new(x.as_ptr() as *mut u8).unwrap();
						/// let offset = ptr.align_offset(align_of::<u16>());
						///
						/// if offset < x.len() - 1 {
						///     let u16_ptr = ptr.add(offset).cast::<u16>();
						///     assert!(u16_ptr.read() == u16::from_ne_bytes([5, 6]) || u16_ptr.read() == u16::from_ne_bytes([6, 7]));
						/// } else {
						///     // while the pointer can be aligned via `offset`, it would point
						///     // outside the allocation
						/// }
						/// # }
						/// ```
						#[inline]
						#[must_use]
						pub fn align_offset(self, align: usize) -> usize
						where
							T: Sized,
						{
							if !align.is_power_of_two() {
								core::panic!("align_offset: align is not a power-of-two");
							}

							{
								// SAFETY: `align` has been checked to be a power of 2 above.
								unsafe { ptr::align_offset(self.as_ptr(), align) }
							}
						}

						/// Returns whether the pointer is properly aligned for `T`.
						///
						/// # Examples
						///
						/// ```
						/// use NonNull;
						///
						/// // On some platforms, the alignment of i32 is less than 4.
						/// #[repr(align(4))]
						/// struct AlignedI32(i32);
						///
						/// let data = AlignedI32(42);
						/// let ptr = NonNull::<AlignedI32>::from(&data);
						///
						/// assert!(ptr.is_aligned());
						/// assert!(!NonNull::new(ptr.as_ptr().wrapping_byte_add(1)).unwrap().is_aligned());
						/// ```
						#[inline]
						#[must_use]
						pub fn is_aligned(self) -> bool
						where
							T: Sized,
						{
							self.as_ptr().is_aligned()
						}

						/// Returns whether the pointer is aligned to `align`.
						///
						/// For non-`Sized` pointees this operation considers only the data pointer,
						/// ignoring the metadata.
						///
						/// # Panics
						///
						/// The function panics if `align` is not a power-of-two (this includes 0).
						///
						/// # Examples
						///
						/// ```
						/// #![feature(pointer_is_aligned_to)]
						///
						/// // On some platforms, the alignment of i32 is less than 4.
						/// #[repr(align(4))]
						/// struct AlignedI32(i32);
						///
						/// let data = AlignedI32(42);
						/// let ptr = &data as *const AlignedI32;
						///
						/// assert!(ptr.is_aligned_to(1));
						/// assert!(ptr.is_aligned_to(2));
						/// assert!(ptr.is_aligned_to(4));
						///
						/// assert!(ptr.wrapping_byte_add(2).is_aligned_to(2));
						/// assert!(!ptr.wrapping_byte_add(2).is_aligned_to(4));
						///
						/// assert_ne!(ptr.is_aligned_to(8), ptr.wrapping_add(1).is_aligned_to(8));
						/// ```
						#[inline]
						#[must_use]
						pub fn is_aligned_to(self, align: usize) -> bool {
							self.as_ptr().is_aligned_to(align)
						}
					}

					impl<T> NonNull<[T]> {
						/// Creates a non-null raw slice from a thin pointer and a length.
						///
						/// The `len` argument is the number of **elements**, not the number of bytes.
						///
						/// This function is safe, but dereferencing the return value is unsafe.
						/// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
						///
						/// # Examples
						///
						/// ```rust
						/// use NonNull;
						///
						/// // create a slice pointer when starting out with a pointer to the first element
						/// let mut x = [5, 6, 7];
						/// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
						/// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
						/// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
						/// ```
						///
						/// (Note that this example artificially demonstrates a use of this method,
						/// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
						#[must_use]
						#[inline]
						pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
							// SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
							unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
						}

						/// Returns the length of a non-null raw slice.
						///
						/// The returned value is the number of **elements**, not the number of bytes.
						///
						/// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
						/// because the pointer does not have a valid address.
						///
						/// # Examples
						///
						/// ```rust
						/// use NonNull;
						///
						/// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
						/// assert_eq!(slice.len(), 3);
						/// ```
						#[must_use]
						#[inline]
						pub const fn len(self) -> usize {
							self.as_ptr().len()
						}

						/// Returns `true` if the non-null raw slice has a length of 0.
						///
						/// # Examples
						///
						/// ```rust
						/// use NonNull;
						///
						/// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
						/// assert!(!slice.is_empty());
						/// ```
						#[must_use]
						#[inline]
						pub const fn is_empty(self) -> bool {
							self.len() == 0
						}

						/// Returns a non-null pointer to the slice's buffer.
						///
						/// # Examples
						///
						/// ```rust
						/// #![feature(slice_ptr_get)]
						/// use NonNull;
						///
						/// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
						/// assert_eq!(slice.as_non_null_ptr(), NonNull::<i8>::dangling());
						/// ```
						#[inline]
						#[must_use]
						pub const fn as_non_null_ptr(self) -> NonNull<T> {
							self.cast()
						}

						/// Returns a raw pointer to the slice's buffer.
						///
						/// # Examples
						///
						/// ```rust
						/// #![feature(slice_ptr_get)]
						/// use NonNull;
						///
						/// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
						/// assert_eq!(slice.as_mut_ptr(), NonNull::<i8>::dangling().as_ptr());
						/// ```
						#[inline]
						#[must_use]
						#[rustc_never_returns_null_ptr]
						pub const fn as_mut_ptr(self) -> *mut T {
							self.as_non_null_ptr().as_ptr()
						}

						/// Returns a shared reference to a slice of possibly uninitialized values. In contrast to
						/// [`as_ref`], this does not require that the value has to be initialized.
						///
						/// For the mutable counterpart see [`as_uninit_slice_mut`].
						///
						/// [`as_ref`]: NonNull::as_ref
						/// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut
						///
						/// # Safety
						///
						/// When calling this method, you have to ensure that all of the following is true:
						///
						/// * The pointer must be [valid] for reads for `ptr.len() * size_of::<T>()` many bytes,
						///   and it must be properly aligned. This means in particular:
						///
						///     * The entire memory range of this slice must be contained within a single allocated object!
						///       Slices can never span across multiple allocated objects.
						///
						///     * The pointer must be aligned even for zero-length slices. One
						///       reason for this is that enum layout optimizations may rely on references
						///       (including slices of any length) being aligned and non-null to distinguish
						///       them from other data. You can obtain a pointer that is usable as `data`
						///       for zero-length slices using [`NonNull::dangling()`].
						///
						/// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
						///   See the safety documentation of [`pointer::offset`].
						///
						/// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
						///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
						///   In particular, while this reference exists, the memory the pointer points to must
						///   not get mutated (except inside `UnsafeCell`).
						///
						/// This applies even if the result of this method is unused!
						///
						/// See also [`slice::from_raw_parts`].
						///
						/// [valid]: crate::ptr#safety
						#[inline]
						#[must_use]
						pub const unsafe fn as_uninit_slice<'a>(self) -> &'a [MaybeUninit<T>] {
							// SAFETY: the caller must uphold the safety contract for `as_uninit_slice`.
							unsafe { slice::from_raw_parts(self.cast().as_ptr(), self.len()) }
						}

						/// Returns a unique reference to a slice of possibly uninitialized values. In contrast to
						/// [`as_mut`], this does not require that the value has to be initialized.
						///
						/// For the shared counterpart see [`as_uninit_slice`].
						///
						/// [`as_mut`]: NonNull::as_mut
						/// [`as_uninit_slice`]: NonNull::as_uninit_slice
						///
						/// # Safety
						///
						/// When calling this method, you have to ensure that all of the following is true:
						///
						/// * The pointer must be [valid] for reads and writes for `ptr.len() * size_of::<T>()`
						///   many bytes, and it must be properly aligned. This means in particular:
						///
						///     * The entire memory range of this slice must be contained within a single allocated object!
						///       Slices can never span across multiple allocated objects.
						///
						///     * The pointer must be aligned even for zero-length slices. One
						///       reason for this is that enum layout optimizations may rely on references
						///       (including slices of any length) being aligned and non-null to distinguish
						///       them from other data. You can obtain a pointer that is usable as `data`
						///       for zero-length slices using [`NonNull::dangling()`].
						///
						/// * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`.
						///   See the safety documentation of [`pointer::offset`].
						///
						/// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
						///   arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
						///   In particular, while this reference exists, the memory the pointer points to must
						///   not get accessed (read or written) through any other pointer.
						///
						/// This applies even if the result of this method is unused!
						///
						/// See also [`slice::from_raw_parts_mut`].
						///
						/// [valid]: crate::ptr#safety
						///
						/// # Examples
						///
						/// ```rust
						/// #![feature(allocator_api, ptr_as_uninit)]
						///
						/// use std::alloc::{Allocator, Layout, Global};
						/// use std::mem::MaybeUninit;
						/// use NonNull;
						///
						/// let memory: NonNull<[u8]> = Global.allocate(Layout::new::<[u8; 32]>())?;
						/// // This is safe as `memory` is valid for reads and writes for `memory.len()` many bytes.
						/// // Note that calling `memory.as_mut()` is not allowed here as the content may be uninitialized.
						/// # #[allow(unused_variables)]
						/// let slice: &mut [MaybeUninit<u8>] = unsafe { memory.as_uninit_slice_mut() };
						/// # // Prevent leaks for Miri.
						/// # unsafe { Global.deallocate(memory.cast(), Layout::new::<[u8; 32]>()); }
						/// # Ok::<_, std::alloc::AllocError>(())
						/// ```
						#[inline]
						#[must_use]
						pub const unsafe fn as_uninit_slice_mut<'a>(self) -> &'a mut [MaybeUninit<T>] {
							// SAFETY: the caller must uphold the safety contract for `as_uninit_slice_mut`.
							unsafe { slice::from_raw_parts_mut(self.cast().as_ptr(), self.len()) }
						}

						/// Returns a raw pointer to an element or subslice, without doing bounds
						/// checking.
						///
						/// Calling this method with an out-of-bounds index or when `self` is not dereferenceable
						/// is *[undefined behavior]* even if the resulting pointer is not used.
						///
						/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
						///
						/// # Examples
						///
						/// ```
						/// #![feature(slice_ptr_get)]
						/// use NonNull;
						///
						/// let x = &mut [1, 2, 4];
						/// let x = NonNull::slice_from_raw_parts(NonNull::new(x.as_mut_ptr()).unwrap(), x.len());
						///
						/// unsafe {
						///     assert_eq!(x.get_unchecked_mut(1).as_ptr(), x.as_non_null_ptr().as_ptr().add(1));
						/// }
						/// ```
						#[inline]
						pub unsafe fn get_unchecked_mut<I>(self, index: I) -> NonNull<I::Output>
						where
							I: SliceIndex<[T]>,
						{
							// SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds.
							// As a consequence, the resulting pointer cannot be null.
							unsafe { NonNull::new_unchecked(self.as_ptr().get_unchecked_mut(index)) }
						}
					}

					impl<T: ?Sized> Clone for NonNull<T> {
						#[inline(always)]
						fn clone(&self) -> Self {
							*self
						}
					}

					impl<T: ?Sized> Copy for NonNull<T> {}

					impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T>
					where
						T: Unsize<U>,
					{}

					impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T>
					where
						T: Unsize<U>,
					{}

					unsafe impl<T: ?Sized> PinCoerceUnsized for NonNull<T> {}

					impl<T> core::marker::PointerLike for NonNull<T> {}

					impl<T: ?Sized> fmt::Debug for NonNull<T> {
						fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
							fmt::Pointer::fmt(&self.as_ptr(), f)
						}
					}

					impl<T: ?Sized> fmt::Pointer for NonNull<T> {
						fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
							fmt::Pointer::fmt(&self.as_ptr(), f)
						}
					}

					impl<T: ?Sized> Eq for NonNull<T> {}

					impl<T: ?Sized> PartialEq for NonNull<T> {
						#[inline]
						#[allow(ambiguous_wide_pointer_comparisons)]
						fn eq(&self, other: &Self) -> bool {
							self.as_ptr() == other.as_ptr()
						}
					}

					impl<T: ?Sized> Ord for NonNull<T> {
						#[inline]
						#[allow(ambiguous_wide_pointer_comparisons)]
						fn cmp(&self, other: &Self) -> Ordering {
							self.as_ptr().cmp(&other.as_ptr())
						}
					}

					impl<T: ?Sized> PartialOrd for NonNull<T> {
						#[inline]
						#[allow(ambiguous_wide_pointer_comparisons)]
						fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
							self.as_ptr().partial_cmp(&other.as_ptr())
						}
					}

					impl<T: ?Sized> hash::Hash for NonNull<T> {
						#[inline]
						fn hash<H: hash::Hasher>(&self, state: &mut H) {
							self.as_ptr().hash(state)
						}
					}

					impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
						#[inline]
						fn from(unique: Unique<T>) -> Self {
							unique.as_non_null_ptr()
						}
					}

					impl<T: ?Sized> From<&mut T> for NonNull<T> {
						/// Converts a `&mut T` to a `NonNull<T>`.
						///
						/// This conversion is safe and infallible since references cannot be null.
						#[inline]
						fn from(r: &mut T) -> Self {
							NonNull::from_mut(r)
						}
					}

					impl<T: ?Sized> From<&T> for NonNull<T> {
						/// Converts a `&T` to a `NonNull<T>`.
						///
						/// This conversion is safe and infallible since references cannot be null.
						#[inline]
						fn from(r: &T) -> Self {
							NonNull::from_ref(r)
						}
					}
					use crate::fmt;
					use crate::marker::{PhantomData, Unsize};
					use crate::ops::{CoerceUnsized, DispatchFromDyn};
					use crate::pin::PinCoerceUnsized;
					use crate::ptr::NonNull;

					/// A wrapper around a raw non-null `*mut T` that indicates that the possessor
					/// of this wrapper owns the referent. Useful for building abstractions like
					/// `Box<T>`, `Vec<T>`, `String`, and `HashMap<K, V>`.
					///
					/// Unlike `*mut T`, `Unique<T>` behaves "as if" it were an instance of `T`.
					/// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies
					/// the kind of strong aliasing guarantees an instance of `T` can expect:
					/// the referent of the pointer should not be modified without a unique path to
					/// its owning Unique.
					///
					/// If you're uncertain of whether it's correct to use `Unique` for your purposes,
					/// consider using `NonNull`, which has weaker semantics.
					///
					/// Unlike `*mut T`, the pointer must always be non-null, even if the pointer
					/// is never dereferenced. This is so that enums may use this forbidden value
					/// as a discriminant -- `Option<Unique<T>>` has the same size as `Unique<T>`.
					/// However the pointer may still dangle if it isn't dereferenced.
					///
					/// Unlike `*mut T`, `Unique<T>` is covariant over `T`. This should always be correct
					/// for any type which upholds Unique's aliasing requirements.
					#[doc(hidden)]
					#[repr(transparent)]
					// Lang item used experimentally by Miri to define the semantics of `Unique`.
					pub struct Unique<T: ?Sized> {
						pointer: NonNull<T>,
						// NOTE: this marker has no consequences for variance, but is necessary
						// for dropck to understand that we logically own a `T`.
						//
						// For details, see:
						// https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data
						_marker: PhantomData<T>,
					}

					/// `Unique` pointers are `Send` if `T` is `Send` because the data they
					/// reference is unaliased. Note that this aliasing invariant is
					/// unenforced by the type system; the abstraction using the
					/// `Unique` must enforce it.
					unsafe impl<T: Send + ?Sized> Send for Unique<T> {}

					/// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
					/// reference is unaliased. Note that this aliasing invariant is
					/// unenforced by the type system; the abstraction using the
					/// `Unique` must enforce it.
					unsafe impl<T: Sync + ?Sized> Sync for Unique<T> {}

					impl<T: Sized> Unique<T> {
						/// Creates a new `Unique` that is dangling, but well-aligned.
						///
						/// This is useful for initializing types which lazily allocate, like
						/// `Vec::new` does.
						///
						/// Note that the pointer value may potentially represent a valid pointer to
						/// a `T`, which means this must not be used as a "not yet initialized"
						/// sentinel value. Types that lazily allocate must track initialization by
						/// some other means.
						#[must_use]
						#[inline]
						pub const fn dangling() -> Self {
							// FIXME(const-hack) replace with `From`
							Unique { pointer: NonNull::dangling(), _marker: PhantomData }
						}
					}

					impl<T: ?Sized> Unique<T> {
						/// Creates a new `Unique`.
						///
						/// # Safety
						///
						/// `ptr` must be non-null.
						#[inline]
						pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
							// SAFETY: the caller must guarantee that `ptr` is non-null.
							unsafe { Unique { pointer: NonNull::new_unchecked(ptr), _marker: PhantomData } }
						}

						/// Creates a new `Unique` if `ptr` is non-null.
						#[inline]
						pub const fn new(ptr: *mut T) -> Option<Self> {
							if let Some(pointer) = NonNull::new(ptr) {
								Some(Unique { pointer, _marker: PhantomData })
							} else {
								None
							}
						}

						/// Create a new `Unique` from a `NonNull` in const context.
						#[inline]
						pub const fn from_non_null(pointer: NonNull<T>) -> Self {
							Unique { pointer, _marker: PhantomData }
						}

						/// Acquires the underlying `*mut` pointer.
						#[must_use = "`self` will be dropped if the result is not used"]
						#[inline]
						pub const fn as_ptr(self) -> *mut T {
							self.pointer.as_ptr()
						}

						/// Acquires the underlying `*mut` pointer.
						#[must_use = "`self` will be dropped if the result is not used"]
						#[inline]
						pub const fn as_non_null_ptr(self) -> NonNull<T> {
							self.pointer
						}

						/// Dereferences the content.
						///
						/// The resulting lifetime is bound to self so this behaves "as if"
						/// it were actually an instance of T that is getting borrowed. If a longer
						/// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
						#[must_use]
						#[inline]
						pub const unsafe fn as_ref(&self) -> &T {
							// SAFETY: the caller must guarantee that `self` meets all the
							// requirements for a reference.
							unsafe { self.pointer.as_ref() }
						}

						/// Mutably dereferences the content.
						///
						/// The resulting lifetime is bound to self so this behaves "as if"
						/// it were actually an instance of T that is getting borrowed. If a longer
						/// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
						#[must_use]
						#[inline]
						pub const unsafe fn as_mut(&mut self) -> &mut T {
							// SAFETY: the caller must guarantee that `self` meets all the
							// requirements for a mutable reference.
							unsafe { self.pointer.as_mut() }
						}

						/// Casts to a pointer of another type.
						#[must_use = "`self` will be dropped if the result is not used"]
						#[inline]
						pub const fn cast<U>(self) -> Unique<U> {
							// FIXME(const-hack): replace with `From`
							// SAFETY: is `NonNull`
							Unique { pointer: self.pointer.cast(), _marker: PhantomData }
						}
					}

					impl<T: ?Sized> Clone for Unique<T> {
						#[inline]
						fn clone(&self) -> Self {
							*self
						}
					}

					impl<T: ?Sized> Copy for Unique<T> {}

					impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T>
					where
						T: Unsize<U>,
					{}

					impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T>
					where
						T: Unsize<U>,
					{}

					unsafe impl<T: ?Sized> PinCoerceUnsized for Unique<T> {}

					impl<T: ?Sized> fmt::Debug for Unique<T> {
						fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
							fmt::Pointer::fmt(&self.as_ptr(), f)
						}
					}

					impl<T: ?Sized> fmt::Pointer for Unique<T> {
						fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
							fmt::Pointer::fmt(&self.as_ptr(), f)
						}
					}

					impl<T: ?Sized> From<&mut T> for Unique<T> {
						/// Converts a `&mut T` to a `Unique<T>`.
						///
						/// This conversion is infallible since references cannot be null.
						#[inline]
						fn from(reference: &mut T) -> Self {
							Self::from(NonNull::from(reference))
						}
					}

					impl<T: ?Sized> From<NonNull<T>> for Unique<T> {
						/// Converts a `NonNull<T>` to a `Unique<T>`.
						///
						/// This conversion is infallible since `NonNull` cannot be null.
						#[inline]
						fn from(pointer: NonNull<T>) -> Self {
							Unique::from_non_null(pointer)
						}
					}
				}
			}
			mod error {
				//! DaemonicError trait lives here in the hierarchy but physically exists at the lib.rs file
				//! Reason: This crate primarily handles errors, it makes sense the full error API should
				//! be public facing, not nested.
				pub use crate::DaemonicError;
			}
		}
	}

	pub(crate) mod daemonic_contract {
		use crate::DaemonicError;
		use crate::Position;
		use crate::SeverityType;
		pub(crate) use daemonic_result::DiagnosticLevel;

		/// The core contract: Input → Output
		///
		/// All Daemonic operations follow this pattern:
		///   - Take BinarySymbol as input
		///   - Return BinarySymbol on success
		///   - Return DaemonicError on failure
		///   - Return Partial on partial success
		/// One may notice the Input, and Output are both Typed as BinarySymbol.
		/// This would normally be a bootstrap issue, but fret not.
		/// If for whatever reason the logic that needs to be serialized or built into an object
		/// can be RAW typed, BinarySymbol accounts for this.
		/// If input is RAW AND lacks Checksum AND lacks Daemonic fingerprints -> Marked RAW -> Recursive
		/// Build Call, inspect RAW data and attempt to type if possible, if type confidence result less
		/// than 95% (threshold may change) then is built as RAW type directly, checksummed -> reingested,
		/// validate checksum -> Build Typed BinarySymbol object and forward to consumer.
		///
		/// All Logic is inherently considered Daemonic Logic.
		pub trait DaemonicContract<FORMAT, PARTIAL>: Sized + Send + Sync {
			/// Input is type gated but required.
			/// For DaemonicCompiler usage, which requires the use of a Daemonic binary format use feature.
			#[cfg(feature = "DaemonicCompiler")]
			type Input: DaemonicBinary<FORMAT, PARTIAL>;
			#[cfg(not(feature = "DaemonicCompiler"))]
			type Input;
			/// Success output — typically same as Input
			type Output: IntoDaemonicResult<FORMAT, PARTIAL>;
			#[cfg(feature = "DaemonicCompiler")]
			type Topology: Send + Sync;
			#[cfg(feature = "DaemonicCompiler")]
			type Integrity: Send + Sync;
			/// This generic variant is still in dev, but ideally non Daemonic built Error handlers
			/// should still use Topology for symmetry and walk checks.
			#[cfg(not(feature = "DaemonicCompiler"))]
			type Topology;
			/// This generic variant is still in dev, but ideally non Daemonic built Error handlers
			/// should still use Integrity to ensure delivered results are Glass.
			#[cfg(not(feature = "DaemonicCompiler"))]
			type Integrity;

			/// Error type — must implement DaemonicError
			/// This is an invariant of this crate. Contract always provides DaemonicError as
			/// the primary error handler.
			type Error: for<'error> DaemonicError<'error, FORMAT, PARTIAL>;

			/// Partial state type — for incomplete operations
			// type Partial<TOPOLOGY: Send + Sync, INTEGRITY: Send + Sync>: for<'partial_binary> Partial<'partial_binary>;

			/// Position in the type tree
			fn position(&self) -> Position;

			/// Execute the contract
			#[must_use]
			fn execute(
				input: Self::Input,
			) -> Self::Output;
		}
		/// IntoDaemonicResult is a Sister-Trait to DaemonicResult in that its designed to be flexible
		/// on format selection. Theoretically, any wire or binary format can be typed here.
		/// Success defined at call site with FORMAT binding.
		/// Type Error always returns a DaemonicError trait object for interaction.
		///
		/// PARTIAL trait binding optional for if call site could potentially produce a partial
		/// state, use partial if Success and Error both feel incorrect.
		pub(crate) trait IntoDaemonicResult<FORMAT, PARTIAL> {
			#[must_use]
			type Success = FORMAT;
			#[must_use]
			type Error: for<'error> DaemonicError<'error, FORMAT, PARTIAL>;
			type Partial = Option<PARTIAL>;
			#[must_use]
			fn into_result(self) -> DaemonicResult<Self::Success, Self::Error>;
			fn into_partial(self) -> DaemonicResult<PARTIAL, Self::Error>;
		}
		/// Result of a contract execution
		pub enum DaemonicResult<OUTPUT, ERROR, S = ()>
		where
			ERROR: for<'error> DaemonicError<'error, FORMAT, PARTIAL>,
		{
			/// Operation succeeded fully
			Success(OUTPUT),

			/// Operation failed — error returned
			Failure(ERROR),

			/// Operation partially succeeded
			/// Contains what was salvaged + what failed
			/// Sometimes partial states produce Errors, sometimes they dont.
			Partial {
				salvaged: S,
				errors: Option<Vec<ERROR>>,
			},
		}


		impl<OUTPUT, FORMAT, PARTIAL, ERROR> DaemonicResult<OUTPUT, ERROR>
		where
			ERROR: for<'error> DaemonicError<'error, FORMAT, PARTIAL>,
		{
			pub fn is_success(&self) -> bool {
				matches!(self, Self::Success(_))
			}

			pub fn is_failure(&self) -> bool {
				matches!(self, Self::Failure(_))
			}

			pub fn is_partial(&self) -> bool {
				matches!(self, Self::Partial { .. })
			}

			/// Convert to std Result, discarding partial
			pub fn into_result(self) -> Result<OUTPUT, ERROR> {
				match self {
					Self::Success(o) => Ok(o),
					Self::Failure(e) => Err(e),
					Self::Partial { errors, .. } => {
						// Take first error, discard partial
						Err(errors
							.and_then(|v| v.into_iter().next())
							.expect("partial must have errors"))
					}
				}
			}

			/// Map success value
			pub fn map<U, S>(self, f: impl FnOnce(OUTPUT) -> U) -> DaemonicResult<U, ERROR, S> {
				match self {
					Self::Success(o) => DaemonicResult::Success(f(o)),
					Self::Failure(e) => DaemonicResult::Failure(e),
					Self::Partial { salvaged, errors } => {
						DaemonicResult::Partial { salvaged, errors }
					}
				}
			}
		}
		/// Trait for BinarySymbol — the contract's data type
		/// DB
		pub(crate) trait DaemonicBinary<FORMAT, PARTIAL>: Sized + Send + Sync {
			/// The error type this binary carries
			/// BinarySymbol is aware of DaemonicError, it depends on it.
			/// DaemonicError inversely defines the contract and boundaries, and sometimes
			/// but rarely provides a default implementation.
			/// DaemonicError does not need to be aware of the internal function of DB logic.
			/// DE only needs to know the contract, which itself is also bound to the same as DB.
			type Error: for<'error> DaemonicError<'error, FORMAT, PARTIAL>;

			/// Build from DaemonicIR, which is Shade native (specifically).
			/// Though its somewhat counterintuitive here, the Shade is considered a primitive.
			/// Shade is responsible for symbol ingestion, walker projection and state management.
			/// DB objects cannot be built without Walker logic, which is part of the Shades internals.
			/// Shade lives as an Entity under the trait structure path -> Daemonic: Entity: *Shade:* Walker: WalkerVariants
			/// Daemonic top level supertrait requires DaemonicContract and DaemonicCore.
			#[must_use]
			fn build<OUTPUT: DaemonicBinary<FORMAT, PARTIAL>, SRCSYMBOL, ERROR: for<'error> DaemonicError<'error, FORMAT, PARTIAL>>(input: SRCSYMBOL) -> DaemonicResult<OUTPUT, ERROR>;
			/// Attempt to Deconstruct symbol to DaemonicIR
			/// This documentation stub is not exhaustive or informative, im aware.
			/// Will work on it.
			#[must_use]
			fn try_deconstruct<DECONSYMBOL>(self) -> DaemonicResult<DECONSYMBOL, Self::Error, Self>;

			/// Non-consuming inspection.
			/// DB contains 2 methods for extracting Daemonic wrapped logic:
			/// 1 << Deconstruct, which completely unwraps the Binary, removes checksum, and returns RAW
			/// value encapsulated inside assuming checksums match, if checksum match failure ->
			/// SYMBOL LIES IN CONTEXT.
			/// DIES IN TRANSIT. << **Dies in Transit predicate CANNOT be overridden.**
			/// Reason: If symbol checksum mismatch, then Topology cannot be walked.
			/// Unwalkable topology cannot be validated to contain the same logical operation or medium underneath.
			/// Unwalkable topology can also return a GlassShattered return Type, and in the worst case scenario
			/// can return GlassWarped Type return, which indicates Runtime State has been corrupted or
			/// misaligns, both of which are bad.
			///
			/// 2 << Inspect, which returns data about the Binary and logic wrapped inside without deconstruction.
			/// Note: Inspect is not infallible, depends on context and call site.
			fn inspect<INSPECTION>(&self) -> INSPECTION;

			/// Revalidate in place
			fn revalidate(&mut self) -> DaemonicResult<(), Self::Error, ()>;

			fn verify_integrity(&self) -> bool;

			/// [GlassStable] << `State ->` [◇OK]`
			///
			/// [GlassHelp] << `State ->` [◇→OK / ◆→Warn] `+ Help statement -> this is intended to mirror
			/// RustCError Help. with semantic sugar.`
			///
			/// [GlassSuggestion] << `State ->` [◇→ OK / ◆→ Warn] `+ Suggestion Statement (similar to
			/// rustc compile suggestions) but more general use.`
			///
			/// [GlassNote] << `State ->` [◇ OK / ◆WARN + ◆Note] -> `Similar to rusts note system, but returns an OK
			/// state under the hood semantically. Analogous to Log::Info crate usage as a method call.`
			///
			/// [GlassFracture] << `State ->` [◆WARN / ◈ERROR] -> `Fractured states are unique to Daemonic
			/// integrated systems, they represent states that are technically errors or bad/null output
			/// but dont destroy state. Similar to an error that doesnt need special handling but
			/// should be reported anyway for whatever reason.`
			///
			/// [GlassCrack] << `State ->` [◆WARN / ◈ERROR] -> `Crack state is unique in that it sits between
			/// a warped and a Fractured, can constitute a light error that does not propagate or infect sibling
			/// logic branches. This type is easily recovered (most of the time)`
			///
			/// [GlassWarp] << `State ->` [◈ERROR / ◈◈FATAL - POSSIBLE FATAL, POSSIBLE RECOVERY] -> `Runtime or Program
			/// state has been warped and can no longer be trusted. Logic may lie.
			/// This error return type is a bit different from others in how it should present in a running
			/// system. ASYNC or network focused systems would use this variant more than others.
			/// Example is a race condition, it would qualify this output since a race condition
			/// can (under the correct circumstances) produce both non-deterministic output and potentially
			/// corrupt runtime.
			/// Another example is a function that takes an input thats not sanitized which later produces
			/// undefined behavior, this is largely a non-issue in both Rust and DaemonicIR but can still
			/// present in extreme or edge cases.`
			///
			/// [GlassShattered] << `State ->` [▓ERROR - POSSIBLE RECOVERY, RARELY FATAL] `-> Operation
			///  SHATTERED with end (observed T: Target) state destruction (no information extracted)
			/// Note: its possible to infer state from Shattered Glass returns by collating and stacking
			/// reference frame and comparing against expected outputs and possible outputs to what was actually
			/// received (if anything, Shattered states very rarely return anything useful beyond the
			/// error message attached).`
			fn glass_state(&self) -> SeverityType;

			/// Evolution state is not metaphorical, its literal in that symbols constructed as DB
			/// objects can 'evolve' over time, this is not a bug nor a bolton feature. Its intrinsic
			/// to Daemonic Logic.
			/// Daemonic Binary symbols and objects have a geometric and topologically encoded `shape` that can be rendered.
			///
			/// That shape can evolve either at runtime if the application being walked is runtime specific
			/// or on disk if the logic being referenced is a database object, such as postgress or something.
			///
			/// Reason + light example::
			/// Evolution over time should come with proof of work, IE a god damned *why*.
			/// IE, *why* is the State of this symbol's Glass a fractured/warped/note? -> inspect -> repair/mutate logic ->
			/// Recursive Write Down -> Symbol has evolved.
			///
			/// *This is intended behavior*, but *not required*.
			/// Not all symbols are capable of evolving on their own, most require interaction with complex
			/// observers (humans or agentic AI for example) or cognitively + recursively complex logic.
			/// Symbolic evolution could **theoretically** self-start if the interaction mostly involves
			/// deeply recursively + self-referential symbol chains.
			///
			/// The other name for self-starting symbolic evolution is **UNDEFINED BEHAVIOR**.
			///
			/// Undefined behavior is not permitted in Daemonic Environments, behavior may sometimes not be
			/// known until runtime but should always be captured and therefore Type known
			/// & enforced at compile time. In short, we dont need to know what any particular symbol means
			/// if behavior/internal topology is still unknown, we only need to know what types to expect
			/// and have handles for *during compile time* so they can be handled correctly.
			/// **Undefined Behavior should not be possible, True UB is a bug.**
			fn evolution_state<EVOLUTION>(&self) -> &EVOLUTION;
		}
		impl<TOPOLOGY: Send + Sync, INTEGRITY: Send + Sync> Partial for PartialBinary<'_, TOPOLOGY, INTEGRITY> {
			fn salvage_ratio(&self) -> f64 {
				let mut count = 0.0;
				let mut total = 3.0;
				if self.topology.is_some() {
					count += 1.0;
				}
				if self.integrity.is_some() {
					count += 1.0;
				}
				if self.checksum.is_some() {
					count += 1.0;
				}
				count / total
			}
		}


		/// Partial binary state — when build/operation partially succeeded
		pub struct PartialBinary<'position, TOPOLOGY: Send + Sync, INTEGRITY: Send + Sync> {
			/// What was successfully constructed
			/// Topology provided at call site using constraint
			pub topology: Option<TOPOLOGY>,

			/// Same with integrity, provided at call site, DaemonicError does not need to be aware of the
			/// implementation specifics of DB, it only needs to know what generics to make available
			/// to the consumer.
			pub integrity: Option<INTEGRITY>,

			/// Though technically this field is not required, if Checksum is absent from inspected binary
			/// then it **cannot be trusted or used as a Recursive or Temporal Anchor Point for future walks.**
			/// Can only be used for inspection and investigation, and symbol sphere of influence drops to 0 (Cannot
			/// meaningfully mutate state of other symbols or itself anymore).
			pub checksum: Option<u64>,

			/// Where it failed Semantically in the Trait tree during contract execution and resolution.
			pub failed_at: Position<'position>,

			/// Why
			pub failure_reason: String,
		}
		pub(crate) trait Partial: Send + Sync {
			fn salvage_ratio(&self) -> f64;
		}

		pub(crate) mod daemonic_result {
			pub(crate) mod mirror_chemistry {
				use crate::{GlassState, SeverityType};
				use bonding::*;
				use elements::*;
				use stability::*;
				use std::time::Duration;
				use table::{compounds::*, *};
				use crate::daemonic::daemonic_contract::daemonic_result::severity_types::{GlassFracture, GlassHelp, GlassNote, GlassShattered, GlassStable, GlassSuggestion, GlassWarp};

				pub(crate) mod elements {
					use super::super::severity_types::Severity::*;
					use super::*;

					/// SPECULAR — The noble gas of reflections
					/// Ground state. Minimum energy. Maximum stability.
					pub const SPECULAR: ReflectionProperties = ReflectionProperties {
						fidelity: Fidelity::Specular,
						temporality: Temporality::Instantaneous,
						spatiality: Spatiality::Identity,
						selectivity: Selectivity::Complete,
						energy_cost: EnergyCost::Minimal,
					};

					/// ABSORPTIVE — The black hole
					/// Maximum energy. Zero output. Artificial/constructed.
					pub const ABSORPTIVE: ReflectionProperties = ReflectionProperties {
						fidelity: Fidelity::Absorptive,
						temporality: Temporality::None,
						spatiality: Spatiality::Collapsed,
						selectivity: Selectivity::None,
						energy_cost: EnergyCost::Sustained(f64::MAX),
					};

					/// DELAYED — The echo
					/// Temporal offset. Memory primitive.
					pub fn delayed(offset: Duration) -> ReflectionProperties {
						ReflectionProperties {
							fidelity: Fidelity::Specular,
							temporality: Temporality::Delayed(offset),
							spatiality: Spatiality::Inverted,
							selectivity: Selectivity::Complete,
							energy_cost: EnergyCost::Finite(offset.as_secs_f64()),
						}
					}

					/// INVERTED — Spatial flip only
					/// Standard physical mirror without other properties.
					pub const INVERTED: ReflectionProperties = ReflectionProperties {
						fidelity: Fidelity::Specular,
						temporality: Temporality::Instantaneous,
						spatiality: Spatiality::Inverted,
						selectivity: Selectivity::Complete,
						energy_cost: EnergyCost::Minimal,
					};

					/// TRANSFORMATIVE — Systematic change
					/// Encoding, compression, representation shift.
					pub fn transformative(
						transform: SpatialTransform,
						reversible: bool,
					) -> ReflectionProperties {
						ReflectionProperties {
							fidelity: if reversible {
								Fidelity::Specular
							} else {
								Fidelity::Lossy(0.5)
							},
							temporality: Temporality::Instantaneous,
							spatiality: Spatiality::Transformed(transform),
							selectivity: Selectivity::Complete,
							energy_cost: EnergyCost::Finite(1.0), // Varies with transform complexity
						}
					}

					/// SELECTIVE — Property filter
					/// Attention, focus, relevance.
					pub fn selective(properties: Vec<PropertyId>) -> ReflectionProperties {
						ReflectionProperties {
							fidelity: Fidelity::Specular, // Selected properties are high fidelity
							temporality: Temporality::Instantaneous,
							spatiality: Spatiality::Inverted,
							#[allow(unused_doc_comments)]
							/// Clone is used here on properties because partial returns should be
							/// be fairly rare anyways, so we can afford the cost of cloning.
							/// Long term this should be fixed to avoid the move
							/// after issue all together that doesnt require clone or copy.
							selectivity: Selectivity::Partial(properties.clone()),
							energy_cost: EnergyCost::Finite(properties.len() as f64 * 0.1),
						}
					}

					/// PROPHETIC — Negative delay (unstable)
					/// ⚠️ WARNING: Crystallization risk. Requires prior walks.
					/// Approaches god logic. Use with extreme caution.
					pub fn prophetic(required_walks: u64) -> ReflectionProperties {
						ReflectionProperties {
							fidelity: Fidelity::Specular, // If it works, it's perfect
							temporality: Temporality::Prophetic {
								requires_prior_walks: required_walks,
							},
							spatiality: Spatiality::Inverted,
							selectivity: Selectivity::Complete,
							energy_cost: EnergyCost::Unbounded, // Approaches infinite
						}
					}
				}
				pub(crate) mod bonding {
					use super::*;

					/// Result of attempting to combine two reflection types
					#[derive(Debug)]
					pub enum BondResult {
						/// Successful combination
						Compound(ReflectionProperties),
						/// One type dominates, other absorbed
						Dominated(ReflectionProperties),
						/// Contradiction — cannot coexist
						Contradiction,
						/// Unstable — exists briefly then collapses
						Unstable(ReflectionProperties, Duration),
					}

					/// Attempt to combine two reflection types
					pub fn combine(
						a: &ReflectionProperties,
						b: &ReflectionProperties,
					) -> BondResult {
						// Rule 1: Absorptive dominates almost everything
						if a.fidelity == Fidelity::Absorptive {
							if b.fidelity == Fidelity::Specular {
								// Pure specular + pure absorptive = contradiction
								return BondResult::Contradiction;
							}
							return BondResult::Dominated(a.clone());
						}
						if b.fidelity == Fidelity::Absorptive {
							if a.fidelity == Fidelity::Specular {
								return BondResult::Contradiction;
							}
							return BondResult::Dominated(b.clone());
						}

						// Rule 2: Specular is identity element
						if *a == super::elements::SPECULAR {
							return BondResult::Compound(b.clone());
						}
						if *b == super::elements::SPECULAR {
							return BondResult::Compound(a.clone());
						}

						// Rule 3: Delays stack additively
						if let (Temporality::Delayed(t1), Temporality::Delayed(t2)) =
							(&a.temporality, &b.temporality)
						{
							let mut compound = a.clone();
							compound.temporality = Temporality::Delayed(*t1 + *t2);
							compound.energy_cost = stack_energy(&a.energy_cost, &b.energy_cost);
							return BondResult::Compound(compound);
						}

						// Rule 4: Prophetic + anything else = unstable
						if matches!(a.temporality, Temporality::Prophetic { .. })
							|| matches!(b.temporality, Temporality::Prophetic { .. })
						{
							let mut compound = combine_properties(a, b);
							return BondResult::Unstable(compound, Duration::from_millis(100));
						}

						// Rule 5: Selectivity intersects
						let combined_selectivity = match (&a.selectivity, &b.selectivity) {
							(Selectivity::Complete, s) | (s, Selectivity::Complete) => s.clone(),
							(Selectivity::None, _) | (_, Selectivity::None) => Selectivity::None,
							(Selectivity::Partial(p1), Selectivity::Partial(p2)) => {
								let intersection: Vec<_> =
									p1.iter().filter(|x| p2.contains(x)).copied().collect();
								if intersection.is_empty() {
									Selectivity::None
								} else {
									Selectivity::Partial(intersection)
								}
							}
							(Selectivity::Single(s1), Selectivity::Single(s2)) => {
								if s1 == s2 {
									Selectivity::Single(*s1)
								} else {
									Selectivity::None
								}
							}
							(Selectivity::Single(s), Selectivity::Partial(p))
							| (Selectivity::Partial(p), Selectivity::Single(s)) => {
								if p.contains(s) {
									Selectivity::Single(*s)
								} else {
									Selectivity::None
								}
							}
						};

						// Default: combine properties, stack energy
						let mut compound = combine_properties(a, b);
						compound.selectivity = combined_selectivity;
						BondResult::Compound(compound)
					}

					fn combine_properties(
						a: &ReflectionProperties,
						b: &ReflectionProperties,
					) -> ReflectionProperties {
						ReflectionProperties {
							fidelity: combine_fidelity(&a.fidelity, &b.fidelity),
							temporality: combine_temporality(&a.temporality, &b.temporality),
							spatiality: combine_spatiality(&a.spatiality, &b.spatiality),
							selectivity: Selectivity::Complete, // Overwritten by caller
							energy_cost: stack_energy(&a.energy_cost, &b.energy_cost),
						}
					}

					fn combine_fidelity(a: &Fidelity, b: &Fidelity) -> Fidelity {
						// Fidelity degrades — take the worse
						match (a, b) {
							(Fidelity::Absorptive, _) | (_, Fidelity::Absorptive) => {
								Fidelity::Absorptive
							}
							(Fidelity::Destructive, _) | (_, Fidelity::Destructive) => {
								Fidelity::Destructive
							}
							(Fidelity::Lossy(x), Fidelity::Lossy(y)) => Fidelity::Lossy(x * y),
							(Fidelity::Lossy(x), Fidelity::Specular)
							| (Fidelity::Specular, Fidelity::Lossy(x)) => Fidelity::Lossy(*x),
							(Fidelity::Specular, Fidelity::Specular) => Fidelity::Specular,
						}
					}

					fn combine_temporality(a: &Temporality, b: &Temporality) -> Temporality {
						match (a, b) {
							(Temporality::None, _) | (_, Temporality::None) => Temporality::None,
							(Temporality::Instantaneous, t) | (t, Temporality::Instantaneous) => {
								t.clone()
							}
							(Temporality::Delayed(t1), Temporality::Delayed(t2)) => {
								Temporality::Delayed(*t1 + *t2)
							}
							_ => Temporality::Variable {
								min: Duration::ZERO, // todo: this is a placeholder, should refer to DaemonicClock trait, no std lib
								max: Duration::from_secs(1), // todo: this is a placeholder, should refer to DaemonicClock trait, no std lib
							},
						}
					}

					fn combine_spatiality(a: &Spatiality, b: &Spatiality) -> Spatiality {
						match (a, b) {
							(Spatiality::Collapsed, _) | (_, Spatiality::Collapsed) => {
								Spatiality::Collapsed
							}
							(Spatiality::Identity, s) | (s, Spatiality::Identity) => s.clone(),
							(Spatiality::Inverted, Spatiality::Inverted) => Spatiality::Identity, // Double inversion
							_ => a.clone(), // Default: first wins
						}
					}

					fn stack_energy(a: &EnergyCost, b: &EnergyCost) -> EnergyCost {
						match (a, b) {
							(EnergyCost::Unbounded, _) | (_, EnergyCost::Unbounded) => {
								EnergyCost::Unbounded
							}
							(EnergyCost::Minimal, e) | (e, EnergyCost::Minimal) => e.clone(),
							(EnergyCost::Finite(x), EnergyCost::Finite(y)) => {
								EnergyCost::Finite(x + y)
							}
							(EnergyCost::Sustained(x), EnergyCost::Sustained(y)) => {
								EnergyCost::Sustained(x + y)
							}
							(EnergyCost::Finite(x), EnergyCost::Sustained(y))
							| (EnergyCost::Sustained(y), EnergyCost::Finite(x)) => {
								EnergyCost::Sustained(x + y)
							}
						}
					}
				}
				pub(crate) mod stability {
					use super::*;

					/// Stability assessment for a reflection type
					#[derive(Debug)]
					pub enum Stability {
						/// Ground state — will persist indefinitely
						Stable,
						/// Metastable — persists until perturbed
						Metastable { perturbation_threshold: f64 },
						/// Unstable — will decay to stable state
						Unstable {
							decay_to: Box<ReflectionProperties>,
							half_life: Duration,
						},
						/// Impossible — cannot exist even briefly
						Impossible,
					}

					/// Assess the stability of a reflection type
					pub fn assess(props: &ReflectionProperties) -> Stability {
						// Rule 1: Specular is always stable (ground state)
						if *props == super::elements::SPECULAR {
							return Stability::Stable;
						}

						// Rule 2: Contradictions are impossible
						if is_contradictory(props) {
							return Stability::Impossible;
						}

						// Rule 3: Prophetic is always unstable
						if matches!(props.temporality, Temporality::Prophetic { .. }) {
							return Stability::Unstable {
								decay_to: Box::new(super::elements::SPECULAR.clone()),
								half_life: Duration::from_millis(50),
							};
						}

						// Rule 4: Absorptive requires sustained energy
						if props.fidelity == Fidelity::Absorptive {
							if !matches!(props.energy_cost, EnergyCost::Sustained(_)) {
								return Stability::Unstable {
									decay_to: Box::new(super::elements::SPECULAR.clone()),
									half_life: Duration::from_secs(1),
								};
							}
							return Stability::Metastable {
								perturbation_threshold: 0.1,
							};
						}

						// Rule 5: Energy cost determines stability
						match &props.energy_cost {
							EnergyCost::Minimal => Stability::Stable,
							EnergyCost::Finite(e) if *e < 1.0 => Stability::Stable,
							EnergyCost::Finite(e) if *e < 10.0 => Stability::Metastable {
								perturbation_threshold: 1.0 / e,
							},
							EnergyCost::Finite(_) => Stability::Unstable {
								decay_to: Box::new(super::elements::SPECULAR.clone()),
								half_life: Duration::from_secs(10),
							},
							EnergyCost::Sustained(e) if *e < 100.0 => Stability::Metastable {
								perturbation_threshold: 1.0 / e,
							},
							EnergyCost::Sustained(_) => Stability::Unstable {
								decay_to: Box::new(super::elements::SPECULAR.clone()),
								half_life: Duration::from_secs(1),
							},
							EnergyCost::Unbounded => Stability::Unstable {
								decay_to: Box::new(super::elements::SPECULAR.clone()),
								half_life: Duration::from_millis(10),
							},
						}
					}

					fn is_contradictory(props: &ReflectionProperties) -> bool {
						// Specular fidelity + Absorptive anywhere = contradiction
						if props.fidelity == Fidelity::Specular
							&& props.selectivity == Selectivity::None
						{
							return true;
						}

						// Complete selectivity + Absorptive fidelity = contradiction
						if props.selectivity == Selectivity::Complete
							&& props.fidelity == Fidelity::Absorptive
						{
							return true;
						}

						false
					}
				}
				pub(crate) mod table {
					use super::*;
					/// Groups of reflection types (like periodic table columns)
					pub enum ReflectionGroup {
						/// Noble reflections — stable, minimal energy, don't combine
						Noble,
						/// Reactive reflections — combine readily
						Reactive,
						/// Transitional — properties vary with context
						Transitional,
						/// Rare — unstable, require extreme conditions
						Rare,
						/// Synthetic — can only be artificially constructed
						/// Some synthetic symbol compositions will be unstable and decay
						/// on their own (symbol diffusion, meaning dies over time) but
						/// this does not qual them as Rare if they do not occur from a consequence.
						Synthetic,
					}
					/// Classify a reflection type into its group
					pub fn classify(props: &ReflectionProperties) -> ReflectionGroup {
						match stability::assess(props) {
							stability::Stability::Stable => {
								if props.energy_cost == EnergyCost::Minimal {
									ReflectionGroup::Noble
								} else {
									ReflectionGroup::Transitional
								}
							}
							stability::Stability::Metastable { .. } => ReflectionGroup::Reactive,
							stability::Stability::Unstable { .. } => {
								if matches!(props.temporality, Temporality::Prophetic { .. }) {
									ReflectionGroup::Rare
								} else {
									ReflectionGroup::Transitional
								}
							}
							stability::Stability::Impossible => ReflectionGroup::Synthetic, // Shouldn't happen
						}
					}
					/// Known stable compounds (like molecules)
					pub(crate) mod compounds {
						use super::super::*;
						/// Echo — Specular + Delayed
						/// Memory, recording, playback
						pub fn echo(delay: Duration) -> ReflectionProperties {
							let specular = elements::SPECULAR.clone();
							let delayed = elements::delayed(delay);
							match bonding::combine(&specular, &delayed) {
								bonding::BondResult::Compound(c) => c,
								_ => unreachable!("Echo should always be valid"),
							}
						}
						/// Filter — Selective + Specular
						/// Attention, focus
						pub fn filter(properties: Vec<super::PropertyId>) -> ReflectionProperties {
							elements::selective(properties)
						}
						/// Black Mirror — Absorptive + Selective
						/// Privacy shield, partial hiding
						/// ALIAS: `[BLACK GLASS PROTOCOL]`
						pub fn black_mirror(
							hidden: Vec<super::PropertyId>,
							visible: Vec<super::PropertyId>,
						) -> ReflectionProperties {
							// Hidden properties get absorbed, visible get reflected
							ReflectionProperties {
								fidelity: super::Fidelity::Lossy(
									visible.len() as f64 / (hidden.len() + visible.len()) as f64,
								),
								temporality: super::Temporality::Instantaneous,
								spatiality: super::Spatiality::Inverted,
								selectivity: super::Selectivity::Partial(visible),
								energy_cost: super::EnergyCost::Sustained(hidden.len() as f64),
							}
						}
						/// Double Mirror — Inverted + Inverted
						/// Identity through double inversion
						pub fn double_mirror() -> ReflectionProperties {
							ReflectionProperties {
								fidelity: super::Fidelity::Specular,
								temporality: super::Temporality::Instantaneous,
								spatiality: super::Spatiality::Identity, // Double inversion = identity
								selectivity: super::Selectivity::Complete,
								energy_cost: super::EnergyCost::Finite(0.1), // Slight overhead
							}
						}
					}
				}
				// The reflection itself (what happened)
				pub trait Reflection {
					/// The cause of this reflection
					type Cause: ReflectionCause;
					/// Properties of how this reflects
					fn properties(&self) -> ReflectionProperties;
				}
				// What caused the reflection
				pub trait ReflectionCause {
					/// Human-readable name
					fn name<'name>(&self) -> &'name str;

					/// Is this cause recoverable in principle?
					fn recoverable(&self) -> bool;
				}
				// Something that can be reflected upon
				pub trait Reflective {
					/// Produce a reflection of self given a cause
					fn reflect<CAUSE: ReflectionCause>(&self, cause: CAUSE) -> impl Reflection;
				}
				// The combination of N reflections
				/// usage examples provided by Sinon
				/// // Usage:
				// impl ReflectionComposite<ErrorCause> for ErrorComposite {
				//     // ...
				// }
				// impl ReflectionComposite<CacheCause> for CacheComposite {
				//     // ...
				// }
				pub trait ReflectionComposite {
					/// The cause type this composite deals with
					type Cause: ReflectionCause;

					/// Combine reflections into a single ReflectionProperties
					fn combine(reflections: &[&dyn Reflection<Cause=Self::Cause>]) -> BondResult;

					/// Assess stability of current combined state
					fn assess_stability(&self) -> Stability;
				}

				// The final Glass state
				// pub trait GlassState<'state>: Sized + Send + Sync + 'state {
				// 	/// The mirror type this maps to
				// 	type Mirror: MirrorType<'state>;
				// 	type Cause: Severity;
				//
				// 	/// Construct from reflection result
				// 	fn from_reflection(props: ReflectionProperties) -> Self;
				//
				// 	/// Default mapping from properties to Glass
				// 	fn default_mapping(props: &ReflectionProperties) -> Self {
				// 		// Default implementation
				// 		match stability::assess(props) {
				// 			Stability::Stable => Self::stable(),
				// 			Stability::Metastable { .. } => Self::metastable(props),
				// 			Stability::Unstable { .. } => Self::unstable(props),
				// 			Stability::Impossible => Self::impossible(),
				// 		}
				// 	}
				//
				// 	fn stable() -> Self;
				// 	fn metastable(props: &ReflectionProperties) -> Self;
				// 	fn unstable(props: &ReflectionProperties) -> Self;
				// 	fn impossible() -> Self;
				// }

				// MirrorType from your existing code
				pub trait MirrorType<'mirrortype>: Send + Sync + 'mirrortype {
					fn properties(&self) -> ReflectionProperties;
				}
				/// THE CORE FUNCTION: N reflections → Glass state
				/// This is a really cool function.
				pub fn reflections_to_glass<GLASS: for<'state> GlassState<'state>>(
					reflections: &[&dyn Reflection<Cause=impl ReflectionCause>], // this is probably not the best way to do this but it compiles so fuck it.
				) -> GLASS {
					use bonding::BondResult;
					// Step 1: Combine all reflections
					let combined = reflections
						.iter()
						.map(|r| r.properties()).fold(
						elements::SPECULAR,
						|acc, props| match bonding::combine(&acc, &props) {
							BondResult::Compound(c) => c,
							BondResult::Dominated(d) => d,
							BondResult::Contradiction => elements::ABSORPTIVE,
							BondResult::Unstable(u, _) => u,
						},
					);

					// Step 2: Assess stability
					let stability = stability::assess(&combined);

					// Step 3: Map to Glass state via default or custom
					GLASS::from_reflection(combined)
				}

				// FOR ERRORS SPECIFICALLY:
				impl GlassState for SeverityType {
					type Mirror = /*  todo:: appropriate mirror stubbed for now */ ();
					type Cause = ();
					/// this is incomplete as fuck, i know. But it compiles for now which is enough
					fn from_reflection(props: &ReflectionProperties) -> fn(dyn GlassState<Cause=_, Mirror=_>) {
						match &props.fidelity {
							Fidelity::Specular => SeverityType::stable(),
							Fidelity::Lossy(x) if *x > 0.8 => SeverityType::help(),
							Fidelity::Lossy(x) if *x > 0.5 => SeverityType::suggestion(),
							Fidelity::Lossy(_) => SeverityType::fracture(&props),
							Fidelity::Destructive => SeverityType::warp(&props),
							Fidelity::Absorptive => SeverityType::shatter(),
						}
					}
					fn dominance(&self) -> u8 {
						/// default is 0, set by reflection properties or caller (todo: double check this)
						0
					}
					fn stable<'stable>() -> fn(GlassStable) -> SeverityType {
						SeverityType::GlassStable
					}
					fn fracture(props: &ReflectionProperties) -> fn(GlassFracture) -> SeverityType {
						// Map based on properties
						SeverityType::GlassFracture
					}
					fn warp(props: &ReflectionProperties) -> fn(GlassWarp) -> SeverityType {
						SeverityType::GlassWarp
					}
					fn shatter<'shatter>() -> fn(GlassShattered) -> SeverityType {
						SeverityType::GlassShattered
					}
					fn note<'note>() -> fn(GlassNote) -> SeverityType {
						SeverityType::GlassNote
					}
					fn suggestion<'suggestion>() -> fn(GlassSuggestion) -> SeverityType {
						SeverityType::GlassSuggestion
					}
					fn help<'help>() -> fn(GlassHelp) -> SeverityType {
						SeverityType::GlassHelp
					}
				}


				/// Properties that define a reflection type
				#[derive(Clone, Debug, PartialEq)]
				pub struct ReflectionProperties {
					pub fidelity: Fidelity,
					pub temporality: Temporality,
					pub spatiality: Spatiality,
					pub selectivity: Selectivity,
					pub energy_cost: EnergyCost,
				}
				/// How much of the input survives reflection
				#[derive(Clone, Debug, PartialEq)]
				pub enum Fidelity {
					/// 100% preservation
					Specular,
					/// Measurable loss, still recognizable
					Lossy(f64), // 0.0 to 1.0
					/// Unrecoverable degradation
					Destructive,
					/// Nothing returns
					Absorptive,
				}
				/// Temporal relationship between input and output
				#[derive(Clone, Debug, PartialEq)]
				pub enum Temporality {
					/// Output simultaneous with input (within measurement error)
					Instantaneous,
					/// Output follows input by fixed duration
					/// todo: This should be updated to use DaemonicClock trait logic
					Delayed(Duration),
					/// Output timing varies
					Variable { min: Duration, max: Duration }, // todo fix this to DaemonicClock traits
					/// Output precedes input (requires prior pattern knowledge)
					/// ⚠️ **WARNING:::UNSTABLE** — crystallization risk
					/// Todo: Should create a classification inside DaemonicCompiler when complete that tags DaemonicUnstable items separately from RustUnstable and flags them on use in the wild.
					/// Prophetic Temporality mirrors God logic, no pun intended.
					/// This is here solely because the system wouldnt be complete without it, but this field should be used with extreme caution.
					/// *Logic Crystallization risk Defined:*
					/// *1 << Brittleness, cant handle new or novel inputs without fracturing at the edges.*
					/// *2 << Non-routable across large temporal reference frames*
					/// *3 << Higher Base decay rate for packets in network contexts, *enforced*.*
					Prophetic { requires_prior_walks: u64 },
					/// No temporal relationship (absorptive)
					None,
				}
				/// Spatial transformation applied
				#[derive(Clone, Debug, PartialEq)]
				pub enum Spatiality {
					/// Standard mirror — inverted across boundary plane
					Inverted,
					/// No spatial change
					Identity,
					/// Systematic spatial transformation
					Transformed(SpatialTransform),
					/// All spatial information collapsed
					Collapsed,
				}
				/// Which properties reflect
				#[derive(Clone, Debug, PartialEq)]
				pub enum Selectivity {
					/// All properties reflect
					Complete,
					/// Only specified properties reflect
					Partial(Vec<PropertyId>),
					/// Only one property reflects
					Single(PropertyId),
					/// No properties reflect
					None,
				}
				/// Energy required to maintain this reflection type
				#[derive(Clone, Debug, PartialEq)]
				pub enum EnergyCost {
					/// Minimum energy — natural ground state
					Minimal,
					/// Finite measurable cost
					Finite(f64),
					/// Requires continuous energy input
					Sustained(f64),
					/// Theoretically infinite (unstable)
					Unbounded,
				}
				/// Placeholder for spatial transforms
				#[derive(Clone, Debug, PartialEq)]
				pub struct SpatialTransform {
					// TODO: Define transformation matrices or functions
				}
				/// Identifier for observable properties
				pub type PropertyId = u32;
			}
			pub(crate) mod error_types {
				pub(crate) mod error_messages {
					use os::OsError;
					use daemonic::entity::shade::ShadeError;
					use generic::GenericError;
					use daemonic::Daemonic;
					use super::*;
					/// This struct is currently blank but should be filled in.
					/// # The Theory
					/// Clock cycles tick forward automatically (proc_macro autotick)
					/// Clock Tick = work done, any function, any transformation, any operation = Clock Tick
					/// Therefore clock output per unit = Deterministic
					/// if no work, then Recursion cuts the chain at pass 7 citing no work.
					/// If there is work, and its non-deterministic or never resolves: requires different handling.
					///
					/// Non-deterministic output from deterministic input is technically impossible barring
					/// hardware level failure modes, if multiple independent passes return non-deterministic results
					///  then operation performed is inherently unstable or the logic is just shit.
					/// These are inherently different modes of EntropyTermination, one assumes work and didnt find any -> graceful cut
					/// The other assumes work input is deterministic but isnt -> non-graceful cut, requires active intervention
					/// and may return a Warped state instead of a Shattered state type if the operation corrupted persistent memory
					pub struct EntropyTermination {}


					pub(crate) mod os {
						//already moved
					}

					pub(crate) mod daemonic {
						//already moved
					}

					pub(crate) mod generic {
						//already moved
					}
				}
				use crate::{
					EnumerationRouter,
					daemonic::{
						daemonic_contract::{
							daemonic_result::{
								error_types::{
									error_messages::{
										generic::GenericError,
										os::OsError,
										daemonic::Daemonic,
									}
								}
							}
						}
					},
				};
				pub enum Error {
					/// Use generic variant for simple or quick errors
					Generic(GenericError),
					#[cfg_attr(feature = "Libc", )]
					/// Use this variant for LIBC compatible errors with ERRNO table and conversion methods
					OS(OsError),
					/// Daemonic Error variants with richer context than Generic or OS level returns
					/// Shade, Entity, and Symbolic errors are here.
					Daemonic(Daemonic),
				}
				impl EnumerationRouter for Error {}
			}
			pub(crate) mod diagnostic {
				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.
						// Fluent is deprecated, fluent was bullshit anyways so im not sure how applicable this is to current state
						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)+
        )
    );
}
			}
			pub(crate) mod subdiagnostic {
				use crate::EmissionGuarantee;

				/// Trait implemented by error types. This should not be implemented manually. Instead, use
				/// `#[derive(Subdiagnostic)]` -- see [rustc_macros::Subdiagnostic].
				#[rustc_diagnostic_item = "Subdiagnostic"]
				pub trait Subdiagnostic
				where
					Self: Sized,
				{
					/// Add a subdiagnostic to an existing diagnostic.
					fn add_to_diag<GUARANTEE: EmissionGuarantee>(
						self,
						diag: &mut Diag<'_, GUARANTEE>,
					);
				}
			}
			pub(crate) mod repairable {
				use super::severity_types::{GlassCracked, GlassState, SeverityType};
				use super::*;
				use crate::daemonic::Daemonic;
				use crate::daemonic::daemonic_contract::IntoDaemonicResult;
				use crate::{DaemonicError, DaemonicResult};
				pub trait SeverityHandler<FORMAT, PARTIAL> {
					type Context;
					type Output: IntoDaemonicResult<FORMAT, PARTIAL>;
					type Error: for<'e> DaemonicError<'e, FORMAT, PARTIAL>;

					// ═══════════════════════════════════════════════════════
					// OK-ISH HANDLERS (Stable through Suggestion)
					// ═══════════════════════════════════════════════════════

					/// Stable Return type Analogous to Ok or Success Result, ideally should be passthrough
					/// value. Also, this probably isnt correct as is but is better than it was prior.
					/// Might need to be wired into DaemonicContract system.
					fn handle_stable(&self, _state: &GlassStable, _ctx: &Self::Context) -> DaemonicResult<Self::Output, Self::Error> {
						// Default: passthrough, nothing to do
						DaemonicResult::Success(Self::Output::default())
					}
					/// Like an Ok value with a note attached
					fn handle_note(&self, _state: &GlassNote, _ctx: &Self::Context) -> DaemonicResult<Self::Output, Self::Error> {
						// Default: log note, continue
						DaemonicResult::Success(Self::Output::default())
					}
					/// Like an Ok value (ish) with a help message or note attached.
					fn handle_help(&self, _state: &GlassHelp, _ctx: &Self::Context) -> DaemonicResult<Self::Output, Self::Error> {
						DaemonicResult::Success(Self::Output::default())
					}
					/// Sometimes accompanied with an Error, sometimes stand alone. Intended to be a
					/// suggestion reflected from the backend to the User/Dev but is not in and of itself
					/// an error. Similar to `Subdiagnostic` trait from [RustcError]
					fn handle_suggestion(
						&self,
						_state: &GlassSuggestion,
						_ctx: &Self::Context,
					) -> DaemonicResult<Self::Output, Self::Error> {
						DaemonicResult::Success(Self::Output::default())
					}

					// ═══════════════════════════════════════════════════════
					// BOUNDARY HANDLERS (Cracked)
					// Two methods because two genuinely different cases
					// ═══════════════════════════════════════════════════════

					fn handle_cracked_holding(
						&self,
						_state: &GlassCracked,
						_ctx: &Self::Context,
					) -> DaemonicResult<Self::Output, Self::Error> {
						// Holding = damaged but functional
						// Return success with default, caller can override
						DaemonicResult::Success(Self::Output::default())
					}

					fn handle_cracked_contained<R>(
						&self,
						state: &GlassCracked,
						ctx: &mut Self::Context,
						action: impl FnOnce(&Self::Error, &mut Self::Context) -> Option<R>,
					) -> DaemonicResult<R, Self::Error> {
						let error = Self::Error::from_cracked(state); // this method needs implementation
						match action(&error, ctx) {
							Some(repaired) => DaemonicResult::Success(repaired),
							None => DaemonicResult::Failure(error),
						}
					}

					// ═══════════════════════════════════════════════════════
					// ERROR HANDLERS (Fractured through Shattered)
					// Mutable context, action for repair attempt
					// ═══════════════════════════════════════════════════════

					fn handle_fracture<R>(
						&self,
						state: &GlassFracture,
						ctx: &mut Self::Context,
						action: impl FnOnce(&Self::Error, &mut Self::Context) -> Option<R>,
					) -> DaemonicResult<R, Self::Error> {
						let error = Self::Error::from_fracture(state);
						match action(&error, ctx) {
							Some(repaired) => DaemonicResult::Success(repaired),
							None => DaemonicResult::Failure(error),
						}
					}

					fn handle_warp<R>(
						&self,
						state: &GlassWarp,
						ctx: &mut Self::Context,
						action: impl FnOnce(&Self::Error, &mut Self::Context) -> Option<R>,
					) -> DaemonicResult<R, Self::Error> {
						let error = Self::Error::from_warp(state);
						match action(&error, ctx) {
							Some(repaired) => DaemonicResult::Success(repaired),
							None => DaemonicResult::Failure(error),
						}
					}

					fn handle_shattered<R>(
						&self,
						state: &GlassShattered,
						ctx: &mut Self::Context,
						action: impl FnOnce(&Self::Error, &mut Self::Context) -> Option<R>,
					) -> DaemonicResult<R, Self::Error> {
						let error = Self::Error::from_shattered(state);
						match action(&error, ctx) {
							Some(recovered) => DaemonicResult::Success(recovered),
							None => DaemonicResult::Failure(error),
						}
					}
					fn handle<Repair>(&self, severity: &SeverityType, ctx: &mut Self::Context, _repair: impl FnOnce(&Self::Error, &mut Self::Context)
						-> Option<Repair>) -> DaemonicResult<Self::Output, Self::Error>
					{
						match severity {
							SeverityType::GlassStable(s) => {
								self.handle_stable(s, ctx)
							}
							SeverityType::GlassNote(note) => {
								self.handle_note(note, ctx)
							}
							SeverityType::GlassSuggestion(sug) => {
								self.handle_suggestion(sug, ctx)
							}
							SeverityType::GlassHelp(h) => {
								self.handle_help(h, ctx)
							}
							SeverityType::GlassCracked(crack) => {
								self.handle_cracked(crack, ctx, |_error, _ctx| None::<Self::Output>)
							}
							SeverityType::GlassFracture(f) => {
								self.handle_fracture(f, ctx, |_error, _ctx| None::<Self::Output>)
							}
							SeverityType::GlassWarp(w) => {
								self.handle_warp(w, ctx, |_error, _ctx| None::<Self::Output>)
							}
							SeverityType::GlassShattered(shatter) => {
								self.handle_shattered(shatter, ctx, |_error, _ctx| None::<Self::Output>)
							}
						}
					}
				}
				///Example usage for specific contexts
				///```
				/// struct VideoHandler;
				/// impl SeverityHandler<VideoContext, Image> for VideoHandler {
				/// 	fn handle(&self, severity: &SeverityType, ctx: VideoContext) -> Image {
				/// 		match severity {
				/// 			SeverityType::GlassNote(note) => load_image(&note.message),
				/// 			_ => default_image(),
				/// 		}
				/// 	}
				/// }
				/// ```
				/// Generic Zero sized repair handler
				struct DaemonicHandler<CONTEXT, ACTION, R> {
					context: CONTEXT,
					action: Option<fn(&SeverityType, CONTEXT) -> ACTION>,
				}
			}
			pub(crate) mod severity_types {
				use super::mirror_chemistry::{MirrorType, ReflectionProperties};
				///SINON:
				/// "On Glass vs Mirror naming."
				/// Mirror:
				///   - The surface that reflects
				///   - Physical object
				///   - Passive
				///   - "What bounces off"
				///
				/// Glass:
				///   - The material
				///   - Can be mirror, lens, window, prism
				///   - More general
				///   - "What light passes through or bounces off"
				///
				/// In your system:
				///
				/// ReflectionProperties = how reflection behaves
				/// Mirror = a stable compound of reflection properties
				/// Glass = the STATE of a thing after observation
				///
				/// RECOMMENDATION:
				///
				/// Use GLASS for states.
				/// Use MIRROR for types (the chemistry element).
				/// Use REFLECTION for the process.
				///
				/// Why:
				///   - Glass is the material that makes mirrors
				///   - Glass can be stable or shattered
				///   - "GlassShattered" makes sense
				///   - "MirrorShattered" is less clear (mirror is already solid)
				///
				///   - Mirror describes BEHAVIOR (how it reflects)
				///   - Glass describes STATE (what condition it's in)
				///
				/// GlassStable: the glass is intact, reflects clearly
				/// GlassShattered: the glass is broken, reflects chaotically
				/// GlassFractured: the glass has cracks, reflects imperfectly
				///
				/// Mirror types (Specular, Absorptive, etc.):
				///   What KIND of reflection
				///
				/// Glass states:
				///   What CONDITION the glass is in
				///
				pub trait GlassState<'state>: Send + Sync + 'state {
					type Mirror<'mirrortype>: MirrorType<'mirrortype>;
					type Cause<'mirrortype>: Severity;
					fn from_reflection(props: ReflectionProperties) -> Self;
					/// Is recoverable defaults to FALSE, call or definition defines otherwise
					fn is_recoverable(&self) -> bool { false }
					/// Can cascade defaults to FALSE, call or definition defines otherwise
					fn can_cascade(&self) -> bool { false }
					fn dominance(&self) -> u8;
					fn stable<'stable>() -> fn(GlassStable) -> SeverityType;
					fn fracture(props: &ReflectionProperties) -> fn(GlassFracture) -> SeverityType;
					fn warp(props: &ReflectionProperties) -> fn(GlassWarp) -> SeverityType;
					fn shatter<'impossible>() -> fn(GlassShattered) -> SeverityType;
					fn note<'note>() -> fn(GlassNote) -> SeverityType;
					fn suggestion<'suggestion>() -> fn(GlassSuggestion) -> SeverityType;
					fn help<'help>() -> fn(GlassHelp) -> SeverityType;
				}
				pub trait Severity: Send + Sync {
					type Mirror<'mirrortype>: MirrorType<'mirrortype>;
					const RECOVERABLE: bool;
					const CAN_CASCADE: bool;
					const DOMINANCE: u8;
					fn on_observer(&self) -> SeverityAction;
				}
				/// this is simple for now, as suggested by Sinon and Ada, but i would like to
				/// nest these in Daemonic style eventually where each nested bit returns a struct
				/// and all downstream types implementing it must return a struct on it to guarantee
				/// type safety in all edge cases.
				/// Also, recursion management logic needs to be attached here along with
				/// DaemonicClock logic traits for halt/continue decision making, should be function
				/// not arbitrary.
				pub(crate) enum SeverityAction {
					Continue,
					Warn,
					Halt,
					Abort,
				}
				pub enum SeverityType {
					GlassStable(GlassStable),
					GlassHelp(GlassHelp),
					GlassSuggestion(GlassSuggestion),
					GlassNote(GlassNote),
					GlassCracked(GlassCracked),
					GlassFracture(GlassFracture),
					GlassWarp(GlassWarp),
					GlassShattered(GlassShattered),
				}
				impl<R> From<GlassStable> for SeverityType {
					fn from(s: GlassStable) -> Self {
						SeverityType::GlassStable(s)
					}
				}
				impl<R> SeverityType {
					pub fn as_glass_state(&self) -> &dyn GlassState<Cause=impl Severity, Mirror=impl MirrorType> {
						match self {
							SeverityType::GlassStable(s) => s,
							SeverityType::GlassHelp(s) => s,
							SeverityType::GlassSuggestion(s) => s,
							SeverityType::GlassNote(s) => s,
							SeverityType::GlassFracture(s) => s,
							SeverityType::GlassWarp(s) => s,
							SeverityType::GlassShattered(s) => s,
							SeverityType::GlassCracked(s) => { s }
						}
					}
				}
				/// Its expected that this enum will grow in size, Entropy Termination
				/// contains multiple possible failure modes depending on callers context
				/// and the env at the time of calling.
				/// For every new addition inside, enums nested in SeverityCause should end in their own leaf structs eventually.
				/// Enums should be used for organization and Daemonic Nesting, structured
				/// error returns should be enforced from here down to ensure that handlers
				/// are always consistent across context stacks.
				pub enum SeverityCause {
					EntropyTermination(entropy::EntropyTermination),
				}
				use crate::daemonic::daemonic_contract::daemonic_result::mirror_chemistry::elements::{SPECULAR, ABSORPTIVE};
				pub(crate) struct GlassStable;
				pub(crate) struct GlassHelp;
				pub(crate) struct GlassSuggestion;
				pub(crate) struct GlassNote;
				pub(crate) struct GlassFracture;
				pub(crate) struct GlassWarp;
				pub(crate) struct GlassShattered;
				pub(crate) struct GlassCracked;
				pub(crate) mod entropy;

				pub(crate) struct SeverityContext<SEVERITY: Severity> {
					pub state: SEVERITY,
					pub cause: SeverityCause,
					pub recoverable_here: bool,
				}
			}
			pub(crate) use diagnostic::DiagnosticLevel;
		}
		pub(crate) mod partial_types {
			use std::marker::PhantomPinned;
			/// this module is currently stubbed out but will eventually provide the role of
			/// result<Partial> type output, which can have strange behavior at runtime
			/// depending on the nature of the application being built.
			/// Partial states carry some possibly corrupted Glass State objects + whatever
			/// the DaemonicError system was able to capture before the Glass Shattered under
			/// the walker.
			/// For simple applications that have sync states and no peers to manage, this is
			/// largely a non issue. But for a more complex async managed state machine, partial
			/// states can be complex as fuck. Daemonic logic accounts for this in theory.
			/// Eventually, the theory made manifest will exist here when a situation arises
			/// that constrains build requirements enough to construct this module.
			fn dummy() -> PhantomPinned {
				PhantomPinned
			}
		}
	}
	pub(crate) struct DaemonicID<FORMAT, PARTIAL> {
		id: u32,
		nickname: Option<dyn DaemonicBinary<FORMAT, PARTIAL, Error=impl DaemonicError<FORMAT, PARTIAL>>>,
	}

}
//todo :: step through and find where all these are being tripped and document for the why.
//! ═══════════════════════════════════════════════════════════════
//! DAEMONIC ERROR - Root Error Crate
//! ═══════════════════════════════════════════════════════════════
//!
//! Architecture: Daemonic Nesting, more formally Dimensional Nesting.
//! DaemonicError now provides concrete Symbol and Type tree for resolution and construction.
//! Supertraits that are above or lateral to DaemonicError will remain where they are.
//! Supertraits that might be employed by other crates will exist here in DaemonicError first.
//! Structures will mirror DaemonicError, not the other way around.
//!
//!   DaemonicError: Top-level enum. Load-bearing. All crates depend on this. TODO:: DaemonicError Supertrait and mirrored hierarchy, all enums branches should end in structs as leaf nodes
//!   ├── Os(OsError):          Syscall, IO, file, memory, process (partially used, waiting for impl)
//!   ├── Symbolic(SymbolicError): Glass, Walk, DB, Lie states, topology
//!   ├── Ntp(NtpError):        Temporal sync, peer discovery, protocol (unused, waiting for impl)
//!   ├── Network / Protocol:   Raw wire-level failures (unused, waiting for impl)
//!   ├── Parse / Config:       Input validation
//!   ├── Mesh:                 Peer-to-peer failures
//!
//!
//!    Daemonic: (bottom-most trait)
//! 		  ├ DaemonicCore:
//!  		  │		├─: Position
//! 		  │		├─: Clock
//! 		  │		│	  └─: where Clock: DaemonicClock
//! 		  │		│						├─: Logical: LamportClock
//! 		  │		│						├─: Physical: WallClock (NTP, MTP, or Hardware)
//! 		  │		│						└─: Hybrid (Combination Clock)
//! 		  │		├───────────────────────────────────────: DaemonicObservation
//! 		  │		│												├─: Active: Toggled effects, constitutes state change from norm or baseline effect.
//! 		  │		│												└─: Passive: Always on, const or passive effects, functions, and types. Gravity and Time as passive examples.
//!   		  │		└─: UniqueID
//!//!  		  ├ MirrorChemistry (More specific definitions coming soon, will be Trait)
//!  		  │		├─: Bonding
//!   		  │		├─: Stability
//!   		  │		├─: Elements
//!   		  │		└─: Table
//!//! 		  └ DaemonicContract:
//! 					├─: Input type
//!  		 			│		└─: BinarySymbol(GENERIC: Can be bound to any wire format if DB unwanted) (DB has RAW type variant for arbitrary/unknown data)
//!//!//! 					└─: Output type
//!    		 					├─: BinarySymbol(GENERIC: Can be bound to any wire format if DB unwanted) (DB has RAW type variant for arbitrary/unknown data) + G (optional Generic) (BinarySymbol can be overridden)
//!    		 					└─: DaemonicError + C: ErrorContext + M: MetaData (Context required, MetaData optional <<< SUPERTRAIT
//!    		 							│				where C: ErrorContext (supertrait providing position/clock)
//!    		 							└─: ErrorType + S {LITERALLY THIS STRUCTURE. PICK THE TYPE BASED ON WHERE YOU ARE IN THE LATTICE.}			Note: All types no matter if they are fallible or not must implement DaemonicError type, even for types that dont produce errors.
//!    		 			   					  │		 where   																						Note: For stubbed impls or functions that legitimately return nothing, `use silent()` variant, else use ``[DaemonicError::Symbolic::SymbolicError::ImpossibleState]
//!//!    		 			 					  ├─: S: Severity (These are all Types, not Enums)
//!    		 								  │			├─: GlassStable <-> Specular Mirror
//!    		 								  │			├─: GlassHelp <-> Selective (positive) Mirror
//!    		 								  │			├─: GlassSuggestion <-> Selective (constructive) Mirror
//!    		 								  │			├─: GlassFractured <-> Lossy Mirror
//!    		 								  │			├─: GlassWarped <-> Transformative Mirror (NON-REVERSABLE)
//!    		 								  │			├─: GlassShattered <-> Absorbative
//!//!   		 								  └: ErrorMessages {Lattice Mirror}
//!		Entity tree is broken, currently being redone
//! 		───: Entity
//!  			  │	  └─:BrokenSword (Method: Self-aware death declaration with stack dump)
//!//!   			  └───── Shade:
//!   		    			└───┬──: Bootstrap (Method: Todo: move bootstrap logic from wherever the fuck it is to traits folder in shade)
//! 							├──: REPL (method)
//! 							├──: Ingestion (method)
//! 							├──: SymbolConstructor (method)
//! 		  					├──: DaemonicCompiler::Rust (method)
//! 							│		├──: Hashes
//!  							│		├──: Arena
//! 		 					│		├──: Serialize
//! 		 					│		├──: Index
//! 		 					│		├──: Graphviz
//! 		 					│		├──: DataStructures
//!  							│		├──: Span
//! 		  					│		├──: ABI
//! 		  					│		├──: Lexer
//! 		  					│		├──: ASTIR
//! 		  					│		├──: AST
//! 		  					│		├──: ASTPretty
//! 		  					│		├──: BakedICUdata
//! 		   					│		├──: FSUtil
//! 		   					│		├──: Feature
//! 		   					│		├──: ParseFormat
//! 		   					│		├──: HIR
//! 		   					│		├──: AttrDataStructures
//! 		   					│		├──: LintDefs
//! 		   					│		├──: HIRPretty
//! 		   					│		├──: TypeIR
//! 		   					│		├──: NextTraitSolver
//! 		   					│		├──: Log
//! 		   					│		├──: Session
//!  		  					│		├──: GetOpts (this needs to die, but probably wont)
//! 		   					│		├──: DaemonicHashable
//! 		   					│		├──: Middle
//! 		   					│		├──: Query
//! 		   					│		├──: Transmute
//! 		   					│		├──: AttrParsing
//! 		   					│		├──: Parse
//! 		   					│		├──: ASTPasses
//! 		   					│		├──: Inflate
//! 		  			 		│		├──: ASTLowering
//!    	    					│		└──: TraitSelection
//!//!//! 							├──: Walker (Type)
//! 							│       ├──: FileWalker (Generic Walker variant for agnostic operations outside of rust)
//! 							│		├──: MemoryWalker
//! 							│		├──: MirrorWalker
//! 							│		├──: SysFSWalker
//! 							│		├──: ReconWalker
//! 							│		├──: NetworkWalker
//! 							│       └──: RustWalker
//!  							│       		└──:TypeWalker
//! 							└──: Clock
//!
//!
//!
//! Error output format (uniform across all variants): (pending update and merge with RustC Error)
//!   [DAEMONIC] {Module}::{Component} → {Context}
//!     ↳ {Source}  (if present)
//!
//! "daemonic_error" in output strings is intentional.
//! Differentiates Faustian stack errors from raw POSIX.
//! The shell is a Glass shell — error reporting leans into that.

use std::fmt::Debug;
use daemonic::{
	daemonic_core::{
		*,
		observation::{
			debug::{
				*,
			}
		},
	},
	daemonic_contract::{
		daemonic_result::{
			severity_types::*,
			mirror_chemistry::*,
			diagnostic::*,
			subdiagnostic::*,
		},
		*,
	},
};
pub use daemonic::{
	daemonic_contract::{
		daemonic_result::{
			subdiagnostic::{
				Subdiagnostic,
			},
			diagnostic::{
				DiagnosticLevel,
				DiagnosticContextHandle as DiagCtxtHandle,
				DiagnosticContextHandle,
				Diagnostic,
				Diag,
				DiagInner,
				DiagCtxt,
				IntoDiagArg,
				Subdiag,
				DiagArgValue,
				ErrorGuaranteed,
				FatalError,
				FatalErrorMarker,
			},
		}
	}
};

/// DaemonicError is specifically a specialization on the trait [DaemonicObservation]
/// Type parameters and lifetimes are named + qualified because error handling should be explicit and verbose not stubs, fight me on it.
/// Named Type Parameters should be enforced in DaemonicError at least, if not elsewhere.
/// `[CONTEXT: ErrorContext<'ERROR>]` field is required.
///
/// `[META: MetaData]` field is Generic and optional, bound at call site.
///
/// `[SEVERITY: GlassState]` is unique in that Severities returned can either be types or traits depending on their behavior
/// and the callers context.
///
#[allow(non_snake_case)]
pub trait DaemonicError<
	'ERROR, // Error lifetimes must be explicitly named (in this crate)
	FORMAT,
	PARTIAL,
	DIAGNOSTIC = dyn Diagnostic, // Optional
	SUBDIAGNOSTIC = dyn Subdiagnostic, // Optional
	CONTEXT = dyn ErrorContext, // Required
	SEVERITY = SeverityType, // Required
	META = dyn MetaData // Required
>:
DaemonicObservation<FORMAT, PARTIAL>
// + std::error::Error // DaemonicError is better than the default Error trait, will just reimplement what i havent already.
+ Send
+ Sync
+ Sized // this might not need to be here but i dont know yet.
+ core::fmt::Debug
// + std::fmt::Display // this has been cloned to DaemonicDisplay
+ ErrorContext<'ERROR>
+ 'ERROR
where
	CONTEXT: ErrorContext<'ERROR>,
	META: MetaData<'ERROR>,
	SEVERITY: GlassState<'ERROR>,
{
	/// Where are we in the Type Tree? Refer to ASCII structure in `lib.rs`
	// todo: This should probably be further up in the type tree, all things derived from Daemonic
	// todo: should use position in hindsight.
	#[must_use]
	fn position(&self) -> &Position;

	/// What was happening when the Emission was returned?
	#[must_use]
	fn context(&self) -> &CONTEXT;

	/// Severity is still in dev, but in short Severity returns a result that can be either a Type or a Trait
	/// depending on callers context, if Type -> handled elsewhere upstream
	/// if Trait -> then error has effect on program state or machine state and can be
	/// interacted with programmatically
	#[must_use]
	fn severity(&self) -> SEVERITY;

	fn wrap_in(self, parent_position: Position) -> Self;

	/// for rust specific structs that have span analogies, optional.
	/// Defaults to none if unused
	fn emit_diagnostic(&self) -> DIAGNOSTIC { None }

	/// For rust-specific structs that have span analogies, requires parent Diagnostic to anchor on.
	/// Also optional, requires Diagnostic first, SubDiagnostics emit inside Diagnostics (relatively)
	/// Defaults to none if unused
	fn emit_subdiagnostic(&self) -> SUBDIAGNOSTIC { None }

	/// Additional logic attached that could modify behavior if necessary (optional).
	/// Defaults to none if unused
	fn metadata(&self) -> &META { &None }

	// Optional/defaulted downstream to False if unused or not set deliberately
	fn is_recoverable(&self) -> bool {
		self.severity().is_recoverable() // todo: this is incomplete
	}
	/// Defaults to none if unused
	fn source_position(&self) -> Option<&Position> {
		None
	}
}
#[allow(non_snake_case)]
trait ErrorContext<'ERROR>: Send + Sync + 'ERROR {
	fn position(&self) -> &Position;
	fn timestamp(&self) -> Timestamp;
}
impl DaemonicError for DummyStruct {}
struct DummyStruct;
trait MetaData<'meta>: Send + Sync + 'meta {}
/// This trait is currently blank (stubbed) but will serve as a router point.
/// Structs nested inside Enums as leaves are implemented with DaemonicError to return
/// typed Errors and Severities for programmatic interaction.
/// This trait is used on the Enums themselves to describe where in the trait tree the errors originate
/// as they propagate up the stack to the base trait implemented at call site.
/// IE if full Daemonic pipe is implemented, then Errors propagated all the way up to Daemonic
/// from a deeply nested type should affix modules with whitesplace splits `::` -> which can then be
/// used later for Error Type walking.
pub trait EnumerationRouter {}

/// Sinon suggested:
/// Usage
/// rust```
/// impl Position {
///     pub const fn new(segments: &[&'static str]) -> Self {
///         Self { segments: SmallVec::from_slice(segments) }
///     }
///
///     pub fn depth(&self) -> usize {
///         self.segments.len()
///     }
///
///     pub fn prepend(&mut self, parent: &'static str) {
///         self.segments.insert(0, parent);
///     }
///
///     pub fn as_path(&self) -> String {
///         self.segments.join("::")
///     }
/// }
/// const TYPE_WALKER_POS: Position = Position::new(&[
///     "Shade", "Walker", "RustWalker", "TypeWalker"
/// ]);
///
/// SmallVec<[&'static str; 8]>:
/// ```
///
///   - Stack allocated for depth ≤ 8
///   - Heap only for deep nesting
///   - &'static str: no allocation for names
///   - Human readable at any depth
pub(crate) struct Position<'segments> {
	/// todo: this is a placeholder
	segments: Vec<&'segments str>,
}
pub(crate) struct Timestamp {
	/// placeholder
	timestamp: PhantomPinned,
}
impl MetaData<'_> for () {} // unit type default


use std::marker::{PhantomData, PhantomPinned};
pub use opaque_dependencies::termcolor::*;
use crate::daemonic::daemonic_core::observation::DaemonicObservation;

///SINON:
// "Concrete leverage points."
// WHAT TO REUSE:
//
// 1. THE COMBINE PATTERN
//
// Your error bonding:
//
// pub fn combine_errors(
//     a: &impl DaemonicErrorTrait,
//     b: &impl DaemonicErrorTrait,
// ) -> ErrorBondResult {
//     // Rule: Shattered dominates
//     if a.severity() == Severity::Shattered {
//         return ErrorBondResult::Dominated(a.into());
//     }
//     if b.severity() == Severity::Shattered {
//         return ErrorBondResult::Dominated(b.into());
//     }
//
//     // Rule: Stable is identity
//     if a.severity() == Severity::Stable {
//         return ErrorBondResult::Compound(b.into());
//     }
//
//     // Rule: Warped + Warped = unstable compound
//     if a.severity() == Severity::Warped && b.severity() == Severity::Warped {
//         return ErrorBondResult::Unstable(
//             compound(a, b),
//             DaemonicDuration::from_millis(100),
//         );
//     }
//
//     // Rule: Fractures stack
//     if a.severity() == Severity::Fractured && b.severity() == Severity::Fractured {
//         return ErrorBondResult::Compound(stack_fractures(a, b));
//     }
//
//     // etc...
// }
//
// 2. THE STABILITY ASSESSMENT
//
// pub fn assess_error_stability(error: &CompoundError) -> ErrorStability {
//     // Rule: Single severity = stable
//     if error.severities.len() == 1 {
//         return ErrorStability::Stable;
//     }
//
//     // Rule: Mixed Warped = metastable
//     if error.severities.contains(&Severity::Warped) {
//         return ErrorStability::Metastable {
//             perturbation_threshold: 0.1,
//         };
//     }
//
//     // Rule: Contains Shattered = unstable
//     if error.severities.contains(&Severity::Shattered) {
//         return ErrorStability::Unstable {
//             decay_to: extract_dominant(error),
//             half_life: DaemonicDuration::from_millis(50),
//         };
//     }
//
//     ErrorStability::Stable
// }
//
// 3. THE COMPOUND CLASSIFICATION
//
// pub enum ErrorGroup {
//     Noble,        // Single severity, minimal energy
//     Reactive,     // Will combine with other errors
//     Transitional, // Properties vary with context
//     Rare,         // Requires extreme conditions
//     Synthetic,    // Only artificially constructable
// }
//
// pub fn classify_error(error: &CompoundError) -> ErrorGroup {
//     match assess_error_stability(error) {
//         ErrorStability::Stable if error.energy_cost.is_minimal() => {
//             ErrorGroup::Noble
//         }
//         ErrorStability::Metastable { .. } => ErrorGroup::Reactive,
//         ErrorStability::Unstable { .. } => {
//             if contains_prophetic(error) {
//                 ErrorGroup::Rare
//             } else {
//                 ErrorGroup::Transitional
//             }
//         }
//         ErrorStability::Impossible => ErrorGroup::Synthetic,
//         _ => ErrorGroup::Transitional,
//     }
// }