Skip to content

Commit b6109c0

Browse files
ericseppanenemilio
authored andcommitted
add custom derives callback
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`.
1 parent 67538b6 commit b6109c0

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/callbacks.rs

+8
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,12 @@ pub trait ParseCallbacks: fmt::Debug + UnwindSafe {
9595
) -> Option<ImplementsTrait> {
9696
None
9797
}
98+
99+
/// Provide a list of custom derive attributes.
100+
///
101+
/// If no additional attributes are wanted, this function should return an
102+
/// empty `Vec`.
103+
fn add_derives(&self, _name: &str) -> Vec<String> {
104+
vec![]
105+
}
98106
}

src/codegen/mod.rs

+9
Original file line numberDiff line numberDiff line change
@@ -2005,6 +2005,15 @@ impl CodeGenerator for CompInfo {
20052005
let mut derives: Vec<_> = derivable_traits.into();
20062006
derives.extend(item.annotations().derives().iter().map(String::as_str));
20072007

2008+
// The custom derives callback may return a list of derive attributes;
2009+
// add them to the end of the list.
2010+
let custom_derives;
2011+
if let Some(cb) = &ctx.options().parse_callbacks {
2012+
custom_derives = cb.add_derives(&canonical_name);
2013+
// In most cases this will be a no-op, since custom_derives will be empty.
2014+
derives.extend(custom_derives.iter().map(|s| s.as_str()));
2015+
};
2016+
20082017
if !derives.is_empty() {
20092018
attributes.push(attributes::derives(&derives))
20102019
}

0 commit comments

Comments
 (0)