Class: Protobug::Compiler

Inherits:
Object
  • Object
show all
Defined in:
lib/protobug/compiler.rb,
lib/protobug/compiler/builder.rb,
lib/protobug/compiler/builder_gen.rb

Defined Under Namespace

Modules: Builder, Descriptor Classes: DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, FieldDescriptorProto, FileDescriptorProto, Files, OneofDescriptorProto, ServiceDescriptorProto

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(request, response) ⇒ Compiler

Returns a new instance of Compiler.



19
20
21
22
# File 'lib/protobug/compiler.rb', line 19

def initialize(request, response)
  @request = request
  @response = response
end

Instance Attribute Details

#filesObject (readonly)

Returns the value of attribute files.



24
25
26
# File 'lib/protobug/compiler.rb', line 24

def files
  @files
end

#requestObject (readonly)

Returns the value of attribute request.



24
25
26
# File 'lib/protobug/compiler.rb', line 24

def request
  @request
end

#responseObject (readonly)

Returns the value of attribute response.



24
25
26
# File 'lib/protobug/compiler.rb', line 24

def response
  @response
end

Class Method Details

.compile!(request) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/protobug/compiler.rb', line 9

def self.compile!(request)
  response = Google::Protobuf::Compiler::CodeGeneratorResponse.new
  begin
    new(request, response).compile!
  rescue StandardError => e
    response.error = e.full_message
  end
  response
end

Instance Method Details

#compile!Object



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/protobug/compiler.rb', line 197

def compile!
  response.supported_features |=
    Google::Protobuf::Compiler::CodeGeneratorResponse::Feature::FEATURE_PROTO3_OPTIONAL.value
  @files = Files.new

  request.proto_file.each do |file|
    files.register_file(file)
  end

  request.file_to_generate.each do |name|
    files.fetch(name).file_to_generate = true
  end

  request.file_to_generate.each do |name| # rubocop:disable Style/CombinableLoops
    file = files.fetch(name)
    file_out = Google::Protobuf::Compiler::CodeGeneratorResponse::File.new
    file_out.name = file.file_name
    file_out.content = file_contents(files, file)
    response.add_file(file_out)
  end
end

#emit_decls(descriptor, group) ⇒ Object



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
# File 'lib/protobug/compiler.rb', line 219

