rustfmt icon indicating copy to clipboard operation
rustfmt copied to clipboard

Rustfmt loses comments in variants between the name and the discriminant

Open LDVSOFT opened this issue 2 years ago • 4 comments

Consider this code that I don't consider to be pretty:

pub enum JmpCondition {
	Overflow = 0b0000,
	NoOverflow = 0b0001,
	Below /* or NotAboveOrEqual */ = 0b0010,
	AboveOrEqual /* or NotBelow */ = 0b0011,
	Equal /* or Zero */ = 0b0100,
	NotEqual /* or NotZero */ = 0b0101,
	BelowOrEqual /* or NotAbove */ = 0b0110,
	Above /* or NotBelowOrEqual */ = 0b0111,
	Sign = 0b1000,
	NoSign = 0b1001,
	ParityEven /* or Parity */ = 0b1010,
	ParityOdd /* or NotPar */ = 0b1011,
	Less /* or NotGreaterOrEqual */ = 0b1100,
	GreaterOrEqual /* or NotLess */ = 0b1101,
	LessOrEqual /* or NotGreater */ = 0b1110,
	Greater /* or NotLessOrEqual */ = 0b1111,
}

Invoking rustfmt on this strips the comments, and while I can agree that's not the best place to put them I'd expect rustfmt will not go to destroy them.

Versions: 1.5.1 / 1.5.2-nightly.

LDVSOFT avatar Mar 12 '23 10:03 LDVSOFT

Thanks for the report!

Confirming I can reproduce this with rustfmt 1.5.2-nightly (34f9ca28 2023-02-16).

The issue is that rustfmt isn't expecting to find comments in that location and doesn't try to recover them when rewriting the enum variant. I also want to highlight that this is an issue for all enum variants:

Running rustfmt on the following:

enum VanishingComments {
    Identifier /* Comment */ = 1,
    Tuple(usize) /* Coment */ = 2,
    Struct{name: String} /* Comment */ = 3,
}

produces:

enum VanishingComments {
    Identifier = 1,
    Tuple(usize) = 2,
    Struct { name: String } = 3,
}

ytmimi avatar Mar 13 '23 03:03 ytmimi

Until this is resolved your best option might be to use #[rustfmt::skip] to prevent rustfmt from performing any rewriting.

#[rustfmt::skip]
pub enum JmpCondition {
	Overflow = 0b0000,
	NoOverflow = 0b0001,
	Below /* or NotAboveOrEqual */ = 0b0010,
	AboveOrEqual /* or NotBelow */ = 0b0011,
	Equal /* or Zero */ = 0b0100,
	NotEqual /* or NotZero */ = 0b0101,
	BelowOrEqual /* or NotAbove */ = 0b0110,
	Above /* or NotBelowOrEqual */ = 0b0111,
	Sign = 0b1000,
	NoSign = 0b1001,
	ParityEven /* or Parity */ = 0b1010,
	ParityOdd /* or NotPar */ = 0b1011,
	Less /* or NotGreaterOrEqual */ = 0b1100,
	GreaterOrEqual /* or NotLess */ = 0b1101,
	LessOrEqual /* or NotGreater */ = 0b1110,
	Greater /* or NotLessOrEqual */ = 0b1111,
}

ytmimi avatar Mar 13 '23 03:03 ytmimi

Thanks! #[rustfmt::skip] is an overkill, I switched to comments outside of variants.

LDVSOFT avatar Mar 23 '23 13:03 LDVSOFT

@rustbot claim

HarrisonHemstreet avatar Jun 29 '23 05:06 HarrisonHemstreet