rootcause 0.12.1

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

use rootcause_internals::{
    RawReport,
    handlers::{ContextFormattingStyle, FormattingFunction},
};

use crate::{
    ReportConversion, ReportIter, ReportMut, ReportRef,
    handlers::{self, ContextHandler},
    markers::{self, Cloneable, Dynamic, Local, Mutable, SendSync, Uncloneable},
    preformatted::{self, PreformattedContext},
    report_attachment::ReportAttachment,
    report_attachments::ReportAttachments,
    report_collection::ReportCollection,
};

/// FIXME: Once rust-lang/rust#132922 gets resolved, we can make the `raw` field
/// an unsafe field and remove this module.
mod limit_field_access {
    use core::marker::PhantomData;

    use rootcause_internals::{RawReport, RawReportMut, RawReportRef};

    use crate::markers::{self, Dynamic, Mutable, SendSync};

    /// An error report that contains a context, child reports, and attachments.
    ///
    /// [`Report`] is the main type for creating and working with error reports
    /// in this library. It can contain a root context (typically an error),
    /// zero or more child reports, and zero or more attachments.
    ///
    /// # Type Parameters
    ///
    /// [`Report`] has three type parameters that control its behavior:
    ///
    /// - **Context (`C`)**: The type of the root error or context (defaults to
    ///   [`Dynamic`])
    /// - **Ownership (`O`)**: Controls whether the report can be cloned
    ///   - [`Mutable`]: Unique ownership, can modify but cannot clone (default)
    ///   - [`Cloneable`]: Shared ownership via [`Arc`], can clone but cannot
    ///     modify root
    /// - **Thread Safety (`T`)**: Controls whether the report can be sent
    ///   across threads
    ///   - [`SendSync`]: Can be sent across threads (default, requires all data
    ///     is [`Send`]+[`Sync`])
    ///   - [`Local`]: Cannot be sent across threads (allows non-thread-safe
    ///     data)
    ///
    /// # Common Usage
    ///
    /// The easiest way to create a [`Report`] is with the [`report!()`] macro:
    ///
    /// ```
    /// # use rootcause::prelude::*;
    /// let report: Report = report!("file missing");
    /// println!("{report}");
    /// ```
    ///
    /// You can add context and attachments using method chaining:
    ///
    /// ```
    /// # use rootcause::prelude::*;
    /// let report = report!("database query failed")
    ///     .context("failed to fetch user data")
    ///     .attach("user_id: 12345");
    /// println!("{report}");
    /// ```
    ///
    /// [`Arc`]: triomphe::Arc
    /// [`Local`]: crate::markers::Local
    /// [`Mutable`]: crate::markers::Mutable
    /// [`Cloneable`]: crate::markers::Cloneable
    /// [`SendSync`]: crate::markers::SendSync
    /// [`report!()`]: crate::report!
    #[repr(transparent)]
    pub struct Report<
        Context: ?Sized + 'static = Dynamic,
        Ownership: 'static = Mutable,
        ThreadSafety: 'static = SendSync,
    > {
        /// # Safety
        ///
        /// The following safety invariants are guaranteed to be upheld as long
        /// as this struct exists:
        ///
        /// 1. `C` must either be a type bounded by `Sized`, or `Dynamic`.
        /// 2. `O` must either be `Mutable` or `Cloneable`.
        /// 3. `T` must either be `SendSync` or `Local`.
        /// 4. If `C` is a `Sized` type: The context embedded in the report must
        ///    be of type `C`
        /// 5. If `O = Mutable`: This is the unique owner of the report. More
        ///    specifically this means that the strong count of the underlying
        ///    `triomphe::Arc` is exactly 1.
        /// 6. If `O = Cloneable`: All other references to this report are
        ///    compatible with shared ownership. Specifically there are no
        ///    references with an assumption that the strong_count is `1`.
        /// 7. All references to any sub-reports of this report are compatible
        ///    with shared ownership. Specifically there are no references with
        ///    an assumption that the strong_count is `1`.
        /// 8. If `T = SendSync`: All contexts and attachments in the report and
        ///    all sub-reports must be `Send+Sync`.
        raw: RawReport,
        _context: PhantomData<Context>,
        _ownership: PhantomData<Ownership>,
        _thread_safety: PhantomData<ThreadSafety>,
    }

    impl<C: ?Sized, O, T> Report<C, O, T> {
        /// Creates a new [`Report`] from a [`RawReport`]
        ///
        /// # Safety
        ///
        /// The caller must ensure:
        ///
        /// 1. `C` must either be a type bounded by `Sized`, or `Dynamic`.
        /// 2. `O` must either be `Mutable` or `Cloneable`.
        /// 3. `T` must either be `SendSync` or `Local`.
        /// 4. If `C` is a `Sized` type: The context embedded in the report must
        ///    be of type `C`
        /// 5. If `O = Mutable`: This is the unique owner of the report. More
        ///    specifically this means that the strong count of the underlying
        ///    `triomphe::Arc` is exactly 1.
        /// 6. If `O = Cloneable`: All other references to this report are
        ///    compatible with shared ownership. Specifically there are no
        ///    references with an assumption that the strong_count is `1`.
        /// 7. All references to any sub-reports of this report are compatible
        ///    with shared ownership. Specifically there are no references with
        ///    an assumption that the strong_count is `1`.
        /// 8. If `T = SendSync`: All contexts and attachments in the report and
        ///    all sub-reports must be `Send+Sync`.
        #[must_use]
        pub(crate) unsafe fn from_raw(raw: RawReport) -> Self {
            // SAFETY: We must uphold the safety invariants of the raw field:
            // 1. Guaranteed by the caller
            // 2. Guaranteed by the caller
            // 3. Guaranteed by the caller
            // 4. Guaranteed by the caller
            // 5. Guaranteed by the caller
            // 6. Guaranteed by the caller
            // 7. Guaranteed by the caller
            // 8. Guaranteed by the caller
            Self {
                raw,
                _context: PhantomData,
                _ownership: PhantomData,
                _thread_safety: PhantomData,
            }
        }

        /// Consumes the [`Report`] and returns the inner [`RawReport`].
        #[must_use]
        pub(crate) fn into_raw(self) -> RawReport {
            // SAFETY: We are destroying `self`, so we no longer
            // need to uphold any safety invariants.
            self.raw
        }

        /// Creates a lifetime-bound [`RawReportRef`] from the inner
        /// [`RawReport`].
        #[must_use]
        pub(crate) fn as_raw_ref(&self) -> RawReportRef<'_> {
            // SAFETY: We must uphold the safety invariants of the raw field:
            // 1. Upheld as the type parameters do not change.
            // 2. Upheld as the type parameters do not change.
            // 3. Upheld as the type parameters do not change.
            // 4. Trivially upheld, as no mutation occurs
            // 5. The only way to break this would be to call `RawReportRef::clone_arc`, but
            //    that method has a `safety` requirement that the caller must ensure that no
            //    owners exist which are incompatible with shared ownership. Since `self` is
            //    incompatible with shared ownership when `O=Mutable`, this cannot happen.
            // 6. Trivially upheld, as no mutation occurs
            // 7. Upheld, as this does not create any such references.
            // 8. Trivially upheld, as no mutation occurs
            let raw = &self.raw;

            raw.as_ref()
        }
    }

    impl<C: ?Sized, T> Report<C, markers::Mutable, T> {
        /// Creates a lifetime-bound [`RawReportMut`] from the inner
        /// [`RawReport`].
        ///
        /// # Safety
        ///
        /// The caller must ensure:
        ///
        /// 1. If `T = SendSync`, no objects are added to the report through
        ///    this that are not `Send+Sync`
        #[must_use]
        pub(crate) unsafe fn as_raw_mut(&mut self) -> RawReportMut<'_> {
            // SAFETY: We need to uphold the safety invariants of the raw field:
            // 1. Upheld as the type parameters do not change.
            // 2. Upheld as the type parameters do not change.
            // 3. Upheld as the type parameters do not change.
            // 4. While mutation of the context is possible through this reference, it is
            //    not possible to change the type of the context. Therefore this invariant
            //    is upheld.
            // 5. The only way to break this would be to call `RawReportRef::clone_arc`, but
            //    that method has a `safety` requirement that the caller must ensure that no
            //    owners exist which are incompatible with shared ownership. Since `self` is
            //    the unique owner, this cannot happen.
            // 6. `O = Mutable`, so this is trivially upheld.
            // 7. Upheld, as this does not create any such references.
            // 8. The caller guarantees that the current report is not modified in an
            //    incompatible way and it is not possible to mutate the sub-reports.
            let raw = &mut self.raw;

            // SAFETY:
            // 1. This method is in an impl for `Report<C, Mutable, T>`, which means that we
            //    can invoke our own safety invariant to show that this is indeed the unique
            //    owner of the report.
            unsafe { raw.as_mut() }
        }
    }
}

pub use limit_field_access::Report;

