Add While statement

main
Olivier Abrivard 1 year ago
parent fd21c650c2
commit cc80306292

@ -55,6 +55,7 @@ val stmtTypes = listOf(
"Expression : Expr expression", "Expression : Expr expression",
"If : Expr condition, Stmt thenBranch, Stmt? elseBranch", "If : Expr condition, Stmt thenBranch, Stmt? elseBranch",
"Print : Expr expression", "Print : Expr expression",
"Var : Token name, Expr? initializer" "Var : Token name, Expr? initializer",
"While : Expr condition, Stmt body"
) )
defineAst("Stmt", stmtTypes) defineAst("Stmt", stmtTypes)

@ -52,6 +52,12 @@ class Interpreter: ExprVisitor<Any?>, StmtVisitor<Unit>{
} }
} }
override fun visitWhile(stmt: While) {
while (isTruthy(evaluate(stmt.condition))) {
execute(stmt.body)
}
}
override fun visitPrint(stmt: Print) { override fun visitPrint(stmt: Print) {
val value = evaluate(stmt.expression) val value = evaluate(stmt.expression)
println(stringify(value)) println(stringify(value))

@ -43,11 +43,20 @@ class Parser(private val tokens: List<Token>) {
return Var(name, initializer) return Var(name, initializer)
} }
private fun whileStatement(): Stmt {
consume(LEFT_PAREN, "Expect '(' after 'while'.")
val condition = expression()
consume(RIGHT_PAREN, "Expect ')' after condition.")
val body = statement()
return While(condition, body)
}
private fun statement(): Stmt { private fun statement(): Stmt {
return when { return when {
match(IF) -> ifStatement() match(IF) -> ifStatement()
match(PRINT) -> printStatement() match(PRINT) -> printStatement()
match(WHILE) -> whileStatement()
match(LEFT_BRACE) -> Block(blockStatement()) match(LEFT_BRACE) -> Block(blockStatement())
else -> expressionStatement() else -> expressionStatement()
} }

@ -8,7 +8,8 @@ interface StmtVisitor<R> {
fun visitExpression(stmt: Expression): R fun visitExpression(stmt: Expression): R
fun visitIf(stmt: If): R fun visitIf(stmt: If): R
fun visitPrint(stmt: Print): R fun visitPrint(stmt: Print): R
fun visitVar(stmt: Var): R fun visitVar(stmt: Var): R
fun visitWhile(stmt: While): R
} }
/** /**
@ -58,4 +59,13 @@ data class Var(
override fun <R> accept(visitor: StmtVisitor<R>): R { override fun <R> accept(visitor: StmtVisitor<R>): R {
return visitor.visitVar(this) return visitor.visitVar(this)
} }
}
data class While(
val condition: Expr,
val body: Stmt
) : Stmt() {
override fun <R> accept(visitor: StmtVisitor<R>): R {
return visitor.visitWhile(this)
}
} }
Loading…
Cancel
Save