Skip to content

Commit cb4e621

Browse files
authored
Merge pull request #210 from karwa/SR-13194
[SR-13194] DoNotUseSemicolons should not strip semicolons which separate a 'do' blocks from 'while' blocks.
2 parents 2b4364b + 33b3383 commit cb4e621

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

Sources/SwiftFormatRules/DoNotUseSemicolons.swift

+14-1
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ public final class DoNotUseSemicolons: SyntaxFormatRule {
5353
}
5454

5555
var newItem = visitedItem
56+
defer { newItems[idx] = newItem }
5657

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

6970
// If there's a semicolon, diagnose and remove it.
7071
if let semicolon = item.semicolon {
72+
73+
// Exception: do not remove the semicolon if it is separating a 'do' statement from a 'while' statement.
74+
if Syntax(item).as(CodeBlockItemSyntax.self)?.children.first?.is(DoStmtSyntax.self) == true,
75+
idx < node.count - 1
76+
{
77+
let nextItem = node.children[node.children.index(after: item.index)]
78+
if Syntax(nextItem).as(CodeBlockItemSyntax.self)?
79+
.children.first?.is(WhileStmtSyntax.self) == true
80+
{
81+
continue
82+
}
83+
}
84+
7185
// This discards any trailingTrivia from the semicolon. That trivia is at most some spaces,
7286
// and the pretty printer adds any necessary spaces so it's safe to discard.
7387
newItem = newItem.withSemicolon(nil)
@@ -77,7 +91,6 @@ public final class DoNotUseSemicolons: SyntaxFormatRule {
7791
diagnose(.removeSemicolon, on: semicolon)
7892
}
7993
}
80-
newItems[idx] = newItem
8194
}
8295
return nodeCreator(newItems)
8396
}

Tests/SwiftFormatRulesTests/DoNotUseSemicolonsTests.swift

+37
Original file line numberDiff line numberDiff line change
@@ -89,4 +89,41 @@ final class DoNotUseSemicolonsTests: LintOrFormatRuleTestCase {
8989
print("7")
9090
""")
9191
}
92+
93+
func testSemicolonsSeparatingDoWhile() {
94+
XCTAssertFormatting(
95+
DoNotUseSemicolons.self,
96+
input: """
97+
do { f() };
98+
while someCondition { g() }
99+
100+
do {
101+
f()
102+
};
103+
104+
// Comment and whitespace separating blocks.
105+
while someCondition {
106+
g()
107+
}
108+
109+
do { f() };
110+
for _ in 0..<10 { g() }
111+
""",
112+
expected: """
113+
do { f() };
114+
while someCondition { g() }
115+
116+
do {
117+
f()
118+
};
119+
120+
// Comment and whitespace separating blocks.
121+
while someCondition {
122+
g()
123+
}
124+
125+
do { f() }
126+
for _ in 0..<10 { g() }
127+
""")
128+
}
92129
}

0 commit comments

Comments
 (0)