Class: Lox::Function

Inherits:
Object
  • Object
show all
Includes:
Callable
Defined in:
lib/loxby/helpers/functions.rb

Overview

A ‘Function’ is a loxby function.

You could manually instantiate one, but why would you?

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(declaration, closure) ⇒ Function

Returns a new instance of Function.



16
17
18
19
# File 'lib/loxby/helpers/functions.rb', line 16

def initialize(declaration, closure)
  @declaration = declaration
  @closure = closure
end

Instance Attribute Details

#declarationObject (readonly)

Returns the value of attribute declaration.



14
15
16
# File 'lib/loxby/helpers/functions.rb', line 14

def declaration
  @declaration
end

#enclosureObject (readonly)

Returns the value of attribute enclosure.



14
15
16
# File 'lib/loxby/helpers/functions.rb', line 14

def enclosure
  @enclosure
end

Instance Method Details

#arityObject



37
# File 'lib/loxby/helpers/functions.rb', line 37

def arity = @declaration.params.size

#call(interpreter, args) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/loxby/helpers/functions.rb', line 21

def call(interpreter, args)
  env = Environment.new(@closure)
  @declaration.params.zip(args).each do |param, arg|
    env[param] = arg # Environment grabs the lexeme automatically
  end

  # Interpreter will `throw :return, return_value` to unwind
  # callstack, jumping out of the `catch` block. `catch` then
  # implicitly returns that value.
  catch(:return) do
    interpreter.execute_block @declaration.body, env
    # If we get here, there was no return statement.
    return nil
  end
end

#to_sObject



38
# File 'lib/loxby/helpers/functions.rb', line 38

def to_s = "<fn #{@declaration.name ? @declaration.name.lexeme : '(anonymous)'}>"