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
use crate::ChainCompat;
use core::fmt;

#[cfg(all(feature = "std", feature = "rust_1_61"))]
use std::process::{ExitCode, Termination};

/// Opinionated solution to format an error in a user-friendly
/// way. Useful as the return type from `main` and test functions.
///
/// Most users will use the [`snafu::report`][] procedural macro
/// instead of directly using this type, but you can if you do not
/// wish to use the macro.
///
/// [`snafu::report`]: macro@crate::report
///
/// ## Rust 1.61 and up
///
/// Change the return type of the function to [`Report`][] and wrap
/// the body of your function with [`Report::capture`][].
///
/// ## Rust before 1.61
///
/// Use [`Report`][] as the error type inside of [`Result`][] and then
/// call either [`Report::capture_into_result`][] or
/// [`Report::from_error`][].
///
/// ## Nightly Rust
///
/// Enabling the [`unstable-try-trait` feature flag][try-ff] will
/// allow you to use the `?` operator directly:
///
/// ```rust
/// use snafu::{prelude::*, Report};
///
/// # #[cfg(all(feature = "unstable-try-trait", feature = "rust_1_61"))]
/// fn main() -> Report<PlaceholderError> {
///     let _v = may_fail_with_placeholder_error()?;
///
///     Report::ok()
/// }
/// # #[cfg(not(all(feature = "unstable-try-trait", feature = "rust_1_61")))] fn main() {}
/// # #[derive(Debug, Snafu)]
/// # struct PlaceholderError;
/// # fn may_fail_with_placeholder_error() -> Result<u8, PlaceholderError> { Ok(42) }
/// ```
///
/// [try-ff]: crate::guide::feature_flags#unstable-try-trait
///
/// ## Interaction with the Provider API
///
/// If you return a [`Report`][] from your function and enable the
/// [`unstable-provider-api` feature flag][provider-ff], additional
/// capabilities will be added:
///
/// 1. If provided, a [`Backtrace`][] will be included in the output.
/// 1. If provided, a [`ExitCode`][] will be used as the return value.
///
/// [provider-ff]: crate::guide::feature_flags#unstable-provider-api
/// [`Backtrace`]: crate::Backtrace
/// [`ExitCode`]: std::process::ExitCode
///
/// ## Stability of the output
///
/// The exact content and format of a displayed `Report` are not
/// stable, but this type strives to print the error and as much
/// user-relevant information in an easily-consumable manner
pub struct Report<E>(Result<(), E>);

impl<E> Report<E> {
    /// Convert an error into a [`Report`][].
    ///
    /// Recommended if you support versions of Rust before 1.61.
    ///
    /// ```rust
    /// use snafu::{prelude::*, Report};
    ///
    /// #[derive(Debug, Snafu)]
    /// struct PlaceholderError;
    ///
    /// fn main() -> Result<(), Report<PlaceholderError>> {
    ///     let _v = may_fail_with_placeholder_error().map_err(Report::from_error)?;
    ///     Ok(())
    /// }
    ///
    /// fn may_fail_with_placeholder_error() -> Result<u8, PlaceholderError> {
    ///     Ok(42)
    /// }
    /// ```
    pub fn from_error(error: E) -> Self {
        Self(Err(error))
    }

    /// Executes a closure that returns a [`Result`][], converting the
    /// error variant into a [`Report`][].
    ///
    /// Recommended if you support versions of Rust before 1.61.
    ///
    /// ```rust
    /// use snafu::{prelude::*, Report};
    ///
    /// #[derive(Debug, Snafu)]
    /// struct PlaceholderError;
    ///
    /// fn main() -> Result<(), Report<PlaceholderError>> {
    ///     Report::capture_into_result(|| {
    ///         let _v = may_fail_with_placeholder_error()?;
    ///
    ///         Ok(())
    ///     })
    /// }
    ///
    /// fn may_fail_with_placeholder_error() -> Result<u8, PlaceholderError> {
    ///     Ok(42)
    /// }
    /// ```
    pub fn capture_into_result<T>(body: impl FnOnce() -> Result<T, E>) -> Result<T, Self> {
        body().map_err(Self::from_error)
    }

    /// Executes a closure that returns a [`Result`][], converting any
    /// error to a [`Report`][].
    ///
    /// Recommended if you only support Rust version 1.61 or above.
    ///
    /// ```rust
    /// use snafu::{prelude::*, Report};
    ///
    /// #[derive(Debug, Snafu)]
    /// struct PlaceholderError;
    ///
    /// # #[cfg(feature = "rust_1_61")]
    /// fn main() -> Report<PlaceholderError> {
    ///     Report::capture(|| {
    ///         let _v = may_fail_with_placeholder_error()?;
    ///
    ///         Ok(())
    ///     })
    /// }
    /// # #[cfg(not(feature = "rust_1_61"))] fn main() {}
    ///
    /// fn may_fail_with_placeholder_error() -> Result<u8, PlaceholderError> {
    ///     Ok(42)
    /// }
    /// ```
    pub fn capture(body: impl FnOnce() -> Result<(), E>) -> Self {
        Self(body())
    }

    /// A [`Report`][] that indicates no error occurred.
    pub const fn ok() -> Self {
        Self(Ok(()))
    }
}

impl<E> From<Result<(), E>> for Report<E> {
    fn from(other: Result<(), E>) -> Self {
        Self(other)
    }
}

impl<E> fmt::Debug for Report<E>
where
    E: crate::Error,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl<E> fmt::Display for Report<E>
where
    E: crate::Error,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            Err(e) => fmt::Display::fmt(&ReportFormatter(e), f),
            _ => Ok(()),
        }
    }
}

#[cfg(all(feature = "std", feature = "rust_1_61"))]
impl<E> Termination for Report<E>
where
    E: crate::Error,
{
    fn report(self) -> ExitCode {
        match self.0 {
            Ok(()) => ExitCode::SUCCESS,
            Err(e) => {
                eprintln!("Error: {}", ReportFormatter(&e));

                #[cfg(feature = "unstable-provider-api")]
                {
                    use crate::error;

                    // Broken. https://github.com/rust-lang/rust/pull/114973
                    // error::request_value::<ExitCode>(&e)
                    //     .or_else(|| error::request_ref::<ExitCode>(&e).copied())

                    error::request_ref::<ExitCode>(&e)
                        .copied()
                        .unwrap_or(ExitCode::FAILURE)
                }

                #[cfg(not(feature = "unstable-provider-api"))]
                {
                    ExitCode::FAILURE
                }
            }
        }
    }
}

#[cfg(feature = "unstable-try-trait")]
impl<T, E> core::ops::FromResidual<Result<T, E>> for Report<E> {
    fn from_residual(residual: Result<T, E>) -> Self {
        Self(residual.map(drop))
    }
}

struct ReportFormatter<'a>(&'a dyn crate::Error);

impl<'a> fmt::Display for ReportFormatter<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[cfg(feature = "std")]
        {
            if trace_cleaning_enabled() {
                self.cleaned_error_trace(f)?;
            } else {
                self.error_trace(f)?;
            }
        }

        #[cfg(not(feature = "std"))]
        {
            self.error_trace(f)?;
        }

        #[cfg(feature = "unstable-provider-api")]
        {
            use crate::error;

            if let Some(bt) = error::request_ref::<crate::Backtrace>(self.0) {
                writeln!(f, "\nBacktrace:\n{}", bt)?;
            }
        }

        Ok(())
    }
}

impl<'a> ReportFormatter<'a> {
    fn error_trace(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        writeln!(f, "{}", self.0)?;

        let sources = ChainCompat::new(self.0).skip(1);
        let plurality = sources.clone().take(2).count();

        match plurality {
            0 => {}
            1 => writeln!(f, "\nCaused by this error:")?,
            _ => writeln!(f, "\nCaused by these errors (recent errors listed first):")?,
        }

        for (i, source) in sources.enumerate() {
            // Let's use 1-based indexing for presentation
            let i = i + 1;
            writeln!(f, "{:3}: {}", i, source)?;
        }

        Ok(())
    }

