Method: Puppet::Pops::Types::PInitType#assert_initialized

Defined in:
lib/puppet/pops/types/p_init_type.rb

#assert_initializedObject



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/puppet/pops/types/p_init_type.rb', line 142

def assert_initialized
  return self if @initialized

  @initialized = true
  @self_recursion = true

  begin
    # Filter out types that will provide a new_function but are unsuitable to be contained in Init
    #
    # Calling Init#new would cause endless recursion
    # The Optional is the same as Variant[T,Undef].
    # The NotUndef is not meaningful to create instances of
    if @type.instance_of?(PInitType) || @type.instance_of?(POptionalType) || @type.instance_of?(PNotUndefType)
      raise ArgumentError
    end

    new_func = @type.new_function
  rescue ArgumentError
    raise ArgumentError, _("Creation of new instance of type '%{type_name}' is not supported") % { type_name: @type.to_s }
  end
  param_tuples = new_func.dispatcher.signatures.map { |closure| closure.type.param_types }

  # An instance of the contained type is always a match to this type.
  single_types = [@type]

  if @init_args.empty?
    # A value that is assignable to the type of a single parameter is also a match
    single_tuples, other_tuples = param_tuples.partition { |tuple| EXACTLY_ONE == tuple.size_range }
    single_types.concat(single_tuples.map { |tuple| tuple.types[0] })
  else
    tc = TypeCalculator.singleton
    init_arg_types = @init_args.map { |arg| tc.infer_set(arg) }
    arg_count = 1 + init_arg_types.size

    # disqualify all parameter tuples that doesn't allow one value (type unknown at ths stage) + init args.
    param_tuples = param_tuples.select do |tuple|
      min, max = tuple.size_range
      if arg_count >= min && arg_count <= max
        # Aside from the first parameter, does the other parameters match?
        tuple.assignable?(PTupleType.new(tuple.types[0..0].concat(init_arg_types)))
      else
        false
      end
    end
    if param_tuples.empty?
      raise ArgumentError, _("The type '%{type}' does not represent a valid set of parameters for %{subject}.new()") %
                           { type: to_s, subject: @type.generalize.name }
    end
    single_types.concat(param_tuples.map { |tuple| tuple.types[0] })
    other_tuples = EMPTY_ARRAY
  end
  @single_type = PVariantType.maybe_create(single_types)
  unless other_tuples.empty?
    @other_type = PVariantType.maybe_create(other_tuples)
    @has_optional_single = other_tuples.any? { |tuple| tuple.size_range.min == 1 }
  end

  guard = RecursionGuard.new
  accept(NoopTypeAcceptor::INSTANCE, guard)
  @self_recursion = guard.recursive_this?(self)
end