Class: Puppet::Pops::Types::RubyGenerator Private

Inherits:
TypeFormatter show all
Defined in:
lib/puppet/pops/types/ruby_generator.rb

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Constant Summary

Constants inherited from TypeFormatter

TypeFormatter::NAME_SEGMENT_SEPARATOR, TypeFormatter::STARTS_WITH_ASCII_CAPITAL

Instance Method Summary collapse

Methods inherited from TypeFormatter

#alias_expanded_string, #append_callable_params, #append_default, #append_indented_string, #append_string, #capitalize_segments, #debug_string, #expanded, #format_type_alias_type, #indented, #indented_string, #ruby, #ruby_string, singleton, #string, string, #string_Array, #string_FalseClass, #string_Hash, #string_Module, #string_NilClass, #string_Numeric, #string_PAnnotatedMember, #string_PAnyType, #string_PArrayType, #string_PBinaryType, #string_PBooleanType, #string_PCallableType, #string_PCatalogEntryType, #string_PClassType, #string_PCollectionType, #string_PDefaultType, #string_PEnumType, #string_PFloatType, #string_PHashType, #string_PInitType, #string_PIntegerType, #string_PIterableType, #string_PIteratorType, #string_PNotUndefType, #string_PNumericType, #string_PObjectType, #string_POptionalType, #string_PPatternType, #string_PRegexpType, #string_PResourceType, #string_PRuntimeType, #string_PScalarDataType, #string_PScalarType, #string_PSemVerRangeType, #string_PSemVerType, #string_PSensitiveType, #string_PStringType, #string_PStructType, #string_PTimespanType, #string_PTimestampType, #string_PTupleType, #string_PTypeAliasType, #string_PTypeReferenceType, #string_PTypeSetType, #string_PTypeType, #string_PUndefType, #string_PUnitType, #string_PVariantType, #string_PuppetObject, #string_Regexp, #string_String, #string_Symbol, #string_Timespan, #string_Timestamp, #string_TrueClass, #string_Version, #string_VersionRange, #struct_element_pair, #symbolic_key, #to_s

Instance Method Details

#array_type?(t) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Boolean)


406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/puppet/pops/types/ruby_generator.rb', line 406

def array_type?(t)
  case t
  when PArrayType
    true
  when POptionalType
    array_type?(t.optional_type)
  when PNotUndefType
    array_type?(t.type)
  when PVariantType
    t.types.all? { |v| array_type?(v) }
  else
    false
  end
end

#class_body(obj, segments, bld) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/puppet/pops/types/ruby_generator.rb', line 165

