main
Alpha Chen 2 years ago
parent 264b30200c
commit fdacd541cb

@ -48,9 +48,7 @@ module Lox
private private
def parenthesize(name, *exprs) def parenthesize(name, *exprs)
inside = [name] "(#{[name, *exprs.map { _1.accept(self) }].join(" ")})"
inside.concat(exprs.map {|expr| expr.accept(self) })
"(#{inside.join(" ")})"
end end
end end
end end

@ -14,8 +14,9 @@ module Lox
env.define(name, value) env.define(name, value)
end end
interpreter.execute_block(@decl.body, env) catch(:return) {
nil interpreter.execute_block(@decl.body, env)
}
end end
def to_s = "<fn #{@decl.name.lexeme}>" def to_s = "<fn #{@decl.name.lexeme}>"

@ -69,6 +69,12 @@ module Lox
nil nil
end end
def visit_return(stmt)
value = stmt.value ? evaluate(stmt.value) : nil
throw(:return, value)
end
def visit_var(stmt) def visit_var(stmt)
value = stmt.initializer&.yield_self { evaluate(_1) } value = stmt.initializer&.yield_self { evaluate(_1) }
@env.define(stmt.name.lexeme, value) @env.define(stmt.name.lexeme, value)

@ -235,6 +235,28 @@ class TestInterpreter < Lox::Test
sayHi("Dear", "Reader"); sayHi("Dear", "Reader");
SRC SRC
end end
def test_function
assert_interpreted <<~EXPECTED.chomp, <<~SRC
0
1
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);
}
SRC
end
private private
def assert_interpreted(expected, src) def assert_interpreted(expected, src)

Loading…
Cancel
Save