Skip to content

E0507 suggestion for borrowing mistake inside of a macro suggests a syntax error #107976

Open
@asottile

Description

@asottile

Code

here's a minimal case -- a bit nonsensical but pulled out of a larger example

Cargo.toml

[package]
name = "wat"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
wat-derive = { path = "wat-derive" }

src/main.rs

use wat_derive::Example;

trait Example {
    fn f(&self);
}

#[derive(Example)]
struct S {
    x: Option<String>
}

fn main() {
    let s = S { x: None };
    s.f();
}

wat-derive/Cargo.toml

[package]
name = "wat-derive"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
quote = "1.0.23"
syn = "1.0.107"

[lib]
proc-macro = true

wat-derive/src/lib.rs

#[proc_macro_derive(Example)]
pub fn m(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    quote::quote! {
        impl Example for S {
            fn f(&self) {
                // borrowing mistake here
                if let Some(v) = self.x {
                    dbg!(v);
                }
            }
        }
    }.into()
}

Current output

$ cargo build
   Compiling wat v0.1.0 (/home/asottile/workspace/pre-commit-rs/y/wat)
error[E0507]: cannot move out of `self.x` as enum variant `Some` which is behind a shared reference
 --> src/main.rs:7:10
  |
7 | #[derive(Example)]
  |          ^^^^^^^
  |          |
  |          data moved here
  |          move occurs because `v` has type `String`, which does not implement the `Copy` trait
  |
  = note: this error originates in the derive macro `Example` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider borrowing here
  |
7 | #[derive(&Example)]
  |          +

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

Desired output

anything else tbh -- I don't really know the correct thing to do here -- it would be nice if it pointed at the borrow error inside the macro-generated code, but I don't think rustc currently displays the generated code anywhere

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