def class_body(obj, segments, bld)
  unless obj.parent.is_a?(PObjectType)
    bld << "\n  include " << namespace_relative(segments, Puppet::Pops::Types::PuppetObject.name) << "\n\n" # marker interface
    bld << "  def self.ref(type_string)\n"
    bld << '    ' << namespace_relative(segments, Puppet::Pops::Types::PTypeReferenceType.name) << ".new(type_string)\n"
    bld << "  end\n"
  end

  # Output constants
  constants, others = obj.attributes(true).values.partition { |a| a.kind == PObjectType::ATTRIBUTE_KIND_CONSTANT }
  constants = constants.select { |ca| ca.container.equal?(obj) }
  unless constants.empty?
    constants.each { |ca| bld << "\n  def self." << ca.name << "\n    _pcore_type['" << ca.name << "'].value\n  end\n" }
    constants.each { |ca| bld << "\n  def " << ca.name << "\n    self.class." << ca.name << "\n  end\n" }
  end

  init_params = others.reject { |a| a.kind == PObjectType::ATTRIBUTE_KIND_DERIVED }
  opt, non_opt = init_params.partition { |ip| ip.value? }
  derived_attrs, obj_attrs = others.select { |a| a.container.equal?(obj) }.partition { |ip| ip.kind == PObjectType::ATTRIBUTE_KIND_DERIVED }

  include_type = obj.equality_include_type? && !(obj.parent.is_a?(PObjectType) && obj.parent.equality_include_type?)
  if obj.equality.nil?
    eq_names = obj_attrs.reject { |a| a.kind == PObjectType::ATTRIBUTE_KIND_CONSTANT }.map(&:name)
  else
    eq_names = obj.equality
  end

  unless obj.parent.is_a?(PObjectType) && obj_attrs.empty?
    # Output type safe hash constructor
    bld << "\n  def self.from_hash(init_hash)\n"
    bld << '    from_asserted_hash(' << namespace_relative(segments, TypeAsserter.name) << '.assert_instance_of('
    bld << "'" << obj.label << " initializer', _pcore_type.init_hash_type, init_hash))\n  end\n\n  def self.from_asserted_hash(init_hash)\n    new"
    unless non_opt.empty? && opt.empty?
      bld << "(\n"
      non_opt.each { |ip| bld << "      init_hash['" << ip.name << "'],\n" }
      opt.each do |ip|
        if ip.value.nil?
          bld << "      init_hash['" << ip.name << "'],\n"
        else
          bld << "      init_hash.fetch('" << ip.name << "') { "
          default_string(bld, ip)
          bld << " },\n"
        end
      end
      bld.chomp!(",\n")
      bld << ')'
    end
    bld << "\n  end\n"

    # Output type safe constructor
    bld << "\n  def self.create"
    if init_params.empty?
      bld << "\n    new"
    else
      bld << '('
      non_opt.each { |ip| bld << ip.name << ', ' }
      opt.each do |ip|
        bld << ip.name << ' = '
        default_string(bld, ip)
        bld << ', '
      end
      bld.chomp!(', ')
      bld << ")\n"
      bld << '    ta = ' << namespace_relative(segments, TypeAsserter.name) << "\n"
      bld << "    attrs = _pcore_type.attributes(true)\n"
      init_params.each do |a|
        bld << "    ta.assert_instance_of('" << a.container.name << '[' << a.name << ']'
        bld << "', attrs['" << a.name << "'].type, " << a.name << ")\n"
      end
      bld << '    new('
      non_opt.each { |a| bld << a.name << ', ' }
      opt.each { |a| bld << a.name << ', ' }
      bld.chomp!(', ')
      bld << ')'
    end
    bld << "\n  end\n"

    # Output attr_readers
    unless obj_attrs.empty?
      bld << "\n"
      obj_attrs.each { |a| bld << '  attr_reader :' << a.name << "\n" }
    end

    bld << "  attr_reader :hash\n" if obj.parent.nil?

    derived_attrs.each do |a|
      bld << "\n  def " << a.name << "\n"
      code_annotation = RubyMethod.annotate(a)
      ruby_body = code_annotation.nil? ? nil: code_annotation.body
      if ruby_body.nil?
        bld << "    raise Puppet::Error, \"no method is implemented for derived #{a.label}\"\n"
      else
        bld << '    ' << ruby_body << "\n"
      end
      bld << "  end\n"
    end

    if init_params.empty?
      bld << "\n  def initialize\n    @hash = " << obj.hash.to_s << "\n  end" if obj.parent.nil?
    else
      # Output initializer
      bld << "\n  def initialize"
      bld << '('
      non_opt.each { |ip| bld << ip.name << ', ' }
      opt.each do |ip|
        bld << ip.name << ' = '
        default_string(bld, ip)
        bld << ', '
      end
      bld.chomp!(', ')
      bld << ')'

      hash_participants = init_params.select { |ip| eq_names.include?(ip.name) }
      if obj.parent.nil?
        bld << "\n    @hash = "
        bld << obj.hash.to_s << "\n" if hash_participants.empty?
      else
        bld << "\n    super("
        super_args = (non_opt + opt).select { |ip| !ip.container.equal?(obj) }
        unless super_args.empty?
          super_args.each { |ip| bld << ip.name << ', ' }
          bld.chomp!(', ')
        end
        bld << ")\n"
        bld << '    @hash = @hash ^ ' unless hash_participants.empty?
      end
      unless hash_participants.empty?
        hash_participants.each { |a| bld << a.name << '.hash ^ ' if a.container.equal?(obj) }
        bld.chomp!(' ^ ')
        bld << "\n"
      end
      init_params.each { |a| bld << '    @' << a.name << ' = ' << a.name << "\n" if a.container.equal?(obj) }
      bld << "  end\n"
    end
  end

  if obj_attrs.empty?
    bld << "\n  def _pcore_init_hash\n    {}\n  end\n" unless obj.parent.is_a?(PObjectType)
  else
    bld << "\n  def _pcore_init_hash\n"
    bld << '    result = '
    bld << (obj.parent.nil? ? '{}' : 'super')
    bld << "\n"
    obj_attrs.each do |a|
      bld << "    result['" << a.name << "'] = @" << a.name
      if a.value?
        bld << ' unless '
        equals_default_string(bld, a)
      end
      bld << "\n"
    end
    bld << "    result\n  end\n"
  end

  content_participants = init_params.select { |a| content_participant?(a) }
  if content_participants.empty?
    unless obj.parent.is_a?(PObjectType)
      bld << "\n  def _pcore_contents\n  end\n"
      bld << "\n  def _pcore_all_contents(path)\n  end\n"
    end
  else
    bld << "\n  def _pcore_contents\n"
    content_participants.each do |cp|
      if array_type?(cp.type)
        bld << '    @' << cp.name << ".each { |value| yield(value) }\n"
      else
        bld << '    yield(@' << cp.name << ') unless @' << cp.name  << ".nil?\n"
      end
    end
    bld << "  end\n\n  def _pcore_all_contents(path, &block)\n    path << self\n"
    content_participants.each do |cp|
      if array_type?(cp.type)
        bld << '    @' << cp.name << ".each do |value|\n"
        bld << "      block.call(value, path)\n"
        bld << "      value._pcore_all_contents(path, &block)\n"
      else
        bld << '    unless @' << cp.name << ".nil?\n"
        bld << '      block.call(@' << cp.name << ", path)\n"
        bld << '      @' << cp.name << "._pcore_all_contents(path, &block)\n"
      end
      bld << "    end\n"
    end
    bld << "    path.pop\n  end\n"
  end

  unless obj.parent.is_a?(PObjectType)
    bld << "\n  def to_s\n"
    bld << '    ' << namespace_relative(segments, TypeFormatter.name) << ".string(self)\n"
    bld << "  end\n"
  end

  # Output function placeholders
  obj.functions(false).each_value do |func|
    code_annotation = RubyMethod.annotate(func)
    if code_annotation
      body = code_annotation.body
      params = code_annotation.parameters
      bld << "\n  def " << func.name
      unless params.nil? || params.empty?
        bld << '(' << params << ')'
      end
      bld << "\n    " << body << "\n"
    else
      bld << "\n  def " << func.name << "(*args)\n"
      bld << "    # Placeholder for #{func.type}\n"
      bld << "    raise Puppet::Error, \"no method is implemented for #{func.label}\"\n"
    end
    bld << "  end\n"
  end

  unless eq_names.empty? && !include_type
    bld << "\n  def eql?(o)\n"
    bld << "    super &&\n" unless obj.parent.nil?
    bld << "    o.instance_of?(self.class) &&\n" if include_type
    eq_names.each { |eqn| bld << '    @' << eqn << '.eql?(o.' <<  eqn << ") &&\n" }
    bld.chomp!(" &&\n")
    bld << "\n  end\n  alias == eql?\n"
  end
