Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a compile time condition in macros

Tags:

macros

rust

I want to set the compile-time condition in macros when it generates code outside the functions. I need something like that:

macro_rules! cond {
    ( $cond_el:expr ) => {
         #[if $cond_el == "i32"]
             struct A {
                 x: i32
             }
         #[else]
             struct A {
                 x: f64
             }
    }
}

cond!("i32");
cond!("f64");

fn main() {}

Or maybe something like that:

macro_rules! cond {
    ( $cond_el:expr ) => {
         match $cond_el {
            "i32" => {
                struct A {
                   x: i32
                }
            }
            _ => {
                struct A {
                    x: f64
                }
            }
        }
    }
}

cond!("i32");
cond!("f64");

fn main() {}

Is it possible with current Rust macros state?

like image 756
Lodin Avatar asked Sep 25 '15 04:09

Lodin


People also ask

How do you define a macro in compile time?

You can define any macro on the compiler command line with -D. Use that to specify the model or variant you want, and based on that, #ifdefs in the code enable the other relevant macros.

What is compile time condition in C?

Compile-time is the time at which the source code is converted into an executable code while the run time is the time at which the executable code is started running. Both the compile-time and runtime refer to different types of error.


1 Answers

What you're asking for is impossible. Thankfully, what you're asking for and what your examples suggest you want are two different things:

macro_rules! cond {
    ("i32") => {
        struct A {
            x: i32,
        }
    };
    ($el:expr) => {
        struct B {
            x: f64
        }
    };
}

cond!("i32");
cond!("f64");

fn main() {}

Taking your question literally, however: no, there is no way to do any sort of complex testing of conditions in macros, nor can macros set or test any kind of state outside of what's passed in to them. You can do literal matches of the direct input to the macro, or you can parse some input as one of a limited number of syntax constructs (which you then cannot match against), and that's about it.

like image 199
DK. Avatar answered Oct 26 '22 10:10

DK.