You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.4 KiB
Kotlin
50 lines
1.4 KiB
Kotlin
package fr.celticinfo.lox
|
|
|
|
class AstPrinter : ExprVisitor<String> {
|
|
fun print(expr: Expr): String {
|
|
return expr.accept(this)
|
|
}
|
|
|
|
override fun visitCall(expr: Call): String {
|
|
return parenthesize("call", expr.callee, *expr.arguments.toTypedArray())
|
|
}
|
|
|
|
override fun visitAssign(expr: Assign): String {
|
|
return parenthesize("=", expr)
|
|
}
|
|
|
|
override fun visitBinary(expr: Binary): String {
|
|
return parenthesize(expr.operator.lexeme, expr.left, expr.right)
|
|
}
|
|
|
|
override fun visitGrouping(expr: Grouping): String {
|
|
return parenthesize("group", expr.expression)
|
|
}
|
|
|
|
override fun visitLiteral(expr: Literal): String {
|
|
return expr.value?.toString() ?: "nil"
|
|
}
|
|
|
|
override fun visitLogical(expr: Logical): String {
|
|
return parenthesize(expr.operator.lexeme, expr.left, expr.right)
|
|
}
|
|
|
|
override fun visitUnary(expr: Unary): String {
|
|
return parenthesize(expr.operator.lexeme, expr.right)
|
|
}
|
|
|
|
override fun visitVariable(expr: Variable): String {
|
|
return expr.name.lexeme
|
|
}
|
|
|
|
private fun parenthesize(name: String, vararg exprs: Expr): String {
|
|
val builder = StringBuilder()
|
|
builder.append("(").append(name)
|
|
for (expr in exprs) {
|
|
builder.append(" ")
|
|
builder.append(expr.accept(this))
|
|
}
|
|
builder.append(")")
|
|
return builder.toString()
|
|
}
|
|
} |