Skip to content

add custom derives callback #2059

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions bindgen-integration/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,17 @@ impl ParseCallbacks for MacroCallback {
}
}
}

// Test the "custom derives" capability by adding `PartialEq` to the `Test` struct.
fn add_derives(&self, name: &str) -> Vec<String> {
if name == "Test" {
vec![
"PartialEq".into(),
]
} else {
vec![]
}
}
}

impl Drop for MacroCallback {
Expand Down
9 changes: 9 additions & 0 deletions bindgen-integration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,3 +267,12 @@ fn test_homogeneous_aggregate_float_union() {
assert_eq!([1., 2., 3., 4.], coord.v)
}
}

#[test]
fn test_custom_derive() {
// The `add_derives` callback should have added `#[derive(PartialEq)]`
// to the `Test` struct. If it didn't, this will fail to compile.
let test1 = unsafe { bindings::Test::new(5) };
let test2 = unsafe { bindings::Test::new(6) };
assert_ne!(test1, test2);
}
8 changes: 8 additions & 0 deletions src/callbacks.rs
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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