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
// Extra checks on nightly
// Make docs.rs generate better docs
//! A flexible, ergonomic, and inspectable error reporting library for Rust.
//!
//! <img src="https://github.com/rootcause-rs/rootcause/raw/main/rootcause.png" width="192">
//!
//! ## Overview
//!
//! This crate provides a structured way to represent and work with errors and
//! their context. The main goal is to enable you to build rich, structured
//! error reports that automatically capture not just what went wrong, but also
//! the context and supporting data at each step in the error's propagation.
//!
//! Unlike simple string-based error messages, rootcause allows you to attach
//! typed data to errors, build error chains, and inspect error contents
//! programmatically. This makes debugging easier while still providing
//! beautiful, human-readable error messages.
//!
//! ## Quick Example
//!
//! ```
//! use rootcause::prelude::{Report, ResultExt};
//!
//! fn read_config(path: &str) -> Result<String, Report> {
//! std::fs::read_to_string(path).context("Failed to read configuration file")?;
//! Ok(String::new())
//! }
//! ```
//!
//! For more examples, see the
//! [examples directory](https://github.com/rootcause-rs/rootcause/tree/main/examples)
//! in the repository. Start with
//! [`basic.rs`](https://github.com/rootcause-rs/rootcause/blob/main/examples/basic.rs)
//! for a hands-on introduction.
//!
//! ## Core Concepts
//!
//! At a high level, rootcause helps you build a tree of error reports. Each
//! node in the tree represents a step in the error's history - you start with a
//! root error, then add context and attachments as it propagates up through
//! your code.
//!
//! Most error reports are linear chains (just like anyhow), but the tree
//! structure lets you collect multiple related errors when needed.
//!
//! Each report has:
//! - A **context** (the error itself)
//! - Optional **attachments** (debugging data)
//! - Optional **children** (one or more errors that caused this error)
//!
//! For implementation details, see the [`rootcause-internals`] crate.
//!
//! [`rootcause-internals`]: rootcause_internals
//!
//! ## Ecosystem
//!
//! rootcause is designed to be lightweight and extensible. The core library
//! provides essential error handling, while optional companion crates add
//! specialized capabilities:
//!
//! - **[`rootcause-backtrace`]** - Automatic stack trace capture for debugging.
//! Install hooks to attach backtraces to all errors, or use the extension
//! trait to add them selectively.
//!
//! [`rootcause-backtrace`]: https://docs.rs/rootcause-backtrace
//!
//! ## Project Goals
//!
//! - **Ergonomic**: The `?` operator should work with most error types, even
//! ones not designed for this library.
//! - **Multi-failure tracking**: When operations fail multiple times (retry
//! attempts, batch processing, parallel execution), all failures should be
//! captured and preserved in a single report.
//! - **Inspectable**: The objects in a Report should not be glorified strings.
//! Inspecting and interacting with them should be easy.
//! - **Optionally typed**: Users should be able to (optionally) specify the
//! type of the context in the root node.
//! - **Beautiful**: The default formatting should look pleasant—and if it
//! doesn't match your style, the [hook system] lets you customize it.
//! - **Cloneable**: It should be possible to clone a [`Report`] when you need
//! to.
//! - **Self-documenting**: Reports should automatically capture information
//! (like locations) that might be useful in debugging. Additional
//! instrumentation like backtraces can be added via extension crates.
//! - **Customizable**: It should be possible to customize what data gets
//! collected, or how reports are formatted.
//! - **Lightweight**: [`Report`] has a pointer-sized representation, keeping
//! `Result<T, Report>` small and fast.
//!
//! [hook system]: crate::hooks
//!
//! ## Report Type Parameters
//!
//! The [`Report`] type is generic over three parameters, but for most users the
//! defaults work fine.
//!
//! **Most common usage:**
//!
//! ```
//! # use rootcause::prelude::*;
//! // Just use Report - works like anyhow::Error
//! fn might_fail() -> Result<(), Report> {
//! # Ok(())
//! }
//! ```
//!
//! **For type safety:**
//!
//! ```
//! # use rootcause::prelude::*;
//! #[derive(Debug)]
//! struct MyError;
//! # impl std::fmt::Display for MyError {
//! # fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//! # write!(f, "MyError")
//! # }
//! # }
//! # impl std::error::Error for MyError {}
//!
//! // Use Report<YourError> - works like error-stack
//! fn typed_error() -> Result<(), Report<MyError>> {
//! # Ok(())
//! }
//! ```
//!
//! **Need cloning or thread-local data?** The sections below explain the other
//! type parameters. Come back to these when you need them - they solve specific
//! problems you'll recognize when you encounter them.
//!
//! ---
//!
//! ## Type Parameters
//!
//! *This section covers the full type parameter system. Most users won't need
//! these variants immediately - but if you do need cloning, thread-local
//! errors, or want to understand what's possible, read on.*
//!
//! The [`Report`] type has three type parameters: `Report<Context, Ownership,
//! ThreadSafety>`. This section explains all the options and when you'd use
//! them.
//!
//! ### Context Type: Typed vs Dynamic Errors
//!
//! **Use `Report<Dynamic>`** (or just [`Report`]) when errors just need to
//! propagate. **Use `Report<YourErrorType>`** when callers need to pattern
//! match on specific error variants.
//!
//! **`Report<Dynamic>`** (or just [`Report`]) — Flexible, like [`anyhow`]
//!
//! Can hold any error type at the root. The `?` operator automatically converts
//! any error into a [`Report`]. Note: [`Dynamic`] is just a marker signaling
//! that the actual type is unknown. No actual instance of [`Dynamic`] is
//! stored. Converting between typed and dynamic reports is zero-cost.
//!
//! [`Dynamic`]: crate::markers::Dynamic
//!
//! ```
//! # use rootcause::prelude::*;
//! // Can return any error type
//! fn might_fail() -> Result<(), Report> {
//! # Ok(())
//! }
//! ```
//!
//! **`Report<YourErrorType>`** — Type-safe, like [`error-stack`]
//!
//! The root error must be `YourErrorType`, but child errors can be anything.
//! Callers can use `.current_context()` to pattern match on the typed error.
//!
//! ```
//! # use rootcause::prelude::*;
//! #[derive(Debug)]
//! struct ConfigError {/* ... */}
//! # impl std::fmt::Display for ConfigError {
//! # fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Ok(()) }
//! # }
//! # impl std::error::Error for ConfigError {}
//!
//! // This function MUST return ConfigError at the root
//! fn load_config() -> Result<(), Report<ConfigError>> {
//! # Ok(())
//! }
//! ```
//!
//! See [`examples/typed_reports.rs`] for a complete example with retry logic.
//!
//! [`examples/typed_reports.rs`]: https://github.com/rootcause-rs/rootcause/blob/main/examples/typed_reports.rs
//!
//! ### Ownership: Mutable vs Cloneable
//!
//! **Use the default ([`Mutable`])** when errors just propagate with `?`.
//! **Use [`.into_cloneable()`]** when you need to store errors in collections
//! or use them multiple times.
//!
//! [`.into_cloneable()`]: crate::report::owned::Report::into_cloneable
//!
//! **[`Mutable`]** (default) — Unique ownership
//!
//! You can add attachments and context to the root, but can't clone the whole
//! [`Report`]. Note: child reports are still cloneable internally (they use
//! `Arc`), but the top-level [`Report`] doesn't implement `Clone`. Start here,
//! then convert to [`Cloneable`] if you need to clone the entire tree.
//!
//! ```
//! # use rootcause::prelude::*;
//! let mut report: Report<String, markers::Mutable> = report!("error".to_string());
//! let report = report.attach("debug info"); // ✅ Can mutate root
//! // let cloned = report.clone(); // ❌ Can't clone whole report
//! ```
//!
//! **[`Cloneable`]** — Shared ownership
//!
//! The [`Report`] can be cloned cheaply (via `Arc`), but can't be mutated. Use
//! when you need to pass the same error to multiple places.
//!
//! ```
//! # use rootcause::prelude::*;
//! let report: Report<String, markers::Mutable> = report!("error".to_string());
//! let cloneable = report.into_cloneable();
//! let copy1 = cloneable.clone(); // ✅ Can clone
//! let copy2 = cloneable.clone(); // ✅ Cheap (Arc clone)
//! // let modified = copy1.attach("info"); // ❌ Can't mutate
//! ```
//!
//! See [`examples/retry_with_collection.rs`] for collection usage.
//!
//! [`examples/retry_with_collection.rs`]: https://github.com/rootcause-rs/rootcause/blob/main/examples/retry_with_collection.rs
//!
//! ### Thread Safety: SendSync vs Local
//!
//! **Use the default ([`SendSync`])** unless you get compiler errors about
//! `Send` or `Sync`. **Use [`Local`]** only when attaching `!Send` types like
//! `Rc` or `Cell`.
//!
//! **[`SendSync`]** (default) — Thread-safe
//!
//! The [`Report`] and all its contents are `Send + Sync`. Most types (String,
//! Vec, primitives) are already `Send + Sync`, so this just works.
//!
//! ```
//! # use rootcause::prelude::*;
//! let report: Report<String, markers::Mutable, markers::SendSync> = report!("error".to_string());
//!
//! # let thread_join_handle =
//! std::thread::spawn(move || {
//! println!("{}", report); // ✅ Can send to other threads
//! });
//! # thread_join_handle.join();
//! ```
//!
//! **[`Local`]** — Not thread-safe
//!
//! Use when your error contains thread-local data like `Rc`, raw pointers, or
//! other `!Send` types.
//!
//! ```
//! # use rootcause::prelude::*;
//! use std::rc::Rc;
//!
//! let data = Rc::new("thread-local".to_string());
//! let report: Report<Rc<String>, markers::Mutable, markers::Local> = report!(data);
//! // std::thread::spawn(move || { ... }); // ❌ Can't send to other threads
//! ```
//!
//! ## Converting Between Report Variants
//!
//! The variant lists above have been ordered so that it is always possible to
//! convert to an element further down the list using the [`From`] trait. This
//! also means you can use `?` when converting downwards. There are also more
//! specific methods (implemented using [`From`]) to help with type inference
//! and to more clearly communicate intent:
//!
//! - [`Report::into_dynamic`] converts from `Report<C, *, *>` to
//! `Report<Dynamic, *, *>`. See [`examples/error_coercion.rs`] for usage
//! patterns.
//! - [`Report::into_cloneable`] converts from `Report<*, Mutable, *>` to
//! `Report<*, Cloneable, *>`. See [`examples/retry_with_collection.rs`] for
//! storing multiple errors.
//! - [`Report::into_local`] converts from `Report<*, *, SendSync>` to
//! `Report<*, *, Local>`.
//!
//! On the other hand, it is generally harder to convert to an element further
//! up the list. Here are some of the ways to do it:
//!
//! - From `Report<Dynamic, *, *>` to `Report<SomeContextType, *, *>`:
//! - You can check if the type of the root node matches a specific type by
//! using [`Report::downcast_report`]. This will return either the requested
//! report type or the original report depending on whether the types match.
//! See [`examples/inspecting_errors.rs`] for downcasting techniques.
//! - From `Report<*, Cloneable, *>` to `Report<*, Mutable, *>`:
//! - You can check if the root node only has a single owner using
//! [`Report::try_into_mutable`]. This will check the number of references
//! to the root node and return either the requested report variant or the
//! original report depending on whether it is unique.
//! - You can allocate a new root node and set the current node as a child of
//! the new node. The new root node will be [`Mutable`]. One method for
//! allocating a new root node is to call [`Report::context`].
//! - From `Report<*, *, *>` to `Report<PreformattedContext, Mutable,
//! SendSync>`:
//! - You can preformat the entire [`Report`] using [`Report::preformat`].
//! This creates an entirely new [`Report`] that has the same structure and
//! will look the same as the current one if printed, but all contexts and
//! attachments will be replaced with a [`PreformattedContext`] version.
//!
//! [`examples/error_coercion.rs`]: https://github.com/rootcause-rs/rootcause/blob/main/examples/error_coercion.rs
//! [`examples/inspecting_errors.rs`]: https://github.com/rootcause-rs/rootcause/blob/main/examples/inspecting_errors.rs
//!
//! # Acknowledgements
//!
//! This library was inspired by and draws ideas from several existing error
//! handling libraries in the Rust ecosystem, including [`anyhow`],
//! [`thiserror`], and [`error-stack`].
//!
//! [`PreformattedContext`]: crate::preformatted::PreformattedContext
//! [`Mutable`]: crate::markers::Mutable
//! [`Cloneable`]: crate::markers::Cloneable
//! [`SendSync`]: crate::markers::SendSync
//! [`Local`]: crate::markers::Local
//! [`anyhow`]: https://docs.rs/anyhow
//! [`anyhow::Error`]: https://docs.rs/anyhow/latest/anyhow/struct.Error.html
//! [`thiserror`]: https://docs.rs/thiserror
//! [`error-stack`]: https://docs.rs/error-stack
//! [`error-stack::Report`]: https://docs.rs/error-stack/latest/error_stack/struct.Report.html
extern crate alloc;
pub use ;
/// A [`Result`](core::result::Result) type alias where the error is [`Report`].
///
/// This is a convenient shorthand for functions that return errors as
/// [`Report`]. The context type defaults to [`Dynamic`].
///
/// # Examples
///
/// ```
/// use rootcause::prelude::*;
///
/// fn might_fail() -> rootcause::Result<String> {
/// Ok("success".to_string())
/// }
/// ```
///
/// With a typed error:
///
/// ```
/// use rootcause::prelude::*;
///
/// #[derive(Debug)]
/// struct MyError;
/// # impl std::fmt::Display for MyError {
/// # fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// # write!(f, "MyError")
/// # }
/// # }
/// # impl std::error::Error for MyError {}
///
/// fn typed_error() -> rootcause::Result<String, MyError> {
/// Err(report!(MyError))
/// }
/// ```
///
/// [`Dynamic`]: crate::markers::Dynamic
pub type Result<T, C = Dynamic> = Result;
// Not public API. Referenced by macro-generated code and rootcause-backtrace.