end

#class_definition(obj, namespace_segments, bld, class_name, *impl_subst) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



128
129
130
131
132
133
134
135
136
# File 'lib/puppet/pops/types/ruby_generator.rb', line 128

def class_definition(obj, namespace_segments, bld, class_name, *impl_subst)
  module_segments = remove_common_namespace(namespace_segments, class_name)
  leaf_name = module_segments.pop
  module_segments.each { |segment| bld << 'module ' << segment << "\n" }
  scoped_class_definition(obj,leaf_name, bld, class_name, *impl_subst)
  module_segments.size.times { bld << "end\n" }
  module_segments << leaf_name
  module_segments.join(TypeFormatter::NAME_SEGMENT_SEPARATOR)
end

#content_participant?(a) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Boolean)


385
386
387
# File 'lib/puppet/pops/types/ruby_generator.rb', line 385

def content_participant?(a)
  a.kind != PObjectType::ATTRIBUTE_KIND_REFERENCE && obj_type?(a.type)
end

#create_class(obj) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Raises:

  • (ArgumentError)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/puppet/pops/types/ruby_generator.rb', line 19

def create_class(obj)
  @dynamic_classes ||= Hash.new do |hash, key|
    cls = key.implementation_class(false)
    if cls.nil?
      rp = key.resolved_parent
      parent_class = rp.is_a?(PObjectType) ? rp.implementation_class : Object
      class_def = ''
      class_body(key, EMPTY_ARRAY, class_def)
      cls = Class.new(parent_class)
      cls.class_eval(class_def)
      cls.define_singleton_method(:_pcore_type) { return key }
      key.implementation_class = cls
    end
    hash[key] = cls
  end
  raise ArgumentError, "Expected a Puppet Type, got '#{obj.class.name}'" unless obj.is_a?(PAnyType)
  @dynamic_classes[obj]
end

#default_string(bld, a) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



421
422
423
424
425
426
427
428
# File 'lib/puppet/pops/types/ruby_generator.rb', line 421

def default_string(bld, a)
  case a.value
  when nil, true, false, Numeric, String
    bld << a.value.inspect
  else
    bld << "_pcore_type['" << a.name << "'].value"
  end
end

#end_module(common_prefix, aliases, class_names, bld) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/puppet/pops/types/ruby_generator.rb', line 98

def end_module(common_prefix, aliases, class_names, bld)
  # Emit registration of contained type aliases
  unless aliases.empty?
    bld << "Puppet::Pops::Pcore.register_aliases({\n"
    aliases.each { |name, type| bld << "  '" << name << "' => " << TypeFormatter.string(type.to_s) << "\n" }
    bld.chomp!(",\n")
    bld << "})\n\n"
  end

  # Emit registration of contained types
  unless class_names.empty?
    bld << "Puppet::Pops::Pcore.register_implementations([\n"
    class_names.each { |class_name| bld << '  ' << class_name << ",\n" }
    bld.chomp!(",\n")
    bld << "])\n\n"
  end
  bld.chomp!("\n")

  common_prefix.size.times { bld << "end\n" }
end

#equals_default_string(bld, a) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



430
431
432
433
434
435
436
437
# File 'lib/puppet/pops/types/ruby_generator.rb', line 430

def equals_default_string(bld, a)
  case a.value
  when nil, true, false, Numeric, String
    bld << '@' << a.name << ' == ' << a.value.inspect
  else
    bld << "_pcore_type['" << a.name << "'].default_value?(@" << a.name << ')'
  end
end

#implementation_names(object_types) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



119
120
121
122
123
124
125
126
# File 'lib/puppet/pops/types/ruby_generator.rb', line 119

def implementation_names(object_types)
  object_types.map do |type|
    ir = Loaders.implementation_registry
    impl_name = ir.module_name_for_type(type)
    raise Puppet::Error, "Unable to create an instance of #{type.name}. No mapping exists to runtime object" if impl_name.nil?
    impl_name[0]
  end
end

#module_definition(types, comment, *impl_subst) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/puppet/pops/types/ruby_generator.rb', line 45

def module_definition(types, comment, *impl_subst)
  object_types, aliased_types = types.partition { |type| type.is_a?(PObjectType) }
  if impl_subst.empty?
    impl_names = implementation_names(object_types)
  else
    impl_names = object_types.map { |type| type.name.gsub(*impl_subst) }
  end

  # extract common implementation module prefix
  names_by_prefix = Hash.new { |hash, key| hash[key] = [] }
  index = 0
  min_prefix_length = impl_names.reduce(Float::INFINITY) do |len, impl_name|
    segments = impl_name.split(TypeFormatter::NAME_SEGMENT_SEPARATOR)
    leaf_name = segments.pop
    names_by_prefix[segments.freeze] << [index, leaf_name, impl_name]
    index += 1
    len > segments.size ? segments.size : len
  end
  min_prefix_length = 0 if min_prefix_length == Float::INFINITY

  common_prefix = []
  segments_array = names_by_prefix.keys
  min_prefix_length.times do |idx|
    segment = segments_array[0][idx]
    break unless segments_array.all? { |sn| sn[idx] == segment }
    common_prefix << segment
  end

  # Create class definition of all contained types
  bld = ''
  start_module(common_prefix, comment, bld)
  class_names = []
  names_by_prefix.each_pair do |seg_array, index_and_name_array|
    added_to_common_prefix = seg_array[common_prefix.length..-1]
    added_to_common_prefix.each { |name| bld << 'module ' << name << "\n" }
    index_and_name_array.each do |idx, name, full_name|
      scoped_class_definition(object_types[idx], name, bld, full_name, *impl_subst)
      class_names << (added_to_common_prefix + [name]).join(TypeFormatter::NAME_SEGMENT_SEPARATOR)
      bld << "\n"
    end
    added_to_common_prefix.size.times { bld << "end\n" }
  end

  aliases = Hash[aliased_types.map { |type| [type.name, type.resolved_type] }]
  end_module(common_prefix, aliases, class_names, bld)
  bld
