use super::helper;
use quote::ToTokens;
use syn::{spanned::Spanned, Fields};
mod keyword {
syn::custom_keyword!(Error);
}
pub struct VariantField {
pub is_named: bool,
}
pub struct VariantDef {
pub ident: syn::Ident,
pub field: Option<VariantField>,
pub cfg_attrs: Vec<syn::Attribute>,
}
pub struct ErrorDef {
pub index: usize,
pub variants: Vec<VariantDef>,
pub instances: Vec<helper::InstanceUsage>,
pub error: keyword::Error,
pub attr_span: proc_macro2::Span,
pub attrs: Vec<syn::Attribute>,
}
impl ErrorDef {
pub fn try_from(
attr_span: proc_macro2::Span,
index: usize,
item: &mut syn::Item,
) -> syn::Result<Self> {
let item = if let syn::Item::Enum(item) = item {
item
} else {
return Err(syn::Error::new(item.span(), "Invalid pallet::error, expected item enum"))
};
if !matches!(item.vis, syn::Visibility::Public(_)) {
let msg = "Invalid pallet::error, `Error` must be public";
return Err(syn::Error::new(item.span(), msg))
}
let instances =
vec![helper::check_type_def_gen_no_bounds(&item.generics, item.ident.span())?];
if item.generics.where_clause.is_some() {
let msg = "Invalid pallet::error, where clause is not allowed on pallet error item";
return Err(syn::Error::new(item.generics.where_clause.as_ref().unwrap().span(), msg))
}
let error = syn::parse2::<keyword::Error>(item.ident.to_token_stream())?;
let variants = item
.variants
.iter()
.map(|variant| {
let field_ty = match &variant.fields {
Fields::Unit => None,
Fields::Named(_) => Some(VariantField { is_named: true }),
Fields::Unnamed(_) => Some(VariantField { is_named: false }),
};
if variant.discriminant.is_some() {
let msg = "Invalid pallet::error, unexpected discriminant, discriminants \
are not supported";
let span = variant.discriminant.as_ref().unwrap().0.span();
return Err(syn::Error::new(span, msg))
}
let cfg_attrs: Vec<syn::Attribute> = helper::get_item_cfg_attrs(&variant.attrs);
Ok(VariantDef { ident: variant.ident.clone(), field: field_ty, cfg_attrs })
})
.collect::<Result<_, _>>()?;
Ok(ErrorDef { attr_span, index, variants, instances, error, attrs: item.attrs.clone() })
}
}