Skip to content

Commit

Permalink
Fix hoisting try after string literal
Browse files Browse the repository at this point in the history
  • Loading branch information
nicklockwood committed Mar 16, 2024
1 parent 1ef5563 commit d4ab4d7
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
6 changes: 3 additions & 3 deletions Sources/FormattingHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1153,8 +1153,7 @@ extension Formatter {
case .operator(_, .prefix), .stringBody,
.endOfScope(")") where prevToken.isStringBody ||
(prevToken.isEndOfScope && prevToken.isStringDelimiter),
.startOfScope where tokens[i].isStringDelimiter,
.endOfScope where tokens[i].isStringDelimiter:
.startOfScope where tokens[i].isStringDelimiter:
break
case _ where tokens[i].isUnwrapOperator:
if last(.nonSpaceOrComment, before: i) == .keyword("try") {
Expand All @@ -1168,7 +1167,8 @@ extension Formatter {
fallthrough
}
case .operator(_, .postfix), .identifier, .number,
.endOfScope(">"), .endOfScope("]"), .endOfScope(")"):
.endOfScope(">"), .endOfScope("]"), .endOfScope(")"),
.endOfScope where tokens[i].isStringDelimiter:
switch prevToken {
case .operator(_, .infix), .operator(_, .postfix), .stringBody,
.startOfScope("<"), .startOfScope("["), .startOfScope("("),
Expand Down
36 changes: 36 additions & 0 deletions Tests/RulesTests+Hoisting.swift
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,42 @@ class HoistingTests: RulesTests {
testFormatting(for: input, output, rule: FormatRules.hoistTry)
}

func testHoistTryAfterString() {
let input = """
let json = "{}"
someFunction(try parse(json), "someKey")
"""
let output = """
let json = "{}"
try someFunction(parse(json), "someKey")
"""
testFormatting(for: input, output, rule: FormatRules.hoistTry)
}

func testHoistTryAfterMultilineString() {
let input = #"""
let json = """
{
"foo": "bar"
}
"""
someFunction(try parse(json), "someKey")
"""#
let output = #"""
let json = """
{
"foo": "bar"
}
"""
try someFunction(parse(json), "someKey")
"""#
testFormatting(for: input, output, rule: FormatRules.hoistTry)
}

// MARK: - hoistAwait

func testHoistAwait() {
Expand Down

0 comments on commit d4ab4d7

Please sign in to comment.