Skip to content

Commit

Permalink
add custom derives callback
Browse files Browse the repository at this point in the history
This callback allows us to specify arbitrary derive attributes for each
named struct. This is useful for adding things that can't easily be
implemented separately, such as `serde::Deserialize` or
`zerocopy::FromBytes`.
  • Loading branch information
ericseppanen committed Jun 6, 2021
1 parent b60339e commit 3f0a0db
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/callbacks.rs
Expand Up @@ -95,4 +95,12 @@ pub trait ParseCallbacks: fmt::Debug + UnwindSafe {
) -> Option<ImplementsTrait> {
None
}

/// Provide a list of custom derive attributes.
///
/// If no additional attributes are wanted, this function should return an
/// empty `Vec`.
fn add_derives(&self, _name: &str) -> Vec<String> {
vec![]
}
}
9 changes: 9 additions & 0 deletions src/codegen/mod.rs
Expand Up @@ -1997,6 +1997,15 @@ impl CodeGenerator for CompInfo {
let mut derives: Vec<_> = derivable_traits.into();
derives.extend(item.annotations().derives().iter().map(String::as_str));

// The custom derives callback may return a list of derive attributes;
// add them to the end of the list.
let custom_derives;
if let Some(cb) = &ctx.options().parse_callbacks {
custom_derives = cb.add_derives(&canonical_name);
// In most cases this will be a no-op, since custom_derives will be empty.
derives.extend(custom_derives.iter().map(|s| s.as_str()));
};

if !derives.is_empty() {
attributes.push(attributes::derives(&derives))
}
Expand Down

0 comments on commit 3f0a0db

Please sign in to comment.