Skip to content

[SR-13194] DoNotUseSemicolons should not strip semicolons which separate a 'do' blocks from 'while' blocks. #210

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion Sources/SwiftFormatRules/DoNotUseSemicolons.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public final class DoNotUseSemicolons: SyntaxFormatRule {
}

var newItem = visitedItem
defer { newItems[idx] = newItem }

// Check if the leading trivia for this statement needs a new line.
if previousHadSemicolon, let firstToken = newItem.firstToken,
Expand All @@ -68,6 +69,19 @@ public final class DoNotUseSemicolons: SyntaxFormatRule {

// If there's a semicolon, diagnose and remove it.
if let semicolon = item.semicolon {

// Exception: do not remove the semicolon if it is separating a 'do' statement from a 'while' statement.
if Syntax(item).as(CodeBlockItemSyntax.self)?.children.first?.is(DoStmtSyntax.self) == true,
idx < node.count - 1
{
let nextItem = node.children[node.children.index(after: item.index)]
if Syntax(nextItem).as(CodeBlockItemSyntax.self)?
.children.first?.is(WhileStmtSyntax.self) == true
{
continue
}
}

// This discards any trailingTrivia from the semicolon. That trivia is at most some spaces,
// and the pretty printer adds any necessary spaces so it's safe to discard.
newItem = newItem.withSemicolon(nil)
Expand All @@ -77,7 +91,6 @@ public final class DoNotUseSemicolons: SyntaxFormatRule {
diagnose(.removeSemicolon, on: semicolon)
}
}
newItems[idx] = newItem
}
return nodeCreator(newItems)
}
Expand Down
37 changes: 37 additions & 0 deletions Tests/SwiftFormatRulesTests/DoNotUseSemicolonsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,41 @@ final class DoNotUseSemicolonsTests: LintOrFormatRuleTestCase {
print("7")
""")
}

func testSemicolonsSeparatingDoWhile() {
XCTAssertFormatting(
DoNotUseSemicolons.self,
input: """
do { f() };
while someCondition { g() }

do {
f()
};

// Comment and whitespace separating blocks.
while someCondition {
g()
}

do { f() };
for _ in 0..<10 { g() }
""",
expected: """
do { f() };
while someCondition { g() }

do {
f()
};

// Comment and whitespace separating blocks.
while someCondition {
g()
}

do { f() }
for _ in 0..<10 { g() }
""")
}
}