Skip to content

Commit 727367c

Browse files
committed
allow custom derives on enums
Custom derives are just as useful on enums as they are on structs; not supporting this was an oversight. Adds a test that will fail to compile if the custom derive doesn't work on enums. This test fails without the codegen fix.
1 parent 2aed6b0 commit 727367c

File tree

4 files changed

+31
-0
lines changed

4 files changed

+31
-0
lines changed

bindgen-integration/build.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,10 @@ impl ParseCallbacks for MacroCallback {
126126
vec![
127127
"PartialEq".into(),
128128
]
129+
} else if name == "MyOrderedEnum" {
130+
vec![
131+
"PartialOrd".into(),
132+
]
129133
} else {
130134
vec![]
131135
}

bindgen-integration/cpp/Test.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,3 +234,10 @@ typedef union {
234234
} Coord;
235235

236236
Coord coord(double x, double y, double z, double t);
237+
238+
// Used to test custom derives on enum. See `test_custom_derive`.
239+
enum MyOrderedEnum {
240+
MICRON,
241+
METER,
242+
LIGHTYEAR,
243+
};

bindgen-integration/src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,4 +275,14 @@ fn test_custom_derive() {
275275
let test1 = unsafe { bindings::Test::new(5) };
276276
let test2 = unsafe { bindings::Test::new(6) };
277277
assert_ne!(test1, test2);
278+
279+
// The `add_derives` callback should have added `#[derive(PartialOrd)]`
280+
// to the `MyOrderedEnum` enum. If it didn't, this will fail to compile.
281+
282+
let micron = unsafe { bindings::MyOrderedEnum::MICRON };
283+
let meter = unsafe { bindings::MyOrderedEnum::METER };
284+
let lightyear = unsafe { bindings::MyOrderedEnum::LIGHTYEAR };
285+
286+
assert!(meter < lightyear);
287+
assert!(meter > micron);
278288
}

src/codegen/mod.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3014,6 +3014,16 @@ impl CodeGenerator for Enum {
30143014
derives.push(derive);
30153015
}
30163016
}
3017+
3018+
// The custom derives callback may return a list of derive attributes;
3019+
// add them to the end of the list.
3020+
let custom_derives;
3021+
if let Some(cb) = &ctx.options().parse_callbacks {
3022+
custom_derives = cb.add_derives(&name);
3023+
// In most cases this will be a no-op, since custom_derives will be empty.
3024+
derives.extend(custom_derives.iter().map(|s| s.as_str()));
3025+
};
3026+
30173027
attrs.push(attributes::derives(&derives));
30183028
}
30193029

0 commit comments

Comments
 (0)