Skip to content

Keep comments that are near an if’s condition closer to that condition #807

@roryokane

Description

@roryokane
The original Prettier 1.13.6 Playground link

Prettier 1.13.6
Playground link

--parser babylon
--trailing-comma false

Prettier 2.1.2
Playground link

--parser babel

Input:

if (foo) { // foo may not exist
  doThing(foo);
}

if (foo)
// foo may not exist
{
  doThing(foo);
}

if (foo) /* foo may not exist */ {
  doThing(foo);
}

Output:

if (foo) {
  // foo may not exist
  doThing(foo);
}

if (foo) {
  // foo may not exist
  doThing(foo);
}

if (foo) {
  /* foo may not exist */ doThing(foo);
}

In the current output, the comments are moved into the block after the if.

As for the desired output, I'm not sure in each of the three cases where the comments should go. Either they shouldn't be moved:

if (foo) { // foo may not exist
  doThing(foo);
}

if (foo)
// foo may not exist
{
  doThing(foo);
}

if (foo) /* foo may not exist */ {
  doThing(foo);
}

Or they should be moved before the if, rather than into the block after the if:

// foo may not exist
if (foo) {
  doThing(foo);
}

// foo may not exist
if (foo) {
  doThing(foo);
}

/* foo may not exist */ if (foo) {
  doThing(foo);
}

I think the second case has a higher likelihood of deserving to be moved than the first and third cases.

Related issue

Pull request #672 “Stabilize comments inside of if/then/else before {” made a change related to the last of the three cases, but it simply made the current output stable, rather than changing what that output was.

Similar cases with acceptable output

For completeness, these similar cases are formatted in a way I am okay with, though it’s possible others would want the comment placement to always be preserved:

The original Prettier 1.13.6 Playground link

Prettier 1.13.6
Playground link

--parser babylon
--trailing-comma false

Prettier 2.1.2
Playground link

--parser babel

Input:

if (foo) // foo may not exist
{
  doThing(foo);
}

if /* foo may not exist */ (foo) {
  doThing(foo);
}

/* foo may not exist */ if (foo) {
  doThing(foo);
}

Output:

if (foo) {
  // foo may not exist
  doThing(foo);
}

if (/* foo may not exist */ foo) {
  doThing(foo);
}

/* foo may not exist */ if (foo) {
  doThing(foo);
}

Scope of this issue

All of these examples also apply to constructs other than if, such as while and for, that can have comments next to their conditions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:commentsIssues with how Prettier prints commentshelp wantedWe're a small group who can't get to every issue promptly. We’d appreciate help fixing this issue!lang:javascriptIssues affecting JSlocked-due-to-inactivityPlease open a new issue and fill out the template instead of commenting.

    Type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions