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


#1

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?


#2

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.


#3

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);
    }
}

#4

Good point!

That’s because macros cannot stomp existing definitions correct?


#5

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.