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
//! Context formatting hooks for customizing how error messages are displayed.
//!
//! Control how the main error type in each report appears:
//! - Custom error descriptions for your types
//! - Better Display output for Debug-only types
//! - Simplify noisy or complex error messages
//! - Hide sensitive details while keeping useful information
//!
//! By installing hooks for specific error types, you can customize how they
//! appear in reports without changing the error type itself.
//!
//! > **Note:** Hooks format a type globally across ALL errors. To control
//! > formatting for a single context, use [`context_custom()`] with a handler
//! > instead (see [`examples/custom_handler.rs`]).
//!
//! [`context_custom()`]: crate::Report::context_custom
//! [`examples/custom_handler.rs`]: https://github.com/rootcause-rs/rootcause/blob/main/examples/custom_handler.rs
//!
//! # Key Components
//!
//! - [`ContextFormatterHook`] - Trait for implementing custom context
//!   formatting
//!
//! # Examples
//!
//! ## Custom formatting for your own types
//!
//! ```
//! use core::fmt;
//!
//! use rootcause::{
//!     ReportRef,
//!     hooks::{Hooks, context_formatter::ContextFormatterHook},
//!     markers::{Local, Uncloneable},
//! };
//!
//! struct DatabaseError {
//!     table: String,
//!     operation: String,
//!     details: String,
//! }
//!
//! struct DatabaseErrorFormatter;
//!
//! impl ContextFormatterHook<DatabaseError> for DatabaseErrorFormatter {
//!     fn display(
//!         &self,
//!         report: ReportRef<'_, DatabaseError, Uncloneable, Local>,
//!         f: &mut fmt::Formatter<'_>,
//!     ) -> fmt::Result {
//!         let err = report.current_context();
//!         write!(
//!             f,
//!             "Database {} failed on table '{}': {}",
//!             err.operation, err.table, err.details
//!         )
//!     }
//! }
//!
//! // Install the custom formatter globally
//! Hooks::new()
//!     .context_formatter::<DatabaseError, _>(DatabaseErrorFormatter)
//!     .install()
//!     .expect("failed to install hooks");
//! ```
//!
//! ## Simplifying complex or Debug-only types
//!
//! When using types that only implement [`Debug`](core::fmt::Debug) (not
//! [`Display`](core::fmt::Display)), reports show "Context of type `TypeName`"
//! by default (see [`crate::handlers::Debug`]). Use a context formatter to
//! provide simplified, user-friendly output:
//!
//! ```
//! use core::fmt;
//!
//! use rootcause::{
//!     ReportRef,
//!     hooks::{Hooks, context_formatter::ContextFormatterHook},
//!     markers::{Local, Uncloneable},
//!     prelude::*,
//! };
//!
//! // External type you can't modify (only has Debug, not Display)
//! #[derive(Debug)]
//! struct InternalState {
//!     connection_count: usize,
//!     pending_requests: usize,
//! }
//!
//! struct InternalStateFormatter;
//!
//! impl ContextFormatterHook<InternalState> for InternalStateFormatter {
//!     fn display(
//!         &self,
//!         report: ReportRef<'_, InternalState, Uncloneable, Local>,
//!         f: &mut fmt::Formatter<'_>,
//!     ) -> fmt::Result {
//!         let state = report.current_context();
//!         write!(
//!             f,
//!             "System overloaded: {} connections, {} pending",
//!             state.connection_count, state.pending_requests
//!         )
//!     }
//! }
//!
//! // Without this hook, would show "Context of type `InternalState`"
//! Hooks::new()
//!     .context_formatter::<InternalState, _>(InternalStateFormatter)
//!     .install()
//!     .expect("failed to install hooks");
//! ```

use alloc::{boxed::Box, fmt};
use core::{any::TypeId, marker::PhantomData};

use hashbrown::HashMap;
use rootcause_internals::handlers::{ContextFormattingStyle, FormattingFunction};

use crate::{
    ReportRef,
    hooks::{HookData, use_hooks},
    markers::{Dynamic, Local, Uncloneable},
    preformatted::PreformattedContext,
};