impl<C: Sized, T> Report<C, Mutable, T> {
    /// Creates a new [`Report`] with the given context.
    ///
    /// This method is generic over the thread safety marker `T`. The context
    /// will use the [`handlers::Error`] handler for formatting.
    ///
    /// See also:
    ///
    /// - The [`report!()`] macro will also create a new [`Report`], but can
    ///   auto-detect the thread safety marker and handler.
    /// - [`Report::new_sendsync`] and [`Report::new_local`] are more
    ///   restrictive variants of this function that might help avoid type
    ///   inference issues.
    /// - [`Report::new_custom`] also allows you to manually specify the
    ///   handler.
    ///
    /// [`report!()`]: crate::report!
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, markers::{SendSync, Mutable, Local}};
    /// # #[derive(Debug)]
    /// # struct MyError;
    /// # impl core::error::Error for MyError {}
    /// # impl core::fmt::Display for MyError { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { unimplemented!() }}
    /// let report_sendsync: Report<MyError, Mutable, SendSync> = Report::new(MyError);
    /// let report_local: Report<MyError, Mutable, Local> = Report::new(MyError);
    /// ```
    #[track_caller]
    #[must_use]
    pub fn new(context: C) -> Self
    where
        C: markers::ObjectMarkerFor<T> + core::error::Error,
    {
        Self::new_custom::<handlers::Error>(context)
    }

    /// Creates a new [`Report`] with the given context and handler.
    ///
    /// This method is generic over the thread safety marker `T`.
    ///
    /// If you're having trouble with type inference for the thread safety
    /// parameter, consider using [`Report::new_sendsync_custom`] or
    /// [`Report::new_local_custom`] instead.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, markers::{SendSync, Local}};
    /// # #[derive(Debug)]
    /// # struct MyError;
    /// # impl core::error::Error for MyError {}
    /// # impl core::fmt::Display for MyError { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { unimplemented!() }}
    /// let report_sendsync: Report<MyError> = Report::new_custom::<handlers::Debug>(MyError);
    /// let report_local: Report<MyError> = Report::new_custom::<handlers::Display>(MyError);
    /// ```
    #[track_caller]
    #[must_use]
    pub fn new_custom<H>(context: C) -> Self
    where
        C: markers::ObjectMarkerFor<T>,
        H: ContextHandler<C>,
    {
        Self::from_parts::<H>(context, ReportCollection::new(), ReportAttachments::new())
    }

    /// Creates a new [`Report`] with the given context, children, and
    /// attachments.
    ///
    /// This method processes hooks during report creation. If you want to skip
    /// hook processing, use [`Report::from_parts_unhooked`] instead.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, report_collection::ReportCollection, report_attachments::ReportAttachments, markers::{SendSync}};
    /// let report: Report<String, _, SendSync> = Report::from_parts::<handlers::Display>(
    ///     "error".to_string(),
    ///     ReportCollection::new(),
    ///     ReportAttachments::new(),
    /// );
    /// ```
    #[track_caller]
    #[must_use]
    pub fn from_parts<H>(
        context: C,
        children: ReportCollection<Dynamic, T>,
        attachments: ReportAttachments<T>,
    ) -> Self
    where
        C: markers::ObjectMarkerFor<T>,
        H: ContextHandler<C>,
    {
        let mut report: Self = Self::from_parts_unhooked::<H>(context, children, attachments);
        C::run_creation_hooks(report.as_mut().into_dynamic());
        report
    }

    /// Creates a new [`Report`] with the given context, children, and
    /// attachments without hook processing.
    ///
    /// This method skips hook processing during report creation. If you want
    /// hooks to be processed, use [`Report::from_parts`] instead.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, report_collection::ReportCollection, report_attachments::ReportAttachments, markers::SendSync};
    /// let report: Report<String, _, SendSync> = Report::from_parts_unhooked::<handlers::Display>(
    ///     "error".to_string(),
    ///     ReportCollection::new(),
    ///     ReportAttachments::new(),
    /// );
    /// ```
    #[track_caller]
    #[must_use]
    pub fn from_parts_unhooked<H>(
        context: C,
        children: ReportCollection<Dynamic, T>,
        attachments: ReportAttachments<T>,
    ) -> Self
    where
        C: markers::ObjectMarkerFor<T>,
        H: ContextHandler<C>,
    {
        let raw = RawReport::new::<C, H>(context, children.into_raw(), attachments.into_raw());

        // SAFETY:
        // 1. `C` is bounded by `Sized`, so this is upheld.
        // 2. `O=Mutable`, so this is trivially upheld.
        // 3. `C` is bounded by `markers::ObjectMarkerFor<T>` and this can only be
        //    implemented for `T=Local` and `T=SendSync`, so this is
        //   upheld.
        // 4. We just created the report and the `C` does indeed match.
        // 5. We just created the report and we are the unique owner.
        // 6. `O=Mutable`, so this is trivially upheld.
        // 7. This is guaranteed by the invariants of the `ReportCollection` we used to
        //    create the raw report.
        // 8. If `T=Local`, then this is trivially true. If `T=SendSync`, then we have
        //    `C: ObjectMarkerFor<SendSync>`, so the context is `Send+Sync`.
        //    Additionally the invariants of the `ReportCollection` and
        //    `ReportAttachments` guarantee that the children and attachments are
        //    `Send+Sync` as well.
        unsafe {
            // @add-unsafe-context: ReportCollection
            // @add-unsafe-context: ReportAttachments
            // @add-unsafe-context: markers::ObjectMarkerFor
            Report::<C, Mutable, T>::from_raw(raw)
        }
    }

    /// Decomposes the [`Report`] into its constituent parts.
    ///
    /// Returns a tuple containing the context, the children collection and the
    /// attachments collection in that order. This is the inverse operation
    /// of [`Report::from_parts`] and [`Report::from_parts_unhooked`].
    ///
    /// This method can be useful when you need to:
    /// - Extract and modify individual components of a report
    /// - Rebuild a report with different components
    /// - Transfer components between different reports
    /// - Perform custom processing on specific parts
    ///
    /// Note that to exactly reconstruct the original report, you will also need
    /// to use the same handler as was used for the original report.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, report_collection::ReportCollection, report_attachments::ReportAttachments};
    /// // Create a report with some children and attachments
    /// let mut report: Report<String> = Report::from_parts::<handlers::Display>(
    ///     "main error".to_string(),
    ///     ReportCollection::new(),
    ///     ReportAttachments::new(),
    /// );
    ///
    /// // Add some content
    /// let child_report = report!("child error").into_dynamic().into_cloneable();
    /// report.children_mut().push(child_report);
    /// report.attachments_mut().push("debug info".into());
    ///
    /// // Decompose into parts
    /// let (context, children, attachments) = report.into_parts();
    ///
    /// assert_eq!(context, "main error");
    /// assert_eq!(children.len(), 1);
    /// assert!(attachments.len() >= 1); // "debug info" + potential automatic attachments
    ///
    /// // Can rebuild with the same or different parts
    /// let rebuilt: Report<String> = Report::from_parts::<handlers::Display>(
    ///     context,
    ///     children,
    ///     attachments,
    /// );
    /// ```
    #[must_use]
    pub fn into_parts(self) -> (C, ReportCollection<Dynamic, T>, ReportAttachments<T>) {
        let raw = self.into_raw();

        // SAFETY:
        // 1. This is guaranteed by the invariants of this type.
        // 2. Since `O=Mutable` and we are consuming `self`, then this is guaranteed to
        //    be the unique owner of the report. We also know that there are no other
        //    references such as `ReportRef` or `ReportMut` active, as those would
        //    require a borrow of `self`.
        let (context, children, attachments) = unsafe { raw.into_parts() };

        // SAFETY:
        // 1. `C=Dynamic` for the created collection, so this is trivially true.
        // 2. The invariants of this type guarantee that `T` is either `Local` or
        //    `SendSync`.
        // 3. `C=Dynamic` for the created collection, so this is trivially true.
        // 4. This is guaranteed by the invariants of this type.
        // 5. If `T=Local`, then this is trivially true. If `T=SendSync`, then this is
        //    guaranteed by the invariants of this type.
        let children = unsafe { ReportCollection::<Dynamic, T>::from_raw(children) };

        // SAFETY:
        // 1. `T` is guaranteed to either be `Local` or `SendSync` by the invariants of
        //    this type.
        // 2. If `T=Local`, then this is trivially true. If `T=SendSync`, then this is
        //    guaranteed by the invariants of this type.
        let attachments = unsafe { ReportAttachments::<T>::from_raw(attachments) };

        (context, children, attachments)
    }

    /// Extracts and returns the context value from the [`Report`].
    ///
    /// This is a convenience method that consumes the [`Report`] and returns
    /// only the context, discarding the children and attachments. It's
    /// equivalent to calling `report.into_parts().0`.
    ///
    /// This method can be useful when:
    /// - You only need the underlying error or context value
    /// - Converting from a [`Report`] back to the original error type
    /// - Extracting context for logging or forwarding to other systems
    /// - Implementing error conversion traits
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// #[derive(Debug, PartialEq, Clone)]
    /// struct MyError {
    ///     message: String,
    ///     code: u32,
    /// }
    ///
    /// impl std::fmt::Display for MyError {
    ///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    ///         write!(f, "Error {}: {}", self.code, self.message)
    ///     }
    /// }
    ///
    /// // Create a report with a custom error context
    /// let original_error = MyError {
    ///     message: "database connection failed".to_string(),
    ///     code: 500,
    /// };
    /// let report: Report<MyError> = report!(original_error.clone());
    ///
    /// // Extract just the context, discarding report structure
    /// let extracted_error = report.into_current_context();
    /// assert_eq!(extracted_error, original_error);
    /// assert_eq!(extracted_error.code, 500);
    /// assert_eq!(extracted_error.message, "database connection failed");
    /// ```
    #[must_use]
    pub fn into_current_context(self) -> C {
        self.into_parts().0
    }

    /// Returns a mutable reference to the current context.
    ///
    /// # Examples
    /// ```
    /// use rootcause::prelude::*;
    /// let mut report: Report<String> = report!(String::from("An error occurred"));
    /// let context: &mut String = report.current_context_mut();
    /// context.push_str(" and that's bad");
    /// ```
    #[must_use]
    pub fn current_context_mut(&mut self) -> &mut C {
        self.as_mut().into_current_context_mut()
    }

    /// Transforms the context type by applying a function, preserving report
    /// structure.
    ///
    /// Converts the context type in-place without creating new nodes. Children,
    /// attachments, and hook data (backtraces, locations) are preserved.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rootcause::prelude::*;
    /// # #[derive(Debug)]
    /// # struct LibError;
    /// # impl std::fmt::Display for LibError {
    /// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "lib error") }
    /// # }
    /// # #[derive(Debug)]
    /// enum AppError {
    ///     Lib(LibError)
    /// }
    /// # impl std::fmt::Display for AppError {
    /// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "app error") }
    /// # }
    ///
    /// let lib_report: Report<LibError> = report!(LibError);
    /// let app_report: Report<AppError> = lib_report.context_transform(AppError::Lib);
    /// ```
    ///
    /// # See Also
    ///
    /// - [`context_transform_nested()`](Report::context_transform_nested) -
    ///   Wraps original as preformatted child
    /// - [`context()`](Report::context) - Adds new parent context
    /// - [`context_to()`](Report::context_to) - Uses
    ///   [`ReportConversion`](crate::ReportConversion) trait
    /// - [`examples/context_methods.rs`] - Comparison guide
    ///
    /// [`examples/context_methods.rs`]: https://github.com/rootcause-rs/rootcause/blob/main/examples/context_methods.rs
    #[track_caller]
    pub fn context_transform<F, D>(self, f: F) -> Report<D, Mutable, T>
    where
        F: FnOnce(C) -> D,
        D: markers::ObjectMarkerFor<T> + core::fmt::Display + core::fmt::Debug,
    {
        let (context, children, attachments) = self.into_parts();
        let new_context = f(context);

        Report::from_parts_unhooked::<handlers::Display>(new_context, children, attachments)
    }

    /// Transforms the context and nests the original report as a preformatted
    /// child.
    ///
    /// Creates a new parent node with fresh hook data (location, backtrace),
    /// but the original context type is lost—the child becomes
    /// [`PreformattedContext`] and cannot be downcast.
    ///
    /// [`PreformattedContext`]: crate::preformatted::PreformattedContext
    ///
    /// # Examples
    ///
    /// ```
    /// # use rootcause::prelude::*;
    /// # #[derive(Debug)]
    /// # struct LibError;
    /// # impl std::fmt::Display for LibError {
    /// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "lib error") }
    /// # }
    /// # #[derive(Debug)]
    /// enum AppError {
    ///     Lib(LibError)
    /// }
    /// # impl std::fmt::Display for AppError {
    /// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "app error") }
    /// # }
    ///
    /// let lib_report: Report<LibError> = report!(LibError);
    /// let app_report: Report<AppError> = lib_report.context_transform_nested(AppError::Lib);
    /// ```
    ///
    /// # See Also
    ///
    /// - [`context_transform()`](Report::context_transform) - Transforms
    ///   without nesting
    /// - [`context()`](Report::context) - Adds new parent, preserves child's
    ///   type
    /// - [`preformat_root()`](Report::preformat_root) - Lower-level operation
    ///   used internally
    /// - [`examples/context_methods.rs`] - Comparison guide
    ///
    /// [`examples/context_methods.rs`]: https://github.com/rootcause-rs/rootcause/blob/main/examples/context_methods.rs
    #[track_caller]
    pub fn context_transform_nested<F, D>(self, f: F) -> Report<D, Mutable, T>
    where
        F: FnOnce(C) -> D,
        D: markers::ObjectMarkerFor<T> + core::fmt::Display + core::fmt::Debug,
        PreformattedContext: markers::ObjectMarkerFor<T>,
    {
        let (context, report) = self.preformat_root();
        report.context_custom::<handlers::Display, _>(f(context))
    }

    /// Extracts the context and returns it with a preformatted version of the
    /// report.
    ///
    /// Returns a tuple: the original typed context and a new report with
    /// [`PreformattedContext`](crate::preformatted::PreformattedContext)
    /// containing the string representation. The preformatted report maintains
    /// the same structure (children and attachments). Useful when you need
    /// the typed value for processing and the formatted version for display.
    ///
    /// This is a lower-level method primarily for custom transformation logic.
    /// Most users should use
    /// [`context_transform`](Self::context_transform),
    /// [`context_transform_nested`](Self::context_transform_nested),
    /// or [`context_to`](Self::context_to) instead.
    ///
    /// See also: [`preformat`](Report::preformat) (formats entire hierarchy),
    /// [`into_parts`](Report::into_parts) (extracts without formatting),
    /// [`current_context`](crate::ReportRef::current_context) (reference
    /// without extraction).
    ///
    /// # Examples
    ///
    /// ```
    /// # use rootcause::{preformatted::PreformattedContext, prelude::*};
    /// # #[derive(Debug)]
    /// struct MyError {
    ///     code: u32
    /// }
    /// # impl std::fmt::Display for MyError {
    /// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "error {}", self.code) }
    /// # }
    ///
    /// let report: Report<MyError> = report!(MyError { code: 500 });
    /// let (context, preformatted): (MyError, Report<PreformattedContext>) = report.preformat_root();
    /// ```
    pub fn preformat_root(self) -> (C, Report<PreformattedContext, Mutable, T>)
    where
        PreformattedContext: markers::ObjectMarkerFor<T>,
    {
        let preformatted = PreformattedContext::new_from_context(self.as_ref());
        let (context, children, attachments) = self.into_parts();

        (
            context,
            Report::from_parts_unhooked::<preformatted::PreformattedHandler>(
                preformatted,
                children,
                attachments,
            ),
        )
    }
}

