comptime-if

Crates.iocomptime-if
lib.rscomptime-if
version0.1.1
created_at2026-01-25 01:57:17.458162+00
updated_at2026-01-25 04:53:21.358897+00
descriptionCompile-time `if` procedural macro for Rust
homepage
repositoryhttps://github.com/sevenc-nanashi/comptime-if
max_upload_size
id2067920
size24,555
Nanashi. (sevenc-nanashi)

documentation

README

comptime_if

docs.rs crates.io License

Simple compile-time conditional code inclusion for Rust macros.

This crate provides the comptime_if! macro, which allows you to include or exclude code blocks based on compile-time boolean expressions.

This macro is useful for macro_rules! macros that accepts boolean parameters, like this:

mod test_module {
    use comptime_if::comptime_if;

    macro_rules! export {
        ($struct_name:ident, $($key:ident = $value:expr),* $(,)?) => {
            // `export = true` before `$(key = $value),*` works as the default value
            comptime_if! {
                if export where (export = true, $($key = $value),*) {
                    pub struct $struct_name;
                } else {
                    struct $struct_name;
                }
            }
        };
        // You might want to provide a default for the case when no key-value pairs are given
        ($struct_name:ident) => {
            export!($struct_name, );
        };
    }

    // Expands to `pub struct MyStruct;`
    export!(MyStruct, export = true);
}

// `MyStruct` is publicly accessible
use test_module::MyStruct;

Syntax

The syntax for the comptime_if! macro is as follows:

comptime_if! {
    if (<condition>) where (<variable assignments>) {
        <code block if condition is true>
    } else {
        <code block if condition is false>
    }
}
  • <condition>: A boolean expression that can include variables, logical operators and parentheses. You can omit the parentheses if the condition is a single variable or a negation of a single variable. Supported operators are:
    • &&, & (logical AND)
    • ||, | (logical OR)
    • ^ (logical XOR)
    • == (logical EQUAL)
    • != (logical NOT EQUAL)
    • ! (logical NOT)
    • Parentheses ( and ) for grouping
  • <variable assignments>: A comma-separated list of variable assignments in the form <variable> = <boolean value>. Multiple assignments to the same variable will use the last assignment.

Example

use comptime_if::comptime_if;

comptime_if! {
    if condition where (condition = true) {
        println!("This code is included because condition is true.");
    } else {
        compile_error!("This code is excluded.");
    }
}

comptime_if! {
    if (a && (b || !c)) where (a = true, b = false, c = false) {
        println!("This code is included because the condition evaluates to true.");
    } else {
        compile_error!("This code is excluded.");
    }
}
Commit count: 6

cargo fmt