Does macro expansion require the whole Rust language or only a subset?

Currently intellij-rust and RLS have trouble dealing with macros. That got me curious: Does macro expansion require the whole Rust language or only a subset?

In other words, can macros be expanded with a python script made in two hours?

1 Like

There are two kinds of macros: macro by example and procedural macro. For macro by example, macro expander can be written relatively easy in any language. Procedural macros would definitely require communication with native Rust code.

2 Likes

Be careful, there may not be a straightforward way to expand certain macros from a Python script at all.

macro_rules! log {
    ($msg:expr) => {{
        let state = 1;
        println!("log({}): {}", state, $msg);
    }};
}

fn main() {
    let state = "reticulating splines";
    log!(state);
}

Cannot be expanded to:

fn main() {
    let state = "reticulating splines";
    {
        let state = 1;
        println!("log({}): {}", state, state);
    }
}

Good point!

That's because macros cannot stomp existing definitions correct?

It is because macros allow you to have multiple distinct variables with exactly the same name in scope at the same time, and ordinary Rust code (i.e. what you would presumably want to get by expanding macros) does not. See the book for more on this.