Fix issue where parseExpressionRange wouldn't handle expressions with generic arguments, like 'Foo<Bar>()'

This commit is contained in:
Cal Stephens
2024-03-16 11:16:31 +00:00
committed by Nick Lockwood
parent 8a090088c8
commit cda4831620
3 changed files with 21 additions and 3 deletions
+3 -3
View File
@@ -1299,7 +1299,7 @@ extension Formatter {
/// - Any value can be preceded by `try`, `try?`, `try!`, or `await`
/// - Any value can be followed by a postfix operator
/// - Any value can be followed by an infix operator plus a right-hand-side expression.
/// - Any value can be followed by an arbitrary number of method calls `(...)` or subscripts `[...]`.
/// - Any value can be followed by an arbitrary number of method calls `(...)`, subscripts `[...]`, or generic arguments `<...>`.
/// - Any value can be followed by a `.identifier`
func parseExpressionRange(startingAt startIndex: Int) -> ClosedRange<Int>? {
// Any expression can start with a prefix operator, or `await`
@@ -1355,8 +1355,8 @@ extension Formatter {
let nextToken = token(at: nextTokenIndex)
{
switch nextToken {
// Any expression can be followed by an arbitrary number of method calls `(...)` or subscripts `[...]`.
case .startOfScope("("), .startOfScope("["):
// Any expression can be followed by an arbitrary number of method calls `(...)`, subscripts `[...]`, or generic arguments `<...>`.
case .startOfScope("("), .startOfScope("["), .startOfScope("<"):
// If there's a linebreak between an expression and a paren or subscript,
// then it's not parsed as a method call and is actually a separate expression
if tokens[endOfExpression ..< nextTokenIndex].contains(where: \.isLinebreak) {
+2
View File
@@ -1879,6 +1879,8 @@ class ParsingHelpersTests: XCTestCase {
XCTAssert(isSingleExpression(#"try? { try printThrows(foo) }()"#))
XCTAssert(isSingleExpression(#"await { await printAsync(foo) }()"#))
XCTAssert(isSingleExpression(#"try await { try await printAsyncThrows(foo) }()"#))
XCTAssert(isSingleExpression(#"Foo<Bar>()"#))
XCTAssert(isSingleExpression(#"Foo<Bar, Baaz>(quux: quux)"#))
XCTAssert(isSingleExpression("""
foo
+16
View File
@@ -8995,6 +8995,22 @@ class RedundancyTests: RulesTests {
options: options, exclude: ["indent", "blankLinesBetweenScopes", "wrapMultilineConditionalAssignment"])
}
func testRemovesRedundantClosureWithGenericExistentialTypes() {
let input = """
let foo: Foo<Bar> = { DefaultFoo<Bar>() }()
let foo: any Foo = { DefaultFoo() }()
let foo: any Foo<Bar> = { DefaultFoo<Bar>() }()
"""
let output = """
let foo: Foo<Bar> = DefaultFoo<Bar>()
let foo: any Foo = DefaultFoo()
let foo: any Foo<Bar> = DefaultFoo<Bar>()
"""
testFormatting(for: input, output, rule: FormatRules.redundantClosure)
}
func testRedundantSwitchStatementReturnInFunctionWithMultipleWhereClauses() {
// https://github.com/nicklockwood/SwiftFormat/issues/1554
let input = """