rust-lang / rust-lang/rust

Bad suggestion for macro_rules macros generated from a proc-macro

Open
#132,906 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics A-edition-2024 A-lints A-suggestion-diagnostics C-bug D-edition D-invalid-suggestion I-edition-triaged L-unsafe_op_in_unsafe_fn T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

In a proc-macro that generates a macro_rules macro that triggers lints like unsafe_op_in_unsafe_fn, or unsafe_attr_outside_unsafe, the suggestion ends up suggesting that the unsafe should go around the attribute, which is invalid syntax.

// proc-macro `pm`
use proc_macro::TokenStream;

#[proc_macro_attribute]
pub fn pm(_attr: TokenStream, _item: TokenStream) -> TokenStream {
    "macro_rules! foo {
        () => {pub unsafe fn foo() { let _ = std::mem::zeroed::<i32>(); } };
    }"
    .parse()
    .unwrap()
}
#![warn(unsafe_op_in_unsafe_fn)]

#[pm::pm]
struct S;

foo! {}

Gives a suggestion that ends up being:

{ unsafe #[pm::pm]}

which is invalid syntax.

Seen with the vtable crate.

This is a bit of curious case, as I would have expected the tokens of the macro_rules definition to be 2021 edition, and that the tokens it in turns generates also be 2021. Offhand I don't know how macro_rules determine which edition the tokens it emits should be (I'm guessing it is using the edition of the local crate, instead of the edition of the generated macro_rules definition).

Meta

rustc --version --verbose:

rustc 1.84.0-nightly (143ce0920 2024-11-10)
binary: rustc
commit-hash: 143ce0920a2307b19831160a01f06f107610f1b2
commit-date: 2024-11-10
host: aarch64-unknown-linux-gnu
release: 1.84.0-nightly
LLVM version: 19.1.3

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the invalid suggestion using the proc-macro and macro_rules examples in the issue, then trace how the unsafe lint constructs suggestions across generated tokens and editions. Done means the same example produces a syntactically valid suggestion rather than placing unsafe around the attribute.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.