0

I have number of source files (001.rs, 002.rs, 003.rs, ...), each having the following content:

// FILE: 001.rs
pub const NUM: i64 = 1; // Different number per file

I would like to load all these values with a macro:

// FILE: main.rs
macro_rules! get_numbers_from_modues {
    ($start: expr, $end: expr) => {{
        let mut numbers = std::vec::Vec::<i64>::with_capacity($end - $start);

        for i in $start..=$end {
            #[path = format!("{:03}.rs", i)] // <= error: unexpected token: `format`
            mod inline_module;
            numbers.push(inline_module::NUM);
        }
        numbers
    }};
}


fn main() {
    let numbers = get_numbers_from_modues!(1, 2);
}

This doesn't compile as the path attribute had an unexpected token. Is there a way to set the attribute in a procedural way? All values are known at compile time.

This is a minimal example, there is more than the number in each file and I can't change the structure. I would simply prefer to not repeat myself for all the cases.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
magu_
  • 4,766
  • 3
  • 45
  • 79
  • Since you have all these files, they are presumably generated. Why not generate one more file that has all of the modules included and defines this `Vec`? – Shepmaster Jan 20 '20 at 13:04
  • 2
    You cannot do this the way you ask with a declarative macro. You are attempting to mix compile-time (`mod foo`) and runtime (`for i in ...`) constructs. This is not allowed. You could potentially create a procedural macro to do it though. – Shepmaster Jan 20 '20 at 13:06
  • @Shepmaster. What would I gain by moving those in a separate file? Wouldn't I still have to list all of them (having the same repetitions)? I was thinking about the procedural macro and I try to make sense out of them. But I can't really seem to be able to make things work. – magu_ Jan 20 '20 at 13:50
  • 1
    My point is that you already have some tool generating the files. **Enhance that tool** to also generate a Rust file with the correct `#[path]` and `mod` attributes, or whatever else you need. The number of files is not important to my suggestion. – Shepmaster Jan 20 '20 at 13:53
  • @Shepmaster. Got it, I'm not in control creating this files. I can always write a python script doing that for me but this seems rather hacky. But this would of course be the last resort. – magu_ Jan 20 '20 at 14:23
  • 2
    I've successfully used a `build.rs` script to do something similar. Generated N Rust files from a sequence of numbers, then a module file listing all of them. – SirDarius Jan 20 '20 at 15:11

0 Answers0