Class: Tapioca::TypeVariableModule

Inherits:
Module
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/tapioca/sorbet_ext/generic_name_patch.rb

Overview

This is subclassing from Module so that instances of this type will be modules. The reason why we want that is because that means those instances will automatically get bound to the constant names they are assigned to by Ruby. As a result, we don’t need to do any matching of constants to type variables to bind their names, Ruby will do that automatically for us and we get the name method for free from Module.

Defined Under Namespace

Classes: Type

Instance Method Summary collapse

Methods inherited from Module

#autoload, #autoload_without_tapioca

Constructor Details

#initialize(context, type, variance, fixed, lower, upper, bounds_proc) ⇒ TypeVariableModule

Returns a new instance of TypeVariableModule.



137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/tapioca/sorbet_ext/generic_name_patch.rb', line 137

def initialize(context, type, variance, fixed, lower, upper, bounds_proc)
  @context = context
  @type = type
  @variance = variance
  @bounds_proc = if bounds_proc
    bounds_proc
  else
    build_bounds_proc(fixed, lower, upper)
  end

  super()
end

Instance Method Details

#coerce_to_type_variableObject



187
188
189
# File 'lib/tapioca/sorbet_ext/generic_name_patch.rb', line 187

def coerce_to_type_variable
  TypeVariable.new(name, @variance)
end

#nameObject



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/tapioca/sorbet_ext/generic_name_patch.rb', line 152

def name
  constant_name = super

  # This is a hack to work around modules under anonymous modules not having
  # names in 2.6 and 2.7: https://bugs.ruby-lang.org/issues/14895
  #
  # This happens when a type variable is declared under `class << self`, for
  # example.
  #
  # The workaround is to give the parent context a name, at which point, our
  # module gets bound to a name under that name, as well.
  unless constant_name
    constant_name = with_bound_name_pre_3_0 { super }
  end

  constant_name&.split("::")&.last
end

#serializeObject



171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/tapioca/sorbet_ext/generic_name_patch.rb', line 171

def serialize
  bounds = @bounds_proc.call
  fixed = bounds[:fixed].to_s if bounds.key?(:fixed)
  lower = bounds[:lower].to_s if bounds.key?(:lower)
  upper = bounds[:upper].to_s if bounds.key?(:upper)

  TypeVariableHelper.serialize_type_variable(
    @type.serialize,
    @variance,
    fixed,
    upper,
    lower
  )
end