Skip to content

Commit 3f0a0db

Browse files
committed
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 b60339e commit 3f0a0db

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
@@ -1997,6 +1997,15 @@ impl CodeGenerator for CompInfo {
19971997
let mut derives: Vec<_> = derivable_traits.into();
19981998
derives.extend(item.annotations().derives().iter().map(String::as_str));
19991999

2000+
// The custom derives callback may return a list of derive attributes;
2001+
// add them to the end of the list.
2002+
let custom_derives;
2003+
if let Some(cb) = &ctx.options().parse_callbacks {
2004+
custom_derives = cb.add_derives(&canonical_name);
2005+
// In most cases this will be a no-op, since custom_derives will be empty.
2006+
derives.extend(custom_derives.iter().map(|s| s.as_str()));
2007+
};
2008+
20002009
if !derives.is_empty() {
20012010
attributes.push(attributes::derives(&derives))
20022011
}

0 commit comments

Comments
 (0)