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
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!("{}", ReportFormatter(&e));

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

                    any::request_value::<ExitCode>(&e)
                        .or_else(|| any::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 core::any;

            if let Some(bt) = any::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 original_messages = ChainCompat::new(self.0).map(ToString::to_string);
        let mut prev = original_messages.next();

        let mut cleaned_messages = vec![];
        let mut any_cleaned = false;
        let mut any_removed = false;
        for msg in original_messages {
            if let Some(mut prev) = prev {
                let cleaned = prev.trim_end_matches(&msg).trim_end().trim_end_matches(':');
                if cleaned.is_empty() {
                    any_removed = true;
                    // Do not add this to the output list
                } else if cleaned != prev {
                    any_cleaned = true;
                    let cleaned_len = cleaned.len();
                    prev.truncate(cleaned_len);
                    prev.push(' ');
                    prev.push(NOTE);
                    cleaned_messages.push(prev);
                } else {
                    cleaned_messages.push(prev);
                }
            }

            prev = Some(msg);
        }
        cleaned_messages.extend(prev);

        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"))
}

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

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