123456789_123456789_123456789_123456789_123456789_

Class: RBS::TypeNameResolver

Relationships & Source Files
Inherits: Object
Defined in: lib/rbs/type_name_resolver.rb

Constant Summary

Class Method Summary

Instance Attribute Summary

Instance Method Summary

Constructor Details

.newTypeNameResolver

[ GitHub ]

  
# File 'lib/rbs/type_name_resolver.rb', line 8

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

Class Method Details

.from_env(env)

[ GitHub ]

  
# File 'lib/rbs/type_name_resolver.rb', line 13

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

Instance Attribute Details

#all_names (readonly)

[ GitHub ]

  
# File 'lib/rbs/type_name_resolver.rb', line 5

attr_reader :all_names

#cache (readonly)

[ GitHub ]

  
# File 'lib/rbs/type_name_resolver.rb', line 6

attr_reader :cache

Instance Method Details

#add_names(names)

[ GitHub ]

  
# File 'lib/rbs/type_name_resolver.rb', line 19

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

#has_name?(full_name) ⇒ Boolean

[ GitHub ]

  
# File 'lib/rbs/type_name_resolver.rb', line 59

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

#resolve(type_name, context:)

[ GitHub ]

  
# File 'lib/rbs/type_name_resolver.rb', line 31

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

#try_cache(query)

[ GitHub ]

  
# File 'lib/rbs/type_name_resolver.rb', line 24

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