cfg_if/
lib.rs

1//! A macro for defining `#[cfg]` if-else statements.
2//!
3//! The macro provided by this crate, `cfg_if`, is similar to the `if/elif` C
4//! preprocessor macro by allowing definition of a cascade of `#[cfg]` cases,
5//! emitting the implementation which matches first.
6//!
7//! This allows you to conveniently provide a long list `#[cfg]`'d blocks of code
8//! without having to rewrite each clause multiple times.
9//!
10//! # Example
11//!
12//! ```
13//! cfg_if::cfg_if! {
14//!     if #[cfg(unix)] {
15//!         fn foo() { /* unix specific functionality */ }
16//!     } else if #[cfg(target_pointer_width = "32")] {
17//!         fn foo() { /* non-unix, 32-bit functionality */ }
18//!     } else {
19//!         fn foo() { /* fallback implementation */ }
20//!     }
21//! }
22//!
23//! # fn main() {}
24//! ```
25
26#![no_std]
27#![doc(html_root_url = "https://docs.rs/cfg-if")]
28#![deny(missing_docs)]
29#![cfg_attr(test, deny(warnings))]
30
31/// The main macro provided by this crate. See crate documentation for more
32/// information.
33#[macro_export]
34macro_rules! cfg_if {
35    // match if/else chains with a final `else`
36    ($(
37        if #[cfg($meta:meta)] { $($tokens:tt)* }
38    ) else * else {
39        $($tokens2:tt)*
40    }) => {
41        $crate::cfg_if! {
42            @__items
43            () ;
44            $( ( ($meta) ($($tokens)*) ), )*
45            ( () ($($tokens2)*) ),
46        }
47    };
48
49    // match if/else chains lacking a final `else`
50    (
51        if #[cfg($i_met:meta)] { $($i_tokens:tt)* }
52        $(
53            else if #[cfg($e_met:meta)] { $($e_tokens:tt)* }
54        )*
55    ) => {
56        $crate::cfg_if! {
57            @__items
58            () ;
59            ( ($i_met) ($($i_tokens)*) ),
60            $( ( ($e_met) ($($e_tokens)*) ), )*
61            ( () () ),
62        }
63    };
64
65    // Internal and recursive macro to emit all the items
66    //
67    // Collects all the negated cfgs in a list at the beginning and after the
68    // semicolon is all the remaining items
69    (@__items ($($not:meta,)*) ; ) => {};
70    (@__items ($($not:meta,)*) ; ( ($($m:meta),*) ($($tokens:tt)*) ), $($rest:tt)*) => {
71        // Emit all items within one block, applying an appropriate #[cfg]. The
72        // #[cfg] will require all `$m` matchers specified and must also negate
73        // all previous matchers.
74        #[cfg(all($($m,)* not(any($($not),*))))] $crate::cfg_if! { @__identity $($tokens)* }
75
76        // Recurse to emit all other items in `$rest`, and when we do so add all
77        // our `$m` matchers to the list of `$not` matchers as future emissions
78        // will have to negate everything we just matched as well.
79        $crate::cfg_if! { @__items ($($not,)* $($m,)*) ; $($rest)* }
80    };
81
82    // Internal macro to make __apply work out right for different match types,
83    // because of how macros matching/expand stuff.
84    (@__identity $($tokens:tt)*) => {
85        $($tokens)*
86    };
87}
88
89#[cfg(test)]
90mod tests {
91    cfg_if! {
92        if #[cfg(test)] {
93            use core::option::Option as Option2;
94            fn works1() -> Option2<u32> { Some(1) }
95        } else {
96            fn works1() -> Option<u32> { None }
97        }
98    }
99
100    cfg_if! {
101        if #[cfg(foo)] {
102            fn works2() -> bool { false }
103        } else if #[cfg(test)] {
104            fn works2() -> bool { true }
105        } else {
106            fn works2() -> bool { false }
107        }
108    }
109
110    cfg_if! {
111        if #[cfg(foo)] {
112            fn works3() -> bool { false }
113        } else {
114            fn works3() -> bool { true }
115        }
116    }
117
118    cfg_if! {
119        if #[cfg(test)] {
120            use core::option::Option as Option3;
121            fn works4() -> Option3<u32> { Some(1) }
122        }
123    }
124
125    cfg_if! {
126        if #[cfg(foo)] {
127            fn works5() -> bool { false }
128        } else if #[cfg(test)] {
129            fn works5() -> bool { true }
130        }
131    }
132
133    #[test]
134    fn it_works() {
135        assert!(works1().is_some());
136        assert!(works2());
137        assert!(works3());
138        assert!(works4().is_some());
139        assert!(works5());
140    }
141
142    #[test]
143    #[allow(clippy::assertions_on_constants)]
144    fn test_usage_within_a_function() {
145        cfg_if! {if #[cfg(debug_assertions)] {
146            // we want to put more than one thing here to make sure that they
147            // all get configured properly.
148            assert!(cfg!(debug_assertions));
149            assert_eq!(4, 2+2);
150        } else {
151            assert!(works1().is_some());
152            assert_eq!(10, 5+5);
153        }}
154    }
155
156    trait Trait {
157        fn blah(&self);
158    }
159
160    #[allow(dead_code)]
161    struct Struct;
162
163    impl Trait for Struct {
164        cfg_if! {
165            if #[cfg(feature = "blah")] {
166                fn blah(&self) {
167                    unimplemented!();
168                }
169            } else {
170                fn blah(&self) {
171                    unimplemented!();
172                }
173            }
174        }
175    }
176}