Skip to content

Placing an attribute on a generic argument confuses the parser #135017

Open
@weiznich

Description

@weiznich

Code

struct Foo<T>(T);

fn main() {
    let foo: Foo<#[cfg(not(wrong))] String> = todo!();
}

Current output

error: invalid const generic expression
 --> /playground/src/main.rs:8:37
  |
8 |     let foo: Foo<#[cfg(not(wrong))] String> = todo!();
  |                                     ^^^^^^
  |
help: expressions must be enclosed in braces to be used as const generic arguments
  |
8 |     let foo: Foo<#[cfg(not(wrong))] { String }> = todo!();

Desired output

error: attributes are not allowed on generic arguments 
--> /playground/src/main.rs:8:37
  |
8 |     let foo: Foo<#[cfg(not(wrong))] String> = todo!();
  |                  ^^^^^^^^^^^^^^^^^^
  |                  attribute not allowed in this context
help: remove the attribute to allow the code to compile:
8 |     let foo: Foo<String> = todo!();

Rationale and extra context

Playground link: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=eaf1097ff4efa3734d3a5e3faa3cb10f

Other cases

If one applies the suggestion made in the current error, you get the "same" error message suggesting to add another level of brackets.

Rust Version

Build using the Nightly version: 1.85.0-nightly

(2025-01-01 45d11e51bb66c2deb63a)

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-parserArea: The lexing & parsing of Rust source code to an ASTT-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