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 3, 2021
1 parent b60339e commit 57fb272
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/callbacks.rs
Expand Up @@ -95,4 +95,9 @@ pub trait ParseCallbacks: fmt::Debug + UnwindSafe {
) -> Option<ImplementsTrait> {
None
}

/// Provide a list of custom derive attributes.
fn add_derives(&self, _name: &str) -> Option<Vec<String>> {
None
}
}
10 changes: 10 additions & 0 deletions src/codegen/mod.rs
Expand Up @@ -1997,6 +1997,16 @@ impl CodeGenerator for CompInfo {
let mut derives: Vec<_> = derivable_traits.into();
derives.extend(item.annotations().derives().iter().map(String::as_str));

// Check to see if there is a custom derives callback, and call that
// function to see if any custom derive attributes should be added.
let custom_derives;
if let Some(cb) = &ctx.options().parse_callbacks {
custom_derives = cb.add_derives(&canonical_name);
if let Some(custom_derive_vec) = &custom_derives {
derives.extend(custom_derive_vec.iter().map(|s| s.as_str()));
}
};

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

0 comments on commit 57fb272

Please sign in to comment.