Skip to content

Commit e1fa88a

Browse files
authored
Merge pull request swiftlang#151 from dabelknap/fix-if-closures
Fix indentation of `if` blocks in closures
2 parents 74c8bbe + 37aa5fa commit e1fa88a

File tree

2 files changed

+51
-6
lines changed

2 files changed

+51
-6
lines changed

Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -427,10 +427,8 @@ private final class TokenStreamCreator: SyntaxVisitor {
427427
}
428428

429429
override func visit(_ node: CodeBlockItemListSyntax) {
430-
if node.parent is AccessorBlockSyntax, node.count > 0 {
431-
for i in 0..<(node.count - 1) {
432-
after(node[i].lastToken, tokens: .newline)
433-
}
430+
if node.parent is AccessorBlockSyntax || node.parent is ClosureExprSyntax, node.count > 0 {
431+
insertToken(.newline, betweenChildrenOf: node)
434432
}
435433
super.visit(node)
436434
}

Tests/SwiftFormatPrettyPrintTests/FunctionCallTests.swift

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,8 @@ public class FunctionCallTests: PrettyPrintTestCase {
4747
public func testBasicFunctionClosures() {
4848
let input =
4949
"""
50-
funcCall(closure: { < })
50+
funcCall(closure: <)
51+
funcCall(closure: { 4 })
5152
funcCall(closure: { $0 < $1 })
5253
funcCall(closure: { s1, s2 in s1 < s2 })
5354
funcCall(closure: { s1, s2 in return s1 < s2})
@@ -59,7 +60,8 @@ public class FunctionCallTests: PrettyPrintTestCase {
5960

6061
let expected =
6162
"""
62-
funcCall(closure: { < })
63+
funcCall(closure: <)
64+
funcCall(closure: { 4 })
6365
funcCall(closure: { $0 < $1 })
6466
funcCall(closure: { s1, s2 in
6567
s1 < s2
@@ -117,4 +119,49 @@ public class FunctionCallTests: PrettyPrintTestCase {
117119

118120
assertPrettyPrintEqual(input: input, expected: expected, linelength: 40)
119121
}
122+
123+
public func testClosuresWithIfs() {
124+
let input =
125+
"""
126+
let a = afunc() {
127+
if condition1 {
128+
return true
129+
}
130+
return false
131+
}
132+
133+
let a = afunc() {
134+
if condition1 {
135+
return true
136+
}
137+
if condition2 {
138+
return true
139+
}
140+
return false
141+
}
142+
"""
143+
144+
let expected =
145+
"""
146+
let a = afunc() {
147+
if condition1 {
148+
return true
149+
}
150+
return false
151+
}
152+
153+
let a = afunc() {
154+
if condition1 {
155+
return true
156+
}
157+
if condition2 {
158+
return true
159+
}
160+
return false
161+
}
162+
163+
"""
164+
165+
assertPrettyPrintEqual(input: input, expected: expected, linelength: 40)
166+
}
120167
}

0 commit comments

Comments
 (0)