FossilOrigin-Name: 58225e550ec53fff4dcdde3678d5850dd91a285ad4ab247baa1fbf71e8d73206
private
alpha 2 years ago
parent ce8c69136a
commit 8350af2632

@ -59,6 +59,13 @@ module Lox
nil nil
end end
def visit_while(stmt)
while truthy?(evaluate(stmt.cond))
execute(stmt.body)
end
nil
end
def visit_grouping(expr) = evaluate(expr.expr) def visit_grouping(expr) = evaluate(expr.expr)
def visit_literal(expr) = expr.value def visit_literal(expr) = expr.value

@ -36,9 +36,19 @@ module Lox
Stmt::Var.new(name, initializer) Stmt::Var.new(name, initializer)
end end
def while_stmt
consume!(:LEFT_PAREN, "Expect '(' after 'if'.")
cond = expression
consume!(:RIGHT_PAREN, "Expect ')' after 'if'.")
body = statement
Stmt::While.new(cond, body)
end
def statement def statement
return if_stmt if match?(:IF) return if_stmt if match?(:IF)
return print if match?(:PRINT) return print if match?(:PRINT)
return while_stmt if match?(:WHILE)
return Stmt::Block.new(block) if match?(:LEFT_BRACE) return Stmt::Block.new(block) if match?(:LEFT_BRACE)
expression_stmt expression_stmt

@ -17,5 +17,6 @@ module Lox
stmt :If, :cond, :then, :else stmt :If, :cond, :then, :else
stmt :Print, :expr stmt :Print, :expr
stmt :Var, :name, :initializer stmt :Var, :name, :initializer
stmt :While, :cond, :body
end end
end end

@ -186,6 +186,20 @@ class TestInterpreter < Lox::Test
SRC SRC
end end
def test_while
assert_interpreted <<~EXPECTED.chomp, <<~SRC
0
1
2
EXPECTED
var a = 0;
while (a < 3) {
print a;
a = a + 1;
}
SRC
end
private private
def assert_interpreted(expected, src) def assert_interpreted(expected, src)

Loading…
Cancel
Save