Skip to content

Rustfmt breaks attributed blocks only containing comments #4522

@vallentin

Description

@vallentin

I was refactoring and commented out a chunk of code inside an attributed block. Wherein rustfmt proceeded to format the code, by repeating the attribute(s) (the first without the #) and the starting brace within the block.

I've tried a few variations, and the issue seems to occur, if a block has at least one attribute, while the block itself only contains comments. (Adding just a single line of code anywhere in the block, before or after the comment(s) stops the issue.)

The issue occurs both on stable and nightly.

Line Comments

Before rustfmt:

fn main() {
    #[cfg(feature = "foo")]
    {
        // let foo = 0;
    }
}

After rustfmt (both stable and nightly):

fn main() {
    #[cfg(feature = "foo")]
    {
        [cfg(feature = "foo")]
    { // let foo = 0;
    }
}

Block Comments

Before rustfmt:

fn main() {
    #[cfg(feature = "foo")]
    {
        /*
        let foo = 0
        */
    }
}

After rustfmt (both stable and nightly):

fn main() {
    #[cfg(feature = "foo")]
    {
        [cfg(feature = "foo")]
    { /*
         let foo = 0
         */
    }
}

Exception

I found one exception. If the block only contains a single block comment, and it is specifically written in a single line. Then rustfmt still formats it, but not in a way that breaks the code.

Before rustfmt:

fn main() {
    #[cfg(feature = "foo")]
    {
        /* let foo = 0; */
    }
}

After rustfmt (both stable and nightly):

fn main() {
    #[cfg(feature = "foo")]
    { /* let foo = 0; */ }
}

Multiple Attributes

Before rustfmt:

fn main() {
    #[foo]
    #[bar]
    #[baz]
    {
        // let foo = 0;
    }
}

After rustfmt (both stable and nightly):

fn main() {
    #[foo]
    #[bar]
    #[baz]
    {
        [foo]
    #[bar]
    #[baz]
    { // let foo = 0;
    }
}

rustfmt 1.4.20-stable (48f6c32 2020-08-09)
rustfmt 1.4.24-nightly (eb894d5 2020-11-05)

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: this is a bug; use also I-* labels for specific bug kinds, e.g. I-non-idempotency or I-ICES-duplicateStatus: duplicate of another issue or PR

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions