use proc_macro2::{Literal, TokenStream}; use quote::{format_ident, quote, ToTokens}; use syn::spanned::Spanned as _;
usecrate::utils::{
attr::{self, ParseMultiple as _},
Spanning,
};
/// Expands a [`TryFrom`] derive macro. pubfn expand(input: &syn::DeriveInput, _: &'static str) -> syn::Result<TokenStream> { match &input.data {
syn::Data::Struct(data) => Err(syn::Error::new(
data.struct_token.span(), "`TryFrom` cannot be derived for structs",
)),
syn::Data::Enum(data) => Ok(Expansion {
repr: attr::ReprInt::parse_attrs(&input.attrs, &format_ident!("repr"))?
.map(Spanning::into_inner)
.unwrap_or_default(),
attr: ItemAttribute::parse_attrs(&input.attrs, &format_ident!("try_from"))?
.map(|attr| { if matches!(attr.item, ItemAttribute::Types(_)) {
Err(syn::Error::new(
attr.span, "`#[try_from(repr(...))]` attribute is not supported yet",
))
} else {
Ok(attr.item)
}
})
.transpose()?,
ident: input.ident.clone(),
generics: input.generics.clone(),
variants: data.variants.clone().into_iter().collect(),
}
.into_token_stream()),
syn::Data::Union(data) => Err(syn::Error::new(
data.union_token.span(), "`TryFrom` cannot be derived for unions",
)),
}
}
/// Representation of a [`TryFrom`] derive macro struct item attribute. /// /// ```rust,ignore /// #[try_from(repr)] /// #[try_from(repr(<types>))] /// ``` type ItemAttribute = attr::ReprConversion;
/// Expansion of a macro for generating [`TryFrom`] implementation of an enum. struct Expansion { /// `#[repr(u/i*)]` of the enum.
repr: attr::ReprInt,
/// [`ItemAttribute`] of the enum.
attr: Option<ItemAttribute>,
/// [`syn::Ident`] of the enum. /// /// [`syn::Ident`]: struct@syn::Ident
ident: syn::Ident,
/// [`syn::Generics`] of the enum.
generics: syn::Generics,
/// [`syn::Variant`]s of the enum.
variants: Vec<syn::Variant>,
}
impl ToTokens for Expansion { /// Expands [`TryFrom`] implementations for a struct. fn to_tokens(&self, tokens: &mut TokenStream) { ifself.attr.is_none() { return;
}
let ident = &self.ident; let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.