class RubyLisp::Environment

Attributes

is_namespace[RW]
namespace[RW]
out_env[RW]
outer[RW]
vars[RW]

Public Class Methods

new(outer: nil, namespace: nil, is_namespace: false, out_env: nil) click to toggle source
# File lib/rubylisp/environment.rb, line 7
def initialize(outer: nil, namespace: nil, is_namespace: false, out_env: nil)
  @vars = {'*ns*' => (outer or self)}
  @outer = outer
  @namespace = namespace or
               (outer.namespace if outer) or
               "__ns_#{rand 10000}"
  @is_namespace = is_namespace
  @out_env = if out_env
               out_env
             else
               find_namespace
             end
end

Public Instance Methods

find(key) click to toggle source
# File lib/rubylisp/environment.rb, line 33
def find key
  if @vars.member? key
    self
  elsif @outer
    @outer.find key
  else
    nil
  end
end
find_namespace() click to toggle source
# File lib/rubylisp/environment.rb, line 21
def find_namespace
  env = self
  while !env.is_namespace && !env.outer.nil?
    env = env.outer
  end
  env
end
get(key) click to toggle source
# File lib/rubylisp/environment.rb, line 43
def get key
  env = find key
  if env
    env.vars[key]
  else
    raise RuntimeError, "Unable to resolve symbol: #{key}"
  end
end
load_rbl_file(path) click to toggle source

TODO: some notion of “required namespaces” whose vars can be accessed when qualified with the namespace name

# File lib/rubylisp/environment.rb, line 68
def load_rbl_file path
  root = File.expand_path '../..', File.dirname(__FILE__)
  input = File.read "#{root}/#{path}"

  namespace = Environment.new
  Parser.parse input, namespace
  namespace
end
refer(other_env) click to toggle source

Copies all vars from `other_env` to this one.

# File lib/rubylisp/environment.rb, line 53
def refer other_env
  @vars = @vars.merge other_env.vars do |key, oldval, newval|
    if key == '*ns*'
      oldval
    else
      puts "WARNING: #{namespace}/#{key} being replaced by " +
           "#{other_env.namespace}/#{key}"
      newval
    end
  end
end
repl() click to toggle source
# File lib/rubylisp/environment.rb, line 83
def repl
  namespace = load_rbl_file 'rubylisp/repl.rbl'
  refer namespace
  self
end
set(key, val) click to toggle source
# File lib/rubylisp/environment.rb, line 29
def set key, val
  @vars[key] = val
end
stdlib() click to toggle source
# File lib/rubylisp/environment.rb, line 77
def stdlib
  namespace = load_rbl_file 'rubylisp/core.rbl'
  refer namespace
  self
end