def emit_decls(descriptor, group)
  source_loc = descriptor.source_loc
  return unless source_loc

  source_loc.leading_detached_comments&.each do |c|
    group.comment(c)
    group.empty
  end

  group.comment(source_loc.leading_comments) if source_loc.leading_comments?

  case descriptor
  when DescriptorProto
    group._class.identifier(descriptor.name).block do |g|
      g.identifier("extend").identifier("Protobug::Message")
      g.empty
      g.identifier("self").dot("full_name").op("=").literal(descriptor.full_name)

      requires_empty = true
      descriptor.each_declaration do |decl|
        g.empty if requires_empty
        requires_empty = emit_decls(decl, g) &&
                         !decl.is_a?(FieldDescriptorProto) && !decl.is_a?(OneofDescriptorProto)
      end

      if descriptor.reserved_range.any? || descriptor.reserved_name.any?
        g.empty
        descriptor.file.loc_by_path(descriptor.source_loc.path +
                                    [DescriptorProto.fields_by_name.fetch("reserved_range").number])&.tap do |loc|
          g.comment(loc.leading_comments) if loc.leading_comments?
        end
        descriptor.reserved_range.each_with_index do |range, idx|
          descriptor.file.loc_by_path(descriptor.source_loc.path + [
            DescriptorProto.fields_by_name.fetch("reserved_range").number, idx
          ]).tap do |loc|
            g.comment(loc.leading_comments) if loc.leading_comments?
          end
          g.identifier("reserved_range").call do |c|
            c.literal(range.start).op("...").literal(range.end)
          end
        end
        descriptor.reserved_name.each do |name|
          g.identifier("reserved_name").call do |c|
            c.literal(name)
          end
        end
      end
    end
  when EnumDescriptorProto
    group._class.identifier(descriptor.name).block do |g|
      g.identifier("extend").identifier("Protobug::Enum")
      g.empty
      g.identifier("self").dot("full_name").op("=")
       .literal(descriptor.full_name)
      g.empty

      descriptor.each_declaration do |decl|
        emit_decls(decl, g)
      end

      if descriptor.reserved_range.any? || descriptor.reserved_name.any?
        g.empty
        descriptor.reserved_range.each do |range|
          g.identifier("reserved_range").call do |c|
            c.literal(range.start).op("..").literal(range.end - 1)
          end
        end
        descriptor.reserved_name.each do |name|
          g.identifier("reserved_name").call do |c|
            c.literal(name)
          end
        end
      end
    end
  when EnumValueDescriptorProto
    const_name = descriptor.name.start_with?("k") ? "K_#{descriptor.name[1..]}" : descriptor.name
    const_name = "K_#{const_name}" unless const_name.match?(/\A[A-Z]/)
    group.identifier(const_name).op("=").identifier("new").call do |c|
      c.literal(descriptor.name)
      c.literal(descriptor.number)
    end.dot("freeze")
  when FieldDescriptorProto
    if descriptor.extendee?
      containing_type = files.fetch_type(
        if descriptor.extendee.start_with?(".")
          descriptor.extendee[1..]
        else
          "#{descriptor.parent.full_name}.#{descriptor.extendee}"
        end
      )
      group.comment("extension: #{containing_type.full_name}\n  #{descriptor.name} #{descriptor.number}")
      return # rubocop:disable Lint/NonLocalExitFromIterator
    end

    type = descriptor.type.name.downcase.delete_prefix("type_").to_sym

    if descriptor.type_name?
      referenced_type = files.fetch_type(descriptor.type_name.delete_prefix("."))
      type = :map unless referenced_type.source_loc
    end

    group.identifier(
      case descriptor.label
      when Google::Protobuf::FieldDescriptorProto::Label::LABEL_OPTIONAL
        "optional"
      when Google::Protobuf::FieldDescriptorProto::Label::LABEL_REPEATED
        if type == :map
          "map"
        else
          "repeated"
        end
      when Google::Protobuf::FieldDescriptorProto::Label::LABEL_REQUIRED
        "required"
      else
        raise "Unknown label: #{descriptor.label}"
      end
    ).call do |c|
      c.literal(descriptor.number)
      c.literal(descriptor.name)
      c.identifier("type:").literal(type) unless type == :map

      if type == :map
        c.identifier("key_type:")
         .literal(referenced_type.field[0].type.name.downcase.delete_prefix("type_").to_sym)
        value_type = referenced_type.field[1].type.name.downcase.delete_prefix("type_").to_sym
        c.identifier("value_type:")
         .literal(value_type)
        if referenced_type.field[1].type_name?
          c.identifier("#{value_type}_type:")
           .literal(referenced_type.field[1].type_name.delete_prefix("."))
        end
      elsif descriptor.type_name?
        c.identifier("#{type}_type:").literal(descriptor.type_name.delete_prefix("."))
      end

      packed = descriptor.options&.packed
      # TODO: exclude other types that cannot be packed
      if !descriptor.options&.packed? && !%i[message bytes string map].include?(type)
        packed = descriptor.label == Google::Protobuf::FieldDescriptorProto::Label::LABEL_REPEATED &&
                 descriptor.file.syntax == "proto3"
      end
      c.identifier("packed:").literal(packed) if packed
      if descriptor.json_name? && descriptor.json_name != descriptor.name
        c.identifier("json_name:").literal(descriptor.json_name)
      end
      if descriptor.oneof_index?
        oneof = descriptor.parent.oneof_decl[descriptor.oneof_index]
        synthetic = descriptor.proto3_optional && (descriptor.parent.field.count do |f|
          f.oneof_index? && f.oneof_index == descriptor.oneof_index
        end == 1)
        c.identifier("oneof:").literal(oneof.name.to_sym) unless synthetic
      end
      if descriptor.label == Google::Protobuf::FieldDescriptorProto::Label::LABEL_OPTIONAL &&
         descriptor.file.syntax == "proto3" && !descriptor.proto3_optional
        c.identifier("proto3_optional:").literal(false)
      end
    end
  when OneofDescriptorProto
    group.empty if source_loc.leading_comments?
    # no-op
  else
    raise "Unknown descriptor type: #{descriptor.class}"
  end.tap do |s|
    s.comment(source_loc.trailing_comments) if source_loc.trailing_comments?
  end
