1

Suppose I have an ident input parameter named module_name. How can I generate the value of the attribute through this parameter?

In simple terms, I want to generate something like this:

macro_rules! import_mod {
    ( $module_name:ident ) => {
        // This does not work,
        // but I want to generate the value of the feature attribute.
        // #[cfg(feature = $module_name)]
        pub mod $module_name;
    }
}

import_mod!(module1);

// #[cfg(feature = "module1")]
// pub mod module1;
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
Hentioe
  • 228
  • 1
  • 9
  • 1
    Does this answer your question? [How to embed a Rust macro variable into documentation?](https://stackoverflow.com/questions/43353077/how-to-embed-a-rust-macro-variable-into-documentation) – Jmb Apr 27 '20 at 06:42
  • @Jmb did you manage to apply that answer to OP's? It doesn't work for me. I think this needs proc macros. – Peter Hall Apr 27 '20 at 10:26
  • @PeterHall no, you're right, the duplicate answer doesn't work here… – Jmb Apr 27 '20 at 13:09

1 Answers1

1

The argument in the compiler directive must be a literal.

One half decent work-around is to take a literal as well as your 'feature':

macro_rules! my_import {
    ( $module_name:ident, $feature_name:literal ) => {
        #[cfg(feature = $feature_name)]
        mod $module_name;
    }
}

my_import!(foo, "foo");

For reference - https://doc.rust-lang.org/stable/reference/attributes.html#meta-item-attribute-syntax

To summarize: most built in attributes have the rule #[<attribute> = <literal>]

chub500
  • 712
  • 6
  • 18