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.
70 lines
2.3 KiB
Kotlin
70 lines
2.3 KiB
Kotlin
import java.util.*
|
|
|
|
fun defineAst(baseName: String, types: List<String>) {
|
|
println("package fr.celticinfo.lox")
|
|
|
|
println()
|
|
println("interface ${baseName}Visitor<R> {")
|
|
for (type in types) {
|
|
val parts = type.split(":")
|
|
val name = parts[0].trim()
|
|
println(" fun visit$name(${baseName.lowercase(Locale.getDefault())}: $name): R")
|
|
}
|
|
println("}")
|
|
|
|
println()
|
|
println("sealed class $baseName {")
|
|
println(" abstract fun <R> accept(visitor: ${baseName}Visitor<R>): R")
|
|
println("}")
|
|
for (type in types) {
|
|
val parts = type.split(":")
|
|
val name = parts[0].trim()
|
|
val fields = parts[1].trim().split(",").map { it.trim() }
|
|
println()
|
|
println("data class $name(")
|
|
for (field in fields) {
|
|
val fparts = field.split(" ")
|
|
val ftype = fparts[0]
|
|
val fname = fparts[1]
|
|
val sep = if (field == fields.last()) "" else ","
|
|
println(" val $fname: $ftype$sep")
|
|
}
|
|
println(") : ${baseName}() {")
|
|
println(" override fun <R> accept(visitor: ${baseName}Visitor<R>): R {")
|
|
println(" return visitor.visit$name(this)")
|
|
println(" }")
|
|
println("}")
|
|
}
|
|
|
|
|
|
}
|
|
|
|
val exprTypes = listOf(
|
|
"Assign : Token name, Expr value",
|
|
"Binary : Expr left, Token operator, Expr right",
|
|
"Call : Expr callee, Token paren, List<Expr> arguments",
|
|
"Get : Expr obj, Token name",
|
|
"Grouping : Expr expression",
|
|
"Literal : Any? value",
|
|
"Logical : Expr left, Token operator, Expr right",
|
|
"Set : Expr obj, Token name, Expr value",
|
|
"Super : Token keyword, Token method",
|
|
"This : Token keyword",
|
|
"Unary : Token operator, Expr right",
|
|
"Variable : Token name"
|
|
)
|
|
defineAst("Expr", exprTypes)
|
|
|
|
val stmtTypes = listOf(
|
|
"Block : List<Stmt?> statements",
|
|
"ClassStmt : Token name, Variable? superClass, List<Function> methods",
|
|
"Expression : Expr expression",
|
|
"Function : Token name, List<Token> params, List<Stmt?> body",
|
|
"If : Expr condition, Stmt thenBranch, Stmt? elseBranch",
|
|
"Print : Expr expression",
|
|
"Return : Token keyword, Expr? value",
|
|
"Var : Token name, Expr? initializer",
|
|
"While : Expr condition, Stmt body"
|
|
)
|
|
defineAst("Stmt", stmtTypes)
|