Skip to content

Commit f919561

Browse files
committed
Add a group around member types used in return clauses.
Without the group, the pretty printer would add a newline at the first break in the return clause where the column limit would overflow. This could fall inside of a member type identifier, before the dot. That results in odd formatting where a func decl has its return clause partially on the first line and partially on the second line (which is only allowed for tuples because of the opening paren special case). With the group, the func decl breaks before the -> when the type would overflow the line.
1 parent 30c280d commit f919561

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1049,6 +1049,13 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
10491049

10501050
override func visit(_ node: ReturnClauseSyntax) -> SyntaxVisitorContinueKind {
10511051
after(node.arrow, tokens: .space)
1052+
1053+
// Member type identifier is used when the return type is a member of another type. Add a group
1054+
// here so that the base, dot, and member type are kept together when they fit.
1055+
if node.returnType.is(MemberTypeIdentifierSyntax.self) {
1056+
before(node.returnType.firstToken, tokens: .open)
1057+
after(node.returnType.lastToken, tokens: .close)
1058+
}
10521059
return .visitChildren
10531060
}
10541061

Tests/SwiftFormatPrettyPrintTests/FunctionDeclTests.swift

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,6 @@ final class FunctionDeclTests: PrettyPrintTestCase {
9090
}
9191

9292
func testFunctionDeclReturns() {
93-
// TODO: The tuple return case needs a lot of work.
9493
let input =
9594
"""
9695
func myFun(var1: Int, var2: Double) -> Double {
@@ -104,6 +103,12 @@ final class FunctionDeclTests: PrettyPrintTestCase {
104103
func tupleFunc() throws -> (one: Int, two: Double, three: Bool, four: String) {
105104
return (one: 1, two: 2.0, three: true, four: "four")
106105
}
106+
func memberTypeThrowingFunc() throws -> SomeBaseType<GenericArg1, GenericArg2, GenericArg3>.SomeInnerType {
107+
}
108+
func memberTypeReallyLongNameFunc() -> Type.InnerMember {
109+
}
110+
func tupleMembersFunc() -> (Type.Inner, Type2.Inner2) {
111+
}
107112
"""
108113

109114
let expected =
@@ -125,6 +130,20 @@ final class FunctionDeclTests: PrettyPrintTestCase {
125130
one: 1, two: 2.0, three: true, four: "four"
126131
)
127132
}
133+
func memberTypeThrowingFunc() throws
134+
-> SomeBaseType<
135+
GenericArg1, GenericArg2, GenericArg3
136+
>.SomeInnerType
137+
{
138+
}
139+
func memberTypeReallyLongNameFunc()
140+
-> Type.InnerMember
141+
{
142+
}
143+
func tupleMembersFunc() -> (
144+
Type.Inner, Type2.Inner2
145+
) {
146+
}
128147
129148
"""
130149

0 commit comments

Comments
 (0)