Skip to content

Syntax error when using multiple cfg attributes #78175

Closed
@lamafab

Description

@lamafab

I encountered a weird behavior when using cfg(test) and cfg(not(test)).

I tried this code:

fn does_not_work() -> usize {
    #[cfg(not(test))]
    0

    #[cfg(test)]
    1
}

Results in:

   Compiling playground v0.0.1 (/playground)
error: expected one of `.`, `;`, `?`, `}`, or an operator, found `#`
 --> src/lib.rs:6:5
  |
4 |     0
  |      - expected one of `.`, `;`, `?`, `}`, or an operator
5 | 
6 |     #[cfg(test)]
  |     ^ unexpected token

error: aborting due to previous error

error: could not compile `playground`.

To learn more, run the command again with --verbose.

Workaround

fn does_work() -> usize {
    #[cfg(not(test))]
    return 0; // `return` including a semicolon

    #[cfg(test)]
    1
}

Meta

Rust stable version 1.47.0

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f7f7eb30327396c209b0f358b1a3072b

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-attributesArea: Attributes (`#[…]`, `#![…]`)A-diagnosticsArea: Messages for errors, warnings, and lintsA-parserArea: The lexing & parsing of Rust source code to an ASTC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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