lib/rouge/namespace.rb in rouge-lang-0.0.11 vs lib/rouge/namespace.rb in rouge-lang-0.0.12

- old
+ new

@@ -3,33 +3,41 @@ require 'rouge/builtins' require 'rouge/var' require 'rouge/atom' class Rouge::Namespace - @namespaces = {} - class VarNotFoundError < StandardError; end class RecursiveNamespaceError < StandardError; end + attr_reader :name, :refers, :table + + @namespaces = {} + def initialize(name) + unless name.is_a? Symbol + raise ArgumentError, "bad ns name" + end + @name = name - raise ArgumentError, "bad ns name" unless @name.is_a? Symbol - @table = {} @refers = [] + @table = {} end def inspect - "#<Rouge::NS #{@name.inspect}, " \ - "refers #{@refers.map(&:inspect).join(", ")}>" + "#<Rouge::Namespace: @name=#{@name.inspect}, " \ + "@refers=[#{@refers.map(&:inspect).join(", ")}]>" end def refer(ns) if ns.name == @name raise RecursiveNamespaceError, "#@name will not refer #{ns.name}" end - @refers << ns if not @refers.include? ns + unless @refers.include?(ns) + @refers << ns + end + self end def [](key) if @table.include? key @@ -62,35 +70,48 @@ def clear @table = {} self end - attr_reader :name, :refers -end - -class << Rouge::Namespace - def exists?(ns) - @namespaces.include? ns + # Returns a hash of all namespaces. + # + # @return [Hash] + # + # @api public + def self.all + @namespaces end - def [](ns) - r = @namespaces[ns] - return r if r - - self[ns] = new(ns) - @namespaces[ns] = new(ns) + # Returns true if the given namespace ns exists, false otherwise. + # + # @param [Symbol] ns the namespace to check for + # + # @return [Boolean] + # + # @api public + def self.exists?(ns) + @namespaces.include?(ns) end - def get(ns) - @namespaces[ns] + def self.[](ns) + if exists?(ns) + @namespaces[ns] + else + self[ns] = new(ns) + @namespaces[ns] = new(ns) + end end - def []=(ns, value) + def self.[]=(ns, value) @namespaces[ns] = value end - def destroy(ns) + def self.get(ns) + @namespaces[ns] + end + + def self.destroy(ns) @namespaces.delete ns end end class Rouge::Namespace::Ruby @@ -113,18 +134,32 @@ end def name :ruby end + + # Returns the result of calling Object.constants. + # + # @return [Array<Symbol>] the list of Ruby constants + # + # @api public + # + def table + Object.constants + end end +# Create the rouge.builtin namespace. ns = Rouge::Namespace[:"rouge.builtin"] + Rouge::Builtins.methods(false).reject {|s| s =~ /^_compile_/}.each do |m| ns.set_here m, Rouge::Builtin[Rouge::Builtins.method(m)] end + Rouge::Builtins::SYMBOLS.each do |name, val| ns.set_here name, val end +# Create the ruby namespace. Rouge::Namespace[:ruby] = Rouge::Namespace::Ruby.new # vim: set sw=2 et cc=80: