Skip to content

Commit d97dd1c

Browse files
dabelknapallevato
authored andcommitted
Preserve leading trivia when transforming a class to an enum.
1 parent a46cbb4 commit d97dd1c

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

Sources/SwiftFormatRules/UseEnumForNamespacing.swift

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,15 +66,34 @@ public final class UseEnumForNamespacing: SyntaxFormatRule {
6666
name: TokenSyntax,
6767
members: MemberDeclBlockSyntax
6868
) -> EnumDeclSyntax {
69+
// Since we remove the "final" modifier, we need to preserve its trivia if it is the first
70+
// modifier.
71+
var newLeadingTrivia: Trivia? = nil
72+
if let firstMod = modifiers?.first, firstMod.name.text == "final" {
73+
newLeadingTrivia = firstMod.leadingTrivia
74+
}
75+
6976
let newModifiers = modifiers?.remove(name: "final")
70-
return EnumDeclSyntax {
77+
78+
let outputEnum = EnumDeclSyntax {
7179
if let mods = newModifiers {
7280
for mod in mods { $0.addModifier(mod) }
7381
}
7482
$0.useEnumKeyword(declarationKeyword.withKind(.enumKeyword))
7583
$0.useIdentifier(name)
7684
$0.useMembers(members)
7785
}
86+
87+
if let trivia = newLeadingTrivia {
88+
return replaceTrivia(
89+
on: outputEnum,
90+
token: outputEnum.firstToken,
91+
leadingTrivia: trivia
92+
) as! EnumDeclSyntax
93+
}
94+
else {
95+
return outputEnum
96+
}
7897
}
7998

8099
/// Determines if the set of declarations is consistent with a class or struct being used

Tests/SwiftFormatRulesTests/UseEnumForNamespacingTests.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ public class UseEnumForNamespacingTests: DiagnosingTestCase {
2424
public final class D {
2525
static func bar()
2626
}
27+
final class E {
28+
static let a = 123
29+
}
2730
""",
2831
expected: """
2932
enum A {
@@ -40,6 +43,9 @@ public class UseEnumForNamespacingTests: DiagnosingTestCase {
4043
public enum D {
4144
static func bar()
4245
}
46+
enum E {
47+
static let a = 123
48+
}
4349
""")
4450
}
4551
}

0 commit comments

Comments
 (0)