snafu_cli_debug/
lib.rs

1#![recursion_limit = "512"]
2
3extern crate proc_macro;
4use proc_macro::TokenStream;
5use syn::DeriveInput;
6
7#[proc_macro_derive(SnafuCliDebug)]
8pub fn derive_parser(input: TokenStream) -> TokenStream {
9    let ast: DeriveInput = syn::parse(input).unwrap();
10    let name = &ast.ident;
11
12    let impl_block = quote::quote! {
13        impl ::std::fmt::Debug for #name {
14            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
15                ::std::writeln!(f, "{}", self)?;
16
17                let mut e: &dyn ::std::error::Error = self;
18                while let Some(source) = e.source() {
19                    ::std::writeln!(f, "\tcause: {}", source)?;
20                    e = source;
21                }
22
23                if ::std::env::var("RUSTC_BACKTRACE").is_ok()
24                    || ::std::env::var("RUST_BACKTRACE").is_ok() {
25                    if let Some(backtrace) = ::snafu::ErrorCompat::backtrace(&self) {
26                        ::std::writeln!(f, "{}", backtrace)?;
27                    }
28                }
29
30                Ok(())
31            }
32        }
33    };
34
35    impl_block.into()
36}