pragma Macro
Mostly an experimentation macro. The pragma! macro provides a powerful experimental inline DSL for conditional item inclusion in Rust code. It lets you specify conditions on functions, modules, or other items and automatically generates #[cfg(...)] attributes with supporting logic (including and, or, not, and parenthesized groups) for complex conditional compilation scenarios.
Full example
Here's a full example that utilizes all of pragma's language extensions:
use pragma;
pragma!
Language extensions
-
Simple Conditional Items: You can write:
pragma! -
Visibility-Aware Items: If you specify a visibility modifier before
(if condition), two versions of the item are generated:- A public version with
#[cfg(condition)] - A private version with
#[cfg(not(condition))]
For example:
pragma!This expands to:
Without any visibility specified, only a single
#[cfg(condition)]version of the item is generated:pragma!Expands to:
- A public version with
-
Unconditional Items: You can mix normal, unconditional items with conditional ones. For example:
pragma! -
Modules With Conditions: You can also apply conditions to entire modules:
pragma!This expands to a public module if
testis enabled, or a private module otherwise. -
Complex Conditions: The conditions inside
(if ...)support a custom DSL withand,or,not, parentheses for grouping, and key-value checks:- Use
andandorfor logical conjunction and disjunction. - Wrap conditions in parentheses to control evaluation.
- Use
not(...)for negation. - Use
key = "value"for cfg key-value pairs, and barekeyfor boolean cfg options.
Examples:
pragma!Expands to:
- Use
Motivation
If you're wondering why this was written in the first place, then the answer is:
(1) having used C I have been very used to pre-processor directives and while the same can often be done with #[cfg(..)] I feel "more at home" using something more C-style. Of course, ideally I would be able to apply it to a whole module file without explicit invocation, but from my understanding of Rust macros, that isn't currently possible.
(2) experimenting to test the limits of what can and cannot be done with procedural macros
I published this here if someone finds it useful.
Say you have something like this in C:
// struct definition when FEATURE_FLAG is enabled
;
// struct definition when FEATURE_FLAG is not enabled
;
Then you can write something similar in Rust using this macro:
pragma!
In vanilla Rust, this would be:
License
This crate is distributed under the Apache-2.0 License.