Alpha Chen 2 years ago
parent fdacd541cb
commit b5bbfa6e48

@ -2,14 +2,14 @@ require_relative "environment"
module Lox module Lox
class Function class Function
def initialize(decl) def initialize(decl, closure)
@decl = decl @decl, @closure = decl, closure
end end
def arity = @decl.params.size def arity = @decl.params.size
def call(interpreter, args) def call(interpreter, args)
env = Environment.new(interpreter.globals) env = Environment.new(@closure)
@decl.params.map(&:lexeme).zip(args).each do |name, value| @decl.params.map(&:lexeme).zip(args).each do |name, value|
env.define(name, value) env.define(name, value)
end end

@ -50,7 +50,7 @@ module Lox
end end
def visit_function(stmt) def visit_function(stmt)
function = Function.new(stmt) function = Function.new(stmt, @env)
@env.define(stmt.name.lexeme, function) @env.define(stmt.name.lexeme, function)
nil nil
end end

@ -257,6 +257,27 @@ class TestInterpreter < Lox::Test
SRC SRC
end end
def test_local_functions_and_closures
assert_interpreted <<~EXPECTED.chomp, <<~SRC
1
2
EXPECTED
fun makeCounter() {
var i = 0;
fun count() {
i = i + 1;
print i;
}
return count;
}
var counter = makeCounter();
counter(); // "1".
counter(); // "2".
SRC
end
private private
def assert_interpreted(expected, src) def assert_interpreted(expected, src)

Loading…
Cancel
Save