Skip to content

Attributes within patterns do not work if there is another attribute in the same pattern or above #118682

Open
@xinyufort

Description

@xinyufort

This issue was originally discussed on https://users.rust-lang.org/t/cfg-attr-to-allow-unused-variables-doesnt-work-in-patterns/103511.

I noticed some weird behavior when it comes to attributes within destructuring patterns. For example, consider the following:

#![deny(unused_variables)]

// All `macro_use` attributes can be replaced with something else too,
// e.g., `#[allow()]`

// #[macro_use]
fn main() {
    #[derive(Default)]
    struct A {
        a: u8,
        b: u8
    }

    // #[macro_use]
    let A {
        // #[macro_use]
        a,
        #[allow(unused_variables)]
        b,
    } = Default::default();
    dbg!(a);
}

This code currently compiles fine. However, if I uncomment any of the commented-out #[macro_use] lines, I get an error from the compiler complaing about b being unused.

For example, if I uncomment the #[macro_use] line on top of the main function, I receive the following error when running it in Rust playground:

   Compiling playground v0.0.1 (/playground)
warning: `#[macro_use]` only has an effect on `extern crate` and modules
 --> src/main.rs:3:2
  |
3 |  #[macro_use]
  |  ^^^^^^^^^^^^
  |
  = note: `#[warn(unused_attributes)]` on by default

error: unused variable: `b`
  --> src/main.rs:16:9
   |
16 |         b,
   |         ^ help: try ignoring the field: `b: _`
   |
note: the lint level is defined here
  --> src/main.rs:1:9
   |
1  | #![deny(unused_variables)]
   |         ^^^^^^^^^^^^^^^^

warning: `playground` (bin "playground") generated 1 warning
error: could not compile `playground` (bin "playground") due to previous error; 1 warning emitted

I would have expected that the #[allow(unused_variables)] attribute on b would be honored by the compiler, and hence not using b anywhere in the code would not trigger a compiler error. However, that is not what seems to be happening.

I have been able to reproduce this in Rust Playground, using the Rust 2021 edition and the stable channel (1.74.0), and under both debug and release mode. I have attempted all seven possible combinations of uncommented #[macro_use] attributes; each one complains about the unused variable b.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-attributesArea: Attributes (`#[…]`, `#![…]`)A-patternsRelating to patterns and pattern matchingC-bugCategory: This is a bug.T-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