    #[cfg(feature = "std")]
    fn cleaned_error_trace(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        const NOTE: char = '*';

        let mut any_cleaned = false;
        let mut any_removed = false;
        let cleaned_messages: Vec<_> = CleanedErrorText::new(self.0)
            .flat_map(|(_, mut msg, cleaned)| {
                if msg.is_empty() {
                    any_removed = true;
                    None
                } else {
                    if cleaned {
                        any_cleaned = true;
                        msg.push(' ');
                        msg.push(NOTE);
                    }
                    Some(msg)
                }
            })
            .collect();

        let mut visible_messages = cleaned_messages.iter();

        let head = match visible_messages.next() {
            Some(v) => v,
            None => return Ok(()),
        };

        writeln!(f, "{}", head)?;

        match cleaned_messages.len() {
            0 | 1 => {}
            2 => writeln!(f, "\nCaused by this error:")?,
            _ => writeln!(f, "\nCaused by these errors (recent errors listed first):")?,
        }

        for (i, msg) in visible_messages.enumerate() {
            // Let's use 1-based indexing for presentation
            let i = i + 1;
            writeln!(f, "{:3}: {}", i, msg)?;
        }

        if any_cleaned || any_removed {
            write!(f, "\nNOTE: ")?;

            if any_cleaned {
                write!(
                    f,
                    "Some redundant information has been removed from the lines marked with {}. ",
                    NOTE,
                )?;
            } else {
                write!(f, "Some redundant information has been removed. ")?;
            }

            writeln!(
                f,
                "Set {}=1 to disable this behavior.",
                SNAFU_RAW_ERROR_MESSAGES,
            )?;
        }

        Ok(())
    }
}

#[cfg(feature = "std")]
const SNAFU_RAW_ERROR_MESSAGES: &str = "SNAFU_RAW_ERROR_MESSAGES";

#[cfg(feature = "std")]
fn trace_cleaning_enabled() -> bool {
    use crate::once_bool::OnceBool;
    use std::env;

    static DISABLED: OnceBool = OnceBool::new();
    !DISABLED.get(|| env::var_os(SNAFU_RAW_ERROR_MESSAGES).map_or(false, |v| v == "1"))
}

/// An iterator over an Error and its sources that removes duplicated
/// text from the error display strings.
///
/// It's common for errors with a `source` to have a `Display`
/// implementation that includes their source text as well:
///
/// ```text
/// Outer error text: Middle error text: Inner error text
/// ```
///
/// This works for smaller errors without much detail, but can be
/// annoying when trying to format the error in a more structured way,
/// such as line-by-line:
///
/// ```text
/// 1. Outer error text: Middle error text: Inner error text
/// 2. Middle error text: Inner error text
/// 3. Inner error text
/// ```
///
/// This iterator compares each pair of errors in the source chain,
/// removing the source error's text from the containing error's text:
///
/// ```text
/// 1. Outer error text
/// 2. Middle error text
/// 3. Inner error text
/// ```
#[cfg(feature = "std")]
pub struct CleanedErrorText<'a>(Option<CleanedErrorTextStep<'a>>);

#[cfg(feature = "std")]
impl<'a> CleanedErrorText<'a> {
    /// Constructs the iterator.
    pub fn new(error: &'a dyn crate::Error) -> Self {
        Self(Some(CleanedErrorTextStep::new(error)))
    }
}

#[cfg(feature = "std")]
impl<'a> Iterator for CleanedErrorText<'a> {
    /// The original error, the display string and if it has been cleaned
    type Item = (&'a dyn crate::Error, String, bool);

    fn next(&mut self) -> Option<Self::Item> {
        use std::mem;

        let mut step = self.0.take()?;
        let mut error_text = mem::take(&mut step.error_text);

        match step.error.source() {
            Some(next_error) => {
                let next_error_text = next_error.to_string();

                let cleaned_text = error_text
                    .trim_end_matches(&next_error_text)
                    .trim_end()
                    .trim_end_matches(':');
                let cleaned = cleaned_text.len() != error_text.len();
                let cleaned_len = cleaned_text.len();
                error_text.truncate(cleaned_len);

                self.0 = Some(CleanedErrorTextStep {
                    error: next_error,
                    error_text: next_error_text,
                });

                Some((step.error, error_text, cleaned))
            }
            None => Some((step.error, error_text, false)),
        }
    }
}

#[cfg(feature = "std")]
struct CleanedErrorTextStep<'a> {
    error: &'a dyn crate::Error,
    error_text: String,
}

#[cfg(feature = "std")]
impl<'a> CleanedErrorTextStep<'a> {
    fn new(error: &'a dyn crate::Error) -> Self {
        let error_text = error.to_string();
        Self { error, error_text }
    }
}

#[doc(hidden)]
pub trait __InternalExtractErrorType {
    type Err;
}

impl<T, E> __InternalExtractErrorType for core::result::Result<T, E> {
    type Err = E;
}