Skip to content

Improve panic messages when in proc_macro #1957

@nik-rev

Description

@nik-rev

It can be hard to figure out which parse_quote! invocation failed because -Zmacro-backtrace is unstable + disabled by default.

What do you think about adding [file:line:column] information to panic!() messages inside of parse_quote! and parse_quote_spanned!, and others places where panic!() is used?

We would define a panic! macro as follows:

macro_rules! panic {
    ($message:literal $($tt:tt)*) => {{
        #[cfg(feature = "proc-macro")]
        let is_available = proc_macro::is_available();
        if is_available {
            let location = core::panic::Location::caller();
            let file = location.file();
            let line = location.line();
            let column = location.column();
            ::core::panic!(concat!("[{}:{}:{}] ", $message), file, line, column $($tt)*)
        } else {
            ::core::panic!($message $($tt)*)
        }
    }};
}

Then use it everywhere in the crate.

This will make it easier to debug proc-macros, by turning an error message like this:

error: proc-macro derive panicked
 --> src/lib.rs:1:10
  |
1 | #[derive(Trait)]
  |          ^^^^^^
  |
  = help: message: expected string literal

Into the following:

error: proc-macro derive panicked
 --> src/lib.rs:1:10
  |
1 | #[derive(Trait)]
  |          ^^^^^^
  |
  = help: message: [/tmp/macr/src/lib.rs:9:10] expected string literal

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions