Skip to content

(..=0 | 2) in macro does not compile without parentheses but generates warning for unnecessary parentheses #120737

Open
@astra90x

Description

@astra90x

I tried this code:

matches!(2, ..=0 | 2)
matches!(2, (..=0 | 2))

I expected to see this happen: At least one of the expressions should compile without warning.

Instead, this happened: The first expression does not compile. The second expression generates a warning asking you to remove the parentheses.

This happens with any macro with a pattern matcher that ends up used. Skipping the parentheses does compile if the unstable exclusive range patterns are used, so I imagine this should work as well.

   Compiling playground v0.0.1 (/playground)
error: no rules expected the token `..=`
   --> src/lib.rs:2:17
    |
2   |     matches!(2, ..=0 | 2);
    |                 ^^^ no rules expected this token in macro call
    |
note: while trying to match meta-variable `$pattern:pat`
   --> /playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/macros/mod.rs:430:24
    |
430 |     ($expression:expr, $pattern:pat $(if $guard:expr)? $(,)?) => {
    |                        ^^^^^^^^^^^^

warning: unnecessary parentheses around pattern
 --> src/lib.rs:3:17
  |
3 |     matches!(2, (..=0 | 2));
  |                 ^        ^
  |
  = note: `#[warn(unused_parens)]` on by default
help: remove these parentheses
  |
3 -     matches!(2, (..=0 | 2));
3 +     matches!(2, ..=0 | 2);
  |

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

Meta

rustc --version --verbose:

rustc 1.75.0 (82e1608df 2023-12-21)
binary: rustc
commit-hash: 82e1608dfa6e0b5569232559e3d385fea5a93112
commit-date: 2023-12-21
host: x86_64-unknown-linux-gnu
release: 1.75.0
LLVM version: 17.0.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.A-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)A-patternsRelating to patterns and pattern matchingA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-bugCategory: This is a bug.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.L-unused_parensLint: unused_parensT-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