nicklockwood / SwiftFormat

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

SwiftFormat breaks build for one liner that combines `try` and `??` #1142

Closed ncooke3 closed 2 years ago

ncooke3 commented 2 years ago

Using latest SwiftFormat 0.49.4 version.

SwiftFormat accidentally breaks builds when trying to style a statement that combines try and ??.

Consider the below snippet:

func foo(_ bar: String?) throws -> String {
    return try bar ?? { throw CustomError.emptyValue }()
}

The returning one-liner is a bit funky, but is supposed to read like:

return this optional string's value if it is non-nil; else, throw an error

Formatting the above swift snippet results in the following diff.

-     return try bar ?? { throw CustomError.emptyValue }()
+     return try bar ?? throw CustomError.emptyValue          // 🔺 Expected expression after operator

The new diff breaks fails to compile with the following error:

main.swift:11:23: error: expected expression after operator
    return try bar ?? throw CustomError.emptyValue

I have a repo with instructions here: https://github.com/ncooke3/repros/tree/main/swiftformat-1142

nicklockwood commented 2 years ago

@ncooke3 thanks for reporting this. Disabling the redundantClosure rule should fix it for now.

nicklockwood commented 2 years ago

cc: @calda

calda commented 2 years ago

Interesting! This rule probably need to filter out closures that include throw. Should be a quick fix, will take a look.

nicklockwood commented 2 years ago

@calda don't worry, I have a fix already.

calda commented 2 years ago

Great, thanks!

nicklockwood commented 2 years ago

@ncooke3 fixed in 0.49.5