end

#emit_register(defn, descriptor) ⇒ Object



471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/protobug/compiler.rb', line 471

def emit_register(defn, descriptor)
  case descriptor
  when DescriptorProto, EnumDescriptorProto
    return unless descriptor.source_loc

    defn.identifier("registry").dot("register").call do |c|
      c.identifier(descriptor.to_constant)
    end
  when FieldDescriptorProto
    return unless descriptor.extendee?

    containing_type = files.fetch_type(
      if descriptor.extendee.start_with?(".")
        descriptor.extendee[1..]
      else
        "#{descriptor.parent.full_name}.#{descriptor.extendee}"
      end
    )
    defn.comment("extension: #{containing_type.full_name}\n  #{descriptor.type} #{descriptor.number}")
  when FileDescriptorProto, EnumValueDescriptorProto, ServiceDescriptorProto, OneofDescriptorProto
    # no-op
  else
    raise "Unknown descriptor type: #{descriptor.class}"
  end
  descriptor.each_declaration do |decl|
    emit_register(defn, decl)
  end
end

#file_contents(files, file) ⇒ Object



386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
# File 'lib/protobug/compiler.rb', line 386

def file_contents(files, file)
  Builder.build_file do |f|
    f.header_comment "frozen_string_literal: true"
    f.header_comment "Code generated by protoc-gen-protobug. DO NOT EDIT."

    f.comment "source: #{file.name}"
    f.comment "syntax: #{file.syntax? ? file.syntax : "proto2"}"
    f.comment "package: #{file.package}"
    f.comment "options:"
    if file.options
      file.options.class.fields_by_name.each_key do |name|
        next unless file.options.send(:"#{name}?")

        value = case value = file.options.send(name)
                when Enum::InstanceMethods
                  value.name
                when Symbol
                  raise "Unknown symbol: #{value} for #{name} in #{file.options.inspect}"
                else
                  value.inspect
                end

        f.comment "   #{name}: #{value}"
      end
    end

    file.source_loc.leading_detached_comments.each do |c|
      f.empty
      f.comment c
    end

    f.empty
    f.identifier("require").literal("protobug")

    local, external = file.dependency.map do |dep|
      files.fetch(dep)
    end.partition(&:file_to_generate)
    if external.any?
      f.empty
      external.each do |dep|
        f.identifier("require").literal(dep.file_name.delete_suffix(".rb"))
      end
    end
    if local.any?
      f.empty
      local.each do |dep|
        relative_path = Pathname(dep.file_name.delete_suffix(".rb"))
                        .relative_path_from(Pathname(file.file_name).dirname)
                        .to_path
        f.identifier("require_relative").literal(relative_path)
      end
    end

    f.empty

    g = f
    file.to_constant.split("::").each do |part|
      g._module.identifier(part).block { |g_| g = g_ }
    end

    first = true
    file.each_declaration do |decl|
      g.empty unless first
      emit_decls(decl, g)
      first = false
    end

    g.empty unless first
    g._def.identifier("self")
     .dot("register_#{File.basename file.name.delete_suffix(".proto")}_protos")
     .call do |c|
      c.identifier("registry")
    end.block do |defn|
      file.dependency.each do |dep|
        defn.identifier(files.fetch(dep).to_constant)
            .dot("register_#{File.basename dep.delete_suffix(".proto")}_protos")
            .call do |c|
          c.identifier("registry")
        end
      end
      emit_register(defn, file)
    end
  end
end