Skip to content

Commit edecb7d

Browse files
committed
Make formatter order agnostic
1 parent d3f000a commit edecb7d

File tree

1 file changed

+11
-7
lines changed
  • pkl-formatter/src/main/kotlin/org/pkl/formatter

1 file changed

+11
-7
lines changed

pkl-formatter/src/main/kotlin/org/pkl/formatter/Builder.kt

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,10 @@ import org.pkl.parser.syntax.generic.NodeType
3636
internal class Builder(sourceText: String, private val grammarVersion: GrammarVersion) {
3737
private var id: Int = 0
3838
private val source: CharArray = sourceText.toCharArray()
39-
private var prevNode: Node? = null
4039
private var noNewlines = false
4140

42-
fun format(node: Node): FormatNode {
43-
prevNode = node
44-
return when (node.type) {
41+
fun format(node: Node): FormatNode =
42+
when (node.type) {
4543
NodeType.MODULE -> formatModule(node)
4644
NodeType.DOC_COMMENT -> Nodes(formatGeneric(node.children, null))
4745
NodeType.DOC_COMMENT_LINE -> formatDocComment(node)
@@ -164,7 +162,6 @@ internal class Builder(sourceText: String, private val grammarVersion: GrammarVe
164162
NodeType.PARENTHESIZED_TYPE_ELEMENTS -> formatParenthesizedTypeElements(node)
165163
else -> throw RuntimeException("Unknown node type: ${node.type}")
166164
}
167-
}
168165

169166
private fun formatModule(node: Node): FormatNode {
170167
val nodes =
@@ -622,7 +619,6 @@ internal class Builder(sourceText: String, private val grammarVersion: GrammarVe
622619
} else {
623620
val separator = getSeparator(normalParams.last(), lastParam[0], Space)
624621
val paramNodes = formatGenericWithGen(normalParams, sep, null)
625-
val lastNodes = formatGenericWithGen(lastParam, sep, null)
626622
group(Group(newId(), paramNodes), separator, Group(newId(), lastNodes), trailingNode)
627623
}
628624
} else {
@@ -1291,7 +1287,7 @@ internal class Builder(sourceText: String, private val grammarVersion: GrammarVe
12911287

12921288
private fun getBaseSeparator(prev: Node, next: Node): FormatNode? {
12931289
return when {
1294-
prevNode?.type == NodeType.LINE_COMMENT -> {
1290+
endsInLineComment(prev) -> {
12951291
if (prev.linesBetween(next) > 1) {
12961292
TWO_NEWLINES
12971293
} else {
@@ -1327,6 +1323,14 @@ internal class Builder(sourceText: String, private val grammarVersion: GrammarVe
13271323
}
13281324
}
13291325

1326+
private tailrec fun endsInLineComment(node: Node): Boolean {
1327+
return when {
1328+
node.type == NodeType.LINE_COMMENT -> true
1329+
node.children.isEmpty() -> false
1330+
else -> endsInLineComment(node.children.last())
1331+
}
1332+
}
1333+
13301334
private fun line(): FormatNode {
13311335
return if (noNewlines) Empty else Line
13321336
}

0 commit comments

Comments
 (0)