Debian Codegraph @

debian/missing-sources/derive_more-impl/src/try_from.rs

raw
1 //! Implementation of a [`TryFrom`] derive macro.
2
3 use proc_macro2::{Literal, TokenStream};
4 use quote::{format_ident, quote, ToTokens};
5 use syn::spanned::Spanned as _;
6
7 use crate::utils::{
8 attr::{self, ParseMultiple as _},
9 Spanning,
10 };
11
12 /// Expands a [`TryFrom`] derive macro.
13 pub fn expand(input: &syn::DeriveInput, _: &'static str) -> syn::Result<TokenStream> {
14 match &input.data {
15 syn::Data::Struct(data) => Err(syn::Error::new(
16 data.struct_token.span(),
17 "`TryFrom` cannot be derived for structs",
18 )),
19 syn::Data::Enum(data) => Ok(Expansion {
20 repr: attr::ReprInt::parse_attrs(&input.attrs, &format_ident!("repr"))?
21 .map(Spanning::into_inner)
22 .unwrap_or_default(),
23 attr: Some(
24 ItemAttribute::parse_attrs(&input.attrs, &format_ident!("try_from"))?
25 .map(|attr| {
26 if matches!(attr.item, ItemAttribute::Types(_)) {
27 Err(syn::Error::new(
28 attr.span,
29 "`#[try_from(repr(...))]` attribute is not supported yet",
30 ))
31 } else {
32 Ok(attr.item)
33 }
34 })
35 .transpose()?
36 .ok_or_else(|| {
37 syn::Error::new(
38 input.ident.span(),
39 "`#[try_from(repr)]` attribute is expected here",
40 )
41 })?,
42 ),
43 ident: input.ident.clone(),
44 generics: input.generics.clone(),
45 variants: data.variants.clone().into_iter().collect(),
46 }
47 .into_token_stream()),
48 syn::Data::Union(data) => Err(syn::Error::new(
49 data.union_token.span(),
50 "`TryFrom` cannot be derived for unions",
51 )),
52 }
53 }
54
55 /// Representation of a [`TryFrom`] derive macro struct item attribute.
56 ///
57 /// ```rust,ignore
58 /// #[try_from(repr)]
59 /// #[try_from(repr(<types>))]
60 /// ```
61 type ItemAttribute = attr::ReprConversion;
62
63 /// Expansion of a macro for generating [`TryFrom`] implementation of an enum.
64 struct Expansion {
65 /// `#[repr(u/i*)]` of the enum.
66 repr: attr::ReprInt,
67
68 /// [`ItemAttribute`] of the enum.
69 attr: Option<ItemAttribute>,
70
71 /// [`syn::Ident`] of the enum.
72 ///
73 /// [`syn::Ident`]: struct@syn::Ident
74 ident: syn::Ident,
75
76 /// [`syn::Generics`] of the enum.
77 generics: syn::Generics,
78
79 /// [`syn::Variant`]s of the enum.
80 variants: Vec<syn::Variant>,
81 }
82
83 impl ToTokens for Expansion {
84 /// Expands [`TryFrom`] implementations for a struct.
85 fn to_tokens(&self, tokens: &mut TokenStream) {
86 if self.attr.is_none() {
87 return;
88 }
89
90 let ident = &self.ident;
91 let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();
92
93 let repr_ty = &self.repr.ty();
94
95 let mut last_discriminant = quote! { 0 };
96 let mut inc = 0usize;
97 let (consts, (discriminants, variants)): (
98 Vec<syn::Ident>,
99 (Vec<TokenStream>, Vec<TokenStream>),
100 ) = self
101 .variants
102 .iter()
103 .filter_map(
104 |syn::Variant {
105 ident,
106 fields,
107 discriminant,
108 ..
109 }| {
110 if let Some(d) = discriminant {
111 last_discriminant = d.1.to_token_stream();
112 inc = 0;
113 }
114 let ret = {
115 let inc = Literal::usize_unsuffixed(inc);
116 fields.is_empty().then_some((
117 format_ident!("__DISCRIMINANT_{ident}"),
118 (
119 quote! { #last_discriminant + #inc },
120 quote! { #ident #fields },
121 ),
122 ))
123 };
124 inc += 1;
125 ret
126 },
127 )
128 .unzip();
129
130 let error = quote! { derive_more::TryFromReprError<#repr_ty> };
131
132 quote! {
133 #[automatically_derived]
134 impl #impl_generics derive_more::core::convert::TryFrom<#repr_ty #ty_generics>
135 for #ident #where_clause {
136 type Error = #error;
137
138 #[allow(deprecated)] // omit warnings on deprecated fields/variants
139 #[allow(non_upper_case_globals)]
140 #[inline]
141 fn try_from(val: #repr_ty) -> derive_more::core::result::Result<Self, #error> {
142 #( const #consts: #repr_ty = #discriminants; )*
143 match val {
144 #(#consts => derive_more::core::result::Result::Ok(#ident::#variants),)*
145 _ => derive_more::core::result::Result::Err(
146 derive_more::TryFromReprError::new(val)
147 ),
148 }
149 }
150 }
151 }.to_tokens(tokens);
152 }
153 }