Skip to content

Commit 74dd900

Browse files
authored
Merge pull request swiftlang#148 from google/fix-protocol-functions
Fix crash for functions inside protocols.
2 parents d60a108 + 805e2df commit 74dd900

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -808,6 +808,10 @@ private final class TokenStreamCreator: SyntaxVisitor {
808808
}
809809
after(body.leftBrace, tokens: .close, .close, .break(offset: 2), .open(.consistent, 0))
810810
before(body.rightBrace, tokens: .break(offset: -2), .close)
811+
} else {
812+
// FunctionDecls in protocols won't have bodies, so make sure we close the correct number of
813+
// groups in that case as well.
814+
after(node.lastToken, tokens: .close, .close)
811815
}
812816

813817
after(node.lastToken, tokens: .close)
@@ -838,6 +842,10 @@ private final class TokenStreamCreator: SyntaxVisitor {
838842
}
839843
after(body.leftBrace, tokens: .close, .close, .break(offset: 2), .open(.consistent, 0))
840844
before(body.rightBrace, tokens: .break(offset: -2), .close)
845+
} else {
846+
// FunctionDecls in protocols won't have bodies, so make sure we close the correct number of
847+
// groups in that case as well.
848+
after(node.lastToken, tokens: .close, .close)
841849
}
842850

843851
after(node.lastToken, tokens: .close)

Tests/SwiftFormatPrettyPrintTests/ProtocolDeclTests.swift

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,4 +141,52 @@ public class ProtocolDeclTests: PrettyPrintTestCase {
141141

142142
assertPrettyPrintEqual(input: input, expected: expected, linelength: 60)
143143
}
144+
145+
public func testProtocolWithFunctions() {
146+
let input =
147+
"""
148+
protocol MyProtocol {
149+
func foo(bar: Int) -> Int
150+
func reallyLongName(reallyLongLabel: Int, anotherLongLabel: Bool) -> Float
151+
}
152+
"""
153+
154+
let expected =
155+
"""
156+
protocol MyProtocol {
157+
func foo(bar: Int) -> Int
158+
func reallyLongName(
159+
reallyLongLabel: Int,
160+
anotherLongLabel: Bool
161+
) -> Float
162+
}
163+
164+
"""
165+
166+
assertPrettyPrintEqual(input: input, expected: expected, linelength: 30)
167+
}
168+
169+
public func testProtocolWithInitializers() {
170+
let input =
171+
"""
172+
protocol MyProtocol {
173+
init(bar: Int)
174+
init(reallyLongLabel: Int, anotherLongLabel: Bool)
175+
}
176+
"""
177+
178+
let expected =
179+
"""
180+
protocol MyProtocol {
181+
init(bar: Int)
182+
init(
183+
reallyLongLabel: Int,
184+
anotherLongLabel: Bool
185+
)
186+
}
187+
188+
"""
189+
190+
assertPrettyPrintEqual(input: input, expected: expected, linelength: 30)
191+
}
144192
}

0 commit comments

Comments
 (0)