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
//! # `err-derive`
//!
//! ## Deriving error causes / sources
//!
//! Add an `#[error(cause)]` attribute to the field:
//!
//! ```
//! #[macro_use]
//! extern crate err_derive;
//!
//! use std::io;
//!
//! /// `MyError::source` will return a reference to the `io_error` field
//! #[derive(Debug, Error)]
//! #[error(display = "An error occurred.")]
//! struct MyError {
//!     #[error(cause)]
//!     io_error: io::Error,
//! }
//! #
//! # fn main() {}
//! ```
//!
//! ## Formatting fields
//!
//! ```rust
//! #[macro_use]
//! extern crate err_derive;
//!
//! use std::path::PathBuf;
//!
//! #[derive(Debug, Error)]
//! pub enum FormatError {
//!     #[error(display = "invalid header (expected: {:?}, got: {:?})", expected, found)]
//!     InvalidHeader {
//!         expected: String,
//!         found: String,
//!     },
//!     // Note that tuple fields need to be prefixed with `_`
//!     #[error(display = "missing attribute: {:?}", _0)]
//!     MissingAttribute(String),
//!
//! }
//!
//! #[derive(Debug, Error)]
//! pub enum LoadingError {
//!     #[error(display = "could not decode file")]
//!     FormatError(#[error(cause)] FormatError),
//!     #[error(display = "could not find file: {:?}", path)]
//!     NotFound { path: PathBuf },
//! }
//! #
//! # fn main() {}
//! ```
//!
//! ## Printing the error
//!
//! ```
//! use std::error::Error;
//!
//! fn print_error(e: &dyn Error) {
//!     eprintln!("error: {}", e);
//!     let mut cause = e.source();
//!     while let Some(e) = cause {
//!         eprintln!("caused by: {}", e);
//!         cause = e.source();
//!     }
//! }
//! ```
//!

extern crate proc_macro2;
extern crate syn;

#[macro_use]
extern crate synstructure;
#[macro_use]
extern crate quote;

use proc_macro2::TokenStream;

decl_derive!([Error, attributes(error, cause)] => error_derive);

const RUSTC_SUPPORTS_STD_ERROR_SOURCE: bool = cfg!(RUSTC_SUPPORTS_STD_ERROR_SOURCE);

fn error_derive(s: synstructure::Structure) -> TokenStream {
    let cause_body = s.each_variant(|v| {
        if let Some(cause) = v.bindings().iter().find(is_cause) {
            quote!(return Some(#cause as & ::std::error::Error))
        } else {
            quote!(return None)
        }
    });

    let source_method = if RUSTC_SUPPORTS_STD_ERROR_SOURCE {
        quote! {
            #[allow(unreachable_code)]
            fn source(&self) -> ::std::option::Option<&(::std::error::Error + 'static)> {
                match *self { #cause_body }
                None
            }
        }
    } else {
        quote! {}
    };

    let cause_method = quote! {
        #[allow(unreachable_code)]
        fn cause(&self) -> ::std::option::Option<& ::std::error::Error> {
            match *self { #cause_body }
            None
        }
    };

    let error = s.unbound_impl(quote!(::std::error::Error), quote! {
        fn description(&self) -> &str {
            "description() is deprecated; use Display"
        }

        #cause_method
        #source_method
    });

    let display = display_body(&s).map(|display_body| {
        s.unbound_impl(
            quote!(::std::fmt::Display),
            quote! {
                #[allow(unreachable_code)]
                fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                    match *self { #display_body }
                    write!(f, "An error has occurred.")
                }
            },
        )
    });

    (quote! {
        #error
        #display
    })
    .into()
}

fn display_body(s: &synstructure::Structure) -> Option<quote::__rt::TokenStream> {
    let mut msgs = s.variants().iter().map(|v| find_error_msg(&v.ast().attrs));
    if msgs.all(|msg| msg.is_none()) {
        return None;
    }

    Some(s.each_variant(|v| {
        let msg =
            find_error_msg(&v.ast().attrs).expect("All variants must have display attribute.");
        if msg.nested.is_empty() {
            panic!("Expected at least one argument to error attribute");
        }

        let format_string = match msg.nested[0] {
            syn::NestedMeta::Meta(syn::Meta::NameValue(ref nv)) if nv.ident == "display" => {
                nv.lit.clone()
            }
            _ => panic!(
                "Error attribute must begin `display = \"\"` to control the Display message."
            ),
        };
        let args = msg.nested.iter().skip(1).map(|arg| match *arg {
            syn::NestedMeta::Literal(syn::Lit::Int(ref i)) => {
                let bi = &v.bindings()[i.value() as usize];
                quote!(#bi)
            }
            syn::NestedMeta::Meta(syn::Meta::Word(ref id)) => {
                let id_s = id.to_string();
                if id_s.starts_with("_") {
                    if let Ok(idx) = id_s[1..].parse::<usize>() {
                        let bi = match v.bindings().get(idx) {
                            Some(bi) => bi,
                            None => {
                                panic!(
                                    "display attempted to access field `{}` in `{}::{}` which \
                                     does not exist (there are {} field{})",
                                    idx,
                                    s.ast().ident,
                                    v.ast().ident,
                                    v.bindings().len(),
                                    if v.bindings().len() != 1 { "s" } else { "" }
                                );
                            }
                        };
                        return quote!(#bi);
                    }
                }
                for bi in v.bindings() {
                    if bi.ast().ident.as_ref() == Some(id) {
                        return quote!(#bi);
                    }
                }
                panic!(
                    "Couldn't find field `{}` in `{}::{}`",
                    id,
                    s.ast().ident,
                    v.ast().ident
                );
            }
            _ => panic!("Invalid argument to error attribute!"),
        });

        quote! {
            return write!(f, #format_string #(, #args)*)
        }
    }))
}

fn find_error_msg(attrs: &[syn::Attribute]) -> Option<syn::MetaList> {
    let mut error_msg = None;
    for attr in attrs {
        if let Some(meta) = attr.interpret_meta() {
            if meta.name() == "error" {
                if error_msg.is_some() {
                    panic!("Cannot have two display attributes")
                } else {
                    if let syn::Meta::List(list) = meta {
                        error_msg = Some(list);
                    } else {
                        panic!("error attribute must take a list in parentheses")
                    }
                }
            }
        }
    }
    error_msg
}

fn is_cause(bi: &&synstructure::BindingInfo) -> bool {
    let mut found_cause = false;
    for attr in &bi.ast().attrs {
        if let Some(meta) = attr.interpret_meta() {
            if meta.name() == "cause" {
                if found_cause {
                    panic!("Cannot have two `cause` attributes");
                }
                found_cause = true;
            }
            if meta.name() == "error" {
                if let syn::Meta::List(ref list) = meta {
                    if let Some(ref pair) = list.nested.first() {
                        if let &&syn::NestedMeta::Meta(syn::Meta::Word(ref word)) = pair.value() {
                            if word == "cause" {
                                if found_cause {
                                    panic!("Cannot have two `cause` attributes");
                                }
                                found_cause = true;
                            }
                        }
                    }
                }
            }
        }
    }
    found_cause
}