err-derive 0.1.6

Derive macro for `std::error::Error`
Documentation
//! # `err-derive`
//!
//! ## Deriving error causes / sources
//!
//! Add an `#[error(cause)]` attribute to the field:
//!
//! ```
//! use std::io;
//! use err_derive::Error;
//!
//! /// `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
//! use std::path::PathBuf;
//! use err_derive::Error;
//!
//! #[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_macro;
extern crate syn;

use quote::quote;
use synstructure::decl_derive;

use syn::spanned::Spanned;
use proc_macro::TokenStream;

extern crate proc_macro_error;
use proc_macro_error::{
    filter_macro_errors,
    span_error,
};

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

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

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

        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 span = v.ast().ident.span();
        let msg = match find_error_msg(&v.ast().attrs) {
            Some(msg) => msg,
            None => span_error!(span, "All variants must have display attribute.")
        };
        if msg.nested.is_empty() {
            span_error!(span, "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
                    .path
                    .get_ident()
                    .map_or(false, |ident| ident == "display") =>
            {
                nv.lit.clone()
            }
            _ => span_error!(
                msg.nested.span(),
                "Error attribute must begin `display = \"\"` to control the Display message."
            ),
        };
        let args = msg.nested.iter().skip(1).map(|arg| match *arg {
            syn::NestedMeta::Lit(syn::Lit::Int(ref i)) => {
                let bi = &v.bindings()[i
                    .base10_parse::<usize>()
                    .unwrap_or_else(|_| panic!("integer literal overflows usize"))];
                quote!(#bi)
            }
            syn::NestedMeta::Meta(syn::Meta::Path(ref path)) => {
                let id = path
                    .get_ident()
                    .unwrap_or_else(|| panic!("found path in display where ident is expected"));
                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 => {
                                span_error!(
                                    id.span(),
                                    "display attempted to access field `{}` in `{}::{}` which \
                                     does not exist (there {} {} field{})",
                                    idx,
                                    s.ast().ident,
                                    v.ast().ident,
                                    if v.bindings().len() != 1 { "are" } else { "is" },
                                    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);
                    }
                }
                span_error!(
                    id.span(),
                    "Couldn't find field `{}` in `{}::{}`",
                    id,
                    s.ast().ident,
                    v.ast().ident
                );
            }
            _ => span_error!(msg.nested.span(), "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 Ok(meta) = attr.parse_meta() {
            if meta
                .path()
                .get_ident()
                .map_or(false, |ident| ident == "error")
            {
                let span = attr.span();
                if error_msg.is_some() {
                    span_error!(span, "Cannot have two display attributes")
                } else if let syn::Meta::List(list) = meta {
                    error_msg = Some(list);
                } else {
                    span_error!(span, "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 Ok(meta) = attr.parse_meta() {
            if meta
                .path()
                .get_ident()
                .map_or(false, |ident| ident == "cause")
            {
                if found_cause {
                    span_error!(attr.span(), "Cannot have two `cause` attributes");
                }
                found_cause = true;
            }

            if meta
                .path()
                .get_ident()
                .map_or(false, |ident| ident == "error")
            {
                if let syn::Meta::List(ref list) = meta {
                    if let Some(ref pair) = list.nested.first() {
                        if let syn::NestedMeta::Meta(syn::Meta::Path(path)) = pair {
                            if path.get_ident().map_or(false, |ident| ident == "cause") {
                                if found_cause {
                                    span_error!(path.span(), "Cannot have two `cause` attributes");
                                }
                                found_cause = true;
                            }
                        }
                    }
                }
            }
        }
    }
    found_cause
}