Class: Orthoses::Utils::TypeList

Inherits:
Object
  • Object
show all
Defined in:
lib/orthoses/utils/type_list.rb

Overview

internal

Constant Summary collapse

UNTYPED =
::RBS::Types::Bases::Any.new(location: nil)
NIL_TYPE =
::RBS::Types::Bases::Nil.new(location: nil)
TRUE_TYPE =
::RBS::Types::Literal.new(literal: true, location: nil)
FALSE_TYPE =
::RBS::Types::Literal.new(literal: false, location: nil)
BOOL_TYPE =
::RBS::Types::Bases::Bool.new(location: nil)

Instance Method Summary collapse

Constructor Details

#initialize(types) ⇒ TypeList

Returns a new instance of TypeList.



13
14
15
# File 'lib/orthoses/utils/type_list.rb', line 13

def initialize(types)
  @types = types
end

Instance Method Details

#injectObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/orthoses/utils/type_list.rb', line 17

def inject
  normalize

  uniqed = @types.uniq

  return UNTYPED if uniqed.find { |t| t == UNTYPED }

  has_true = uniqed.delete(TRUE_TYPE)
  has_false = uniqed.delete(FALSE_TYPE)
  if has_true || has_false
    uniqed << BOOL_TYPE
  end

  return UNTYPED if uniqed.empty?
  return uniqed.first if uniqed.length == 1

  args_or_other = uniqed.group_by do |type|
    type.respond_to?(:args) && !type.args.empty?
  end
  if args_or_other[true]
    # { Array => [Array[Intger], Array[String]], Hash => [Hash[untyped, untyped]], ... }
    type_by_name = args_or_other[true].group_by do |type|
      type.name
    end
    type_by_name.each do |name, types|
      if with_untyped_type = types.find { |type| type.args.include?(UNTYPED) }
        types.replace([with_untyped_type])
      end
    end
    args_injected = type_by_name.values.flatten
    args_injected.concat(args_or_other[false]) if args_or_other[false]
    uniqed = args_injected
  end

  after_optional = uniqed.delete(NIL_TYPE)
  injected = uniqed.inject do |r, type|
    case r
    when ::RBS::Types::Union
      r.tap { r.types << type }
    else
      ::RBS::Types::Union.new(types: [r, type], location: nil)
    end
  end

  if after_optional
    return ::RBS::Types::Optional.new(type: injected, location: nil)
  end

  injected
end