|
|
|
@ -54,6 +54,7 @@ class Parser(private val tokens: List<Token>) {
|
|
|
|
|
|
|
|
|
|
|
|
private fun statement(): Stmt {
|
|
|
|
private fun statement(): Stmt {
|
|
|
|
return when {
|
|
|
|
return when {
|
|
|
|
|
|
|
|
match(FOR) -> forStatement()
|
|
|
|
match(IF) -> ifStatement()
|
|
|
|
match(IF) -> ifStatement()
|
|
|
|
match(PRINT) -> printStatement()
|
|
|
|
match(PRINT) -> printStatement()
|
|
|
|
match(WHILE) -> whileStatement()
|
|
|
|
match(WHILE) -> whileStatement()
|
|
|
|
@ -62,6 +63,42 @@ class Parser(private val tokens: List<Token>) {
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private fun forStatement(): Stmt {
|
|
|
|
|
|
|
|
consume(LEFT_PAREN, "Expect '(' after 'for'.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
val initializer = when {
|
|
|
|
|
|
|
|
match(SEMICOLON) -> null
|
|
|
|
|
|
|
|
match(VAR) -> varDeclaration()
|
|
|
|
|
|
|
|
else -> expressionStatement()
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
val condition = when {
|
|
|
|
|
|
|
|
!check(SEMICOLON) -> expression()
|
|
|
|
|
|
|
|
else -> Literal(true)
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
consume(SEMICOLON, "Expect ';' after loop condition.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
val increment = when {
|
|
|
|
|
|
|
|
!check(RIGHT_PAREN) -> expression()
|
|
|
|
|
|
|
|
else -> null
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
consume(RIGHT_PAREN, "Expect ')' after for clauses.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
var body = statement()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (increment != null) {
|
|
|
|
|
|
|
|
body = Block(listOf(body, Expression(increment)))
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
body = While(condition, body)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (initializer != null) {
|
|
|
|
|
|
|
|
body = Block(listOf(initializer, body))
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return body
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private fun ifStatement(): Stmt {
|
|
|
|
private fun ifStatement(): Stmt {
|
|
|
|
consume(LEFT_PAREN, "Expect '(' after 'if'.")
|
|
|
|
consume(LEFT_PAREN, "Expect '(' after 'if'.")
|
|
|
|
val condition = expression()
|
|
|
|
val condition = expression()
|
|
|
|
|