You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
795 B

2 years ago
require_relative "environment"
module Lox
class Function
2 years ago
def initialize(decl, closure, is_initializer)
@decl, @closure, @is_initializer = decl, closure, is_initializer
2 years ago
end
2 years ago
def bind(instance)
env = Environment.new(@closure)
env.define("this", instance)
2 years ago
Function.new(@decl, env, @is_initializer)
2 years ago
end
2 years ago
def arity = @decl.params.size
def call(interpreter, args)
2 years ago
env = Environment.new(@closure)
2 years ago
@decl.params.map(&:lexeme).zip(args).each do |name, value|
env.define(name, value)
end
2 years ago
return_value = catch(:return) {
2 years ago
interpreter.execute_block(@decl.body, env)
}
2 years ago
return @closure.get_at(0, "this") if @is_initializer
return_value
2 years ago
end
def to_s = "<fn #{@decl.name.lexeme}>"
end
end