Class: Flea::Interpreter
- Inherits:
-
Object
- Object
- Flea::Interpreter
- Defined in:
- lib/flea/interpreter.rb
Instance Attribute Summary collapse
-
#base_environment ⇒ Object
Returns the value of attribute base_environment.
-
#current_environment ⇒ Object
Returns the value of attribute current_environment.
Instance Method Summary collapse
- #evaluate(expression) ⇒ Object
-
#initialize(environment: Environment.new, standard_library: true) ⇒ Interpreter
constructor
A new instance of Interpreter.
- #parse(string) ⇒ Object
- #run(program) ⇒ Object
- #to_sexp(expression) ⇒ Object
Constructor Details
#initialize(environment: Environment.new, standard_library: true) ⇒ Interpreter
Returns a new instance of Interpreter.
7 8 9 10 11 |
# File 'lib/flea/interpreter.rb', line 7 def initialize(environment: Environment.new, standard_library: true) @base_environment = @current_environment = environment load_standard_library if standard_library end |
Instance Attribute Details
#base_environment ⇒ Object
Returns the value of attribute base_environment.
5 6 7 |
# File 'lib/flea/interpreter.rb', line 5 def base_environment @base_environment end |
#current_environment ⇒ Object
Returns the value of attribute current_environment.
5 6 7 |
# File 'lib/flea/interpreter.rb', line 5 def current_environment @current_environment end |
Instance Method Details
#evaluate(expression) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/flea/interpreter.rb', line 31 def evaluate(expression) return @current_environment.find(expression) if expression.is_a? Symbol return expression unless expression.is_a? Array case expression[0] when :define then @current_environment.define(expression[1], evaluate(expression[2])) when :native_function then eval expression[1] else function = evaluate(expression[0]) raise "\n#{to_sexp(expression)}\n ^\n\n#{expression[0]} is not a function\n\n#{@current_environment.table.keys}" unless function.is_a? Proc arguments = expression.slice(1, expression.length) function.call(arguments, self) end end |
#parse(string) ⇒ Object
47 48 49 |
# File 'lib/flea/interpreter.rb', line 47 def parse(string) Sexpistol.parse(string, parse_ruby_keyword_literals: true) end |
#run(program) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/flea/interpreter.rb', line 13 def run(program) program = parse(program) result = nil if program.is_a?(Sexpistol::SExpressionArray) program.each do |expression| result = evaluate(expression) end else result = evaluate(program) end result end |
#to_sexp(expression) ⇒ Object
51 52 53 |
# File 'lib/flea/interpreter.rb', line 51 def to_sexp(expression) Sexpistol.to_sexp(expression, scheme_compatability: true) end |