Skip to content

Commit

Permalink
Restore fixes accidentally reverted in previous release
Browse files Browse the repository at this point in the history
This reverts commit db0c7cb.
  • Loading branch information
nicklockwood committed Aug 6, 2023
1 parent db0c7cb commit 9136609
Show file tree
Hide file tree
Showing 6 changed files with 238 additions and 57 deletions.
12 changes: 9 additions & 3 deletions Sources/Rules.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4083,7 +4083,7 @@ public struct _FormatRules {
wasDeclaration = false
}
let token = formatter.tokens[i]
switch token {
outer: switch token {
case .keyword("guard"):
isGuard = true
case .keyword("let"), .keyword("var"), .keyword("func"), .keyword("for"):
Expand All @@ -4103,8 +4103,14 @@ public struct _FormatRules {
formatter.currentScope(at: i) == .startOfScope("[")
{
if isDeclaration {
tempLocals.insert(name)
break
switch formatter.next(.nonSpaceOrCommentOrLinebreak, after: i) {
case .endOfScope(")")?, .operator("=", .infix)?,
.delimiter(",")? where !isConditional || formatter.currentScope(at: i) == .startOfScope("("):
tempLocals.insert(name)
break outer
default:
break
}
}
argNames.remove(at: index)
associatedData.remove(at: index)
Expand Down
35 changes: 26 additions & 9 deletions Sources/Tokenizer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,10 @@ extension UnicodeScalar {
return false
}
}

var isSpaceOrLinebreak: Bool {
isSpace || "\n\r\u{000B}\u{000C}".unicodeScalars.contains(self)
}
}

// Workaround for horribly slow String.UnicodeScalarView.Subsequence perf
Expand Down Expand Up @@ -728,7 +732,7 @@ private extension UnicodeScalarView {
}

mutating func readToEndOfToken() -> String {
readCharacters { !$0.isSpace && !"\n\r".unicodeScalars.contains($0) } ?? ""
readCharacters { !$0.isSpaceOrLinebreak } ?? ""
}
}

Expand All @@ -738,13 +742,18 @@ private extension UnicodeScalarView {
}

mutating func parseLineBreak() -> Token? {
if read("\r") {
switch first {
case "\r":
removeFirst()
if read("\n") {
return .linebreak("\r\n", 0)
}
return .linebreak("\r", 0)
case "\n", "\u{000B}", "\u{000C}":
return .linebreak(String(removeFirst()), 0)
default:
return nil
}
return read("\n") ? .linebreak("\n", 0) : nil
}

mutating func parseDelimiter() -> Token? {
Expand Down Expand Up @@ -1467,8 +1476,10 @@ public func tokenize(_ source: String) -> [Token] {
return
}
guard let prevNonSpaceIndex = index(of: .nonSpaceOrCommentOrLinebreak, before: i) else {
if tokens.count > i + 1 {
tokens[i] = string == "/" ? .startOfScope("/") : .operator(string, .prefix)
if string == "/" {
tokens[i] = .startOfScope("/")
} else if tokens.count > i + 1 {
tokens[i] = .operator(string, .prefix)
}
return
}
Expand Down Expand Up @@ -1538,11 +1549,8 @@ public func tokenize(_ source: String) -> [Token] {
guard let nextNonSpaceToken =
index(of: .nonSpaceOrCommentOrLinebreak, after: i).map({ tokens[$0] })
else {
if prevToken.isLvalue {
type = .postfix
break
}
if token == .operator("/", .none),
prevToken.isSpaceOrLinebreak ||
prevNonSpaceToken.isOperator(ofType: .infix) || (
prevNonSpaceToken.isUnwrapOperator &&
prevNonSpaceIndex > 0 &&
Expand All @@ -1554,6 +1562,9 @@ public func tokenize(_ source: String) -> [Token] {
].contains(prevNonSpaceToken)
{
tokens[i] = .startOfScope("/")
} else if prevToken.isLvalue {
type = .postfix
break
}
return
}
Expand Down Expand Up @@ -1864,6 +1875,12 @@ public func tokenize(_ source: String) -> [Token] {
token = tokens[count - 1]
switch token {
case .startOfScope("/"):
if let next = characters.first, next.isSpaceOrLinebreak {
// Misidentified as regex
token = .operator("/", .none)
tokens[count - 1] = token
return
}
scopeIndexStack.append(count - 1)
let start = characters
processStringBody(regex: true, hashCount: 0)
Expand Down
54 changes: 16 additions & 38 deletions Tests/RulesTests+Linebreaks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,52 +10,30 @@ import XCTest
@testable import SwiftFormat

class LinebreakTests: RulesTests {
// MARK: - trailingSpace
// MARK: - linebreaks

// truncateBlankLines = true

func testTrailingSpace() {
let input = "foo \nbar"
func testCarriageReturn() {
let input = "foo\rbar"
let output = "foo\nbar"
testFormatting(for: input, output, rule: FormatRules.trailingSpace)
}

func testTrailingSpaceAtEndOfFile() {
let input = "foo "
let output = "foo"
testFormatting(for: input, output, rule: FormatRules.trailingSpace)
testFormatting(for: input, output, rule: FormatRules.linebreaks)
}

func testTrailingSpaceInMultilineComments() {
let input = "/* foo \n bar */"
let output = "/* foo\n bar */"
testFormatting(for: input, output, rule: FormatRules.trailingSpace)
}

func testTrailingSpaceInSingleLineComments() {
let input = "// foo \n// bar "
let output = "// foo\n// bar"
testFormatting(for: input, output, rule: FormatRules.trailingSpace)
}

func testTruncateBlankLine() {
let input = "foo {\n // bar\n \n // baz\n}"
let output = "foo {\n // bar\n\n // baz\n}"
testFormatting(for: input, output, rule: FormatRules.trailingSpace)
func testCarriageReturnLinefeed() {
let input = "foo\r\nbar"
let output = "foo\nbar"
testFormatting(for: input, output, rule: FormatRules.linebreaks)
}

func testTrailingSpaceInArray() {
let input = "let foo = [\n 1,\n \n 2,\n]"
let output = "let foo = [\n 1,\n\n 2,\n]"
testFormatting(for: input, output, rule: FormatRules.trailingSpace, exclude: ["redundantSelf"])
func testVerticalTab() {
let input = "foo\u{000B}bar"
let output = "foo\nbar"
testFormatting(for: input, output, rule: FormatRules.linebreaks)
}

// truncateBlankLines = false

func testNoTruncateBlankLine() {
let input = "foo {\n // bar\n \n // baz\n}"
let options = FormatOptions(truncateBlankLines: false)
testFormatting(for: input, rule: FormatRules.trailingSpace, options: options)
func testFormfeed() {
let input = "foo\u{000C}bar"
let output = "foo\nbar"
testFormatting(for: input, output, rule: FormatRules.linebreaks)
}

// MARK: - consecutiveBlankLines
Expand Down
45 changes: 45 additions & 0 deletions Tests/RulesTests+Redundancy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6482,6 +6482,34 @@ class RedundancyTests: RulesTests {
testFormatting(for: input, output, rule: FormatRules.unusedArguments)
}

func testClosureArgumentUsedInGuardNotRemoved() {
let input = """
bar(for: quux) { _, _, foo in
guard
let baz = quux.baz,
foo.contains(where: { $0.baz == baz })
else {
return
}
}
"""
testFormatting(for: input, rule: FormatRules.unusedArguments)
}

func testClosureArgumentUsedInIfNotRemoved() {
let input = """
foo = { reservations, _ in
if let reservations, eligibleToShow(
reservations,
accountService: accountService
) {
coordinator.startFlow()
}
}
"""
testFormatting(for: input, rule: FormatRules.unusedArguments)
}

// init

func testParameterUsedInInit() {
Expand Down Expand Up @@ -7067,6 +7095,23 @@ class RedundancyTests: RulesTests {
testFormatting(for: input, output, rule: FormatRules.unusedArguments)
}

func testFunctionArgumentUsedInGuardNotRemoved() {
let input = """
func scrollViewDidEndDecelerating(_ visibleDayRange: DayRange) {
guard
store.state.request.isIdle,
let nextDayToLoad = store.state.request.nextCursor?.lowerBound,
visibleDayRange.upperBound.distance(to: nextDayToLoad) < 30
else {
return
}
store.handle(.loadNext)
}
"""
testFormatting(for: input, rule: FormatRules.unusedArguments)
}

// functions (closure-only)

func testNoMarkFunctionArgument() {
Expand Down
48 changes: 48 additions & 0 deletions Tests/RulesTests+Spacing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1354,6 +1354,54 @@ class SpacingTests: RulesTests {
testFormatting(for: input, rule: FormatRules.consecutiveSpaces)
}

// MARK: - trailingSpace

// truncateBlankLines = true

func testTrailingSpace() {
let input = "foo \nbar"
let output = "foo\nbar"
testFormatting(for: input, output, rule: FormatRules.trailingSpace)
}

func testTrailingSpaceAtEndOfFile() {
let input = "foo "
let output = "foo"
testFormatting(for: input, output, rule: FormatRules.trailingSpace)
}

func testTrailingSpaceInMultilineComments() {
let input = "/* foo \n bar */"
let output = "/* foo\n bar */"
testFormatting(for: input, output, rule: FormatRules.trailingSpace)
}

func testTrailingSpaceInSingleLineComments() {
let input = "// foo \n// bar "
let output = "// foo\n// bar"
testFormatting(for: input, output, rule: FormatRules.trailingSpace)
}

func testTruncateBlankLine() {
let input = "foo {\n // bar\n \n // baz\n}"
let output = "foo {\n // bar\n\n // baz\n}"
testFormatting(for: input, output, rule: FormatRules.trailingSpace)
}

func testTrailingSpaceInArray() {
let input = "let foo = [\n 1,\n \n 2,\n]"
let output = "let foo = [\n 1,\n\n 2,\n]"
testFormatting(for: input, output, rule: FormatRules.trailingSpace, exclude: ["redundantSelf"])
}

// truncateBlankLines = false

func testNoTruncateBlankLine() {
let input = "foo {\n // bar\n \n // baz\n}"
let options = FormatOptions(truncateBlankLines: false)
testFormatting(for: input, rule: FormatRules.trailingSpace, options: options)
}

// MARK: - emptyBraces

func testLinebreaksRemovedInsideBraces() {
Expand Down
Loading

0 comments on commit 9136609

Please sign in to comment.