-
I would like to ask, if there is any recommended way of handling the following situation? Let's assume we have a struct, which defines common attributes which are always present / supported independent of the type of item (field vs variant): #[derive(Debug, FromMeta)]
#[darling(and_then = ItemAttributes::validate)]
pub struct ItemAttributes {
pub my_common_attr: String,
}
impl ItemAttributes {
fn validate(self) -> Result<Self, Error> {
return Err(Error::custom("validation failed").with_span(ident));
// What to put here, we have no access to ident yet ^^^^^
}
} Next, we have the field and variant specific structs, which flatten the common struct into it: #[derive(Debug, FromField)]
#[darling(
attributes(versioned),
forward_attrs(allow, doc, cfg, serde),
and_then = FieldAttributes::validate
)]
pub(crate) struct FieldAttributes {
#[darling(flatten)]
pub(crate) common: ItemAttributes,
// The ident (automatically extracted by darling) cannot be moved into the
// shared item attributes because for struct fields, the type is
// `Option<Ident>`, while for enum variants, the type is `Ident`.
pub(crate) ident: Option<Ident>,
}
impl FieldAttributes {
fn validate(self) -> Result<Self, Error> {
return Err(Error::custom("validation failed").with_span(&self.ident));
// This is totally fine and results in great DX ^^^^^^^^^^^
}
} Now to my question: Is there a way to get access to the ident of the field / variant to ultimately get access to its span?. This could allow handling common validation with the same amount of DX as handling item specific validation. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Magic fields like In my opinion, a better solution would be to change |
Beta Was this translation helpful? Give feedback.
Magic fields like
ident
don’t work with flatten, so even if the types were identical you wouldn’t be able to do what’s depicted here.In my opinion, a better solution would be to change
ItemAttributes::my_common_attr
to be aSpannedValue<String>
or asyn::LitStr
so you have the span of that specific field, and put the error there rather than being on the variant or field ident.