nicklockwood / SwiftFormat

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

swiftFormat incorrectly removes parentheses #1756

Open Ahbee opened 1 month ago

Ahbee commented 1 month ago

Im using the Xcode source editor extension with the default options, however swiftFormat removes parentheses which makes the math incorrect

here is my input (I leave no space between b and + to show the bug)

import Foundation

func test() -> Double {
  let a = 2.0
  let b = 3.0
  let c = a * (b+ a)
  return c
}

here is the output, notice that parentheses are gone and the function produces different results

import Foundation

func test() -> Double {
  let a = 2.0
  let b = 3.0
  let c = a * b+ a
  return c
}

a lot of times I copy and paste equations from other sources like Matlab and Python. I run swift format immediately after the paste just to clean it up a little. Then I will fix any compile issues. This bug affects my workflow since I don't expect the formatting to change math like that.

nicklockwood commented 1 month ago

Writing b+ a is not permitted in Swift anyway because whitespace around operators is meaningful, so b+ would refer to a postfix unary + operator not the infix + operator.

I'm rather surprised that your (pre-SwiftFormat) example compiles ok, but perhaps Swift just treats it as a warning instead of an error?

I might be able to handle this as a special case, but the workaround for now would be to balance the spaces around the + (either a+b or a + b should work fine)

nicklockwood commented 1 month ago

Ah, sorry I should have read your comment more closely - you aren't saying that it did compile, but that you were running SwiftFormat as a pre-compile step.

TBH I think this is a bad idea. SwiftFormat is designed to function only with valid code. If the code is malformed then the behavior of SwiftFormat is undefined.

I might be able to handle this particular case because it's possible to infer the intent from the context, but in general I can't guarantee SwiftFormat won't mangle code that isn't valid Swift to begin with

Ahbee commented 1 month ago

hmm ok I understand about the valid code thing,
but even fixing the particular case of "postfix unary operators" would be good, I am sure its a common mistake for people to write a+ b instead of a+b

On a more general note I don't think SwiftFormat should remove parentheses if the math is undefined