impl<C: ?Sized, T> Report<C, Mutable, T> {
    /// Returns a mutable reference to the report.
    ///
    /// # Examples
    /// ```
    /// use rootcause::{ReportMut, prelude::*};
    /// let mut report: Report = report!("error message");
    /// let report_mut: ReportMut<'_> = report.as_mut();
    /// ```
    #[must_use]
    pub fn as_mut(&mut self) -> ReportMut<'_, C, T> {
        // SAFETY:
        // 1. If `T=Local`, then this is trivially true. If `T=SendSync`, then we are
        //    not allowed to mutate the returned raw report in a way that adds
        //    non-`Send+Sync` objects. However the invariants of the created `ReportMut`
        //    guarantee that no such mutation can occur.
        let raw = unsafe { self.as_raw_mut() };

        // SAFETY:
        // 1. This is guaranteed by the invariants of this type.
        // 2. This is guaranteed by the invariants of this type.
        // 3. This is guaranteed by the invariants of this type.
        // 4. This is guaranteed by the invariants of this type.
        // 5. This is guaranteed by the invariants of this type.
        // 6. This is guaranteed by the invariants of this type.
        // 7. We have a `&mut self`. This means that there are no other borrows active
        //    to `self`. We also know that this is the unique owner of the report, so
        //    there are no other references to it through different ownership. This
        //    means that there are no other references to this report at all, so there
        //    cannot be any incompatible references.
        unsafe { ReportMut::from_raw(raw) }
    }

    /// Adds a new attachment to the [`Report`].
    ///
    /// This is a convenience method used for chaining method calls; it consumes
    /// the [`Report`] and returns it.
    ///
    /// If you want more direct control over the attachments, you can use the
    /// [`Report::attachments_mut`].
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// let report: Report = report!("error message");
    /// let with_attachment = report.attach("additional info");
    /// ```
    #[must_use]
    pub fn attach<A>(mut self, attachment: A) -> Self
    where
        A: markers::ObjectMarkerFor<T> + core::fmt::Display + core::fmt::Debug,
    {
        self.attachments_mut()
            .push(ReportAttachment::new(attachment).into_dynamic());
        self
    }

    /// Adds a new attachment to the [`Report`].
    ///
    /// This is a convenience method used for chaining method calls; it consumes
    /// the [`Report`] and returns it.
    ///
    /// If you want more direct control over the attachments, you can use the
    /// [`Report::attachments_mut`].
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// let report: Report = report!("error message");
    /// let with_attachment = report.attach_custom::<handlers::Display, _>("info");
    /// ```
    #[must_use]
    pub fn attach_custom<H, A>(mut self, attachment: A) -> Self
    where
        A: markers::ObjectMarkerFor<T>,
        H: handlers::AttachmentHandler<A>,
    {
        self.attachments_mut()
            .push(ReportAttachment::new_custom::<H>(attachment).into_dynamic());
        self
    }

    /// Returns a mutable reference to the child reports.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, report_collection::ReportCollection};
    /// let mut report: Report = report!("error message");
    /// let children_mut: &mut ReportCollection = report.children_mut();
    /// ```
    #[must_use]
    pub fn children_mut(&mut self) -> &mut ReportCollection<Dynamic, T> {
        self.as_mut().into_children_mut()
    }

    /// Returns a mutable reference to the attachments.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, report_attachments::ReportAttachments};
    /// let mut report: Report = report!("error message");
    /// let attachments_mut: &mut ReportAttachments = report.attachments_mut();
    /// ```
    #[must_use]
    pub fn attachments_mut(&mut self) -> &mut ReportAttachments<T> {
        self.as_mut().into_attachments_mut()
    }
}

impl<C: ?Sized, O, T> Report<C, O, T> {
    /// Creates a new [`Report`] with the given context and sets the current
    /// report as a child of the new report.
    ///
    /// The new context will use the [`handlers::Display`] handler to format the
    /// context.
    ///
    /// This is a convenience method used for chaining method calls; it consumes
    /// the [`Report`] and returns it.
    ///
    /// If you want a different context handler, you can use
    /// [`Report::context_custom`].
    ///
    /// If you want to more directly control the allocation of the new report,
    /// you can use [`Report::from_parts`], which is the underlying method
    /// used to implement this method.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// let report: Report = report!("initial error");
    /// let contextual_report: Report<&str> = report.context("additional context");
    /// ```
    #[track_caller]
    #[must_use]
    pub fn context<D>(self, context: D) -> Report<D, Mutable, T>
    where
        D: markers::ObjectMarkerFor<T> + core::fmt::Display + core::fmt::Debug,
    {
        self.context_custom::<handlers::Display, _>(context)
    }

    /// Creates a new [`Report`] with the given context and sets the current
    /// report as a child of the new report.
    ///
    /// This is a convenience method used for chaining method calls; it consumes
    /// the [`Report`] and returns it.
    ///
    /// If you want to more directly control the allocation of the new report,
    /// you can use [`Report::from_parts`], which is the underlying method
    /// used to implement this method.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// let report: Report = report!("initial error");
    /// let contextual_report: Report<&str> = report.context_custom::<handlers::Debug, _>("context");
    /// ```
    #[track_caller]
    #[must_use]
    pub fn context_custom<H, D>(self, context: D) -> Report<D, Mutable, T>
    where
        D: markers::ObjectMarkerFor<T>,
        H: ContextHandler<D>,
    {
        Report::from_parts::<H>(
            context,
            ReportCollection::from([self.into_dynamic().into_cloneable()]),
            ReportAttachments::<T>::new(),
        )
    }

    /// Converts this report to a different context type using
    /// [`ReportConversion`].
    ///
    /// Implement [`ReportConversion`] once to define conversion logic, then use
    /// `context_to()` at call sites. Useful for consistent error type
    /// coercion across your codebase, especially when integrating with
    /// external libraries. You typically need to specify the target type
    /// (`::<Type>`).
    ///
    /// See also: [`context_transform`](Self::context_transform) for direct
    /// conversion,
    /// [`context_transform_nested`](Self::context_transform_nested) for
    /// wrapping, [`examples/thiserror_interop.rs`] for integration
    /// patterns.
    ///
    /// [`examples/thiserror_interop.rs`]: https://github.com/rootcause-rs/rootcause/blob/main/examples/thiserror_interop.rs
    ///
    /// # Examples
    ///
    /// ```
    /// # use rootcause::{ReportConversion, markers::Mutable, prelude::*};
    /// # #[derive(Debug)]
    /// enum AppError { Parse }
    /// # impl std::fmt::Display for AppError {
    /// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "error") }
    /// # }
    /// impl<T> ReportConversion<std::num::ParseIntError, Mutable, T> for AppError
    ///   where AppError: markers::ObjectMarkerFor<T>
    /// {
    ///     fn convert_report(report: Report<std::num::ParseIntError, Mutable, T>) -> Report<Self, Mutable, T>
    ///     {
    ///         report.context(AppError::Parse)
    ///     }
    /// }
    /// // After implementing ReportConversion, use at call sites:
    /// let result: Result<i32, Report<AppError>> = "abc".parse::<i32>().context_to();
    /// ```
    #[track_caller]
    #[must_use]
    pub fn context_to<D: ReportConversion<C, O, T>>(self) -> Report<D, Mutable, T> {
        D::convert_report(self)
    }

    /// Returns a reference to the child reports.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, report_collection::ReportCollection};
    /// let report: Report = report!("error message");
    /// let children: &ReportCollection = report.children();
    /// assert_eq!(children.len(), 0); // The report has just been created, so it has no children
    /// ```
    #[must_use]
    pub fn children(&self) -> &ReportCollection<Dynamic, T> {
        self.as_uncloneable_ref().children()
    }

    /// Returns a reference to the attachments.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, report_attachments::ReportAttachments};
    /// let report: Report = report!("error message");
    /// let attachments: &ReportAttachments = report.attachments();
    /// ```
    #[must_use]
    pub fn attachments(&self) -> &ReportAttachments<T> {
        self.as_uncloneable_ref().attachments()
    }

