Ensure comment formatting is idempotent. #1610
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
In some cases, a line comment can appear between two tokens that otherwise never split, like after "if (" and before the condition. That leads to some tricky edge case behavior. If you formatted:
It would see the newline before the comment and decide the comment was a "leading comment" which means it gets attached to the condition expression. Then the formatter would output it like:
That's because leading comments don't write a newline before themselves. Then if you format that again, there's no newline before the
//
, so now it's a hanging comment. Hanging comments get a space before them, so you get:Really, leading comments (as the name implies) are intended to always begin a line. So this PR makes sure they do that.
While I was at it, I modified the test runner to run the formatter twice on every test to ensure that everything is idempotent. That doesn't prove that the formatter will always produce idempotent output, but it at least gives us pretty good test coverage that it does behave idempotent-ly.
In practice, most normal looking code would never hit this edge case. You have to put a comment in an unusual spot where a split doesn't occur.
This still feels like a fairly brittle part of the formatter to me. Comments appearing between tokens that never split otherwise is handled on a pretty ad hoc basis (which is why some of the tests in this PR have weird indentation). I'd like a cleaner more systematic solution, but I'm not sure what that would look like.
Fix #1606.