nicklockwood / SwiftFormat

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

`redundantParens` rule not removing redundant parens in return statement #1415

Open calda opened 1 year ago

calda commented 1 year ago

We've found some cases where the redundantParens rule isn't removing redundant parenthesis, for example in a return statement. Here are some test cases that currently fail on develop:

func testRedundantParensInReturnRemoved() {
    let input = "return (true)"
    let output = "return true"
    testFormatting(for: input, output, rule: FormatRules.redundantParens)
}

func testRedundantParensAroundTryExpressionRemoved() {
  let input = "return (try bar())"
  let output = "return try bar()"
  testFormatting(for: input, output, rule: FormatRules.redundantParens)
}

Is this a bug / oversight, or is this intentional?

jparise commented 1 year ago

Adding "return" to the rule's set of "conditionals" addresses the first case (return (true)return true). Adding it to either of these locations seems to be equivalent:

https://github.com/nicklockwood/SwiftFormat/blob/da92ec47672f1f962d60ce2a0f93c0b1293060b8/Sources/Rules.swift#L2619

https://github.com/nicklockwood/SwiftFormat/blob/da92ec47672f1f962d60ce2a0f93c0b1293060b8/Sources/Rules.swift#L2687

... but it seems like the second case (return try (...)) needs some additional support.

nicklockwood commented 1 year ago

I don't think it was intentional, but there may be some edges cases with return that I've forgotten about (e.g. if statement spans multiple lines and removing parens changes meaning).

With try, removing parens should also be fine, but have to be careful in try? case due to optional elision.