Macro Fragment: keyword (kw)

pretty self explanatory, a macro fragment that takes any keyword, this wouldn't always be useful but here's one example

Examples

macro_rules! declare_x {
    ($decl_kw:kw = $v:expr) => {
        $decl_kw x = $v;
    };
}

this is one example, here's another

// Using the `macro` keyword
macro declare_fn($($keywords:kw)*) {
    $($keywords)* fn x() {}
}

Unanswered Questions

  • would this be useful in libraries, i feel its only useful for those one time macros
macro_rules! impl_marker {
    ($($safety:kw)? $Trait:ident for $($ty:ty)*) => {$(
        // we are using a variable(?) here, so a user can EASILY misuse this
        $($safety:kw)? impl $Trait for $ty {}
    )*};
}
  • what would happen with auto, safe and default? (contextual keywords)
// #![feature(specialization)]
// same macro
macro_rules! impl_marker {
    ($($safety:kw)? $Trait:ident for $($ty:ty)*) => {$(
        // we are using a variable(?) here, so a user can EASILY misuse this
        $($safety:kw)? impl $Trait for $ty {}
    )*};
}
trait MyTrait {}
impl_marker!(default MyTrait for i32);
// now what, is it ok or no?

You can pass keywords as ident; does that meet your need?

I don't think that can work since fn is a keyword, so the repeat doesn't know whether to end.

2 Likes

It's not really something for my needs, it just- something

The problem with this construct is that matching on any and every keyword is much less useful than matching on a set of specific keywords

That's because on every usage there will be some keywords that don't make sense in that position, but is matched anyway by the macro

2 Likes

For future compatibility, it seems safer to match the potential keyword as ident, and then document what you expect people to pass there. If you only want to accept a specific subset of keywords, you might want to match those keywords specifically. (I wish we had some kind of simple alternation in macro matchers.)

10 Likes

well if you really need that much power over your macros, use proc-macros