    /// Changes the context type of the [`Report`] to [`Dynamic`].
    ///
    /// Calling this method is equivalent to calling `report.into()`, however
    /// this method has been restricted to only change the context mode to
    /// [`Dynamic`].
    ///
    /// This method can be useful to help with type inference or to improve code
    /// readability, as it more clearly communicates intent.
    ///
    /// This method does not actually modify the report in any way. It only has
    /// the effect of "forgetting" that the context actually has the type
    /// `C`.
    ///
    /// To get back the report with a concrete `C` you can use the method
    /// [`Report::downcast_report`].
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, markers::Dynamic};
    /// # struct MyError;
    /// # let my_error = MyError;
    /// let report: Report<MyError> = report!(my_error);
    /// let dyn_report: Report<Dynamic> = report.into_dynamic();
    /// ```
    #[must_use]
    pub fn into_dynamic(self) -> Report<Dynamic, O, T> {
        let raw = self.into_raw();

        // SAFETY:
        // 1. `C=Dynamic`, so this is trivially true.
        // 2. This is guaranteed by the invariants of this type.
        // 3. This is guaranteed by the invariants of this type.
        // 4. `C=Dynamic`, so this is trivially true.
        // 5. This is guaranteed by the invariants of this type.
        // 6. This is guaranteed by the invariants of this type.
        // 7. This is guaranteed by the invariants of this type.
        // 8. This is guaranteed by the invariants of this type.
        unsafe {
            // @add-unsafe-context: Dynamic
            Report::<Dynamic, O, T>::from_raw(raw)
        }
    }

    /// Changes the ownership of the [`Report`] to [`Cloneable`].
    ///
    /// Calling this method is equivalent to calling `report.into()`, however
    /// this method has been restricted to only change the ownership mode to
    /// [`Cloneable`].
    ///
    /// This method can be useful to help with type inference or to improve code
    /// readability, as it more clearly communicates intent.
    ///
    /// This method does not actually modify the report in any way. It only has
    /// the effect of "forgetting" that the [`Report`] only has a single
    /// owner.
    ///
    /// After calling this method, you can clone the [`Report`], but you can no
    /// longer add attachments to the [`Report`] or otherwise modify the
    /// root node.
    ///
    /// To get back a [`Mutable`] you need to either:
    /// - Allocate a new root node using e.g. [`Report::context`].
    /// - If there is a single unique owner of the report, you can use
    ///   [`Report::try_into_mutable`].
    /// - Preformat the root node using [`Report::preformat`].
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, markers::{Mutable, Cloneable}};
    /// # let my_error = "error message";
    /// let report: Report<_, Mutable> = report!(my_error);
    /// let cloneable_report: Report<_, Cloneable> = report.into_cloneable();
    /// let cloned = cloneable_report.clone();
    /// ```
    #[must_use]
    pub fn into_cloneable(self) -> Report<C, Cloneable, T> {
        let raw = self.into_raw();

        // SAFETY:
        // 1. This is guaranteed by the invariants of `self`.
        // 2. `O=Cloneable`, so this is trivially true.
        // 3. This is guaranteed by the invariants of `self`.
        // 4. This is guaranteed by the invariants of `self`.
        // 5. `O=Cloneable`, so this is trivially true.
        // 6. If the ownership of `self` is already `Cloneable`, then this is guaranteed
        //    by the invariants of `self`. If the ownership of `self` is `Mutable`, then
        //    the invariants of `self` guarantee that we are the only owner and we are
        //    consuming `self` in this method, so there are no other owners.
        // 7. This is guaranteed by the invariants of `self`.
        // 8. This is guaranteed by the invariants of `self`.
        unsafe { Report::<C, Cloneable, T>::from_raw(raw) }
    }

    /// Changes the thread safety mode of the [`Report`] to [`Local`].
    ///
    /// Calling this method is equivalent to calling `report.into()`, however
    /// this method has been restricted to only change the thread safety
    /// mode to [`Local`].
    ///
    /// This method can be useful to help with type inference or to improve code
    /// readability, as it more clearly communicates intent.
    ///
    /// This method does not actually modify the report in any way. It only has
    /// the effect of "forgetting" that all objects in the [`Report`] might
    /// actually be [`Send`] and [`Sync`].
    ///
    /// After calling this method, you can add objects to the [`Report`] that
    /// are neither [`Send`] nor [`Sync`], but the report itself will no
    /// longer be [`Send`]+[`Sync`].
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, markers::{Local, SendSync}};
    /// # let my_error = "error message";
    /// let report: Report<_, _, SendSync> = report!(my_error);
    /// let local_report: Report<_, _, Local> = report.into_local();
    /// ```
    #[must_use]
    pub fn into_local(self) -> Report<C, O, Local> {
        let raw = self.into_raw();

        // SAFETY:
        // 1. This is guaranteed by the invariants of this type.
        // 2. This is guaranteed by the invariants of this type.
        // 3. `T=Local`, so this is trivially upheld.
        // 4. This is guaranteed by the invariants of this type.
        // 5. This is guaranteed by the invariants of this type.
        // 6. This is guaranteed by the invariants of this type.
        // 7. This is guaranteed by the invariants of this type.
        // 8. `T=Local`, so this is trivially true.
        unsafe { Report::<C, O, Local>::from_raw(raw) }
    }

    /// Checks if there is only a single unique owner of the root node of the
    /// [`Report`].
    ///
    /// If there is only a single unique owner, this method
    /// marks the current [`Report`] as [`Mutable`] and returns `Ok`,
    /// otherwise it returns `Err` with the original [`Report`].
    ///
    /// This method does not actually modify the report in any way. It only has
    /// the effect of checking for unique ownership and returns the same
    /// report (with different type parameters) no matter the outcome of the
    /// check.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, markers::{Mutable, Cloneable}};
    /// # let some_report = report!("error message").into_cloneable();
    /// let cloneable: Report<_, Cloneable> = some_report;
    /// match cloneable.try_into_mutable() {
    ///     Ok(mutable) => println!("Converted to mutable"),
    ///     Err(cloneable) => println!("Still cloneable"),
    /// }
    /// ```
    pub fn try_into_mutable(self) -> Result<Report<C, Mutable, T>, Report<C, O, T>> {
        if self.strong_count() == 1 {
            let raw = self.into_raw();

            // SAFETY:
            // 1. This is guaranteed by the invariants of this type.
            // 2. `O=Mutable`, so this is trivially true.
            // 3. This is guaranteed by the invariants of this type.
            // 4. This is guaranteed by the invariants of this type.
            // 5. We just checked that the strong count is `1`, and we are taking ownership
            //    of `self`, so we are the unique owner.
            // 6. `O=Mutable`, so this is trivially upheld.
            // 7. This is guaranteed by the invariants of this type.
            // 8. This is guaranteed by the invariants of this type.
            let report = unsafe { Report::<C, Mutable, T>::from_raw(raw) };
            Ok(report)
        } else {
            Err(self)
        }
    }

    pub(crate) fn as_uncloneable_ref(&self) -> ReportRef<'_, C, Uncloneable, T> {
        let raw = self.as_raw_ref();

        // SAFETY:
        // 1. This is guaranteed by the invariants of this type.
        // 2. `O=Uncloneable`, so this is trivially true.
        // 3. This is guaranteed by the invariants of this type.
        // 4. This is guaranteed by the invariants of this type.
        // 5. `O=Uncloneable`, so this is trivially true.
        // 6. This is guaranteed by the invariants of this type.
        // 7. This is guaranteed by the invariants of this type.
        unsafe {
            // @add-unsafe-context: markers::ReportOwnershipMarker
            ReportRef::<C, Uncloneable, T>::from_raw(raw)
        }
    }

    /// Returns an immutable reference to the report.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, ReportRef, markers::{Cloneable, Mutable, Uncloneable}};
    /// let report: Report<_, Mutable> = report!("error message");
    /// let report_ref: ReportRef<'_, _, Uncloneable> = report.as_ref();
    ///
    /// let report: Report<_, Cloneable> = report!("error message").into_cloneable();
    /// let report_ref: ReportRef<'_, _, Cloneable> = report.as_ref();
    /// ```
    #[must_use]
    pub fn as_ref(&self) -> ReportRef<'_, C, O::RefMarker, T>
    where
        O: markers::ReportOwnershipMarker,
    {
        let raw = self.as_raw_ref();

        // SAFETY:
        // 1. This is guaranteed by the invariants of this type.
        // 2. If the ownership of `self` is `Mutable`, then the `O=Uncloneable`, which
        //    means that this is trivially true. On the other hand, if the ownership of
        //    `self` is `Cloneable`, then the `O=Cloneable`, which is also trivially
        //    true.
        // 3. This is guaranteed by the invariants of this type.
        // 4. This is guaranteed by the invariants of this type.
        // 5. If the ownership of `self` is `Mutable`, then the `O=Uncloneable`, which
        //    means that this is trivially true. On the other hand, if the ownership of
        //    `self` is `Cloneable`, then the `O=Cloneable`. However in that case, the
        //    invariants of this type guarantee that all references are compatible.
        // 6. This is guaranteed by the invariants of this type.
        // 7. This is guaranteed by the invariants of this type.
        unsafe {
            // @add-unsafe-context: markers::ReportOwnershipMarker
            ReportRef::<C, O::RefMarker, T>::from_raw(raw)
        }
    }

    /// Returns an iterator over the complete report hierarchy including this
    /// report.
    ///
    /// The iterator visits reports in a depth-first order: it first visits the
    /// current report, then recursively visits each child report and all of
    /// their descendants before moving to the next sibling. Unlike
    /// [`Report::iter_sub_reports`], this method includes the report on
    /// which it was called as the first item in the iteration.
    ///
    /// The ownership marker of the returned iterator references matches the
    /// ownership of this report. For mutable reports, the references may
    /// not be cloneable, which can limit how you can use them. If you need
    /// cloneable references, consider using [`Report::iter_sub_reports`]
    /// instead, which only iterates over children but guarantees
    /// cloneable references.
    ///
    /// See also: [`Report::iter_sub_reports`] for iterating only over child
    /// reports with cloneable references.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// // Create base reports
    /// let error1: Report = report!("error 1");
    /// let error2: Report = report!("error 2");
    ///
    /// // Build hierarchy using .context() which creates new nodes
    /// let with_context1 = error1.context("context for error 1");  // Creates new node with error1 as child
    /// let with_context2 = error2.context("context for error 2");  // Creates new node with error2 as child
    ///
    /// // Create root that contains both context nodes as children
    /// let mut root = report!("root error").context("context for root error");
    /// root.children_mut().push(with_context1.into_dynamic().into_cloneable());
    /// root.children_mut().push(with_context2.into_dynamic().into_cloneable());
    ///
    /// // At this point our report tree looks like this:
    /// // - context for root error
    /// //   - root error
    /// //   - context for error 1
    /// //     - error 1
    /// //   - context for error 2
    /// //     - error 2
    ///
    /// let all_reports: Vec<String> = root
    ///     .iter_reports()
    ///     .map(|report| report.format_current_context().to_string())
    ///     .collect();
    ///
    /// assert_eq!(all_reports[0], "context for root error");  // Current report is included
    /// assert_eq!(all_reports[1], "root error");
    /// assert_eq!(all_reports.len(), 6);
    /// ```
    pub fn iter_reports(&self) -> ReportIter<'_, O::RefMarker, T>
    where
        O: markers::ReportOwnershipMarker,
    {
        self.as_ref().iter_reports()
    }

    /// Returns an iterator over child reports in the report hierarchy
    /// (excluding this report).
    ///
    /// The iterator visits reports in a depth-first order: it first visits the
    /// current report's children, then recursively visits each child report
    /// and all of their descendants before moving to the next sibling.
    /// Unlike [`Report::iter_reports`], this method does NOT include the
    /// report on which it was called - only its descendants.
    ///
    /// This method always returns cloneable report references, making it
    /// suitable for scenarios where you need to store or pass around the
    /// report references. This is different from [`Report::iter_reports`],
    /// which returns references that match the ownership marker of the
    /// current report and may not be cloneable for mutable reports.
    ///
    /// See also: [`Report::iter_reports`] for iterating over all reports
    /// including the current one.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, markers::Cloneable};
    /// // Create base reports
    /// let error1: Report = report!("error 1");
    /// let error2: Report = report!("error 2");
    ///
    /// // Build hierarchy using .context() which creates new nodes
    /// let with_context1 = error1.context("context for error 1");  // Creates new node with error1 as child
    /// let with_context2 = error2.context("context for error 2");  // Creates new node with error2 as child
    ///
    /// // Create root that contains both context nodes as children
    /// let mut root = report!("root error").context("context for root error");
    /// root.children_mut().push(with_context1.into_dynamic().into_cloneable());
    /// root.children_mut().push(with_context2.into_dynamic().into_cloneable());
    ///
    /// let sub_reports: Vec<String> = root
    ///     .iter_sub_reports()  // Note: using iter_sub_reports, not iter_reports
    ///     .map(|report| report.format_current_context().to_string())
    ///     .collect();
    ///
    /// // Current "root" report is NOT included in the results
    /// assert_eq!(sub_reports[0], "root error");
    /// assert_eq!(sub_reports[1], "context for error 1");
    /// assert_eq!(sub_reports.len(), 5);
    /// ```
    pub fn iter_sub_reports(&self) -> ReportIter<'_, Cloneable, T>
    where
        O: markers::ReportOwnershipMarker,
    {
        self.as_uncloneable_ref().iter_sub_reports()
    }

    /// Creates a new report, which has the same structure as the current
    /// report, but has all the contexts and attachments preformatted.
    ///
    /// This can be useful, as the new report is mutable because it was just
    /// created, and additionally the new report is [`Send`]+[`Sync`].
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, preformatted::PreformattedContext, ReportRef, markers::{Uncloneable, Mutable, SendSync, Local}};
    /// # #[derive(Default)]
    /// # struct NonSendSyncError(core::cell::Cell<()>);
    /// # let non_send_sync_error = NonSendSyncError::default();
    /// let mut report: Report<NonSendSyncError, Mutable, Local> = report!(non_send_sync_error);
    /// let preformatted: Report<PreformattedContext, Mutable, SendSync> = report.preformat();
    /// assert_eq!(format!("{report}"), format!("{preformatted}"));
    /// ```
    #[track_caller]
    #[must_use]
    pub fn preformat(&self) -> Report<PreformattedContext, Mutable, SendSync> {
        self.as_uncloneable_ref().preformat()
    }

    /// Returns the [`TypeId`] of the current context.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, markers::Dynamic};
    /// # use core::any::TypeId;
    /// # struct MyError;
    /// let report: Report<MyError> = report!(MyError);
    /// let type_id = report.current_context_type_id();
    /// assert_eq!(type_id, TypeId::of::<MyError>());
    ///
    /// let report: Report<Dynamic> = report.into_dynamic();
    /// let type_id = report.current_context_type_id();
    /// assert_eq!(type_id, TypeId::of::<MyError>());
    /// ```
    #[must_use]
    pub fn current_context_type_id(&self) -> TypeId {
        self.as_uncloneable_ref().current_context_type_id()
    }

    /// Returns the [`core::any::type_name`] of the current context.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, markers::Dynamic};
    /// # use core::any::TypeId;
    /// # struct MyError;
    /// # let report = report!(MyError).into_cloneable();
    /// let report: Report<MyError> = report!(MyError);
    /// let type_name = report.current_context_type_name();
    /// assert_eq!(type_name, core::any::type_name::<MyError>());
    ///
    /// let report: Report<Dynamic> = report.into_dynamic();
    /// let type_name = report.current_context_type_name();
    /// assert_eq!(type_name, core::any::type_name::<MyError>());
    /// ```
    #[must_use]
    pub fn current_context_type_name(&self) -> &'static str {
        self.as_uncloneable_ref().current_context_type_name()
    }

    /// Returns the [`TypeId`] of the handler used for the current context.
    ///
    /// This can be useful for debugging or introspection to understand which
    /// handler was used to format the context.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, markers::SendSync};
    /// # use core::any::TypeId;
    /// let report = Report::new_sendsync_custom::<handlers::Debug>("error message");
    /// let handler_type = report.current_context_handler_type_id();
    /// assert_eq!(handler_type, TypeId::of::<handlers::Debug>());
    /// ```
    #[must_use]
    pub fn current_context_handler_type_id(&self) -> TypeId {
        self.as_uncloneable_ref().current_context_handler_type_id()
    }

    /// Returns the error source if the context implements [`Error`].
    ///
    /// [`Error`]: core::error::Error
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// # use core::any::TypeId;
    /// let report: Report = report!("error message");
    /// let source: Option<&dyn core::error::Error> = report.current_context_error_source();
    /// assert!(source.is_none()); // The context does not implement Error, so no source
    ///
    /// #[derive(Debug, thiserror::Error)]
    /// enum MyError {
    ///     #[error("Io error: {0}")]
    ///     Io(#[from] std::io::Error),
    ///     // ...
    /// }
    ///
    /// let report: Report<MyError> = report!(MyError::Io(std::io::Error::other("My inner error")));
    /// let source: Option<&dyn std::error::Error> = report.current_context_error_source();
    /// assert_eq!(format!("{}", source.unwrap()), "My inner error");
    /// ```
    #[must_use]
    pub fn current_context_error_source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        self.as_uncloneable_ref().current_context_error_source()
    }

    /// Formats the current context with hook processing.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// let report: Report = report!("error message");
    /// let formatted = report.format_current_context();
    /// println!("{formatted}");
    /// ```
    #[must_use]
    pub fn format_current_context(&self) -> impl core::fmt::Display + core::fmt::Debug {
        self.as_uncloneable_ref().format_current_context()
    }

    /// Formats the current context without hook processing.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// let report: Report = report!("error message");
    /// let formatted = report.format_current_context_unhooked();
    /// println!("{formatted}");
    /// ```
    #[must_use]
    pub fn format_current_context_unhooked(&self) -> impl core::fmt::Display + core::fmt::Debug {
        self.as_uncloneable_ref().format_current_context_unhooked()
    }

    /// Formats the entire report using a specific report formatting hook.
    ///
    /// This method allows you to format a report with a custom formatter
    /// without globally registering it. This is useful for:
    /// - One-off custom formatting
    /// - Testing different formatters
    /// - Using different formatters in different parts of your application
    ///
    /// Unlike the default `Display` and `Debug` implementations which use the
    /// globally registered hook, this method uses the hook you provide
    /// directly.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{hooks::builtin_hooks::report_formatter::DefaultReportFormatter, prelude::*};
    ///
    /// let report = report!("error message");
    ///
    /// // Format with ASCII-only output (no Unicode or ANSI colors)
    /// let formatted = report.format_with(&DefaultReportFormatter::ASCII);
    /// println!("{}", formatted);
    /// ```
    #[must_use]
    pub fn format_with<H>(&self, hook: &H) -> impl core::fmt::Display + core::fmt::Debug
    where
        H: crate::hooks::report_formatter::ReportFormatter,
    {
        self.as_uncloneable_ref().format_with(hook)
    }

    /// Gets the preferred formatting style for the context with hook
    /// processing.
    ///
    /// # Arguments
    ///
    /// - `report_formatting_function`: Whether the report in which this context
    ///   will be embedded is being formatted using [`Display`] formatting or
    ///   [`Debug`]
    ///
    /// [`Display`]: core::fmt::Display
    /// [`Debug`]: core::fmt::Debug
    ///
    /// See also [`Report::preferred_context_formatting_style_unhooked`].
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// let report: Report = report!("error message");
    /// let style = report.preferred_context_formatting_style(handlers::FormattingFunction::Display);
    /// ```
    #[must_use]
    pub fn preferred_context_formatting_style(
        &self,
        report_formatting_function: FormattingFunction,
    ) -> ContextFormattingStyle {
        let report: ReportRef<'_, Dynamic, Uncloneable, Local> = self
            .as_uncloneable_ref()
            .into_dynamic()
            .into_uncloneable()
            .into_local();
        crate::hooks::context_formatter::get_preferred_context_formatting_style(
            report,
            report_formatting_function,
        )
    }

    /// Gets the preferred formatting style for the context without hook
    /// processing.
    ///
    /// # Arguments
    ///
    /// - `report_formatting_function`: Whether the report in which this context
    ///   will be embedded is being formatted using [`Display`] formatting or
    ///   [`Debug`]
    ///
    /// [`Display`]: core::fmt::Display
    /// [`Debug`]: core::fmt::Debug
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// let report: Report = report!("error message");
    /// let style =
    ///     report.preferred_context_formatting_style_unhooked(handlers::FormattingFunction::Display);
    /// ```
    #[must_use]
    pub fn preferred_context_formatting_style_unhooked(
        &self,
        report_formatting_function: FormattingFunction,
    ) -> ContextFormattingStyle {
        self.as_uncloneable_ref()
            .preferred_context_formatting_style_unhooked(report_formatting_function)
    }

    /// Returns the number of references to this report.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// let report: Report = report!("error message");
    /// assert_eq!(report.strong_count(), 1); // We just created the report so it has a single owner
    /// ```
    #[must_use]
    pub fn strong_count(&self) -> usize {
        self.as_uncloneable_ref().strong_count()
    }
}

