Macro_rules! - can tokens be transformed?

Suppose I were trying to write a macro that transforms the case of an identifier:

macro_rules! caser {
    ($i:ident: Camel) => { // => AbcDef ... // };
    ($i:ident: camel) => { // => abcDef ... // };
    ($i:ident: kebab) => { // => abc-def ... // };
    ($i:ident: snake) => { // => abc_def ... // };
};

Is there any way with macro_rules! macros to transform matched pattern tokens before they're used in the template? It does not appear so. The Little Book of Rust Macros has some clever techniques but none of them seems to address this particular "case". I could call stringify!() on the token and do string or regexp replacement, but then it would be only be usable as a string literal in contexts expecting an expr. Is there any way to coerce it back into an ident (and yes, I'm aware that kebab-case output wouldn't work in any context - this is only an example) ?

No, you'll have to write a procedural macro.

Or use a pre-existing one.

4 Likes

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.