From ace7fc018cffe892c197f4e1fe4802b746f34784 Mon Sep 17 00:00:00 2001 From: Nick Lockwood Date: Sat, 25 Mar 2023 12:13:34 +0000 Subject: [PATCH] Fix parsing trailing closure after unwrap operator --- Sources/ParsingHelpers.swift | 6 +++--- Tests/ParsingHelpersTests.swift | 7 +++++++ Tests/RulesTests+Redundancy.swift | 14 ++++++++++++++ 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/Sources/ParsingHelpers.swift b/Sources/ParsingHelpers.swift index 021c422d..8f177690 100644 --- a/Sources/ParsingHelpers.swift +++ b/Sources/ParsingHelpers.swift @@ -529,7 +529,8 @@ extension Formatter { } } fallthrough - case .endOfScope where tokens[prevIndex].isStringDelimiter, .identifier, .number: + case .identifier, .number, .operator("?", .postfix), .operator("!", .postfix), + .endOfScope where tokens[prevIndex].isStringDelimiter: if let nextIndex = index(of: .nonSpaceOrCommentOrLinebreak, after: i), isAccessorKeyword(at: nextIndex) || isAccessorKeyword(at: prevIndex) { @@ -573,8 +574,7 @@ extension Formatter { default: return true } - case .operator("?", .postfix), .operator("!", .postfix), - .keyword, .endOfScope("]"), .endOfScope(">"): + case .keyword, .endOfScope("]"), .endOfScope(">"): return false default: return true diff --git a/Tests/ParsingHelpersTests.swift b/Tests/ParsingHelpersTests.swift index e6498aa9..e28b75ba 100644 --- a/Tests/ParsingHelpersTests.swift +++ b/Tests/ParsingHelpersTests.swift @@ -550,6 +550,13 @@ class ParsingHelpersTests: XCTestCase { XCTAssert(formatter.isStartOfClosure(at: 6)) } + func testTrailingClosureOnOptionalMethod() { + let formatter = Formatter(tokenize(""" + foo.bar? { print("") } + """)) + XCTAssert(formatter.isStartOfClosure(at: 5)) + } + // MARK: isAccessorKeyword func testDidSet() { diff --git a/Tests/RulesTests+Redundancy.swift b/Tests/RulesTests+Redundancy.swift index 913fdedf..1809388a 100644 --- a/Tests/RulesTests+Redundancy.swift +++ b/Tests/RulesTests+Redundancy.swift @@ -4405,6 +4405,20 @@ class RedundancyTests: RulesTests { XCTAssertNoThrow(try format(input, rules: [FormatRules.redundantSelf])) } + func testRedundantSelfParsingBug5() { + let input = """ + Button.primary( + title: "Title", + tapHandler: { [weak self] in + self?.dismissBlock? { + // something + } + } + ) + """ + XCTAssertNoThrow(try format(input, rules: [FormatRules.redundantSelf])) + } + func testRedundantSelfWithStaticMethodAfterForLoop() { let input = """ struct Foo {