Skip to content

Commit

Permalink
improved while formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
stackoverflow committed Oct 22, 2022
1 parent 72bb349 commit f3f2b12
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 16 deletions.
34 changes: 18 additions & 16 deletions src/main/kotlin/novah/formatter/Formatter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -150,21 +150,7 @@ class Formatter {
fun show(e: Expr, op: OpExpr? = null): String {
val cmt = if (e.comment != null) show(e.comment!!) + tab else ""
return cmt + when (e) {
is Expr.Do -> {
val str = StringBuilder()
var last: Expr? = null
for (exp in e.exps) {
if (last != null) {
// respect empty new lines between statements
val adjacent = exp.span.startLine - 1 == last.span.endLine
if (adjacent) str.append("\n$tab")
else str.append("\n\n$tab")
}
str.append(show(exp))
last = exp
}
str.toString()
}
is Expr.Do -> showExprList(e.exps)
is Expr.Match -> {
val expsStr = e.exps.joinToString { show(it) }
"case $expsStr of" + withIndent { e.cases.joinToString("\n$tab", prefix = tab) { show(it) } }
Expand Down Expand Up @@ -340,7 +326,7 @@ class Formatter {
}
is Expr.While -> {
val cond = show(e.cond)
"while $cond do" + withIndent { e.exps.joinToString("\n$tab", prefix = tab) { show(it) } }
"while $cond do" + withIndent { tab + showExprList(e.exps) }
}
is Expr.Computation -> {
"do." + e.builder.name + withIndent { e.exps.joinToString("\n$tab", prefix = tab) { show(it) } }
Expand All @@ -361,6 +347,22 @@ class Formatter {
}
}

private fun showExprList(exps: List<Expr>): String {
val str = StringBuilder()
var last: Expr? = null
for (exp in exps) {
if (last != null) {
// respect empty new lines between statements
val adjacent = exp.span.startLine - 1 == last.span.endLine
if (adjacent) str.append("\n$tab")
else str.append("\n\n$tab")
}
str.append(show(exp))
last = exp
}
return str.toString()
}

private fun showLabelExpr(l: String, e: Expr): String =
if (e is Expr.Var && e.name == l && e.alias == null) l else "$l: ${show(e)}"

Expand Down
21 changes: 21 additions & 0 deletions src/test/kotlin/novah/frontend/FormatterSpec.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,27 @@ class FormatterSpec : StringSpec({
)
}

"while test" {
expect(
input = """
fun =
while true do
println 1

println 2
println 3
""",
output = """
fun =
while true do
println 1

println 2
println 3
"""
)
}

"computation test" {
expect(
input = """
Expand Down

0 comments on commit f3f2b12

Please sign in to comment.