Macro debug help


macro_rules! def_db {
    ($db_name:ident,
    $db_diff_name:ident,
    ($($field_name:ident, $field_type:tt),* )) => {
        pub struct $db_name {}

        pub struct $db_diff_name {}
    };
}

def_db!(Blah, BlahDiff, ((x, u32),));

I am baffled by why the repetition pattern is not capturing. I am expecting field_name = x, field_type = u32.

Your macro doesn't allow trailing commas. Try removing the comma or adding an $(,)? to consume trailing commas. You're also missing a parenthesis.

macro_rules! def_db {
    ($db_name:ident,
    $db_diff_name:ident,
    ($(($field_name:ident, $field_type:tt)),* $(,)? )) => {
        pub struct $db_name {}

        pub struct $db_diff_name {}
    };
}
1 Like

I don’t understand your question. The error message is

   Compiling playground v0.0.1 (/playground)
error: no rules expected the token `(`
  --> src/lib.rs:14:26
   |
3  | macro_rules! def_db {
   | ------------------- when calling this macro
...
14 | def_db!(Blah, BlahDiff, ((x, u32),));
   |                          ^ no rules expected this token in macro call

We have

def_db!(Blah          , BlahDiff           , (    (                 //x, u32),));
       ($db_name:ident, $db_diff_name:ident, ( $( $field_name:ident //, $field_type:tt),* ))
//                                                ^^^^^^^^^^^^^^^^^
//                                     parenthesis doesn’t match `:ident`
1 Like
def_db!(Blah          , BlahDiff           , (   (                //x, u32),));
       ($db_name:ident, $db_diff_name:ident, ($( $field_name:ident//, $field_type:tt),* ))

I failed to recognize that $( was a single token.

By the way, if you want to emulate Rust’s typical behavior of allowing optional trailing commas on everything except on an empty list of things, the way to do it is with

$($( …………… ),+ $(,)?)?
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.