Skip to content

Commit f3f2b12

Browse files
committed
improved while formatting
1 parent 72bb349 commit f3f2b12

File tree

2 files changed

+39
-16
lines changed

2 files changed

+39
-16
lines changed

src/main/kotlin/novah/formatter/Formatter.kt

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -150,21 +150,7 @@ class Formatter {
150150
fun show(e: Expr, op: OpExpr? = null): String {
151151
val cmt = if (e.comment != null) show(e.comment!!) + tab else ""
152152
return cmt + when (e) {
153-
is Expr.Do -> {
154-
val str = StringBuilder()
155-
var last: Expr? = null
156-
for (exp in e.exps) {
157-
if (last != null) {
158-
// respect empty new lines between statements
159-
val adjacent = exp.span.startLine - 1 == last.span.endLine
160-
if (adjacent) str.append("\n$tab")
161-
else str.append("\n\n$tab")
162-
}
163-
str.append(show(exp))
164-
last = exp
165-
}
166-
str.toString()
167-
}
153+
is Expr.Do -> showExprList(e.exps)
168154
is Expr.Match -> {
169155
val expsStr = e.exps.joinToString { show(it) }
170156
"case $expsStr of" + withIndent { e.cases.joinToString("\n$tab", prefix = tab) { show(it) } }
@@ -340,7 +326,7 @@ class Formatter {
340326
}
341327
is Expr.While -> {
342328
val cond = show(e.cond)
343-
"while $cond do" + withIndent { e.exps.joinToString("\n$tab", prefix = tab) { show(it) } }
329+
"while $cond do" + withIndent { tab + showExprList(e.exps) }
344330
}
345331
is Expr.Computation -> {
346332
"do." + e.builder.name + withIndent { e.exps.joinToString("\n$tab", prefix = tab) { show(it) } }
@@ -361,6 +347,22 @@ class Formatter {
361347
}
362348
}
363349

350+
private fun showExprList(exps: List<Expr>): String {
351+
val str = StringBuilder()
352+
var last: Expr? = null
353+
for (exp in exps) {
354+
if (last != null) {
355+
// respect empty new lines between statements
356+
val adjacent = exp.span.startLine - 1 == last.span.endLine
357+
if (adjacent) str.append("\n$tab")
358+
else str.append("\n\n$tab")
359+
}
360+
str.append(show(exp))
361+
last = exp
362+
}
363+
return str.toString()
364+
}
365+
364366
private fun showLabelExpr(l: String, e: Expr): String =
365367
if (e is Expr.Var && e.name == l && e.alias == null) l else "$l: ${show(e)}"
366368

src/test/kotlin/novah/frontend/FormatterSpec.kt

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,27 @@ class FormatterSpec : StringSpec({
3636
)
3737
}
3838

39+
"while test" {
40+
expect(
41+
input = """
42+
fun =
43+
while true do
44+
println 1
45+
46+
println 2
47+
println 3
48+
""",
49+
output = """
50+
fun =
51+
while true do
52+
println 1
53+
54+
println 2
55+
println 3
56+
"""
57+
)
58+
}
59+
3960
"computation test" {
4061
expect(
4162
input = """

0 commit comments

Comments
 (0)