impl<C: Sized, O, T> Report<C, O, T> {
    /// Returns a reference to the current context.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// # struct MyError;
    /// # let my_error = MyError;
    /// let report: Report<MyError> = report!(my_error);
    /// let context: &MyError = report.current_context();
    /// ```
    #[must_use]
    pub fn current_context(&self) -> &C {
        self.as_uncloneable_ref().current_context()
    }
}

impl<O, T> Report<Dynamic, O, T> {
    /// Attempts to downcast the current context to a specific type.
    ///
    /// Returns `Some(&C)` if the current context is of type `C`, otherwise
    /// returns `None`.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::{prelude::*, markers::Dynamic};
    /// # struct MyError;
    /// let report: Report<MyError> = report!(MyError);
    /// let dyn_report: Report<Dynamic> = report.into_dynamic();
    /// let context: Option<&MyError> = dyn_report.downcast_current_context();
    /// assert!(context.is_some());
    /// ```
    #[must_use]
    pub fn downcast_current_context<C>(&self) -> Option<&C>
    where
        C: Sized + 'static,
    {
        self.as_uncloneable_ref().downcast_current_context()
    }

    /// Downcasts the current context to a specific type without checking.
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    ///
    /// 1. The current context is actually of type `C` (can be verified by
    ///    calling [`current_context_type_id()`] first)
    ///
    /// [`current_context_type_id()`]: Report::current_context_type_id
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// # use core::any::TypeId;
    /// # struct MyError;
    /// let report: Report<MyError> = report!(MyError);
    /// let dyn_report: Report = report.into_dynamic();
    ///
    /// // Verify the type first
    /// if dyn_report.current_context_type_id() == TypeId::of::<MyError>() {
    ///     // SAFETY: We verified the type matches
    ///     let context: &MyError = unsafe { dyn_report.downcast_current_context_unchecked() };
    /// }
    /// ```
    #[must_use]
    pub unsafe fn downcast_current_context_unchecked<C>(&self) -> &C
    where
        C: Sized + 'static,
    {
        let report = self.as_uncloneable_ref();

        // SAFETY:
        // 1. Guaranteed by the caller
        unsafe { report.downcast_current_context_unchecked() }
    }

