Skip to content

Commit

Permalink
derive: Add skip option to ExtensionDispatch
Browse files Browse the repository at this point in the history
This patch adds a skip option to the ExtensionDispatch macro that makes
it possible to ignore some fields.
  • Loading branch information
robin-nitrokey committed Apr 16, 2024
1 parent fdf05f5 commit d3309b9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 14 deletions.
4 changes: 4 additions & 0 deletions derive/examples/extension-dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ struct Dispatch {
a_sample: (),

b: backends::BBackend,

#[allow(unused)]
#[dispatch(skip)]
other: String,
}

fn main() {
Expand Down
36 changes: 22 additions & 14 deletions derive/src/extension_dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@ impl ExtensionDispatch {
};
let dispatch_attrs = DispatchAttrs::new(&input)?;
let extension_attrs = ExtensionAttrs::new(&input)?;
let raw_backends: Vec<_> = data_struct
.fields
.iter()
.map(RawBackend::new)
.collect::<Result<_>>()?;
let mut raw_backends = Vec::new();
for field in &data_struct.fields {
if let Some(raw_backend) = RawBackend::new(field)? {
raw_backends.push(raw_backend);
}
}
let mut backends = Vec::new();
let mut delegated_backends = Vec::new();
for raw_backend in raw_backends {
Expand Down Expand Up @@ -204,38 +205,45 @@ struct RawBackend {
}

impl RawBackend {
fn new(field: &Field) -> Result<Self> {
let ident = field.ident.clone().ok_or_else(|| {
Error::new_spanned(
field,
"ExtensionDispatch can only be derived for a struct with named fields",
)
})?;
fn new(field: &Field) -> Result<Option<Self>> {
let mut delegate_to = None;
let mut skip = false;
for attr in util::get_attrs(&field.attrs, "dispatch") {
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("delegate_to") {
let s: LitStr = meta.value()?.parse()?;
delegate_to = Some(s.parse()?);
Ok(())
} else if meta.path.is_ident("skip") {
skip = true;
Ok(())
} else {
Err(meta.error("unsupported dispatch attribute"))
}
})?;
}
if skip {
return Ok(None);
}
let ident = field.ident.clone().ok_or_else(|| {
Error::new_spanned(
field,
"ExtensionDispatch can only be derived for a struct with named fields",
)
})?;
let mut extensions = Vec::new();
for attr in util::get_attrs(&field.attrs, "extensions") {
for s in attr.parse_args_with(Punctuated::<LitStr, Token![,]>::parse_terminated)? {
extensions.push(s.parse()?);
}
}
Ok(Self {
Ok(Some(Self {
id: util::to_camelcase(&ident),
field: ident,
ty: field.ty.clone(),
delegate_to,
extensions,
})
}))
}
}

Expand Down

0 comments on commit d3309b9

Please sign in to comment.