prettier-plugin-solidity icon indicating copy to clipboard operation
prettier-plugin-solidity copied to clipboard

Unwanted line wrap in if/else conditions without curly brackets

Open LilaRest opened this issue 2 years ago • 4 comments

Hi ! Firstly, thanks for this amazing plugin.

Then, a thing I visually love is to write inline if/else conditions when their content is composed by a single simple line, e.g.,

// Comment 1 and Comment 2
if (balanceOf(msg.sender) >= 1000) priority = true;

// Instead of

// Comment 1
if (balanceOf(msg.sender) >= 1000) {
    // Comment 2
    priority = true;
}

This plugin seems to allow this except if the if statement is followed by an else if or else statement that uses curly brackets. So the above example will work but this one will receive a line wrap :

// Comment 1 and Comment 2
if (balanceOf(msg.sender) >= 1000)
    priority = true;

    // Comment 3
else {
    // ...multi-line stuff here
}

As you can see the else comment is not anymore aligned with the else statement, and the if statement is not inline anymore.

However, if the if line doesn't exceed the Prettier's printWidth, the expected result would be:

// Comment 1 and Comment 2
if (balanceOf(msg.sender) >= 1000) priority = true;

// Comment 3
else {
    // ...multi-line stuff here
}

LilaRest avatar Jun 11 '23 16:06 LilaRest

Oh I've figured that by removing // Comment 3 it works as expected. But now I can't comment my else statement ^^

LilaRest avatar Jun 11 '23 17:06 LilaRest

I see, thanks for reporting this. Fixing this kind of comment-related stuff tends to be a PITA, but I agree it's not ideal.

For the record, prettier-js does what you expect (so we should aim for the same behavior):

function f() {
  // Comment 1
  if (x > 0) x--;
  // Comment 2
  else {
    x++;
  }
}

fvictorio avatar Jun 14 '23 07:06 fvictorio

@fvictorio Yeah indeed I'm used to use this syntax too in JS/TS, thanks for checking. I'm really not familiar with your codebase so it's probably not relevant, but it looks like by adding the // Comment 3 the formatter is considering that the if statement is a kind of 2 lines inline if statement, which shouldn't be possible if there is not wrapping. Any inline if statement that doesn't wrap should be considered as one single line.

LilaRest avatar Jun 14 '23 09:06 LilaRest

Hi,

Sorry for the late reply.

This is not an new idea for me. I've actually attempted twice over the years implementing all the cases for if/else statements that prettier has in JS. both times it took me too long since, it required me to drop current cases and reimplement them using the new comment strategy, and the branch stayed too far away in the Git tree.

Will give it yet another go at these cases and see if the third time is the charmed.

Janther avatar Jul 05 '23 21:07 Janther