auto_enums/derive/std/
error.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3use crate::derive::prelude::*;
4
5pub(crate) const NAME: &[&str] = &["Error"];
6
7pub(crate) fn derive(_cx: &Context, data: &Data) -> Result<TokenStream> {
8    let ident = &data.ident;
9    let source =
10        data.variant_idents().map(|v| quote!(#ident::#v(x) => ::std::option::Option::Some(x)));
11
12    let source = parse_quote! {
13        fn source(&self) -> ::std::option::Option<&(dyn (::std::error::Error) + 'static)> {
14            match self { #(#source,)* }
15        }
16    };
17
18    let mut impl_ =
19        EnumImpl::from_trait(data, &parse_quote!(::std::error::Error), None, parse_quote! {
20            trait Error {
21                #[allow(deprecated)]
22                fn description(&self) -> &str;
23            }
24        });
25
26    data.field_types().for_each(|f| impl_.push_where_predicate(parse_quote!(#f: 'static)));
27    impl_.push_item(source);
28
29    Ok(impl_.build())
30}