Sha256: 70225e1354010ce05e3d22f4766fd7a5e423467aa37c3c93498ab5fe2258e1e1

Contents?: true

Size: 1.56 KB

Versions: 25

Compression:

Stored size: 1.56 KB

Contents

module RBS
  class TypeNameResolver
    Query = _ = Struct.new(:type_name, :context, keyword_init: true)

    attr_reader :all_names
    attr_reader :cache

    def initialize()
      @all_names = Set[]
      @cache = {}
    end

    def self.from_env(env)
      new.add_names(env.class_decls.keys)
        .add_names(env.interface_decls.keys)
        .add_names(env.alias_decls.keys)
    end

    def add_names(names)
      all_names.merge(names)
      self
    end

    def try_cache(query)
      cache.fetch(query) do
        result = yield
        cache[query] = result
      end
    end

    def resolve(type_name, context:)
      if type_name.absolute?
        return type_name
      end

      query = Query.new(type_name: type_name, context: context)
      try_cache(query) do
        path_head, *path_tail = type_name.to_namespace.path
        raise unless path_head

        name_head = TypeName.new(name: path_head, namespace: Namespace.empty)

        absolute_head = context.find do |namespace|
          # @type break: TypeName
          full_name = name_head.with_prefix(namespace)
          has_name?(full_name) and break full_name
        end

        case absolute_head
        when TypeName
          has_name?(Namespace.new(path: absolute_head.to_namespace.path.push(*path_tail), absolute: true).to_type_name)
        when Namespace
          # This cannot happen because the `context.find` doesn't return a Namespace.
          raise
        end
      end
    end

    def has_name?(full_name)
      if all_names.include?(full_name)
        full_name
      end
    end
  end
end

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
rbs-1.1.1 lib/rbs/type_name_resolver.rb
rbs-1.1.0 lib/rbs/type_name_resolver.rb
rbs-1.0.6 lib/rbs/type_name_resolver.rb
rbs-1.0.5 lib/rbs/type_name_resolver.rb
rbs-1.0.4 lib/rbs/type_name_resolver.rb
rbs-1.0.3 lib/rbs/type_name_resolver.rb
rbs-1.0.2 lib/rbs/type_name_resolver.rb
rbs-1.0.1 lib/rbs/type_name_resolver.rb
rbs-1.0.0 lib/rbs/type_name_resolver.rb
rbs-1.0.0.pre2 lib/rbs/type_name_resolver.rb
rbs-1.0.0.pre lib/rbs/type_name_resolver.rb
rbs-0.20.1 lib/rbs/type_name_resolver.rb
rbs-0.20.0 lib/rbs/type_name_resolver.rb
rbs-0.19.0 lib/rbs/type_name_resolver.rb
rbs-0.18.1 lib/rbs/type_name_resolver.rb
rbs-0.18.0 lib/rbs/type_name_resolver.rb
rbs-0.17.0 lib/rbs/type_name_resolver.rb
rbs-0.16.0 lib/rbs/type_name_resolver.rb
rbs-0.15.0 lib/rbs/type_name_resolver.rb
rbs-0.14.0 lib/rbs/type_name_resolver.rb