1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! A macro for defining `#[cfg]` if-else statements containing potentially cross-crate variables.
//!
//! This macro is similar to [`cfg_if!`][cfg_if]—so similar, in fact, that we're going to plagiarize its
//! documentation for a bit:
//!
//! > The macro provided by this crate, [`cond!`](crate::cond), is similar to the `if/elif` C
//! > preprocessor macro by allowing definition of a cascade of `#[cfg]` cases, emitting the
//! > implementation which matches first.
//! >
//! > This allows you to conveniently provide a long list `#[cfg]`'d blocks of code without having
//! > to rewrite each clause multiple times.
//! >
//! > ## Example
//! >
//! > ```
//! > cfgenius::cond! {
//! >     if cfg(unix) {
//! >         fn foo() { /* unix specific functionality */ }
//! >     } else if cfg(target_pointer_width = "32") {
//! >         fn foo() { /* non-unix, 32-bit functionality */ }
//! >     } else {
//! >         fn foo() { /* fallback implementation */ }
//! >     }
//! > }
//! > ```
//!
//! ---
//!
//! What's new, however, is the ability to [`define!`](crate::define) custom conditional-compilation
//! variables and use those variables in your [`cond!`](crate::cond) predicates:
//!
//! ```
//! // In `crate_1`...
//! # mod crate_1 {
//! cfgenius::define! {
//!     pub(super) is_32_bit_or_more = cfg(any(
//!         target_pointer_width = "32",
//!         target_pointer_width = "64",
//!     ));
//!
//!     pub is_recommended = all(
//!         macro(is_32_bit_or_more),
//!         macro(is_supported),
//!         cfg(target_has_atomic),
//!     );
//! }
//!
//! cfgenius::cond! {
//!     if all(cfg(windows), not(macro(is_32_bit_or_more))) {
//!         cfgenius::define!(pub is_supported = true());
//!
//!         // windows-specific non-32-bit functionality
//!     } else if all(cfg(windows), macro(is_32_bit_or_more)) {
//!         cfgenius::define!(pub is_supported = true());
//!
//!         // windows-specific non-32-bit functionality
//!     } else {
//!         cfgenius::define!(pub is_supported = false());
//!     }
//! }
//!
//! pub const IS_SUPPORTED: bool = cfgenius::cond_expr!(macro(is_supported));
//! # }
//!
//! // In `crate_2`...
//! cfgenius::cond! {
//!     if any(
//!         macro(crate_1::is_recommended),
//!         all(cfg(feature = "force_crate_1_backend"), macro(crate_1::is_supported))
//!     ) {
//!         // (`crate_1` implementation)
//!     } else {
//!         // (fallback implementation)
//!     }
//! }
//! ```
//!
//! This is not possible in regular `#[cfg]` attributes:
//!
//! ```compile_fail
//! macro_rules! truthy {
//!     () => { all() };
//! }
//!
//! #[cfg(truthy!())]
//! //          ^ Syntax Error: expected one of `(`, `,`, `::`, or `=`, found `!`
//! mod this_is_compiled {}
//! ```
//!
//! ## Predicates
//!
//! In every place where we could expect a conditionally compiled predicate, the following predicates
//! are supported:
//!
//! - `true()`: is always truthy
//!
//! - `false()`: is always falsy
//!
//! - `cfg(<cfg input>)`: resolves to the result of a regular [cfg attribute][cfg_attr] with the
//!   same input.
//!
//! - `not(<predicate>)`: negates the resolution of the provided `cfgenius` predicate.
//!
//! - `all(<predicate 1>, <predicate 2>, ...)`: resolves to truthy if none of the provided `cfgenius`
//!   predicates fail. `all()` with no provided predicates resolves to true.
//!
//! - `any(<predicate 1>, <predicate 2>, ...)`: resolves to truthy if at least of the provided `cfgenius`
//!   predicates succeed. `any()` with no provided predicates resolves to false.
//!
//! - `macro(<path to macro>)`: uses the macro to determine the truthiness of the predicate.
//!
//! - `macro(<path to macro> => <macro arguments>)`: uses the macro with the provided arguments to
//!   determine the truthiness of the predicate.
//!
//! ## Custom Variables
//!
//! Most variables can be succinctly defined using [`define!`](crate::define). However, because
//! variables are just macros which are expanded to get their result, you can define your own
//! variables by following this protocol.
//!
//! The predicate `macro(<path to macro>)` is evaluated by expanding:
//!
//! ```no_compile
//! path::to::macro! {
//!     yes { /* truthy tokens */ }
//!     no { /* falsy tokens */ }
//! }
//! ```
//!
//! ...and the predicate `macro(<path to macro> => <macro arguments>)` is evaluated by expanding:
//!
//! ```no_compile
//! path::to::macro! {
//!     args { /* macro arguments */ }
//!     yes { /* truthy tokens */ }
//!     no { /* falsy tokens */ }
//! }
//! ```
//!
//! If the variable should be truthy, the macro should expand to `/* truthy tokens */` and nothing
//! more. If the variable should be falsy, the macro should expand to `/* falsy tokens */` and
//! nothing more.
//!
//! These macros should be effectless and pure with respect to their environment. You should not
//! rely on this macro being evaluated once for every time it appears in a predicate, even though
//! this is the current behavior.
//!
//! [cfg_if]: https://docs.rs/cfg-if/1.0.0/cfg_if/index.html
//! [cfg_attr]: https://doc.rust-lang.org/reference/conditional-compilation.html

