Class: Philiprehberger::SafeExec::Evaluator

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/safe_exec/evaluator.rb

Overview

Evaluates an AST node tree against a context hash

Instance Method Summary collapse

Constructor Details

#initialize(context = {}) ⇒ Evaluator

Returns a new instance of Evaluator.

Parameters:

  • context (Hash) (defaults to: {})

    variable bindings for evaluation



8
9
10
# File 'lib/philiprehberger/safe_exec/evaluator.rb', line 8

def initialize(context = {})
  @context = normalize_context(context)
end

Instance Method Details

#evaluate(node) ⇒ Object

Evaluate an AST node

Parameters:

  • node (Hash)

    the AST node

Returns:

  • (Object)

    the evaluation result

Raises:



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/philiprehberger/safe_exec/evaluator.rb', line 17

def evaluate(node)
  case node[:type]
  when :literal then node[:value]
  when :identifier then resolve_identifier(node[:name])
  when :binary then evaluate_binary(node)
  when :comparison then evaluate_comparison(node)
  when :and then evaluate(node[:left]) && evaluate(node[:right])
  when :or then evaluate(node[:left]) || evaluate(node[:right])
  when :not then !evaluate(node[:operand])
  when :negate then -evaluate(node[:operand])
  when :index then evaluate_index(node)
  when :property then evaluate_property(node)
  when :ternary then evaluate_ternary(node)
  when :function_call then evaluate_function_call(node)
  else raise Error, "unknown node type: #{node[:type]}"
  end
end