Skip to content

Commit 1477e57

Browse files
committed
Fix CodeGenerationFormat to not add extra indentation
1 parent 2b69380 commit 1477e57

26 files changed

+15962
-15943
lines changed

CodeGeneration/Sources/Utils/CodeGenerationFormat.swift

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,25 @@ public class CodeGenerationFormat: BasicFormat {
104104
}
105105
}
106106

107+
public override func requiresIndent(_ node: some SyntaxProtocol) -> Bool {
108+
switch node.kind {
109+
case .arrayElementList, .dictionaryElementList, .functionParameterList, .labeledExprList:
110+
let indentManually = node.children(viewMode: .sourceAccurate).count > maxElementsOnSameLine
111+
if indentManually {
112+
return false
113+
}
114+
let startsOnNewline =
115+
node.leadingTrivia.contains { $0.isNewline }
116+
|| node.previousToken(viewMode: .sourceAccurate)?.trailingTrivia.contains { $0.isNewline } ?? false
117+
if !startsOnNewline {
118+
return false
119+
}
120+
default:
121+
break
122+
}
123+
return super.requiresIndent(node)
124+
}
125+
107126
// MARK: - Private
108127

109128
private func shouldBeSeparatedByTwoNewlines(node: CodeBlockItemSyntax) -> Bool {
@@ -124,16 +143,16 @@ public class CodeGenerationFormat: BasicFormat {
124143
children: SyntaxChildren,
125144
elementType: SyntaxType.Type
126145
) -> [SyntaxType] {
127-
increaseIndentationLevel()
128-
var formattedChildren = children.map {
129-
self.rewrite($0.cast(SyntaxType.self)).cast(SyntaxType.self)
146+
var formattedChildren = children.map { child in
147+
var child = child.cast(SyntaxType.self)
148+
child.leadingTrivia = Trivia(pieces: child.leadingTrivia.drop(while: \.isWhitespace))
149+
return self.rewrite(child).cast(SyntaxType.self)
130150
}
131-
formattedChildren = formattedChildren.map {
132-
if $0.leadingTrivia.first?.isNewline == true {
133-
return $0
134-
} else {
135-
return $0.with(\.leadingTrivia, indentedNewline + $0.leadingTrivia)
136-
}
151+
increaseIndentationLevel()
152+
formattedChildren = formattedChildren.map { child in
153+
var child = child
154+
child.leadingTrivia = indentedNewline + child.leadingTrivia
155+
return child
137156
}
138157
decreaseIndentationLevel()
139158
if let lastChild = formattedChildren.last {

0 commit comments

Comments
 (0)