Class: Theta::Interpreter
- Inherits:
-
Object
- Object
- Theta::Interpreter
- Defined in:
- lib/theta/interpreter.rb
Overview
interpret scheme code
Instance Attribute Summary collapse
-
#current_environment ⇒ Object
Returns the value of attribute current_environment.
Instance Method Summary collapse
-
#evaluate(expression) ⇒ Object
evaluate the scheme expression.
-
#initialize ⇒ Interpreter
constructor
initialize the environment and the parser.
-
#load_library ⇒ Object
load any predefined library files.
-
#make_readable(value) ⇒ Object
call the parser to make something readable.
-
#parse(string) ⇒ Object
call the parser to make a string interpretable.
-
#run(program) ⇒ Object
run some code.
Constructor Details
#initialize ⇒ Interpreter
initialize the environment and the parser
11 12 13 14 15 |
# File 'lib/theta/interpreter.rb', line 11 def initialize @global_environment = @current_environment = Environment.new @parser = Parser.new load_library end |
Instance Attribute Details
#current_environment ⇒ Object
Returns the value of attribute current_environment.
8 9 10 |
# File 'lib/theta/interpreter.rb', line 8 def current_environment @current_environment end |
Instance Method Details
#evaluate(expression) ⇒ Object
evaluate the scheme expression
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/theta/interpreter.rb', line 47 def evaluate(expression) if expression.is_a? Symbol return @current_environment.find(expression) elsif not expression.is_a? Array return expression end case expression[0] when :define @current_environment.define(expression [1], evaluate(expression[2])) when :ruby_func return eval expression[1] else function = evaluate(expression[0]) if function.is_a? Proc arguments = expression[1, expression.length] return function.call(arguments, self) else raise RuntimeError, "#{expression[0]} is not a function" end end return nil end |
#load_library ⇒ Object
load any predefined library files
18 19 20 21 22 23 24 25 26 |
# File 'lib/theta/interpreter.rb', line 18 def load_library library_directory = File.(File.join(File.dirname(__FILE__), "library")) Dir.foreach(library_directory) do |file| if file != "." && file != ".." f = File.open(File.join(library_directory, file)) run(f.read) end end end |
#make_readable(value) ⇒ Object
call the parser to make something readable
42 43 44 |
# File 'lib/theta/interpreter.rb', line 42 def make_readable(value) @parser.to_string(value) end |
#parse(string) ⇒ Object
call the parser to make a string interpretable
37 38 39 |
# File 'lib/theta/interpreter.rb', line 37 def parse(string) @parser.parse(string) end |
#run(program) ⇒ Object
run some code
29 30 31 32 33 34 |
# File 'lib/theta/interpreter.rb', line 29 def run(program) expression = parse(program) output = [] expression.each { |e| output << evaluate(e) } return output.delete_if { |x| x.nil? } end |