Boiethios
Boiethios

Reputation: 42889

How to name an arbitrary sequence of things in a macro?

I am trying to use ? in a macro, matching an arbitrary keyword:

#![feature(macro_at_most_once_rep)]

macro_rules! foo {
    (
        pub fn $name:ident (
            & $m : $( mut )? self
        )
    ) => (
        pub fn $name (
            & $m self
        ) {}
    )
}

struct Foo;

impl Foo {
    foo!( pub fn bar(&mut self) );
    foo!( pub fn baz(&self) );
}

fn main() {}

I tried varied syntax, but they all failed. How to do this?

Upvotes: 6

Views: 337

Answers (1)

Masaki Hara
Masaki Hara

Reputation: 3545

One trick would be to insert a repetition with a dummy token.

#![feature(macro_at_most_once_rep)]

macro_rules! foo {
    (
        pub fn $name:ident (
            & $( $(@$m:tt)* mut )? self
        )
    ) => (
        pub fn $name (
            & $( $(@$m)* mut )? self
        ) {}
    )
}

struct Foo;

impl Foo {
    foo!( pub fn bar(&mut self) );
    foo!( pub fn baz(&self) );
}

fn main() {
    (&mut Foo).bar();
    (&mut Foo).baz();
    // (&Foo).bar(); //~ERROR cannot borrow
    (&Foo).baz();
}

Upvotes: 1

Related Questions