dart-lang / dart_style

An opinionated formatter/linter for Dart code
https://pub.dev/packages/dart_style
BSD 3-Clause "New" or "Revised" License
645 stars 118 forks source link

Allow comments before infix expressions to not split the operator. #1433

Closed munificent closed 5 months ago

munificent commented 5 months ago

Currently, unless captured by some SequenceBuilder or DelimitedListBuilder, comments (that aren't hanging of the previous token) get attached to the token immediately following them. For example:

value =
    // comment
    a + b;

Here, since there is a newline before // comment, it's not attached to the = and is instead attached as a leading comment to the a token owned by the identifier expression as the first operand to +.

That means that as far as the + expression is concerned, there is a newline in one of its operands, so it thinks it needs to split, leading to:

value =
    // comment
    a +
        b;

But since the comment is, to a user, outside of the infix expression, that split looks pointless.

This fixes that. When leading comments appear right before any infix-like expression (binary operator, conditional operator, binary pattern, etc.), we hoist them out of the innermost operand that would otherwise claim them and make them precede the infix piece itself.