// #![no_std]

/// A conditionally-compiled statement or item.
///
/// ## Syntax
///
/// ```plain_text
/// cond! {
///     if <if predicate> {
///         // arbitrary tokens
///     } else if <else-if predicate> {  // There can be zero or more of these.
///         // arbitrary tokens
///     } else {                         // This is optional.
///         // arbitrary tokens
///     }
/// }
/// ```
///
/// See the [predicates](index.html#predicates) section of the crate documentation for more
/// information about the predicate grammar.
#[cfg(doc)]
#[macro_export]
macro_rules! cond {
    (
        $(if $pred:ident ($($pred_args:tt)*) {
            $($yes:tt)*
        }) else + $(else {
            $($no:tt)*
        })?
    ) => {};
}

#[cfg(not(doc))]
#[macro_export]
macro_rules! cond {
    // We begin by implementing `cond!` for one level of `if ... { ... } else { ... }`.

    // true
    (
        @__internal_single_munch
        if true() {
            $($yes:tt)*
        } else {
            $($no:tt)*
        }
    ) => {
        $($yes)*
    };

    // false
    (
        @__internal_single_munch
        if false() {
            $($yes:tt)*
        } else {
            $($no:tt)*
        }
    ) => {
        $($no)*
    };

    // cfg
    (@__internal_id $($id:tt)*) => { $($id)* };
    (
        @__internal_single_munch
        if cfg($($args:tt)*) {
            $($yes:tt)*
        } else {
            $($no:tt)*
        }
    ) => {
        #[cfg($($args)*)] $crate::cond! { @__internal_id $($yes)* }
        #[cfg(not($($args)*))] $crate::cond! { @__internal_id $($no)* }
    };

    // not
    (
        @__internal_single_munch
        if not($pred:ident ($($pred_args:tt)*)) {
            $($yes:tt)*
        } else {
            $($no:tt)*
        }
    ) => {
        $crate::cond! {
            if $pred($($pred_args)*) {
                $($no)*
            } else {
                $($yes)*
            }
        }
    };

    // all
    (
        @__internal_single_munch
        if all(
            $first_pred:ident($($first_args:tt)*)
            $(, $($rest:tt)*)?
        ) {
            $($yes:tt)*
        } else {
            $($no:tt)*
        }
    ) => {
        $crate::cond! {
            @__internal_single_munch
            if $first_pred($($first_args)*) {
                $crate::cond! {
                    @__internal_single_munch
                    if all($($($rest)*)?) {
                        $($yes)*
                    } else {
                        $($no)*
                    }
                }
            } else {
                $($no)*
            }
        }
    };
    (
        @__internal_single_munch
        if all() {
            $($yes:tt)*
        } else {
            $($no:tt)*
        }
    ) => { $($yes)* };

    // any
    (
        @__internal_single_munch
        if any($first_pred:ident($($first_args:tt)*) $(, $($rest:tt)*)?) {
            $($yes:tt)*
        } else {
            $($no:tt)*
        }
    ) => {
        $crate::cond! {
            @__internal_single_munch
            if $first_pred($($first_args)*) {
                $($yes)*
            } else {
                $crate::cond! {
                    @__internal_single_munch
                    if any($($($rest)*)?) {
                        $($yes)*
                    } else {
                        $($no)*
                    }
                }
            }
        }
    };
    (
        @__internal_single_munch
        if any() {
            $($yes:tt)*
        } else {
            $($no:tt)*
        }
    ) => { $($no)* };

    // macro
    (
        @__internal_single_munch
        if macro($path:path $( => $($args:tt)*)?) {
            $($yes:tt)*
        } else {
            $($no:tt)*
        }
    ) => {
        $path! { $(args { $($args)* })? yes { $($yes)* } no { $($no)* } }
    };

    // Now, we can implement support for an arbitrary chaining of these.
    // TODO: Validate `cond!` grammar in its entirety, even if the faulty branches are never taken.

    // Because falsy paths are never expanded into the final output, bad macro calls to `cond!` are
    // ignored in the falsy paths, which is a bit janky. We avoid this scenario by validating the
    // syntax before munching through it.
    (
        $(if $pred:ident ($($pred_args:tt)*) {
            $($yes:tt)*
        }) else + $(else {
            $($no:tt)*
        })?
    ) => {
        $crate::cond! {
            @__internal_chained_munch
            $(
                if $pred($($pred_args)*) {
                    $($yes)*
                }
            ) else + $(else {
                $($no)*
            })?
        }
    };

    (
        @__internal_chained_munch
        if $pred:ident ($($pred_args:tt)*) {
            $($yes:tt)*
        } $(else $($rest:tt)*)?
    ) => {
        $crate::cond! {
            @__internal_single_munch
            if $pred($($pred_args)*) {
                $($yes)*
            } else {
                $($crate::cond! {
                    @__internal_chained_munch
                    $($rest)*
                })?
            }
        }
    };
    (
        @__internal_chained_munch
        { $($rest:tt)* }
    ) => {
        $($rest)*
    };
}

/// A conditionally-compiled expression.
///
/// ## Syntax
///
/// ```plain_text
/// cond_expr! {
///     if <if predicate> {
///         // arbitrary tokens forming a `BlockExpression`.
///     } else if <else-if predicate> {  // There can be zero or more of these.
///         // arbitrary tokens forming a `BlockExpression`.
///     } else {                         // This is optional.
///         // arbitrary tokens forming a `BlockExpression`.
///     }
/// }
/// ```
///
/// or, if you just want to evaluate a boolean literal for the predicate, the following alias can
/// be used instead:
///
/// ```plain_text
/// cond_expr!(<predicate>)
/// ```
///
/// See the [predicates](index.html#predicates) section of the crate documentation for more
/// information about the predicate grammar.
#[macro_export]
macro_rules! cond_expr {
    (
        $(if $pred:ident ($($pred_args:tt)*) {
            $($yes:tt)*
        }) else + $(else {
            $($no:tt)*
        })?
    ) => {'__cond_expr_out: {
        $crate::cond! {
            $(if $pred ($($pred_args)*) {
                break '__cond_expr_out ({ $($yes)* });
            }) else + $(else {
                break '__cond_expr_out ({ $($no)* });
            })?
        }
    }};
    ($pred:ident ($($pred_args:tt)*)) => {
        $crate::cond_expr! {
            if $pred($($pred_args)*) {
                true
            } else {
                false
            }
        }
    }
}

/// A conditional-compilation variable that always resolves to `true`.
///
/// Note that you can equivalently use the `true()` predicate inside `cfgenius` predicates.
#[macro_export]
macro_rules! truthy {
    (yes { $($yes:tt)* } no { $($no:tt)* }) => { $($yes)* };
}

/// A conditional-compilation variable that always resolves to `false`.
///
/// Note that you can equivalently use the `false()` predicate inside `cfgenius` predicates.
#[macro_export]
macro_rules! falsy {
    (yes { $($yes:tt)* } no { $($no:tt)* }) => { $($no)* };
}

/// Defines a zero or more conditional-compilation variables which evaluate to the provided `cfgenius`
/// predicate.
///
/// These merely desugar to `use` items of [`truthy!`](crate::truthy) and [`falsy!`](crate::falsy).
///
/// ## Syntax
///
/// ```plain_text
/// define! {
///     <visibility> <name> = <predicate>
/// }
/// ```
///
/// ...or, if you want to define more than one predicate:
///
/// ```plain_text
/// define! {
///     <visibility 1> <name 1> = <predicate 1>;
///     <visibility 2> <name 2> = <predicate 2>;
///     // ...
///     <visibility N> <name N> = <predicate N> // <-- the semicolon is optional.
/// }
/// ```
///
/// See the [predicates](index.html#predicates) section of the crate documentation for more
/// information about the predicate grammar.
///
/// See also the [custom variable](index.html#custom-variables) section of the crate documentation
/// for information how to define more complex variables, potentially with arguments.
#[macro_export]
macro_rules! define {
    (
        $( $vis:vis $name:ident = $pred:ident ($($pred_args:tt)*) );* $(;)?
    ) => {
        $(
            $crate::cond! {
                if $pred($($pred_args)*) {
                    $vis use $crate::truthy as $name;
                } else {
                    $vis use $crate::falsy as $name;
                }
            }
        )*
    };
}