#[derive(Default)]
pub(crate) struct HookMap {
    /// # Safety Invariant
    ///
    /// The hook stored under `TypeId::of::<C>()` is guaranteed to be an
    /// instance of the type `Hook<C, H>`.
    map: HashMap<TypeId, Box<dyn StoredHook>, rustc_hash::FxBuildHasher>,
}

impl core::fmt::Debug for HookMap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.map.values().fmt(f)
    }
}

impl HookMap {
    /// Retrieves the formatter hook for the specified context
    /// type.
    ///
    /// The returned hook is guaranteed to be an instance of type `Hook<C, H>`,
    /// where `TypeId::of::<C>() == type_id`.
    fn get(&self, type_id: TypeId) -> Option<&dyn StoredHook> {
        Some(&**self.map.get(&type_id)?)
    }

    pub(crate) fn insert<C, H>(&mut self, hook: H)
    where
        C: 'static,
        H: ContextFormatterHook<C>,
    {
        let hook: Hook<C, H> = Hook {
            hook,
            _hooked_type: PhantomData,
        };
        let hook: Box<Hook<C, H>> = Box::new(hook);
        // We must uphold the safety invariant of HookMap.
        //
        // The safety invariant requires that the hook stored under
        // `TypeId::of::<C>()` is always of type `Hook<C, H>`.
        //
        // However this is exactly what we are doing here,
        // so the invariant is upheld.
        self.map.insert(TypeId::of::<C>(), hook);
    }
}

struct Hook<C, H>
where
    C: 'static,
{
    hook: H,
    _hooked_type: PhantomData<fn(C) -> C>,
}

impl<C, H> core::fmt::Debug for Hook<C, H>
where
    C: 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "ContextFormattingHook<{}, {}>",
            core::any::type_name::<C>(),
            core::any::type_name::<H>(),
        )
    }
}

/// Trait for untyped context formatter hooks.
///
/// This trait is guaranteed to only be implemented for [`Hook<C, H>`].
trait StoredHook: 'static + Send + Sync + core::fmt::Debug {
    /// Formats the context using Display formatting.
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    ///
    /// 1. The type `C` stored in the context matches the `C` from type `Hook<C,
    ///    H>` this is implemented for.
    unsafe fn display(
        &self,
        report: ReportRef<'_, Dynamic, Uncloneable, Local>,
        formatter: &mut fmt::Formatter<'_>,
    ) -> fmt::Result;

    /// Formats the context using Debug formatting.
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    ///
    /// 1. The type `C` stored in the context matches the `C` from type `Hook<C,
    ///    H>` this is implemented for.
    unsafe fn debug(
        &self,
        report: ReportRef<'_, Dynamic, Uncloneable, Local>,
        formatter: &mut fmt::Formatter<'_>,
    ) -> fmt::Result;

    fn display_preformatted(
        &self,
        report: ReportRef<'_, PreformattedContext, Uncloneable, Local>,
        formatter: &mut fmt::Formatter<'_>,
    ) -> fmt::Result;

    fn debug_preformatted(
        &self,
        report: ReportRef<'_, PreformattedContext, Uncloneable, Local>,
        formatter: &mut fmt::Formatter<'_>,
    ) -> fmt::Result;

    fn preferred_context_formatting_style(
        &self,
        report: ReportRef<'_, Dynamic, Uncloneable, Local>,
        report_formatting_function: FormattingFunction,
    ) -> ContextFormattingStyle;
}

