nicklockwood / SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
MIT License
7.67k stars 623 forks source link

Indent rule doesn't handle conditional assignment with line break after = operator #1575

Closed calda closed 7 months ago

calda commented 8 months ago

The indent rule doesn't properly handle conditional assignment expressions when formatted with a line break after the = operator.

Take this example if expression from SE-0380:

let bullet =
    if isRoot && (count == 0 || !willExpand) { "" }
    else if count == 0 { "- " }
    else if maxDepth <= 0 { "▹ " }
    else { "▿ " }

print(bullet)

on develop, this is unexpectedly re-indented to:

let bullet =
    if isRoot && (count == 0 || !willExpand) { "" }
else if count == 0 { "- " }
else if maxDepth <= 0 { "▹ " }
else { "▿ " }

print(bullet)

Since this is the formatting used in SE-0380, it seems like this will be a common preferred way to format these sorts of conditional assignment expressions.

calda commented 8 months ago

I tried to fix this as a part of https://github.com/nicklockwood/SwiftFormat/pull/1574, and made some progress.

My change indents this example correctly:

let foo =
  if let foo {
    bar
  } else {
    baaz
  }

but clearly leaves the indentation stack in the wrong state, because if you add a print statement on the following line it unexpectedly indents that to:

let foo =
  if let foo {
    bar
  } else {
    baaz
  }

  print("Unexpectedly indented, whoops")

and it also has multiple issues with the above example, outputting:

let bullet =
    if isRoot && (count == 0 || !willExpand) { "" }
        else if count == 0 { "- " }
        else if maxDepth <= 0 { "▹ " }
        else { "▿ " }

        print(bullet)
calda commented 8 months ago

@nicklockwood, I spent a few hours trying to fix this as a part of https://github.com/nicklockwood/SwiftFormat/pull/1574 and wasn't able to make much progress. I was wondering if you could take a pass on it and see if you're able to implement a better fix than me. If so it would be much appreciated!

nicklockwood commented 8 months ago

@calda thanks for looking into this. Yeah the indent logic is not the easiest thing to decipher. I'll have a stab at it.

calda commented 8 months ago

@nicklockwood, I revisited this with a different approach in https://github.com/nicklockwood/SwiftFormat/pull/1574/commits/e6b98ed4dad1086ebed875c02ee0d9a7945a48df and was able to get all of the tests passing :)

nicklockwood commented 7 months ago

Landed in 0.52.11