Is it possible to define a macro that processes grammar cases?

I would like to define a macro callmethat can be applied as follows.

fn main() {
    let a=4;
    let b=5;
    callme!(
        a (b) => { a+b } ;
        a (b) => { a*b } ;
        a (b) ~ C
    );
}

I do not know how to get a working macro definition for callme. I'm currently trying to do something like this:

macro_rules! callme {
    (
        $($A: ident ($B: ident) => {$E: expr}) ; *
    ) => (
        $(
            println!("{:?} {:?} {:?}", $A, $B, $E);
        ) *
    );
    (
        $($A: ident ($B: ident) ~ $Q: ident) ; *
    ) => (
        $(
            println!("We got {:?} . {:?} . {:?}", $A, $B, $Q);
        ) *
    );
}

This does not work because I cannot use both cases of syntax at once.

+4
source share
1 answer

When you work with a stream of tokens, it is easier to leave it for recursion in order to process your fragments in such cases. For example, you can:

macro_rules! callme {
    ($A:ident ($B:ident) => { $E:expr }; $($rest:tt)*) => {
        println!("{:?} {:?} {:?}", $A, $B, $E);

        callme!($($rest)*);
    };
    ($A:ident ($B:ident) ~ $Q:ident; $($rest:tt)*) => {
        println!("We got {:?} . {:?} . {:?}", $A, $B, $Q);

        callme!($($rest)*);
    };
    () => {};
}

fn main() {
    let a=4;
    let b=5;
    let c = "C";
    callme!(
        a (b) => { a+b } ;
        a (b) => { a*b } ;
        a (b) ~ c;
    );
}

( On the playground )

, callme!, () => {} .

+8

Source: https://habr.com/ru/post/1685561/


All Articles