Skip to content

Commit 38aac98

Browse files
dabelknapallevato
authored andcommitted
Properly handle colons for empty dictionary declarations. (swiftlang#100)
1 parent 48c733e commit 38aac98

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

Sources/Rules/ColonWhitespace.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@ public final class ColonWhitespace: SyntaxFormatRule {
1717
public override func visit(_ token: TokenSyntax) -> Syntax {
1818
guard let next = token.nextToken else { return token }
1919

20+
if token.tokenKind == .colon,
21+
token.containingExprStmtOrDecl is DictionaryExprSyntax,
22+
next.tokenKind == .rightSquareBracket,
23+
token.trailingTrivia.numberOfSpaces > 0 {
24+
diagnose(.noSpacesAfterColon, on: token)
25+
return token.withoutTrailingTrivia()
26+
}
27+
2028
/// Colons own their trailing spaces, so ensure it only has 1 if there's
2129
/// another token on the same line.
2230
if token.tokenKind == .colon,
@@ -51,4 +59,6 @@ extension Diagnostic.Message {
5159
Diagnostic.Message(.warning, "add one space after ':'")
5260
static let noSpacesBeforeColon =
5361
Diagnostic.Message(.warning, "remove spaces before ':'")
62+
static let noSpacesAfterColon =
63+
Diagnostic.Message(.warning, "remove spaces after ':'")
5464
}

Tests/SwiftFormatTests/ColonWhitespaceTests.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,16 @@ public class ColonWhitespaceTests: DiagnosingTestCase {
1212
let v2 : Int = 1
1313
let v3 :Int = 1
1414
let v4 \t: \t Int = 1
15+
let v5: [Int: String] = [: ]
16+
let v6: [Int: String] = [23: "twenty three"]
1517
""",
1618
expected: """
1719
let v1: Int = 0
1820
let v2: Int = 1
1921
let v3: Int = 1
2022
let v4: Int = 1
23+
let v5: [Int: String] = [:]
24+
let v6: [Int: String] = [23: "twenty three"]
2125
""")
2226
}
2327

0 commit comments

Comments
 (0)