RUSTFLAGS="-Zmacro-backtrace" cargo +nightly expand

For me, this works fine on code that COMPILES.

However, for code that does NOT compile, I get the compile error instead of the expanded code.

In the case where the code does NOT compile, is there a way to get the procedural-macro generated output ?

I suppose it depends on why it doesn't compile.

If it's mismatched braces, like this example, I don't think it can possibly work, because macro expansion can only run on a well-formed token tree, which needs to have properly nested braces.

fn main() {
  println!("Hello!"}

If it's a type mismatch, then it actually seems to work fine when I try it, like in the console session below:

$ cat src/main.rs 
fn main() {
  myfn("test");
}
fn myfn(i: u32) {
  println!("{i}");
}

$ RUSTFLAGS="-Zmacro-backtrace" cargo +nightly expand
    Checking mytest v0.1.0 (/Users/michaelhowell/mytest)
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s

#![feature(prelude_import)]
#[prelude_import]
use std::prelude::rust_2021::*;
#[macro_use]
extern crate std;
fn main() {
    myfn("test");
}
fn myfn(i: u32) {
    {
        ::std::io::_print(format_args!("{0}\n", i));
    };
}

$ cargo run
   Compiling mytest v0.1.0 (/Users/michaelhowell/mytest)
error[E0308]: mismatched types
 --> src/main.rs:2:8
  |
2 |   myfn("test");
  |   ---- ^^^^^^ expected `u32`, found `&str`
  |   |
  |   arguments to this function are incorrect
  |
note: function defined here
 --> src/main.rs:4:4
  |
4 | fn myfn(i: u32) {
  |    ^^^^ ------

For more information about this error, try `rustc --explain E0308`.
error: could not compile `mytest` (bin "mytest") due to previous error
1 Like