    /// Attempts to downcast the report to a specific context type.
    ///
    /// Returns `Ok(report)` if the current context is of type `C`,
    /// otherwise returns `Err(self)` with the original report.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// # struct MyError;
    /// let report: Report<MyError> = report!(MyError);
    /// let dyn_report: Report = report.into_dynamic();
    /// let downcasted: Result<Report<MyError>, _> = dyn_report.downcast_report();
    /// assert!(downcasted.is_ok());
    /// ```
    pub fn downcast_report<C>(self) -> Result<Report<C, O, T>, Self>
    where
        C: Sized + 'static,
    {
        if TypeId::of::<C>() == self.current_context_type_id() {
            // SAFETY:
            // 1. We just checked that the type IDs match.
            let report = unsafe { self.downcast_report_unchecked() };

            Ok(report)
        } else {
            Err(self)
        }
    }

    /// Downcasts the report to a specific context type without checking.
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    ///
    /// 1. The current context is actually of type `C` (can be verified by
    ///    calling [`current_context_type_id()`] first)
    ///
    /// [`current_context_type_id()`]: Report::current_context_type_id
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// # use core::any::TypeId;
    /// # struct MyError;
    /// let report: Report<MyError> = report!(MyError);
    /// let dyn_report: Report = report.into_dynamic();
    ///
    /// // Verify the type first
    /// if dyn_report.current_context_type_id() == TypeId::of::<MyError>() {
    ///     // SAFETY: We verified the type matches
    ///     let downcasted: Report<MyError> = unsafe { dyn_report.downcast_report_unchecked() };
    /// }
    /// ```
    #[must_use]
    pub unsafe fn downcast_report_unchecked<C>(self) -> Report<C, O, T>
    where
        C: Sized + 'static,
    {
        let raw = self.into_raw();

        // SAFETY:
        // 1. `C` is bounded by `Sized` in the function signature.
        // 2. This is guaranteed by the invariants of this type.
        // 3. This is guaranteed by the invariants of this type.
        // 4. Guaranteed by the caller
        // 5. This is guaranteed by the invariants of this type.
        // 6. This is guaranteed by the invariants of this type.
        // 7. This is guaranteed by the invariants of this type.
        // 8. This is guaranteed by the invariants of this type.
        unsafe { Report::from_raw(raw) }
    }
}

impl<C: Sized + Send + Sync> Report<C, Mutable, SendSync> {
    /// Creates a new [`Report`] with [`SendSync`] thread safety.
    ///
    /// This is a convenience method that calls [`Report::new`] with explicit
    /// [`SendSync`] thread safety. Use this method when you're having
    /// trouble with type inference for the thread safety parameter.
    ///
    /// The context will use the [`handlers::Error`] handler to format the
    /// context.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// # #[derive(Debug)]
    /// # struct MyError;
    /// # impl core::error::Error for MyError {}
    /// # impl core::fmt::Display for MyError { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { unimplemented!() }}
    /// let report = Report::new_sendsync(MyError);
    /// ```
    #[track_caller]
    #[must_use]
    pub fn new_sendsync(context: C) -> Self
    where
        C: core::error::Error,
    {
        Self::new(context)
    }

    /// Creates a new [`Report`] with [`SendSync`] thread safety and the given
    /// handler.
    ///
    /// This is a convenience method that calls [`Report::new_custom`] with
    /// explicit [`SendSync`] thread safety. Use this method when you're
    /// having trouble with type inference for the thread safety parameter.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// let report = Report::new_sendsync_custom::<handlers::Display>("error");
    /// ```
    #[track_caller]
    #[must_use]
    pub fn new_sendsync_custom<H>(context: C) -> Self
    where
        H: ContextHandler<C>,
    {
        Self::new_custom::<H>(context)
    }
}

impl<C: Sized> Report<C, Mutable, Local> {
    /// Creates a new [`Report`] with [`Local`] thread safety.
    ///
    /// This is a convenience method that calls [`Report::new`] with explicit
    /// [`Local`] thread safety. Use this method when you're having trouble
    /// with type inference for the thread safety parameter.
    ///
    /// The context will use the [`handlers::Error`] handler to format the
    /// context.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// # #[derive(Debug)]
    /// # struct MyError;
    /// # impl core::error::Error for MyError {}
    /// # impl core::fmt::Display for MyError { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { unimplemented!() }}
    /// let report = Report::new_local(MyError);
    /// ```
    #[track_caller]
    #[must_use]
    pub fn new_local(context: C) -> Self
    where
        C: core::error::Error,
    {
        Self::new(context)
    }

    /// Creates a new [`Report`] with [`Local`] thread safety and the given
    /// handler.
    ///
    /// This is a convenience method that calls [`Report::new_custom`] with
    /// explicit [`Local`] thread safety. Use this method when you're having
    /// trouble with type inference for the thread safety parameter.
    ///
    /// # Examples
    /// ```
    /// # use rootcause::prelude::*;
    /// let report = Report::new_local_custom::<handlers::Display>("error");
    /// ```
    #[track_caller]
    #[must_use]
    pub fn new_local_custom<H>(context: C) -> Self
    where
        H: ContextHandler<C>,
    {
        Self::new_custom::<H>(context)
    }
}

// SAFETY: The `SendSync` marker indicates that all objects in the report are
// `Send`+`Sync`. Therefore it is safe to implement `Send`+`Sync` for the report
// itself.
unsafe impl<C: ?Sized, O> Send for Report<C, O, SendSync> {}

// SAFETY: The `SendSync` marker indicates that all objects in the report are
// `Send`+`Sync`. Therefore it is safe to implement `Send`+`Sync` for the report
// itself.
unsafe impl<C: ?Sized, O> Sync for Report<C, O, SendSync> {}

impl<C: Sized, T> From<C> for Report<C, Mutable, T>
where
    C: markers::ObjectMarkerFor<T> + core::error::Error,
{
    #[track_caller]
    fn from(context: C) -> Self {
        Report::new(context)
    }
}

impl<C: Sized, T> From<C> for Report<C, Cloneable, T>
where
    C: markers::ObjectMarkerFor<T> + core::error::Error,
{
    #[track_caller]
    fn from(context: C) -> Self {
        Report::new(context).into_cloneable()
    }
}

impl<C: Sized, T> From<C> for Report<Dynamic, Mutable, T>
where
    C: markers::ObjectMarkerFor<T> + core::error::Error,
{
    #[track_caller]
    fn from(context: C) -> Self {
        Report::new(context).into_dynamic()
    }
}

impl<C: Sized, T> From<C> for Report<Dynamic, Cloneable, T>
where
    C: markers::ObjectMarkerFor<T> + core::error::Error,
{
    #[track_caller]
    fn from(context: C) -> Self {
        Report::new(context).into_dynamic().into_cloneable()
    }
}

impl<C: ?Sized, T> Clone for Report<C, Cloneable, T> {
    fn clone(&self) -> Self {
        self.as_ref().clone_arc()
    }
}

impl<C: ?Sized, O, T> core::fmt::Display for Report<C, O, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(&self.as_uncloneable_ref(), f)
    }
}

