Skip to content

Confusing diagnostic message for a derive-macro implementation bug #107977

Open
@kiscad

Description

@kiscad

Code

// the code is from THE BOOK
// https://doc.rust-lang.org/book/ch19-06-macros.html#how-to-write-a-custom-derive-macro
// but I forgot to append `!` to `stringify`, in the `hello_macro_derive/src/lib.rs/impl_hello_macro`.
// However, the `hello_macro_derive` crate was built successfully, but the `pancake` crate,
// which uses the derive-macro, was built failed with a confusing diagnostic message.

//
// pancake/src/main.rs
//
use hello_macro::HelloMacro;
use hello_macro_derive::HelloMacro;

#[derive(HelloMacro)]
struct Pancake;

fn main() {
    Pancake::hello_macro();
}

//
// hello_macro/hello_macro_derive/src/lib.rs
//
use proc_macro::TokenStream;
use quote::quote;
use syn;

#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
    let ast = syn::parse(input).unwrap();
    impl_hello_macro(&ast)
}

fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    let gen = quote! {
        impl HelloMacro for #name {
            fn hello_macro() {
                println!("Hello Macro! This is {}", stringify(#name))
            }
        }
    };
    gen.into()
}

Current output

error[E0423]: expected function, found macro `stringify`
 --> src/main.rs:4:10
  |
4 | #[derive(HelloMacro)]
  |          ^^^^^^^^^^ not a function
  |
  = note: this error originates in the derive macro `HelloMacro` (in Nightly builds, run with -Z macro-backtrace for more info)
help: use `!` to invoke the macro
  |
4 | #[derive(HelloMacro!)]
  |                    +

For more information about this error, try `rustc --explain E0423`.
error: could not compile `pancakes` due to previous error

Desired output

`hello_macro_derive` crate should be failed to build due to `stringify`, since this does not pass the compilation in the normal crate.

Rationale and extra context

No response

Other cases

No response

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions