Class: Ynl::Generator

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

Defined Under Namespace

Modules: Refinements

Constant Summary collapse

PRELUDE =
-<<~RUBY
  # frozen_string_literal: true
  # rbs_inline: enabled
  # 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.



40
41
42
43
44
# File 'lib/ynl/generator.rb', line 40

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

Instance Method Details

#generate(superclass: '::Nl::Family', namespace: nil) ⇒ Object



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
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
# File 'lib/ynl/generator.rb', line 46

def generate(superclass: '::Nl::Family', namespace: nil)
  @protocol = '::Nl::Protocols::' + (@ynl.protocol == 'netlink-raw' ? 'Raw' : 'Genl')

  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)

    if @ynl.protocol == 'netlink-raw'
      emit_const('PROTOCOL', "Ractor.make_shareable(::Nl::Protocols::Raw.new(#{@ynl.name.as_string_literal}, #{@ynl.protonum}))")
    else
      emit_const('PROTOCOL', "Ractor.make_shareable(::Nl::Protocols::Genl.new(#{@ynl.name.as_string_literal}))")
    end

    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, ', #: ', member.type.rbs_type)
          end
        end
        write(')')
        emit_class(name.as_class_name) do
          emit_nodoc
          emit_const(
            'MEMBERS',
            "Ractor.make_shareable({#{struct.members.map { "#{it.name.as_variable_name}: #{to_datatype(it.type, nil)}" }.join(', ') }})",
            rbs: 'Hash[::Symbol, ::Nl::_DataType]',
          )

          emit_comment('Decodes the struct.')
          emit_rbs_comment(
            'decoder: ::Nl::Decoder',
            'return: instance',
          )
          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',
          )
          write('def encode(encoder)')
          indent do
            write('MEMBERS.each {|name, datatype| datatype.encode(encoder, self.public_send(name)) }')
          end
          write('end')
        end
      end
    end

    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, @protocol + '::AttributeSet') do
          emit_comment("Abstract class")
          emit_class('Attribute', @protocol + '::AttributeSet::Attribute') do
          end
          attr_set.attributes.each do |attr|
            emit_comment(attr.doc)
            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)
              if attr.type.is_a?(Types::NestedAttributes) ||
                (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)]
              else
                emit_const('DATATYPE', to_datatype(attr.type, attr.checks))
              end
            end
          end

          emit_nodoc
          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]',
          )

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

          emit_singleton_class do
            emit_comment('Looks up Attribute class by name.')
            emit_rbs_comment(
              'name: Symbol',
              '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_getter('by_type(type)', 'BY_TYPE.fetch(type)')
          end
        end
      end
      deferred_consts.each { emit_const(*it) }
    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_comment(oper.doc)
              emit_class(method.as_class_name + oper.name.as_class_name + type.as_class_name, "#{@protocol}::Message") do
                emit_const('TYPE', msg.value)
                emit_const('FIXED_HEADER', oper.fixed_header&.then { 'Structs::' + it.name.as_class_name } || 'nil')
                emit_const('ATTRIBUTE_SET', "AttributeSets::#{oper.attribute_set.name.as_class_name}")
                params = msg.attributes
                attribute_params = oper.attribute_set.attributes.map(&:name) & params
                emit_const('ATTRIBUTES', "Ractor.make_shareable(%i[#{attribute_params.map { it.as_variable_name }.join(' ')}])")
                oper.fixed_header.members.each do |member|
                  param = member.name
                  datatype = member.type
                  next if datatype.is_a? Types::Pad
                  next if attribute_params.include?(param)
                  emit_comment("Gets the value of `#{param}` field in the message's fixed header.")
                  emit_rbs_comment(
                    'return: ' + datatype.rbs_type,
                  )
                  emit_getter(param.as_method_name, "fixed_header.#{param.as_method_name}")
                end if oper.fixed_header
                attribute_params.each do |param|
                  datatype = oper.attribute_set.attributes.find { it.name == param }.type
                  next if datatype.is_a? Types::Pad
                  extending = oper.fixed_header&.members&.any? { it.name == param }

                  if extending
                    emit_comment("Gets the value of `#{param}` attribute or fixed header in the message.")
                  else
                    emit_comment("Gets the value of `#{param}` attribute in the message.")
                  end
                  emit_rbs_comment(
                    'return: ' + datatype.rbs_type,
                  )
                  if extending
                    # If the fixed header and the attribute set have the same-name parameter, the value from the attribute should have
                    # the precedence over that from the header.
                    emit_getter(param.as_method_name, "attributes[#{param.as_variable_name.as_symbol_literal}]&.value || fixed_header.#{param.as_method_name}")
                  else
                    emit_getter(param.as_method_name, "attributes[#{param.as_variable_name.as_symbol_literal}]&.value")
                  end
                end
              end
            end
          end
        end
      end
    end

    # emit request methods
    @ynl.operations.each do |name, oper|
      %w[do dump].each do |method|
        if request_reply = oper.public_send(method + 'it')
          next unless request = request_reply.request  # FIXME: what should we do in this case?

          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}: #{it.type.rbs_type}" }.join(', ')
          rbs_result = request_reply.reply ? reply_class : 'void'

          emit_comment(oper.doc)
          if method == 'dump'
            emit_rbs_comment(
              "(#{rbs_params}) -> Enumerable[#{rbs_result}]\n  | (#{rbs_params}) { (#{rbs_result}) -> void } -> void",
            )
            write("def #{method.as_method_name}_#{oper.name.as_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}",
            )
            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
  end

  classname
end