impl<C: ?Sized, O, T> core::fmt::Debug for Report<C, O, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Debug::fmt(&self.as_uncloneable_ref(), f)
    }
}

impl<C: ?Sized, O, T> Unpin for Report<C, O, T> {}

macro_rules! from_impls {
    ($(
        <
            $($param:ident),*
        >:
        $context1:ty => $context2:ty,
        $ownership1:ty => $ownership2:ty,
        $thread_safety1:ty => $thread_safety2:ty,
        [$($op:ident),*]
    ),* $(,)?) => {
        $(
            impl<$($param),*> From<Report<$context1, $ownership1, $thread_safety1>> for Report<$context2, $ownership2, $thread_safety2>
             {
                #[track_caller]
                fn from(report: Report<$context1, $ownership1, $thread_safety1>) -> Self {
                    report
                        $(.$op())*
                }
            }
        )*
    };
}

from_impls!(
    <C>: C => C, Mutable => Mutable, SendSync => Local, [into_local],
    <C>: C => C, Mutable => Cloneable, SendSync => SendSync, [into_cloneable],
    <C>: C => C, Mutable => Cloneable, SendSync => Local, [into_cloneable, into_local],
    <C>: C => C, Mutable => Cloneable, Local => Local, [into_cloneable],
    <C>: C => C, Cloneable => Cloneable, SendSync => Local, [into_local],
    <C>: C => Dynamic, Mutable => Mutable, SendSync => SendSync, [into_dynamic],
    <C>: C => Dynamic, Mutable => Mutable, SendSync => Local, [into_dynamic, into_local],
    <C>: C => Dynamic, Mutable => Mutable, Local => Local, [into_dynamic],
    <C>: C => Dynamic, Mutable => Cloneable, SendSync => SendSync, [into_dynamic, into_cloneable],
    <C>: C => Dynamic, Mutable => Cloneable, SendSync => Local, [into_dynamic, into_cloneable, into_local],
    <C>: C => Dynamic, Mutable => Cloneable, Local => Local, [into_dynamic, into_cloneable],
    <C>: C => Dynamic, Cloneable => Cloneable, SendSync => SendSync, [into_dynamic, into_cloneable],
    <C>: C => Dynamic, Cloneable => Cloneable, SendSync => Local, [into_dynamic, into_cloneable, into_local],
    <C>: C => Dynamic, Cloneable => Cloneable, Local => Local, [into_dynamic, into_cloneable],
    <>:  Dynamic => Dynamic, Mutable => Mutable, SendSync => Local, [into_local],
    <>:  Dynamic => Dynamic, Mutable => Cloneable, SendSync => SendSync, [into_cloneable],
    <>:  Dynamic => Dynamic, Mutable => Cloneable, SendSync => Local, [into_cloneable, into_local],
    <>:  Dynamic => Dynamic, Mutable => Cloneable, Local => Local, [into_cloneable],
    <>:  Dynamic => Dynamic, Cloneable => Cloneable, SendSync => Local, [into_local],
);

#[cfg(test)]
mod tests {
    use alloc::string::String;

    use super::*;

    #[allow(dead_code)]
    struct NonSend(*const ());
    static_assertions::assert_not_impl_any!(NonSend: Send, Sync);

    #[test]
    fn test_report_send_sync() {
        static_assertions::assert_impl_all!(Report<(), Mutable, SendSync>: Send, Sync);
        static_assertions::assert_impl_all!(Report<(), Cloneable, SendSync>: Send, Sync);
        static_assertions::assert_impl_all!(Report<String, Mutable, SendSync>: Send, Sync);
        static_assertions::assert_impl_all!(Report<String, Cloneable, SendSync>: Send, Sync);
        static_assertions::assert_impl_all!(Report<NonSend, Mutable, SendSync>: Send, Sync); // This still makes sense, since you won't actually be able to construct this report
        static_assertions::assert_impl_all!(Report<NonSend, Cloneable, SendSync>: Send, Sync);
        static_assertions::assert_impl_all!(Report<Dynamic, Mutable, SendSync>: Send, Sync);
        static_assertions::assert_impl_all!(Report<Dynamic, Cloneable, SendSync>: Send, Sync);

        static_assertions::assert_not_impl_any!(Report<(), Mutable, Local>: Send, Sync);
        static_assertions::assert_not_impl_any!(Report<(), Cloneable, Local>: Send, Sync);
        static_assertions::assert_not_impl_any!(Report<String, Mutable, Local>: Send, Sync);
        static_assertions::assert_not_impl_any!(Report<String, Cloneable, Local>: Send, Sync);
        static_assertions::assert_not_impl_any!(Report<NonSend, Mutable, Local>: Send, Sync);
        static_assertions::assert_not_impl_any!(Report<NonSend, Cloneable, Local>: Send, Sync);
        static_assertions::assert_not_impl_any!(Report<Dynamic, Mutable, Local>: Send, Sync);
        static_assertions::assert_not_impl_any!(Report<Dynamic, Cloneable, Local>: Send, Sync);
    }

    #[test]
    fn test_report_unpin() {
        static_assertions::assert_impl_all!(Report<(), Mutable, SendSync>: Unpin);
        static_assertions::assert_impl_all!(Report<(), Cloneable, SendSync>: Unpin);
        static_assertions::assert_impl_all!(Report<String, Mutable, SendSync>: Unpin);
        static_assertions::assert_impl_all!(Report<String, Cloneable, SendSync>: Unpin);
        static_assertions::assert_impl_all!(Report<NonSend, Mutable, SendSync>: Unpin); // This still makes sense, since you won't actually be able to construct this report
        static_assertions::assert_impl_all!(Report<NonSend, Cloneable, SendSync>: Unpin);
        static_assertions::assert_impl_all!(Report<Dynamic, Mutable, SendSync>: Unpin);
        static_assertions::assert_impl_all!(Report<Dynamic, Cloneable, SendSync>: Unpin);

        static_assertions::assert_impl_all!(Report<(), Mutable, Local>: Unpin);
        static_assertions::assert_impl_all!(Report<(), Cloneable, Local>: Unpin);
        static_assertions::assert_impl_all!(Report<String, Mutable, Local>: Unpin);
        static_assertions::assert_impl_all!(Report<String, Cloneable, Local>: Unpin);
        static_assertions::assert_impl_all!(Report<NonSend, Mutable, Local>: Unpin);
        static_assertions::assert_impl_all!(Report<NonSend, Cloneable, Local>: Unpin);
        static_assertions::assert_impl_all!(Report<Dynamic, Mutable, Local>: Unpin);
        static_assertions::assert_impl_all!(Report<Dynamic, Cloneable, Local>: Unpin);
    }

    #[test]
    fn test_report_copy_clone() {
        static_assertions::assert_not_impl_any!(Report<(), Mutable, SendSync>: Copy, Clone);
        static_assertions::assert_not_impl_any!(Report<(), Mutable, Local>: Copy, Clone);
        static_assertions::assert_not_impl_any!(Report<String, Mutable, SendSync>: Copy, Clone);
        static_assertions::assert_not_impl_any!(Report<String, Mutable, Local>: Copy, Clone);
        static_assertions::assert_not_impl_any!(Report<NonSend, Mutable, SendSync>: Copy, Clone);
        static_assertions::assert_not_impl_any!(Report<NonSend, Mutable, Local>: Copy, Clone);
        static_assertions::assert_not_impl_any!(Report<Dynamic, Mutable, SendSync>: Copy, Clone);
        static_assertions::assert_not_impl_any!(Report<Dynamic, Mutable, Local>: Copy, Clone);

        static_assertions::assert_impl_all!(Report<(), Cloneable, SendSync>: Clone);
        static_assertions::assert_impl_all!(Report<(), Cloneable, Local>: Clone);
        static_assertions::assert_impl_all!(Report<String, Cloneable, SendSync>: Clone);
        static_assertions::assert_impl_all!(Report<String, Cloneable, Local>: Clone);
        static_assertions::assert_impl_all!(Report<NonSend, Cloneable, SendSync>: Clone);
        static_assertions::assert_impl_all!(Report<NonSend, Cloneable, Local>: Clone);
        static_assertions::assert_impl_all!(Report<Dynamic, Cloneable, SendSync>: Clone);
        static_assertions::assert_impl_all!(Report<Dynamic, Cloneable, Local>: Clone);

        static_assertions::assert_not_impl_any!(Report<(), Cloneable, SendSync>: Copy);
        static_assertions::assert_not_impl_any!(Report<(), Cloneable, Local>: Copy);
        static_assertions::assert_not_impl_any!(Report<String, Cloneable, SendSync>: Copy);
        static_assertions::assert_not_impl_any!(Report<String, Cloneable, Local>: Copy);
        static_assertions::assert_not_impl_any!(Report<NonSend, Cloneable, SendSync>: Copy);
        static_assertions::assert_not_impl_any!(Report<NonSend, Cloneable, Local>: Copy);
        static_assertions::assert_not_impl_any!(Report<Dynamic, Cloneable, SendSync>: Copy);
        static_assertions::assert_not_impl_any!(Report<Dynamic, Cloneable, Local>: Copy);
    }
}