1

I'm working on a project that uses some complex declarative macros. I ran into an issue, which I have dumbed down in the following simple code snippet. I can't understand why I cannot form the set of arguments to pass to a function with a macro.

What am I missing? Thank you all in advance!

macro_rules! replace {
    () => {a, b};
}

fn add_num (a: u32, b: u32) -> u32 {
    a+b
}

fn main() {
    let a : u32 = 2;
    let b : u32 = 4;

    println!("{}", add_num(replace!()));
}
pedro
  • 83
  • 5
  • An alternative would be to have the macros take in the function name and call the function themselves. – EvilTak Feb 19 '22 at 17:19
  • 1
    I believe, even if this macro worked, that it would be considered "unhygienic" -- macros should not refer to identifiers that they aren't given access to. – cdhowie Feb 19 '22 at 20:16
  • @EvilTak that would work for this small example - but not in the larger project, where I have to go through a tt recursively in order to extract some parameters/recognize some conditions... meaning that I would always have to call the macro again add_num( ) - leading to the same situation above. – pedro Feb 19 '22 at 20:54
  • @cdhowie passing the identifiers themselves with replace!(a, b) also doesn't work: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=5277756e43c8c0e8b9d5cd4bd531fa52 – pedro Feb 19 '22 at 21:00
  • I don't think you can do this with declarative macros. In expression position, they are expected to generate a single expression. `a, b` is not an expression. You may need to use procedural macros. – cdhowie Feb 19 '22 at 21:08
  • Does this answer your question? [Using macros so that you don't have to write down a long parameter list every time](https://stackoverflow.com/questions/70059146/using-macros-so-that-you-dont-have-to-write-down-a-long-parameter-list-every-ti) – Chayim Friedman Feb 19 '22 at 23:27
  • (I know this is talking about the parameters list, but the answer it the same) – Chayim Friedman Feb 19 '22 at 23:27

1 Answers1

1

This answer has exactly what I was looking for:

Calling functions with different numbers of arguments in Rust macros

My code snippet was an over simplification which actually lead me to a different problem. The original issue I had was solved similarly to the answer in the link: by building the argument list and keep passing the function name until the last match, which is where the function is called with the final argument list.

Thank you all!

pedro
  • 83
  • 5