end

#module_definition_from_typeset(typeset, *impl_subst) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



38
39
40
41
42
43
# File 'lib/puppet/pops/types/ruby_generator.rb', line 38

def module_definition_from_typeset(typeset, *impl_subst)
  module_definition(
    typeset.types.values,
    "# Generated by #{self.class.name} from TypeSet #{typeset.name} on #{Date.new}\n",
    *impl_subst)
end

#namespace_relative(namespace_segments, name) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



15
16
17
# File 'lib/puppet/pops/types/ruby_generator.rb', line 15

def namespace_relative(namespace_segments, name)
  remove_common_namespace(namespace_segments, name).join(TypeFormatter::NAME_SEGMENT_SEPARATOR)
end

#obj_type?(t) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Boolean)


389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/puppet/pops/types/ruby_generator.rb', line 389

def obj_type?(t)
  case t
  when PObjectType
    true
  when POptionalType
    obj_type?(t.optional_type)
  when PNotUndefType
    obj_type?(t.type)
  when PArrayType
    obj_type?(t.element_type)
  when PVariantType
    t.types.all? { |v| obj_type?(v) }
  else
    false
  end
end

#remove_common_namespace(namespace_segments, name) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



6
7
8
9
10
11
12
13
# File 'lib/puppet/pops/types/ruby_generator.rb', line 6

def remove_common_namespace(namespace_segments, name)
  segments = name.split(TypeFormatter::NAME_SEGMENT_SEPARATOR)
  namespace_segments.size.times do |idx|
    break if segments.empty? || namespace_segments[idx] != segments[0]
    segments.shift
  end
  segments
end

#scoped_class_definition(obj, leaf_name, bld, class_name, *impl_subst) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/puppet/pops/types/ruby_generator.rb', line 138

def scoped_class_definition(obj, leaf_name, bld, class_name, *impl_subst)
  bld << 'class ' << leaf_name
  segments = class_name.split(TypeFormatter::NAME_SEGMENT_SEPARATOR)

  unless obj.parent.nil?
    if impl_subst.empty?
      ir = Loaders.implementation_registry
      parent_impl = ir.module_name_for_type(obj.parent)
      raise Puppet::Error, "Unable to create an instance of #{obj.parent.name}. No mapping exists to runtime object" if parent_impl.nil?
      parent_name = parent_impl[0]
    else
      parent_name = obj.parent.name.gsub(*impl_subst)
    end
    bld << ' < ' << namespace_relative(segments, parent_name)
  end

  bld << "\n"
  bld << "  def self._pcore_type\n"
  bld << '    @_pcore_type ||= ' << namespace_relative(segments, obj.class.name) << ".new('" << obj.name << "', "
  bld << TypeFormatter.singleton.ruby('ref').indented(2).string(obj._pcore_init_hash(false)) << ")\n"
  bld << "  end\n"

  class_body(obj, segments, bld)

  bld << "end\n"
end

#start_module(common_prefix, comment, bld) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



93
94
95
96
# File 'lib/puppet/pops/types/ruby_generator.rb', line 93

def start_module(common_prefix, comment, bld)
  bld << '# ' << comment << "\n"
  common_prefix.each { |cp| bld << 'module ' << cp << "\n" }
end