Class: Schaefer::Interpreter

Inherits:
Object
  • Object
show all
Defined in:
lib/schaefer/interpreter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeInterpreter

Returns a new instance of Interpreter.



5
6
7
8
9
# File 'lib/schaefer/interpreter.rb', line 5

def initialize()
	@base_environment = @current_environment = Schaefer::Environment.new 
    @parser = Parser.new
    loadLibrary
end

Instance Attribute Details

#base_environmentObject

Returns the value of attribute base_environment.



3
4
5
# File 'lib/schaefer/interpreter.rb', line 3

def base_environment
  @base_environment
end

#current_environmentObject

Returns the value of attribute current_environment.



3
4
5
# File 'lib/schaefer/interpreter.rb', line 3

def current_environment
  @current_environment
end

#parserObject

Returns the value of attribute parser.



3
4
5
# File 'lib/schaefer/interpreter.rb', line 3

def parser
  @parser
end

Instance Method Details

#evaluate(expression) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/schaefer/interpreter.rb', line 20

def evaluate(expression)
	return @current_environment.find(expression) if expression.is_a? Symbol
	return expression unless expression.is_a? Array

	if expression[0] == :define
		return @current_environment.define(expression[1], evaluate(expression[2]))
	elsif expression[0] == :native_function
		return eval(expression[1])
	else
		function = evaluate(expression[0])
		raise RuntimeError, "\n#{expression[0]} is not a function" unless function.is_a? Proc
      arguments = expression.slice(1, expression.length)
		return function.call(arguments, self)
	end
end

#run(program) ⇒ Object



11
12
13
14
15
16
17
18
# File 'lib/schaefer/interpreter.rb', line 11

def run(program)
		expressions = @parser.parse(program)
	result = nil
	expressions.each do |expression|
		result = evaluate(expression)
	end
	return result
end