I am building a crate which has the feature foo. This crate has a macro bar! that does subtly different things based on whether foo is set.
I could duplicate the entire macro:
#[cfg(feature = "foo")]
macro_rules! bar {
// Lots of rules...
( A ) => {
B
}
}
#[cfg(not(feature = "foo"))]
macro_rules! bar {
// Lots of rules...
( A ) => {
C
}
}
That's a lot of error-prone duplication. Two approaches that don't work:
We can't move the
cfginside the macro, because then it will expand in the crate user's scope, which does not have featurefooappropriately set.We can't use a
#[doc(hidden)] #[macro_export] macro_rules! bar_priv_impl__helper macro and use#[cfg]on the helper macro since Rust 1.30, because users can now requestuse mycrate::bar;to only import thebar!macro, giving errors about howbar_priv_impl__!is not defined.
Is there any way that's better than full macro duplication? It gets really bad if you have N features you're testing on, as you need 2n duplications.