Class: Ynl::Generator

Inherits:
Object
  • Object
show all
Defined in:
ynl/lib/ynl/generator.rb

Overview

Generates Ruby code from a parsed YNL specification.

Constant Summary collapse

PRELUDE =
-<<~RUBY
  # frozen_string_literal: true
  # This code is generated by Ynl::Generator. DO NOT EDIT.
  require 'nl'
RUBY

Instance Method Summary collapse

Constructor Details

#initialize(ynl, out) ⇒ Generator

Returns a new instance of Generator.



49
50
51
52
53
# File 'ynl/lib/ynl/generator.rb', line 49

def initialize(ynl, out)
  @ynl = ynl
  @out = out
  @indent = 0
end

Instance Method Details

#generate(superclass: nil, namespace: nil, default_resolver: nil) ⇒ Object



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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'ynl/lib/ynl/generator.rb', line 56

def generate(superclass: nil, namespace: nil, default_resolver: nil)
  raw = @ynl.protocol == 'netlink-raw'
  @wire = raw ? '::Nl::Raw' : '::Nl::Genl'
  superclass ||= raw ? '::Nl::Raw::Family' : '::Nl::Genl::Family'
  build_selector_plan

  emit_comment(@ynl.doc)

  classname = @ynl.name.as_class_name
  emit_class([*namespace, classname].join('::'), superclass) do
    emit_const('NAME', @ynl.name.as_string_literal)

    emit_const('PROTONUM', @ynl.protonum) if raw
    emit_const('VERSION', @ynl.version) unless raw
    emit_open(raw:, default_resolver:, classname:)

    emit_mcast_groups

    unless @ynl.consts.empty?
      emit_module('Constants') do
        @ynl.consts.each_value do |const|
          emit_comment(const.doc)
          emit_const(const.name.as_const_name, const_value_literal(const.value))
        end
      end
    end

    emit_value_definitions('Enums', @ynl.enums.values) { |_definition, entry| entry.value }
    emit_value_definitions('Flags', @ynl.flags.values + enums_used_as_flags) do |definition, entry|
      definition.is_a?(Models::Enum) ? 1 << entry.value : entry.value
    end

    deferred_struct_consts = []
    emit_module('Structs') do
      @ynl.structs.each do |name, struct|
        emit_comment(struct.doc)
        write(name.as_class_name, " = Struct.new(")
        indent do
          struct.members.each do |member|
            write(member.name.as_variable_name.as_symbol_literal, ', #: ', struct_member_rbs_type(member.type))
          end
        end
        write(')')
        emit_class(name.as_class_name) do
          struct.members.each do |member|
            emit_yard_attribute(
              member.name.as_method_name,
              struct_member_yard_type(member.type),
              member.doc,
            )
          end
          members = struct.members.map do |member|
            "#{member.name.as_variable_name}: #{to_struct_member_datatype(member.type)}"
          end
          members = "Ractor.make_shareable({#{members.join(', ')}})"
          if struct.members.any? { it.type.is_a?(Types::Binary) && it.type.struct }
            deferred_struct_consts << ["Structs::#{name.as_class_name}::MEMBERS", members]
          else
            emit_const('MEMBERS', members, rbs: 'Hash[::Symbol, ::Nl::_DataType]', internal: true)
          end

          emit_comment('Decodes the struct.')
          emit_rbs_comment(
            'decoder: ::Nl::Decoder',
            'return: instance',
          )
          emit_yard_param('decoder', 'Nl::Decoder')
          emit_yard_return('self')
          write('def self.decode(decoder)')
          indent do
            write('self.new(*MEMBERS.map {|name, datatype| datatype.decode(decoder) })')
          end
          write('end')

          emit_comment('Encodes the struct.')
          emit_rbs_comment(
            'encoder: ::Nl::Encoder',
            'return: void',
          )
          emit_yard_param('encoder', 'Nl::Encoder')
          emit_yard_return('void')
          write('def encode(encoder)')
          indent do
            write('MEMBERS.each {|name, datatype| datatype.encode(encoder, self.public_send(name)) }')
          end
          write('end')
        end
      end
    end
    deferred_struct_consts.each do |name, members|
      emit_const(name, members, rbs: 'Hash[::Symbol, ::Nl::_DataType]', internal: true)
    end

    deferred_sub_message_datatypes = []
    emit_module('AttributeSets') do
      deferred_consts = []
      @ynl.attribute_sets.each do |name, attr_set|
        emit_comment(attr_set.doc)
        emit_class(name.as_class_name, '::Nl::AttributeSet') do
          emit_comment("Abstract class")
          emit_class('Attribute', '::Nl::AttributeSet::Attribute') do
          end
          attr_set.attributes.each do |attr|
            emit_comment(attribute_doc(attr))
            emit_class(attr.name.as_class_name, 'Attribute') do
              emit_const('TYPE', attr.value)
              emit_const('NAME', attr.name.as_variable_name.as_symbol_literal)
              emit_const('MULTI', 'true', internal: true) if attr.multi?
              emit_const('ORDER', @attribute_orders.fetch(attr_set).fetch(attr), internal: true)
              if slot = @local_selectors.fetch(attr_set).index(attr.name)
                emit_const('SELECTOR_SLOT', slot, internal: true)
              end
              if attr.type.is_a?(Types::SubMessage)
                deferred_sub_message_datatypes << [
                  "AttributeSets::#{name.as_class_name}::#{attr.name.as_class_name}::DATATYPE",
                  to_datatype(attr.type, attr.checks, owner: attr_set),
                ]
              elsif attr.type.is_a?(Types::NestedAttributes) ||
                attr.type.is_a?(Types::NestTypeValue) ||
                (attr.type.is_a?(Types::IndexedArray) && attr.type.sub_type.is_a?(Types::NestedAttributes))
                deferred_consts << ["#{name.as_class_name}::#{attr.name.as_class_name}::DATATYPE", to_datatype(attr.type, attr.checks, owner: attr_set)]
              else
                emit_const('DATATYPE', to_datatype(attr.type, attr.checks, owner: attr_set), internal: true)
              end
            end
          end

          selector_names = @local_selectors.fetch(attr_set)
          external_selector_names = @external_selectors.fetch(attr_set)
          unless selector_names.empty? && external_selector_names.empty?
            emit_const(
              'SELECTOR_NAMES',
              "Ractor.make_shareable({local: [#{selector_names.map { it.as_variable_name.as_symbol_literal }.join(', ')}], external: [#{external_selector_names.map { it.as_variable_name.as_symbol_literal }.join(', ')}]})",
              internal: true,
            )
          end

          emit_const(
            'BY_NAME',
            "Ractor.make_shareable({#{attr_set.attributes.map { "#{it.name.as_variable_name.as_symbol_literal} => #{it.name.as_class_name}" }.join(', ') }})",
            rbs: 'Hash[::Symbol, Attribute]',
            internal: true,
          )

          emit_const(
            'BY_TYPE',
            "Ractor.make_shareable({#{attr_set.attributes.map { "#{it.value} => #{it.name.as_class_name}" }.join(', ') }})",
            rbs: 'Hash[::Integer, Attribute]',
            internal: true,
          )

          attr_set.attributes.each do |attribute|
            next if attribute.type.is_a?(Types::Pad)

            emit_comment(attribute_doc(attribute))
            emit_rbs_comment('return: ' + attribute_rbs_type(attribute))
            emit_yard_return(attribute_yard_type(attribute))
            emit_yard_see(attribute.name.as_class_name)
            expression = if attribute.multi?
              "self[#{attribute.name.as_variable_name.as_symbol_literal}].map(&:value)"
            else
              "self[#{attribute.name.as_variable_name.as_symbol_literal}]&.value"
            end
            emit_getter(attribute.name.as_method_name, expression)
          end

          emit_singleton_class do
            emit_comment('Looks up Attribute class by name.')
            emit_rbs_comment(
              'name: Symbol',
              'return: Attribute',
            )
            emit_yard_param('name', 'Symbol')
            emit_yard_return('Attribute')
            emit_getter('by_name(name)', 'BY_NAME.fetch(name)')

            emit_comment('Looks up Attribute class by type value.')
            emit_rbs_comment(
              'type: Integer',
              'return: Attribute',
            )
            emit_yard_param('type', 'Integer')
            emit_yard_return('Attribute')
            emit_getter('by_type(type)', 'BY_TYPE.fetch(type)')
          end
        end
      end
      deferred_consts.each do |const|
        emit_const(*const, internal: true)
      end
    end


    emit_sub_messages
    deferred_sub_message_datatypes.each do |const|
      emit_const(*const, internal: true)
    end

    emit_module('Messages') do
      @ynl.operations.each do |name, oper|
        %w[do dump].each do |method|
          if request_reply = oper.public_send(method + 'it')
            %w[request reply].to_h { [it, request_reply.public_send(it)] }.compact.each do |type, msg|
              emit_message_class(
                method.as_class_name + oper.name.as_class_name + type.as_class_name,
                msg,
                fixed_header: oper.fixed_header,
                attribute_set: oper.attribute_set,
                doc: operation_doc(oper),
              )
            end
          end
        end
      end
    end

    emit_module('Notifications') do
      notification_operations.each do |oper|
        message, fixed_header, attribute_set = notification_layout(oper)
        emit_message_class(
          oper.name.as_class_name,
          message,
          fixed_header:,
          attribute_set:,
          doc: notification_doc(oper),
        )
      end
    end

    emit_const(
      'NOTIFICATIONS',
      "Ractor.make_shareable({#{notification_operations.map { |oper| "#{oper.notification.message.value} => Notifications::#{oper.name.as_class_name}" }.join(', ') }})",
      rbs: 'Hash[::Integer, ::Class]',
      internal: true,
    )

    # emit request methods
    @ynl.operations.each do |name, oper|
      %w[do dump].each do |method|
        if request_reply = oper.public_send(method + 'it')
          request = request_reply.request

          request_class = "Messages::#{method.as_class_name}#{oper.name.as_class_name}Request"
          reply_class = request_reply.reply ? "Messages::#{method.as_class_name}#{oper.name.as_class_name}Reply" : 'nil'

          header_params = oper.fixed_header&.members || []
          attribute_params = oper.attribute_set.attributes.filter { request.attributes.include?(it.name) }
          attribute_params.reject! {|a| header_params.any? {|h| h.name == a.name  } }  # The two params should have the same Ruby type anyway
          params = header_params + attribute_params
          params.reject! { it.type.is_a? Types::Pad }

          rbs_params = params.map { |it| "?#{it.name.as_variable_name}: #{parameter_rbs_type(it)}" }.join(', ')
          rbs_result = request_reply.reply ? reply_class : 'void'

          emit_comment(operation_doc(oper))
          if method == 'dump'
            method_name = "#{method.as_method_name}_#{oper.name.as_method_name}"
            emit_rbs_comment(
              "(#{rbs_params}) -> Array[#{rbs_result}]\n  | (#{rbs_params}) { (#{rbs_result}) -> void } -> void",
            )
            emit_yard_overload("#{method_name}(**args)") do |indentation|
              emit_comment("#{indentation}Returns an array when no block is given.")
              emit_yard_options(params, indentation:)
              emit_yard_return("Array<#{rbs_result}>", indentation:)
            end
            emit_yard_overload("#{method_name}(**args, &block)") do |indentation|
              emit_comment("#{indentation}Yields each reply when a block is given.")
              emit_yard_options(params, indentation:)
              emit_yard_yieldparam('reply', rbs_result, indentation:)
              emit_yard_return('void', indentation:)
            end
            emit_yard_see(request_class)
            write("def #{method_name}(**args, &block)")
            indent do
              write("exchange_message(#{method.as_symbol_literal}, #{request_class}, #{reply_class}, args, &block)")
            end
          else
            emit_rbs_comment(
              "(#{rbs_params}) -> #{rbs_result}",
            )
            emit_yard_options(params)
            emit_yard_return(rbs_result)
            emit_yard_see(request_class)
            write("def #{method.as_method_name}_#{oper.name.as_method_name}(**args)")
            indent do
              write("exchange_message(#{method.as_symbol_literal}, #{request_class}, #{reply_class}, args)")
            end
          end
          write('end')
        end
      end
    end

    emit_class('AsyncOperations') do
      emit_internal
      write('def initialize(&exchange)')
      indent do
        write('@exchange = exchange')
      end
      write('end')

      @ynl.operations.each do |name, oper|
        %w[do dump].each do |method|
          next unless request_reply = oper.public_send(method + 'it')

          request_class = "Messages::#{method.as_class_name}#{oper.name.as_class_name}Request"
          reply_class = request_reply.reply ? "Messages::#{method.as_class_name}#{oper.name.as_class_name}Reply" : 'nil'
          header_params = oper.fixed_header&.members || []
          attribute_params = oper.attribute_set.attributes.filter { request_reply.request.attributes.include?(it.name) }
          attribute_params.reject! {|a| header_params.any? {|h| h.name == a.name } }
          params = (header_params + attribute_params).reject { it.type.is_a? Types::Pad }
          rbs_params = params.map { |it| "?#{it.name.as_variable_name}: #{parameter_rbs_type(it)}" }.join(', ')
          result = request_reply.reply ? reply_class : 'void'
          operation = method == 'dump' ? "::Nl::Async::Stream[#{result}]" : "::Nl::Async::Future[#{result}]"
          yard_operation = method == 'dump' ? "Nl::Async::Stream<#{result}>" : "Nl::Async::Future<#{result}>"

          emit_comment(operation_doc(oper))
          emit_rbs_comment("(#{rbs_params}) -> #{operation}")
          emit_yard_options(params)
          emit_yard_return(yard_operation)
          emit_yard_see(request_class)
          write("def #{method.as_method_name}_#{oper.name.as_method_name}(**args)")
          indent do
            write("@exchange.call(#{method.as_symbol_literal}, #{request_class}, #{reply_class}, args)")
          end
          write('end')
        end
      end
    end

    emit_comment('Returns the asynchronous operation facade for this family.')
    emit_rbs_comment('(?stream_capacity: ::Integer?) -> AsyncOperations')
    emit_yard_param('stream_capacity', '::Integer, nil')
    emit_yard_return('AsyncOperations')
    write('def async(stream_capacity: nil)')
    indent do
      write('return @async_operations ||= build_async_facade(AsyncOperations) if stream_capacity.nil?')
      write('build_async_facade(AsyncOperations, stream_capacity:)')
    end
    write('end')

    emit_subscription_methods unless @ynl.mcast_groups.empty?
  end

  classname
end