[Solved] Macro: "text" satisfies ident in some cases

#1

I have the following macro:

macro_rules! foo {
    ($a:ident) => { println!("Hello"); };
}

and calling it like so works:

foo!(int)

and prints “Hello”, but when I change it to be either

macro_rules! foo {
    ($($a:ident)+) => { println!("Hello"); };
}

or

macro_rules! foo {
    ($($a:ident),+) => { println!("Hello"); };
}

and run it with

foo!(int int)
//or
foo!(int, int,)

I get an error:

   |   foo!(int, int,)
   |        ^^^ no rules expected this token in macro call

Why doesn’t this work?
Note that the entire file I’m using is this:

// src/main.rs
pub fn main() {
    foo!(int, int,)
}

By the way I’m using int in this case just because it is what I had created an error message for, I’m writing a macro to turn a C# type to its equivalent rust type. Specifically for things like this:

type ffi_fn = ffi!(csharp public static void run_abc(string name));
//ffi_fn = `extern fn(*const u8) -> ()
0 Likes

#2

I can’t replicate the problems you’re describing on the playpen. Instead of isolated snippets of code, please post a complete example of the macro, the usage, and the error you’re getting.

0 Likes

#3

Sorry for the short reply, but here’s a playpen and it should describe the error on compilation. I’m on mobile by the way
Oops sorry I didn’t read the error message properly, seems I might have to look further into it

0 Likes

#4

Yeah, that is because you have a trailing comma. That’s fixed by putting $(,)* at the end of the macro pattern.

1 Like

#5

Or even better: $(,)? on the 2018 edition

1 Like

#6

Ah it seems I was missing a $ in my macro before the start of a repeat. Sorry for the confusion. :sweat_smile:

1 Like