I want to insert code only when "a" and "b" are both passed in like foo!(a;b). But that code won't exist in foo!(a) and foo!(;b). Is there any way to do it.
Below is how I want to write it. The issue is the nested repetition.
macro_rules! ignore {
($to_ignore:ident) => {}
}
macro_rules! foo {
($($a:ident)?$(;$b:ident)?) => {
/* duplicated code */
$(
/* code that need $a */
ignore!($a);
$(
ignore!($b);
/* code that need both $a and $b */
)?
)?
/* duplicated code */
$(
ignore!($a);
/* code that only need $a */
)?
/* duplicated code */
$(
ignore!($b);
/* code that only need $b */
)?
/* duplicated code */
};
}
fn func_1(a: i32) {
foo!(a);
}
fn func_2(b: i32) {
foo!(;b);
}
fn func_3(a: i32, b: i32) {
foo!(a;b);
}
I want this part
$(
/* code that only need $a */
ignore!($a);
$(
ignore!($b);
/* code that need both $a and $b */
)?
)?
to be expanded like
foo!(;b) becomes nothing cause there's no $a
foo!(a) becomes
/* code that only need $a */
foo!(a;b) becomes
/* code that only need $a */
/* code that need both $a and $b */
but the compiler says
error: attempted to repeat an expression containing no syntax variables matched as repeating at this depth
--> src/main.rs:12:14
|
12 | $(
| ______________^
13 | | ignore!($b);
14 | | /* code that need both $a and $b */
15 | | )?
| |_____________^
error: meta-variable `a` repeats 1 time, but `b` repeats 0 times
--> src/main.rs:9:10
|
9 | $(
| __________^
10 | | /* code that only need $a */
11 | | ignore!($a);
12 | | $(
... |
15 | | )?
16 | | )?
| |_________^
error: meta-variable `a` repeats 0 times, but `b` repeats 1 time
--> src/main.rs:9:10
|
9 | $(
| __________^
10 | | /* code that only need $a */
11 | | ignore!($a);
12 | | $(
... |
15 | | )?
16 | | )?
| |_________^