Adding line!() to macro expansion

I'm trying to insert line number into macro expansion.

I have:

#[macro_export]
macro_rules! static_probe {
    ( $( $provider:ident, $name:ident ),* ) => {
        mod foo_ { 
        }
    }
}

I want to get:

mod foo_20 {
}
(where 20 would be line number. I do not care if it means number before or after expansion )

Things that don't work:

mod foo_line!() {
mod foo_$(line!()) {
mod foo_((line!())) {

How do I get it?

You can't do this with macro_rules!. You cannot construct identifiers with macro_rules!. No, not even concatention. No, not even simple ones. No, really. No, that won't work, either. Or that. Or that.

Yes, I know concat_idents! is a thing; it's useless. No, really. I don't know; it must've seemed like a good idea at the time. Because it can't actually produce an identifier. Because that's how the macro system works. Well maybe it is stupid, but that's what we've got.

Because macros can't return names; the closest they can do is an expression. Because then everywhere in the compiler it uses a simple interned Name it suddenly has to deal with potentially un-expanded macro trees. I dunno, I suppose you could, but clearly no one's been crazy enough to change it so that works.

Yes, I know, but you still can't do it. Well, have you tried a build script? Or a procedural macro with the new "Macros 1.1" business? No, I know, but that doesn't mean you can't trick the compiler into it. Write a macro that expands to an attribute on a dummy struct that just drops the struct. No, I don't know why they didn't just allow it, either.

Well you can't stick to macro_rules!. Crying isn't going to help.

No, that isn't going to help, either. I don't even know what kind of whiskey would work.

I don't know, Tuesdays, I suppose.

No, I don't drink.

(Can you tell this has come up before? :P)

4 Likes

Thanks. ProcMacro will do in that case.