@ -48,9 +48,7 @@ module Lox
private
def parenthesize(name, *exprs)
inside = [name]
inside.concat(exprs.map {|expr| expr.accept(self) })
"(#{inside.join(" ")})"
"(#{[name, *exprs.map { _1.accept(self) }].join(" ")})"
end
@ -14,8 +14,9 @@ module Lox
env.define(name, value)
catch(:return) {
interpreter.execute_block(@decl.body, env)
nil
}
def to_s = "<fn #{@decl.name.lexeme}>"
@ -69,6 +69,12 @@ module Lox
def visit_return(stmt)
value = stmt.value ? evaluate(stmt.value) : nil
throw(:return, value)
def visit_var(stmt)
value = stmt.initializer&.yield_self { evaluate(_1) }
@env.define(stmt.name.lexeme, value)
@ -235,6 +235,28 @@ class TestInterpreter < Lox::Test
sayHi("Dear", "Reader");
SRC
def test_function
assert_interpreted <<~EXPECTED.chomp, <<~SRC
0
1
2
3
5
8
EXPECTED
fun fib(n) {
if (n <= 1) return n;
return fib(n - 2) + fib(n - 1);
for (var i = 0; i < 7; i = i + 1) {
print fib(i);
def assert_interpreted(expected, src)