Skip to content

Allow #[attr] if to be passed to proc macros #68618

Description

@Aaron1011

The following code:

fn main() {
    #[attr] if let Some(_) = Ok(true) {}
}

produces this error:

error: attributes are not yet allowed on `if` expressions
 --> src/main.rs:2:5
  |
2 |     #[attr] if let Some(_) = Ok(true) {}
  |     ^^^^^^^

error: aborting due to previous error

Proc macros like pin-project currently use a trick to work around attributes on expressions being unstable: The entire function is annotated with a 'wrapper' attribute, which goes through and manually parses expression attributes. For example:

#[my_attr]
fn foo() {
    #[my_attr] let a = 25;
}

In the example above, the #[my_attr] let a = 25; will be processed by the outer #[my_attr] fn foo() implementation, which will strip away the expression-based #[my_attr] before emitting the final TokenStream.

Unfortunately, the current 'attributes are not yet allowed on if expressions' check is done during parsing:

self.error_attr_on_if_expr(&expr);

While the proc-macro itself can parse the attribute on the if let without any errors, compilation will still fail due to the parsing error that was emitted before any proc-macros were run.

It would be extremely useful if this check were to be moved until after parsing, so that proc macros had a chance to remove attributes from if expressions.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-attributesArea: Attributes (`#[…]`, `#![…]`)A-frontendArea: Compiler frontend (errors, parsing and HIR)A-parserArea: The lexing & parsing of Rust source code to an ASTC-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions