Skip to content

Confusing "arbitrary expressions aren't allowed in patterns" error #99380

Closed
@est31

Description

@est31

Take the following code:

macro_rules! foo {
    ($p:expr) => {
        if let $p = Some(42) {
            return;
        }
    };
}

fn main() {
    foo!(Some(3));
}

Currently it fails with:

error: arbitrary expressions aren't allowed in patterns
  --> src/main.rs:10:10
   |
10 |     foo!(Some(3));
   |          ^^^^^^^

If you expanded the macro manually, Some(3) would be parsed as a pattern, but the $p:expr above changes it to be parsed as an expression. So what you need to do here is to change the $p:expr above to $p:pat. But this is very non-obvious.

Ideally, the compiler would try to check if the input is a valid pattern, and if so, add a note like "Some(3) is a valid pattern but the metavariable $p is specified to be an expression", and maybe also point to the metavariable's matcher.

@rustbot label A-macros

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.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