Idea: assigning variable names to groups

When having a group in a declarative macro ($(...) followed by ?, *, or +), you should be able to add in a name to it, to become $name(...)? (for example). This means you can still reference the group and repeat at its depth even if it contains no variables - you'd just do $name(...)? part.

For example, you could write

macro_rules! foo {
    ($name: ident, $($fields: ident $foo(special)?),*) => {
        struct $name {
            $(
                $foo(#[cfg(debug)]))?
                $fields: i64,
            )*
        }
    }
}

which would be called:

foo!(Bar, a, b, c special, d)

// produces

struct Bar {
    a: i64,
    b: i64,
    #[foo]
    c: i64
}

i.e, it'd be similar to having a macro such as

macro_rules! foo {
    (special $field: ident) => {
        #[foo]
        $field: i64
    };
    ($field: ident) => {
        $field: i64
    };
}

except that we can't expand macros to fields. Currently, the only way to do this with a declarative maco would be

macro_rules! foo {
    ($name: ident, $($fields: ident $(special $($_impl: ident)?)?),*) => {
        struct $name {
            $(
                $(#[cfg(debug)] $($_impl)?)?
                $fields: i64,
            )*
        }
    }
}

(playground)

which works, but is ugly and means the user could add arbitrary junk after #[foo].

1 Like

It's very hard to tell what you're proposing here.

After spending some time studying it, I think it's a way to check whether an optional pattern is matched or not, even if the pattern doesn't contain any variables? But you could have explained this much better.

Also, your "works" version doesn't actually compile.

1 Like

Sorry, it was very late when I wrote that up, I'll fix it.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.