[Solved] How to write a compiler plugin to conditionally compile module?


#1

Hi, all!

I am writing a compiler plugin that expands

choose! {
    test_a
    test_b
}

to

#[cfg(feature = "a")]
mod test_a;
#[cfg(feature = "b")]
mod test_b;

It is almost done now, but the module contains nothing in the finally expanded code. I guess the reason is the span didn’t cover the module file.

My code is pasted here. I am looking forward to any suggestion or advice!

Thanks in advance!


#2

One way would be to use the quote_item! macros like that:

 let module = quote_item!(cx, mod $module_ident;);

Where module_ident is a variable containing the identifier you parsed (so arg in your case, I believe).

One issue with that solution is that it will panic if it can’t parse the module. If this a problem for you, you could look at the implementation of the macro (https://github.com/rust-lang/rust/blob/308824acecf902f2b6a9c1538bde0324804ba68e/src/libsyntax/ext/quote.rs#L427) and rewrite it in a non panicking way.


#3

Thanks! And I have found out the solution myself.