/// Trait for customizing how contexts of a specific type are formatted in error
/// reports.
///
/// This trait allows you to override the default formatting behavior for
/// contexts (the main error types) of type `C`. You can customize both Display
/// and Debug formatting, handle preformatted contexts, and specify preferred
/// formatting styles.
///
/// # Type Parameters
///
/// * `C` - The context type that this formatter handles
///
/// # Default Implementations
///
/// All methods have default implementations that delegate to the unhooked
/// formatting, so you only need to implement the methods for the formatting you
/// want to customize.
///
/// # Examples
///
/// Custom Display formatting for a business logic error:
/// ```
/// use core::fmt;
///
/// use rootcause::{
///     ReportRef,
///     hooks::context_formatter::ContextFormatterHook,
///     markers::{Local, Uncloneable},
/// };
///
/// struct ValidationError {
///     field: String,
///     rule: String,
///     value: String,
/// }
///
/// struct ValidationErrorFormatter;
///
/// impl ContextFormatterHook<ValidationError> for ValidationErrorFormatter {
///     fn display(
///         &self,
///         report: ReportRef<'_, ValidationError, Uncloneable, Local>,
///         f: &mut fmt::Formatter<'_>,
///     ) -> fmt::Result {
///         let err = report.current_context();
///         write!(
///             f,
///             "Validation failed for field '{}': value '{}' violates rule '{}'",
///             err.field, err.value, err.rule
///         )
///     }
/// }
/// ```
pub trait ContextFormatterHook<C>: 'static + Send + Sync {
    /// Formats the context using Display formatting.
    ///
    /// This method is called when the context needs to be displayed in a
    /// user-friendly format. The default implementation delegates to the
    /// context's unhooked Display formatting.
    ///
    /// # Arguments
    ///
    /// * `report` - Reference to the report containing the context to format
    /// * `formatter` - The formatter to write output to
    ///
    /// # Examples
    ///
    /// ```
    /// use core::fmt;
    ///
    /// use rootcause::{
    ///     ReportRef,
    ///     hooks::context_formatter::ContextFormatterHook,
    ///     markers::{Local, Uncloneable},
    /// };
    ///
    /// struct HttpError {
    ///     status: u16,
    ///     message: String,
    /// }
    ///
    /// struct HttpErrorFormatter;
    ///
    /// impl ContextFormatterHook<HttpError> for HttpErrorFormatter {
    ///     fn display(
    ///         &self,
    ///         report: ReportRef<'_, HttpError, Uncloneable, Local>,
    ///         f: &mut fmt::Formatter<'_>,
    ///     ) -> fmt::Result {
    ///         let err = report.current_context();
    ///         write!(f, "HTTP {} - {}", err.status, err.message)
    ///     }
    /// }
    /// ```
    fn display(
        &self,
        report: ReportRef<'_, C, Uncloneable, Local>,
        formatter: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        fmt::Display::fmt(&report.format_current_context_unhooked(), formatter)
    }

    /// Formats a preformatted context using Display formatting.
    ///
    /// This method handles contexts that have been preformatted (typically done
    /// using [`ReportRef::preformat`] for performance or consistency reasons).
    /// The default implementation delegates to the context's unhooked
    /// Display formatting.
    ///
    /// # Arguments
    ///
    /// * `report` - Reference to the report containing the preformatted context
    /// * `formatter` - The formatter to write output to
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{
    ///     ReportRef,
    ///     hooks::context_formatter::ContextFormatterHook,
    ///     markers::{Local, Uncloneable},
    ///     preformatted::PreformattedContext,
    /// };
    ///
    /// struct MyFormatter;
    /// impl ContextFormatterHook<String> for MyFormatter {
    ///     fn display_preformatted(
    ///         &self,
    ///         report: ReportRef<'_, PreformattedContext, Uncloneable, Local>,
    ///         f: &mut core::fmt::Formatter<'_>,
    ///     ) -> core::fmt::Result {
    ///         write!(
    ///             f,
    ///             "[Preformatted] {}",
    ///             report.format_current_context_unhooked()
    ///         )
    ///     }
    /// }
    /// ```
    fn display_preformatted(
        &self,
        report: ReportRef<'_, PreformattedContext, Uncloneable, Local>,
        formatter: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        fmt::Display::fmt(&report.format_current_context_unhooked(), formatter)
    }

    /// Formats the context using Debug formatting.
    ///
    /// This method is called when the context needs to be displayed in a
    /// debug-friendly format (typically more verbose and detailed). The default
    /// implementation delegates to the context's unhooked Debug formatting.
    ///
    /// # Arguments
    ///
    /// * `report` - Reference to the report containing the context to format
    /// * `formatter` - The formatter to write output to
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{
    ///     ReportRef,
    ///     hooks::context_formatter::ContextFormatterHook,
    ///     markers::{Local, Uncloneable},
    /// };
    ///
    /// struct MyFormatter;
    /// impl ContextFormatterHook<String> for MyFormatter {
    ///     fn debug(
    ///         &self,
    ///         report: ReportRef<'_, String, Uncloneable, Local>,
    ///         f: &mut core::fmt::Formatter<'_>,
    ///     ) -> core::fmt::Result {
    ///         write!(f, "Debug: {:?}", report.current_context())
    ///     }
    /// }
    /// ```
    fn debug(
        &self,
        report: ReportRef<'_, C, Uncloneable, Local>,
        formatter: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        fmt::Debug::fmt(&report.format_current_context_unhooked(), formatter)
    }

    /// Formats a preformatted context using Debug formatting.
    ///
    /// This method handles preformatted contexts when debug formatting is
    /// requested. The default implementation delegates to the context's
    /// unhooked Debug formatting.
    ///
    /// # Arguments
    ///
    /// * `report` - Reference to the report containing the preformatted context
    /// * `formatter` - The formatter to write output to
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{
    ///     ReportRef,
    ///     hooks::context_formatter::ContextFormatterHook,
    ///     markers::{Local, Uncloneable},
    ///     preformatted::PreformattedContext,
    /// };
    ///
    /// struct MyFormatter;
    /// impl ContextFormatterHook<String> for MyFormatter {
    ///     fn debug_preformatted(
    ///         &self,
    ///         report: ReportRef<'_, PreformattedContext, Uncloneable, Local>,
    ///         f: &mut core::fmt::Formatter<'_>,
    ///     ) -> core::fmt::Result {
    ///         write!(
    ///             f,
    ///             "[Preformatted Debug] {:?}",
    ///             report.format_current_context_unhooked()
    ///         )
    ///     }
    /// }
    /// ```
    fn debug_preformatted(
        &self,
        report: ReportRef<'_, PreformattedContext, Uncloneable, Local>,
        formatter: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        fmt::Debug::fmt(&report.format_current_context_unhooked(), formatter)
    }

    /// Determines the preferred formatting style for this context.
    ///
    /// This method allows the formatter to specify how the context should be
    /// presented, including which formatting function should be used. The
    /// default implementation delegates to the context's unhooked
    /// preference.
    ///
    /// # Arguments
    ///
    /// * `report` - Reference to the report (as [`Dynamic`] as it can be either
    ///   a `C` or a [`PreformattedContext`])
    /// * `report_formatting_function` - Whether the overall report uses Display
    ///   or Debug formatting
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{
    ///     ReportRef,
    ///     handlers::{ContextFormattingStyle, FormattingFunction},
    ///     hooks::context_formatter::ContextFormatterHook,
    ///     markers::{Dynamic, Local, Uncloneable},
    /// };
    ///
    /// struct MyFormatter;
    /// impl ContextFormatterHook<String> for MyFormatter {
    ///     fn preferred_context_formatting_style(
    ///         &self,
    ///         _report: ReportRef<'_, Dynamic, Uncloneable, Local>,
    ///         _function: FormattingFunction,
    ///     ) -> ContextFormattingStyle {
    ///         ContextFormattingStyle {
    ///             function: FormattingFunction::Display,
    ///             follow_source: false,
    ///             follow_source_depth: None,
    ///         }
    ///     }
    /// }
    /// ```
    fn preferred_context_formatting_style(
        &self,
        report: ReportRef<'_, Dynamic, Uncloneable, Local>,
        report_formatting_function: FormattingFunction,
    ) -> ContextFormattingStyle {
        report.preferred_context_formatting_style_unhooked(report_formatting_function)
    }
}

impl<C, H> StoredHook for Hook<C, H>
where
    C: 'static,
    H: ContextFormatterHook<C>,
{
    unsafe fn display(
        &self,
        report: ReportRef<'_, Dynamic, Uncloneable, Local>,
        formatter: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        // SAFETY:
        // 1. Guaranteed by the caller
        let report = unsafe { report.downcast_report_unchecked::<C>() };
        self.hook.display(report, formatter)
    }

    unsafe fn debug(
        &self,
        report: ReportRef<'_, Dynamic, Uncloneable, Local>,
        formatter: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        // SAFETY:
        // 1. Guaranteed by the caller
        let report = unsafe { report.downcast_report_unchecked::<C>() };
        self.hook.debug(report, formatter)
    }

    fn display_preformatted(
        &self,
        report: ReportRef<'_, PreformattedContext, Uncloneable, Local>,
        formatter: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        self.hook.display_preformatted(report, formatter)
    }

    fn debug_preformatted(
        &self,
        report: ReportRef<'_, PreformattedContext, Uncloneable, Local>,
        formatter: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        self.hook.debug_preformatted(report, formatter)
    }

    fn preferred_context_formatting_style(
        &self,
        report: ReportRef<'_, Dynamic, Uncloneable, Local>,
        report_formatting_function: FormattingFunction,
    ) -> ContextFormattingStyle {
        self.hook
            .preferred_context_formatting_style(report, report_formatting_function)
    }
}

pub(crate) fn display_context(
    report: ReportRef<'_, Dynamic, Uncloneable, Local>,
    formatter: &mut fmt::Formatter<'_>,
) -> fmt::Result {
    use_hooks(|hook_data: Option<&HookData>| {
        if let Some(hook_data) = hook_data {
            let context_formatters: &HookMap = &hook_data.context_formatters;
            if let Some(report) = report.downcast_report::<PreformattedContext>()
                && let Some(hook) =
                    context_formatters.get(report.current_context().original_type_id())
            {
                return hook.display_preformatted(report, formatter);
            }

            if let Some(hook) = context_formatters.get(report.current_context_type_id()) {
                // SAFETY:
                // 1. The call to `get` guarantees that the returned hook is of type `Hook<C,
                //    H>`, and `TypeId::of<C>() == report.current_context_type_id()`. Therefore
                //    the type `C` stored in the context matches the `C` from type `Hook<C, H>`.
                unsafe {
                    // @add-unsafe-context: StoredHook
                    return hook.display(report, formatter);
                }
            }
        }
        fmt::Display::fmt(&report.format_current_context_unhooked(), formatter)
    })
}

pub(crate) fn debug_context(
    report: ReportRef<'_, Dynamic, Uncloneable, Local>,
    formatter: &mut fmt::Formatter<'_>,
) -> fmt::Result {
    use_hooks(|hook_data: Option<&HookData>| {
        if let Some(hook_data) = hook_data {
            let context_formatters: &HookMap = &hook_data.context_formatters;
            if let Some(report) = report.downcast_report::<PreformattedContext>()
                && let Some(hook) =
                    context_formatters.get(report.current_context().original_type_id())
            {
                return hook.debug_preformatted(report, formatter);
            }

            if let Some(hook) = context_formatters.get(report.current_context_type_id()) {
                // SAFETY:
                // 1. The call to `get` guarantees that the returned hook is of type `Hook<C,
                //    H>`, and `TypeId::of<C>() == report.current_context_type_id()`. Therefore
                //    the type `C` stored in the context matches the `C` from type `Hook<C, H>`.
                unsafe {
                    // @add-unsafe-context: StoredHook
                    return hook.debug(report, formatter);
                }
            }
        }
        fmt::Debug::fmt(&report.format_current_context_unhooked(), formatter)
    })
}

/// # 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
pub(crate) fn get_preferred_context_formatting_style(
    report: ReportRef<'_, Dynamic, Uncloneable, Local>,
    report_formatting_function: FormattingFunction,
) -> ContextFormattingStyle {
    use_hooks(|hook_data: Option<&HookData>| {
        if let Some(hook_data) = hook_data {
            let context_formatters: &HookMap = &hook_data.context_formatters;

            if let Some(current_context) = report.downcast_current_context::<PreformattedContext>()
                && let Some(hook) = context_formatters.get(current_context.original_type_id())
            {
                return hook.preferred_context_formatting_style(report, report_formatting_function);
            }

            if let Some(hook) = context_formatters.get(report.current_context_type_id()) {
                return hook.preferred_context_formatting_style(report, report_formatting_function);
            }
        }
        report.preferred_context_formatting_style_unhooked(report_formatting_function)
    })
}