Class: Campa::Evaler

Inherits:
Object
  • Object
show all
Defined in:
lib/campa/evaler.rb

Overview

All the actual logic on how to evaluate the differente known forms in implemented in here.

Instance Method Summary collapse

Constructor Details

#initializeEvaler

Returns a new instance of Evaler.



6
7
8
# File 'lib/campa/evaler.rb', line 6

def initialize
  @printer = Printer.new
end

Instance Method Details

#call(expression, env = {}) ⇒ Object

Returns the result of a given form evaluation.

The parameter expression is evaluated based on it’s type. Primitives (like booleans, nil, strings…) are returned as is. Symbols and Lists are handled like this:

  • Symbol‘s are searched in the given Context (env parameter).

  • List‘s are considered function invocations.

Parameters:

  • expression

    Can be any known form.

  • env (#[], #[]=) (defaults to: {})

    Hash or Context containing the bindings for the current Campa execution.



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/campa/evaler.rb', line 22

def call(expression, env = {})
  context = self.context(env)

  case expression
  when Numeric, TrueClass, FalseClass, NilClass, String, ::Symbol, List::EMPTY
    expression
  when Symbol
    resolve(expression, context)
  when List
    invoke(expression, context)
  end
end

#eval(reader, env = {}) ⇒ Object

Receives a Reader object and evaluate all forms returned by each #next call. Uses #call to do the actual evaluation.

Parameters:

  • reader (Reader)

    representing the source code to be evaluated

  • env (Context) (defaults to: {})

    to evaluate the code

Returns:

  • (Object)

    the result of evaluating the last form available in the given Reader



44
45
46
47
48
49
50
51
52
# File 'lib/campa/evaler.rb', line 44

def eval(reader, env = {})
  context = self.context(env)

  result = nil
  while (token = reader.next)
    result = call(token, context)
  end
  result
end