//  [ruby]
  def self._all # :nodoc:
    unless defined?(@@all) && @@all then
      @@all = stubs.map(&:to_spec)

      # After a reset, make sure already loaded specs
      # are still marked as activated.
      specs = {}
      Gem.loaded_specs.each_value{|s| specs[s] = true}
      @@all.each{|s| s.activated = true if specs[s]}
    end
    @@all
  end

  def self._clear_load_cache # :nodoc:
    LOAD_CACHE.clear
  end

  def self.each_gemspec(dirs) # :nodoc:
    dirs.each do |dir|
      Dir[File.join(dir, "*.gemspec")].each do |path|
        yield path.untaint
      end
    end
  end

  def self.gemspec_stubs_in dir, pattern
    Dir[File.join(dir, pattern)].map { |path| yield path }.select(&:valid?)
  end
  private_class_method :gemspec_stubs_in

  def self.default_stubs pattern
    base_dir = Gem.default_dir
    gems_dir = File.join base_dir, "gems"
    gemspec_stubs_in(default_specifications_dir, pattern) do |path|
      Gem::StubSpecification.default_gemspec_stub(path, base_dir, gems_dir)
    end
  end
  private_class_method :default_stubs

  def self.installed_stubs dirs, pattern
    map_stubs(dirs, pattern) do |path, base_dir, gems_dir|
      Gem::StubSpecification.gemspec_stub(path, base_dir, gems_dir)
    end
  end
  private_class_method :installed_stubs

  if [].respond_to? :flat_map
    def self.map_stubs(dirs, pattern) # :nodoc:
      dirs.flat_map { |dir|
        base_dir = File.dirname dir
        gems_dir = File.join base_dir, "gems"
        gemspec_stubs_in(dir, pattern) { |path| yield path, base_dir, gems_dir }
      }
    end
  else # FIXME: remove when 1.8 is dropped
    def self.map_stubs(dirs, pattern) # :nodoc:
      dirs.map { |dir|
        base_dir = File.dirname dir
        gems_dir = File.join base_dir, "gems"
        gemspec_stubs_in(dir, pattern) { |path| yield path, base_dir, gems_dir }
      }.flatten 1
    end
  end
  private_class_method :map_stubs

  uniq_takes_a_block = false
  [1,2].uniq { uniq_takes_a_block = true }

  if uniq_takes_a_block
    def self.uniq_by(list, &block) # :nodoc:
      list.uniq(&block)
    end
  else # FIXME: remove when 1.8 is dropped
    def self.uniq_by(list) # :nodoc:
      values = {}
      list.each { |item|
        value = yield item
        values[value] ||= item
      }
      values.values
    end
  end
  private_class_method :uniq_by

  if [].respond_to? :sort_by!
    def self.sort_by! list, &block
      list.sort_by!(&block)
    end
  else # FIXME: remove when 1.8 is dropped
    def self.sort_by! list, &block
      list.replace list.sort_by(&block)
    end
  end
  private_class_method :sort_by!

  def self.each_spec(dirs) # :nodoc:
    each_gemspec(dirs) do |path|
      spec = self.load path
      yield spec if spec
    end
  end

  ##
  # Returns a Gem::StubSpecification for every installed gem

  def self.stubs
    @@stubs ||= begin
      pattern = "*.gemspec"
      stubs = default_stubs(pattern).concat installed_stubs(dirs, pattern)
      stubs = uniq_by(stubs) { |stub| stub.full_name }

      _resort!(stubs)
      @@stubs_by_name = stubs.group_by(&:name)
      stubs
    end
  end

  EMPTY = [].freeze # :nodoc:

  ##
  # Returns a Gem::StubSpecification for installed gem named +name+

  def self.stubs_for name
    if @@stubs
      @@stubs_by_name[name] || []
    else
      pattern = "#{name}-*.gemspec"
      stubs = default_stubs(pattern) + installed_stubs(dirs, pattern)
      stubs = uniq_by(stubs) { |stub| stub.full_name }.group_by(&:name)
      stubs.each_value { |v| _resort!(v) }

      @@stubs_by_name.merge! stubs
      @@stubs_by_name[name] ||= EMPTY
    end
  end

  def self._resort!(specs) # :nodoc:
    specs.sort! { |a, b|
      names = a.name <=> b.name
      next names if names.nonzero?
      b.version <=> a.version
    }
  end

  ##
  # Loads the default specifications. It should be called only once.

  def self.load_defaults
    each_spec([default_specifications_dir]) do |spec|
      # #load returns nil if the spec is bad, so we just ignore
      # it at this stage
      Gem.register_default_spec(spec)
    end
  end

  ##
  # Adds +spec+ to the known specifications, keeping the collection
  # properly sorted.

  def self.add_spec spec
    warn "Gem::Specification.add_spec is deprecated and will be removed in Rubygems 3.0" unless Gem::Deprecate.skip
    # TODO: find all extraneous adds
    # puts
    # p :add_spec => [spec.full_name, caller.reject { |s| s =~ /minitest/ }]

    # TODO: flush the rest of the crap from the tests
    # raise "no dupes #{spec.full_name} in #{all_names.inspect}" if
    #   _all.include? spec

    raise "nil spec!" unless spec # TODO: remove once we're happy with tests

    return if _all.include? spec

    _all << spec
    stubs << spec
    (@@stubs_by_name[spec.name] ||= []) << spec
    sort_by!(@@stubs_by_name[spec.name]) { |s| s.version }
    _resort!(_all)
    _resort!(stubs)
  end

  ##
  # Adds multiple specs to the known specifications.

  def self.add_specs *specs
    warn "Gem::Specification.add_specs is deprecated and will be removed in Rubygems 3.0" unless Gem::Deprecate.skip

    raise "nil spec!" if specs.any?(&:nil?) # TODO: remove once we're happy

    # TODO: this is much more efficient, but we need the extra checks for now
    # _all.concat specs
    # _resort!

    Gem::Deprecate.skip_during do
      specs.each do |spec| # TODO: slow
        add_spec spec
      end
    end
  end

  ##
  # Returns all specifications. This method is discouraged from use.
  # You probably want to use one of the Enumerable methods instead.

  def self.all
    warn "NOTE: Specification.all called from #{caller.first}" unless
      Gem::Deprecate.skip
    _all
  end

  ##
  # Sets the known specs to +specs+. Not guaranteed to work for you in
  # the future. Use at your own risk. Caveat emptor. Doomy doom doom.
  # Etc etc.
  #
  #--
  # Makes +specs+ the known specs
  # Listen, time is a river
  # Winter comes, code breaks
  #
  # -- wilsonb

  def self.all= specs
    @@stubs_by_name = specs.group_by(&:name)
    @@all = @@stubs = specs
  end

  ##
  # Return full names of all specs in sorted order.

  def self.all_names
    self._all.map(&:full_name)
  end

  ##
  # Return the list of all array-oriented instance variables.
  #--
  # Not sure why we need to use so much stupid reflection in here...

  def self.array_attributes
    @@array_attributes.dup
  end

  ##
  # Return the list of all instance variables.
  #--
  # Not sure why we need to use so much stupid reflection in here...

  def self.attribute_names
    @@attributes.dup
  end

  ##
  # Return the directories that Specification uses to find specs.

  def self.dirs
    @@dirs ||= Gem.path.collect { |dir|
      File.join dir.dup.untaint, "specifications"
    }
  end

  ##
  # Set the directories that Specification uses to find specs. Setting
  # this resets the list of known specs.

  def self.dirs= dirs
    self.reset

    @@dirs = Array(dirs).map { |dir| File.join dir, "specifications" }
  end

  extend Enumerable

  ##
  # Enumerate every known spec.  See ::dirs= and ::add_spec to set the list of
  # specs.

  def self.each
    return enum_for(:each) unless block_given?

    self._all.each do |x|
      yield x
    end
  end

  ##
  # Returns every spec that matches +name+ and optional +requirements+.

  def self.find_all_by_name name, *requirements
    requirements = Gem::Requirement.default if requirements.empty?

    # TODO: maybe try: find_all { |s| spec === dep }

    Gem::Dependency.new(name, *requirements).matching_specs
  end

  ##
  # Find the best specification matching a +name+ and +requirements+. Raises
  # if the dependency doesn't resolve to a valid specification.

  def self.find_by_name name, *requirements
    requirements = Gem::Requirement.default if requirements.empty?

    # TODO: maybe try: find { |s| spec === dep }

    Gem::Dependency.new(name, *requirements).to_spec
  end

  ##
  # Return the best specification that contains the file matching +path+.

  def self.find_by_path path
    path = path.dup.freeze
    spec = @@spec_with_requirable_file[path] ||= (stubs.find { |s|
      s.contains_requirable_file? path
    } || NOT_FOUND)
    spec.to_spec
  end

  ##
  # Return the best specification that contains the file matching +path+
  # amongst the specs that are not activated.

  def self.find_inactive_by_path path
    stub = stubs.find { |s|
      s.contains_requirable_file? path unless s.activated?
    }
    stub && stub.to_spec
  end

  def self.find_active_stub_by_path path
    stub = @@active_stub_with_requirable_file[path] ||= (stubs.find { |s|
      s.activated? and s.contains_requirable_file? path
    } || NOT_FOUND)
    stub.this
  end

  ##
  # Return currently unresolved specs that contain the file matching +path+.

  def self.find_in_unresolved path
    # TODO: do we need these?? Kill it
    specs = unresolved_deps.values.map { |dep| dep.to_specs }.flatten

    specs.find_all { |spec| spec.contains_requirable_file? path }
  end

  ##
  # Search through all unresolved deps and sub-dependencies and return
  # specs that contain the file matching +path+.

  def self.find_in_unresolved_tree path
    specs = unresolved_deps.values.map { |dep| dep.to_specs }.flatten

    specs.each do |spec|
      spec.traverse do |from_spec, dep, to_spec, trail|
        if to_spec.has_conflicts? || to_spec.conficts_when_loaded_with?(trail)
          :next
        else
          return trail.reverse if to_spec.contains_requirable_file? path
        end
      end
    end

    []
  end

  ##
  # Special loader for YAML files.  When a Specification object is loaded
  # from a YAML file, it bypasses the normal Ruby object initialization
  # routine (#initialize).  This method makes up for that and deals with
  # gems of different ages.
  #
  # +input+ can be anything that YAML.load() accepts: String or IO.

  def self.from_yaml(input)
    Gem.load_yaml

    input = normalize_yaml_input input
    spec = Gem::SafeYAML.safe_load input

    if spec && spec.class == FalseClass then
      raise Gem::EndOfYAMLException
    end

    unless Gem::Specification === spec then
      raise Gem::Exception, "YAML data doesn't evaluate to gem specification"
    end

    spec.specification_version ||= NONEXISTENT_SPECIFICATION_VERSION
    spec.reset_nil_attributes_to_default

    spec
  end

  ##
  # Return the latest specs, optionally including prerelease specs if
  # +prerelease+ is true.

  def self.latest_specs prerelease = false
    _latest_specs Gem::Specification._all, prerelease
  end

  def self._latest_specs specs, prerelease = false # :nodoc:
    result = Hash.new { |h,k| h[k] = {} }
    native = {}

    specs.reverse_each do |spec|
      next if spec.version.prerelease? unless prerelease

      native[spec.name] = spec.version if spec.platform == Gem::Platform::RUBY
      result[spec.name][spec.platform] = spec
    end

    result.map(&:last).map(&:values).flatten.reject { |spec|
      minimum = native[spec.name]
      minimum && spec.version < minimum
    }.sort_by{ |tup| tup.name }
  end

  ##
  # Loads Ruby format gemspec from +file+.

  def self.load file
    return unless file

    _spec = LOAD_CACHE[file]
    return _spec if _spec

    file = file.dup.untaint
    return unless File.file?(file)

    code = if defined? Encoding
             File.read file, :mode => 'r:UTF-8:-'
           else
             File.read file
           end

    code.untaint

    begin
      _spec = eval code, binding, file

      if Gem::Specification === _spec
        _spec.loaded_from = File.expand_path file.to_s
        LOAD_CACHE[file] = _spec
        return _spec
      end

      warn "[#{file}] isn't a Gem::Specification (#{_spec.class} instead)."
    rescue SignalException, SystemExit
      raise
    rescue SyntaxError, Exception => e
      warn "Invalid gemspec in [#{file}]: #{e}"
    end

    nil
  end