Class: RubyBindgen::Generators::FFI

Inherits:
Generator
  • Object
show all
Defined in:
lib/ruby-bindgen/generators/ffi/ffi.rb

Constant Summary collapse

C_INT_SUFFIX =

Convert a C literal token spelling into something that parses as Ruby. libclang gives us the verbatim source text, so C numeric suffixes (2.5f, 100000L, 42U, 1ULL, 0xABCDuLL) flow through unchanged and break the generated module. Char (‘A’) and string (“hello”) literals are returned as-is — they’re already valid Ruby strings.

Hex literals need different treatment: f/F are valid hex digits, so 0xff must NOT have its trailing f stripped (would yield 0xf = 15 instead of 255). Hex strips integer suffixes only.

/(?:[uU][lL]{0,2}|[lL]{1,2}[uU]?)\z/.freeze
C_FLOAT_SUFFIX =
/(?:[uU][lL]{0,2}|[lL]{1,2}[uU]?|[fFlL])\z/.freeze
VA_LIST_NAMES =

Check if any parameter is a va_list type, which cannot be constructed from Ruby. va_list representation varies by platform:

Linux x86_64: elaborated(va_list) -> typedef(__builtin_va_list) -> struct __va_list_tag[1]
Other targets: may use __builtin_va_list, __gnuc_va_list, or other forms

The typedef declaration spelling is the most reliable check.

Set.new(%w[va_list __builtin_va_list __gnuc_va_list]).freeze

Instance Attribute Summary collapse

Attributes inherited from Generator

#config, #inputter, #outputter

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Generator

#project, #render_template, #translation_unit_file?

Constructor Details

#initialize(inputter, outputter, config) ⇒ FFI

Returns a new instance of FFI.

Raises:

  • (ArgumentError)


10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 10

def initialize(inputter, outputter, config)
  super(inputter, outputter, config)
  raise ArgumentError, "FFI format requires the 'project' option" unless @project
  @version_check = config[:version_check]
  @library_names = config[:library_names] || []
  @library_versions = config[:library_versions] || []
  @symbols = RubyBindgen::Symbols.new(config[:symbols] || {})
  raise ArgumentError, "version_check is required when symbols.versions is non-empty" if @symbols.has_versions? && !@version_check
  @library_search_path = config[:library_search_path]
  @export_macros = config[:export_macros] || []
  @module_name = config[:module]
end

Instance Attribute Details

#library_namesObject (readonly)

Returns the value of attribute library_names.



4
5
6
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 4

def library_names
  @library_names
end

#library_versionsObject (readonly)

Returns the value of attribute library_versions.



4
5
6
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 4

def library_versions
  @library_versions
end

Class Method Details

.template_dirObject



6
7
8
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 6

def self.template_dir
  __dir__
end

Instance Method Details

#add_indentation(content, indentation) ⇒ Object



604
605
606
607
608
609
610
611
612
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 604

def add_indentation(content, indentation)
  content.lines.map do |line|
    if line.strip.empty?
      line
    else
      " " * indentation + line
    end
  end.join
end

#create_project_fileObject



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 71

def create_project_file
  return if @generated_files.empty?

  module_name = @module_name || @project.camelize
  module_parts = module_name.split("::")
  depth = module_parts.length
  library = add_indentation(render_template("library"), depth * 2)

  has_versions = @symbols.has_versions?
  version_file = has_versions ? "#{@project}_version" : nil

  content = render_template("project",
                            :module_parts => module_parts,
                            :library => library.rstrip,
                            :version_file => version_file,
                            :files => @generated_files)

  self.outputter.write("#{@project}_ffi.rb", content)

  create_version_file(module_parts) if version_file
end

#create_version_file(module_parts) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 93

def create_version_file(module_parts)
  relative_path = "#{@project}_version.rb"
  full_path = self.outputter.output_path(relative_path)
  return if File.exist?(full_path)

  method_name = @version_check
  depth = module_parts.length
  method_body = add_indentation(render_template("version_method", :method_name => method_name), depth * 2)

  content = render_template("version",
                            :module_parts => module_parts,
                            :method_body => method_body.rstrip)
  self.outputter.write(relative_path, content)
end

#figure_ffi_declared_type(type, context = nil) ⇒ Object



532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 532

def figure_ffi_declared_type(type, context = nil)
  if type.declaration.spelling == "va_list"
    # va_list cannot be constructed from Ruby — functions with va_list
    # params are skipped in visit_function. Map to :pointer as fallback.
    ":pointer"
  elsif type.canonical.kind == :type_pointer && type.canonical.function?
    # Typedef'd function pointer (callback) — use the callback name
    ":#{type.declaration.ruby_name}"
  elsif type.canonical.kind == :type_function_proto
    ":pointer"
  elsif type.canonical.kind == :type_record
    figure_ffi_record_type(type, context)
  elsif type.canonical.kind == :type_enum
    figure_ffi_type(type.canonical, context)
  else
    spelling = type.declaration.spelling
    if ::FFI::TypeDefs.key?(spelling.to_sym)
      ":#{spelling}"
    else
      self.figure_ffi_type(type.canonical, context)
    end
  end
end

#figure_ffi_pointer_type(type, context) ⇒ Object



575
576
577
578
579
580
581
582
583
584
585
586
587
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 575

def figure_ffi_pointer_type(type, context)
  case type.pointee.kind
    when :type_char_s
      case context
      when :callback_return
        ":pointer"
      else
        type.pointee.const_qualified? ? ":string" : ":pointer"
      end
    else
      figure_ffi_record_pointer_type(type.pointee, context) || ":pointer"
  end
end

#figure_ffi_record_pointer_type(type, context) ⇒ Object



589
590
591
592
593
594
595
596
597
598
599
600
601
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 589

def figure_ffi_record_pointer_type(type, context)
  return nil unless type.canonical.kind == :type_record
  return ":pointer" if type.canonical.declaration.opaque_declaration?

  case context
    when :union, :structure, :typedef
      "#{type.canonical.declaration.ruby_name}.ptr"
    when :function, :callback, :callback_return
      "#{type.canonical.declaration.ruby_name}.by_ref"
    else
      type.canonical.declaration.ruby_name
  end
end

#figure_ffi_record_type(type, context = nil) ⇒ Object



556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 556

def figure_ffi_record_type(type, context = nil)
  if type.canonical.declaration.opaque_declaration?
    return ":pointer"
  end
  if type.anonymous?
    definer = type.declaration.anonymous_definer
    return definer ? definer.spelling.camelize : ":pointer"
  end

  case
    when context == :function
      "#{type.declaration.ruby_name}.by_value"
    when context == :callback
      "#{type.declaration.ruby_name}.by_value"
    else
      type.declaration.ruby_name
  end
end

#figure_ffi_type(type, context = nil) ⇒ Object



458
459
460
461
462
463
464
465
466
467
468
469
470
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 458

def figure_ffi_type(type, context = nil)
  case type.kind
    when :type_bool
      ":bool"
    when :type_float
      ":float"
    when :type_double
      ":double"
    when :type_int
      ":int"
    when :type_long
      ":long"
    when :type_longlong
      ":long_long"
    when :type_ulong
      ":ulong"
    when :type_ulonglong
      ":ulong_long"
    when :type_uint
      ":uint"
    when :type_short
      ":short"
    when :type_ushort
      ":ushort"
    when :type_char_s
      ":char"
    when :type_uchar, :type_char_u
      ":uchar"
    when :type_schar
      ":int8"
    when :type_wchar
      figure_ffi_type(type.canonical, context)
    when :type_char16
      ":uint16"
    when :type_char32
      ":uint32"
    when :type_longdouble
      ":long_double"
    when :type_int128, :type_uint128
      raise("Unsupported 128-bit integer type: #{type.kind}")
    when :type_void
      ":void"
    when :type_elaborated
      figure_ffi_declared_type(type, context)
    when :type_record
      figure_ffi_record_type(type, context)
    when :type_typedef
      figure_ffi_declared_type(type, context)
    when :type_pointer
      figure_ffi_pointer_type(type, context)
    when :type_enum
      type.declaration.ruby_name
    when :type_constant_array
      case context
        when :structure
          "[#{figure_ffi_type(type.element_type)}, #{type.size}]"
        else
          ":pointer"
      end
    when :type_incomplete_array
      case type.element_type.kind
        when :type_char_s
          ":string"
        else
          raise("Unsupported incomplete array type: #{type.element_type.kind}")
      end
    when :type_block_pointer
      # Objective-C block pointers (macOS) — treat as opaque pointer
      ":pointer"
    else
      raise("Unsupported type: #{type.kind}")
  end
end

#figure_method(cursor) ⇒ Object



407
408
409
410
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 407

def figure_method(cursor)
  name = cursor.kind.to_s.delete_prefix("cursor_")
  "visit_#{name.underscore}".to_sym
end

#generateObject



23
24
25
26
27
28
29
30
31
32
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 23

def generate
  clang_args = @config[:clang_args] || []
  parser = RubyBindgen::Parser.new(@inputter, clang_args, libclang: @config[:libclang])
  symbols_config = @config[:symbols] || {}
  rename_types = RubyBindgen::NameMapper.from_config(symbols_config[:rename_types] || [])
  rename_methods = RubyBindgen::NameMapper.from_config(symbols_config[:rename_methods] || [])
  @namer = RubyBindgen::Namer.new(rename_types, rename_methods)
  ::FFI::Clang::Cursor.namer = @namer
  parser.generate(self)
end

#has_export_macro?(cursor) ⇒ Boolean

Check if cursor has one of the required export macros in its source text. When export_macros is empty, all symbols pass (no filtering).

Returns:

  • (Boolean)


36
37
38
39
40
41
42
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 36

def has_export_macro?(cursor)
  return true if @export_macros.empty?

  source_text = cursor.extent.text
  return false if source_text.nil?
  @export_macros.any? { |macro| source_text.include?(macro) }
end

#has_skipped_param_type?(cursor) ⇒ Boolean

Check if any parameter type of a function references a skipped symbol.

Returns:

  • (Boolean)


435
436
437
438
439
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 435

def has_skipped_param_type?(cursor)
  (0...cursor.type.args_size).any? do |i|
    references_skipped_type?(cursor.type.arg_type(i))
  end
end

#has_va_list_param?(cursor) ⇒ Boolean

Returns:

  • (Boolean)


419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 419

def has_va_list_param?(cursor)
  cursor.find_by_kind(false, :cursor_parm_decl).any? do |param|
    type = param.type
    # Check declaration spelling (works for elaborated and typedef types)
    decl = type.declaration
    next true if decl.kind == :cursor_typedef_decl && VA_LIST_NAMES.include?(decl.spelling)

    # Fallback: check canonical type for __va_list_tag (Linux x86_64 array form)
    canonical = type.canonical
    canonical.kind == :type_constant_array &&
      canonical.element_type.kind == :type_record &&
      canonical.element_type.declaration.spelling == "__va_list_tag"
  end
end

#literal_to_ruby(spelling) ⇒ Object



401
402
403
404
405
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 401

def literal_to_ruby(spelling)
  return spelling if spelling.start_with?("'", '"')
  suffix = spelling.match?(/\A[+-]?0[xX]/) ? C_INT_SUFFIX : C_FLOAT_SUFFIX
  spelling.sub(suffix, '')
end

#merge_children(versions, indentation: 0, comma: false, strip: false) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 157

def merge_children(versions, indentation: 0, comma: false, strip: false)
  lines = versions.keys.sort_by { |key| key.to_s }.each_with_object([]) do |version, result|
    next unless versions[version]&.any?
    result << "if #{@version_check} >= #{version}" if version
    versions[version].each do |line|
      line = line.rstrip if strip
      line = add_indentation(line, 2) if version
      result << line
    end
    result << "end" if version
  end

  return "" if lines.empty?

  separator = comma ? ",\n" : "\n"
  result = lines.join(separator)
  result = add_indentation(result, indentation) if indentation > 0
  result
end

#pointer_to_forward_declaration?(type) ⇒ Boolean

Returns:

  • (Boolean)


449
450
451
452
453
454
455
456
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 449

def pointer_to_forward_declaration?(type)
  return false unless type.kind == :type_pointer

  decl = type.pointee.canonical.declaration
  return false if [:cursor_invalid_file, :cursor_no_decl_found].include?(decl.kind)

  decl.opaque_declaration?
end

#references_skipped_type?(type) ⇒ Boolean

Check if a type references a skipped symbol (unwrapping pointers).

Returns:

  • (Boolean)


442
443
444
445
446
447
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 442

def references_skipped_type?(type)
  type = type.intrinsic_type
  decl = type.declaration
  return false if decl.kind == :cursor_no_decl_found
  @symbols.skip?(decl)
end

#render_callback(name, parameter_types, result_type) ⇒ Object



681
682
683
684
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 681

def render_callback(name, parameter_types, result_type)
  render_template("callback", :ruby => name, :parameter_types => parameter_types,
                  :result_type => result_type)
end

#render_children(cursor, indentation: 0, comma: false, strip: false, exclude_kinds: Set.new) ⇒ Object



177
178
179
180
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 177

def render_children(cursor, indentation: 0, comma: false, strip: false, exclude_kinds: Set.new)
  versions = visit_children(cursor, exclude_kinds: exclude_kinds)
  merge_children(versions, indentation: indentation, comma: comma, strip: strip)
end

#render_cursor(cursor, template, local_variables = {}) ⇒ Object



677
678
679
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 677

def render_cursor(cursor, template, local_variables = {})
  render_template(template, local_variables.merge(:cursor => cursor))
end

#render_versioned_enum(cursor, versions) ⇒ Object

Render an enum with versioned constants as separate definitions per version threshold.



649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 649

def render_versioned_enum(cursor, versions)
  thresholds = versions.keys.compact.sort.reverse

  lines = []
  first = true
  thresholds.each do |threshold|
    guard = first ? "if" : "elsif"
    first = false
    lines << "#{guard} #{@version_check} >= #{threshold}"

    cumulative = (versions[nil] || []).dup
    versions.keys.compact.sort.each do |v|
      cumulative.concat(versions[v]) if v <= threshold
    end

    children = add_indentation(cumulative.map(&:rstrip).join(",\n"), 2)
    lines << add_indentation(render_cursor(cursor, "enum_decl", :children => children).strip, 2)
  end

  # else branch: unversioned constants only (may be empty, but enum must still be defined)
  base = versions[nil] || []
  lines << "else"
  children = add_indentation(base.map(&:rstrip).join(",\n"), 2)
  lines << add_indentation(render_cursor(cursor, "enum_decl", :children => children).strip, 2)
  lines << "end"
  lines.join("\n")
end

#render_versioned_layout(cursor, versions, template) ⇒ Object

Render a struct/union with versioned fields as separate definitions per version threshold. Each version gets a complete definition with cumulative fields up to that version. Output is wrapped in if/elsif/else guards.



617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 617

def render_versioned_layout(cursor, versions, template)
  # Build sorted version thresholds (nil = unversioned, always included)
  thresholds = versions.keys.compact.sort.reverse

  # Build cumulative field lists: each threshold includes all fields from lower versions
  lines = []
  first = true
  thresholds.each do |threshold|
    guard = first ? "if" : "elsif"
    first = false
    lines << "#{guard} #{@version_check} >= #{threshold}"

    # Collect all fields: unversioned + all versions <= threshold
    cumulative_fields = (versions[nil] || []).dup
    versions.keys.compact.sort.each do |v|
      cumulative_fields.concat(versions[v]) if v <= threshold
    end

    children = cumulative_fields.map(&:rstrip).join(",\n" + " " * 9)
    lines << add_indentation(render_cursor(cursor, template, :children => children).strip, 2)
  end

  # else branch: unversioned fields only (may be empty, but type must still be defined)
  base_fields = versions[nil] || []
  lines << "else"
  children = base_fields.map(&:rstrip).join(",\n" + " " * 9)
  lines << add_indentation(render_cursor(cursor, template, :children => children).strip, 2)
  lines << "end"
  lines.join("\n")
end

#visit_callback(name, parameters, type) ⇒ Object



182
183
184
185
186
187
188
189
190
191
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 182

def visit_callback(name, parameters, type)
  parameter_types = parameters.map do |parameter|
    if parameter.find_first_by_kind(false, :cursor_type_ref) && parameter.type.is_a?(::FFI::Clang::Types::Pointer)
      ":pointer"
    else
      figure_ffi_type(parameter.type, :callback)
    end
  end
  self.render_callback(name, parameter_types, type.result_type)
end

#visit_children(cursor, exclude_kinds: Set.new) ⇒ Object



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
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 108

def visit_children(cursor, exclude_kinds: Set.new)
  versions = Hash.new { |h, k| h[k] = [] }
  cursor.each(false) do |child_cursor, parent_cursor|
    if child_cursor.location.in_system_header?
      next :continue
    end

    # Note: from_main_file? doesn't work when -include is used, so manually check.
    unless translation_unit_file?(child_cursor)
      next :continue
    end

    # For some reason child.cursor.public? filters out way too much
    if child_cursor.private? || child_cursor.protected?
      next :continue
    end

    if child_cursor.deleted?
      next :continue
    end

    unless child_cursor.declaration? || child_cursor.kind == :cursor_linkage_spec
      next :continue
    end

    if child_cursor.forward_declaration?
      next :continue
    end

    if exclude_kinds.include?(child_cursor.kind)
      next :continue
    end

    visit_method = self.figure_method(child_cursor)
    if self.respond_to?(visit_method)
      content = self.send(visit_method, child_cursor)
      version = @symbols.version(child_cursor)
      case content
        when Array
          versions[version] += content
        when String
          versions[version] << content
      end
    end
    next :continue
  end
  versions
end

#visit_endObject



67
68
69
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 67

def visit_end
  create_project_file
end

#visit_enum_constant_decl(cursor) ⇒ Object



208
209
210
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 208

def visit_enum_constant_decl(cursor)
  self.render_cursor(cursor,"enum_constant_decl")
end

#visit_enum_decl(cursor) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 193

def visit_enum_decl(cursor)
  return if @symbols.skip?(cursor)

  versions = visit_children(cursor)
  has_versioned_constants = versions.keys.any? { |k| !k.nil? }

  if has_versioned_constants
    render_versioned_enum(cursor, versions)
  else
    children = merge_children(versions, indentation: 2, comma: true, strip: true)
    template = cursor.anonymous? ? "enum_decl_anonymous" : "enum_decl"
    self.render_cursor(cursor, template, :children => children)
  end
end

#visit_field_decl(cursor) ⇒ Object



295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 295

def visit_field_decl(cursor)
  ffi_type = if cursor.type.is_a?(::FFI::Clang::Types::Pointer)
                if cursor.type.function?
                  ":#{cursor.semantic_parent.spelling.underscore}_#{cursor.spelling.underscore}_callback"
                elsif pointer_to_forward_declaration?(cursor.type)
                 ":pointer"
                end
              end

  ffi_type ||= figure_ffi_type(cursor.type, :structure)
  self.render_cursor(cursor, "field_decl", ffi_type: ffi_type)
end

#visit_function(cursor) ⇒ Object



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
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 218

def visit_function(cursor)
  return if cursor.availability == :deprecated
  return if @symbols.skip?(cursor)
  return if references_skipped_type?(cursor.type.result_type)
  return if has_skipped_param_type?(cursor)
  return if has_va_list_param?(cursor)
  return unless has_export_macro?(cursor)

  signature = @symbols.override(cursor)
  if signature
    return self.render_cursor(cursor, "function", :parameter_types => nil, :signature => signature)
  end

  result = Array.new
  parameter_types = cursor.find_by_kind(false, :cursor_parm_decl).map do |parameter|
    callback_name = "#{cursor.spelling.underscore}_#{parameter.spelling.underscore}_callback"
    if parameter.type.is_a?(::FFI::Clang::Types::Pointer) && parameter.type.function?
      parameters = parameter.find_by_kind(false, :cursor_parm_decl)
      result << self.visit_callback(callback_name, parameters, parameter.type.pointee)
    end

    if parameter.type.is_a?(::FFI::Clang::Types::Pointer) && parameter.type.function?
      ":#{callback_name}"
    else
      figure_ffi_type(parameter.type, :function)
    end
  end
  parameter_types << ":varargs" if cursor.type.variadic?
  result << self.render_cursor(cursor, "function", :parameter_types => parameter_types, :signature => nil)
  result.join("\n")
end

#visit_linkage_spec(cursor) ⇒ Object

extern “C” {} — transparent wrapper, recurse into children



213
214
215
216
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 213

def visit_linkage_spec(cursor)
  versions = visit_children(cursor)
  merge_children(versions)
end

#visit_startObject



44
45
46
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 44

def visit_start
  @generated_files = []
end

#visit_struct(cursor) ⇒ Object



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
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 250

def visit_struct(cursor)
  return if cursor.forward_declaration?
  return if cursor.opaque_declaration?
  return if @symbols.skip?(cursor)
  return if cursor.anonymous? && !cursor.anonymous_definer

  result = Hash.new { |h, k| h[k] = [] }

  # Define any embedded structures
  cursor.find_by_kind(false, :cursor_struct).each do |struct|
    content = visit_struct(struct)
    next unless content
    version = @symbols.version(struct)
    result[version] << content
  end

  # Define any embedded unions
  cursor.find_by_kind(false, :cursor_union).each do |union|
    content = visit_union(union)
    next unless content
    version = @symbols.version(union)
    result[version] << content
  end

  # Define any embedded callbacks
  cursor.find_by_kind(false, :cursor_field_decl).each do |field|
    if field.type.is_a?(::FFI::Clang::Types::Pointer) && field.type.function?
      callback_name = "#{cursor.spelling.underscore}_#{field.spelling.underscore}_callback"
      parameters = field.find_by_kind(false, :cursor_parm_decl)
      result[nil] << self.visit_callback(callback_name, parameters, field.type.pointee)
    end
  end

  versions = visit_children(cursor, exclude_kinds: [:cursor_struct, :cursor_union])
  has_versioned_fields = versions.keys.any? { |k| !k.nil? }

  if has_versioned_fields
    result[nil] << render_versioned_layout(cursor, versions, "struct")
  else
    children = merge_children(versions, indentation: 9, comma: true, strip: true)
    result[nil] << self.render_cursor(cursor, "struct", :children => children.lstrip)
  end
  merge_children(result)
end

#visit_translation_unit(translation_unit, path, relative_path) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 48

def visit_translation_unit(translation_unit, path, relative_path)
  basename = File.basename(relative_path, ".*").underscore
  relative_path_2 = File.join(File.dirname(relative_path), "#{basename}.rb")

  cursor = translation_unit.cursor
  module_name = @module_name || cursor.ruby_name
  module_parts = module_name.split("::")

  content = render_children(cursor, indentation: module_parts.length * 2)

  result = render_template("translation_unit",
                           :module_parts => module_parts,
                           :content => content.rstrip)

  result.gsub!(/\n\n\n/, "\n\n")
  @generated_files << File.join(File.dirname(relative_path), basename)
  self.outputter.write(relative_path_2, result)
end

#visit_typedef_decl(cursor) ⇒ Object



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 308

def visit_typedef_decl(cursor)
  return if @symbols.skip?(cursor)

  underlying_type = cursor.underlying_type
  canonical_type = underlying_type.canonical

  if [:type_record, :type_enum].include?(canonical_type.kind)
    # Opaque struct/union typedef - emit typedef :pointer
    if canonical_type.declaration.opaque_declaration?
      return render_cursor(cursor, "typedef_decl")
    end
    # Otherwise it's a struct/union/enum we have already rendered - skip
    return
  elsif underlying_type.kind == :type_pointer && underlying_type.function?
    func_type = underlying_type.pointee
    parameter_types = (0...func_type.args_size).map { |i| figure_ffi_type(func_type.arg_type(i), :callback) }
    return render_callback(cursor.ruby_name, parameter_types, func_type.result_type)
  end
  render_cursor(cursor, "typedef_decl")
end

#visit_union(cursor) ⇒ Object



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
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 329

def visit_union(cursor)
  return if cursor.forward_declaration?
  return if cursor.opaque_declaration?
  return if @symbols.skip?(cursor)
  return if cursor.anonymous? && !cursor.anonymous_definer

  result = Hash.new { |h, k| h[k] = [] }

  # Define any embedded unions
  cursor.find_by_kind(false, :cursor_union).each do |union|
    content = visit_union(union)
    next unless content
    version = @symbols.version(union)
    result[version] << content
  end

  # Define any embedded structures
  cursor.find_by_kind(false, :cursor_struct).each do |struct|
    content = visit_struct(struct)
    next unless content
    version = @symbols.version(struct)
    result[version] << content
  end

  # Define any embedded callbacks
  cursor.find_by_kind(false, :cursor_field_decl).each do |field|
    if field.type.is_a?(::FFI::Clang::Types::Pointer) && field.type.function?
      callback_name = "#{cursor.spelling.underscore}_#{field.spelling.underscore}_callback"
      parameters = field.find_by_kind(false, :cursor_parm_decl)
      result[nil] << self.visit_callback(callback_name, parameters, field.type.pointee)
    end
  end

  versions = visit_children(cursor, exclude_kinds: [:cursor_struct, :cursor_union])
  has_versioned_fields = versions.keys.any? { |k| !k.nil? }

  if has_versioned_fields
    result[nil] << render_versioned_layout(cursor, versions, "union")
  else
    children = merge_children(versions, indentation: 9, comma: true, strip: true)
    result[nil] << self.render_cursor(cursor, "union", :children => children.lstrip)
  end
  merge_children(result)
end

#visit_variable(cursor) ⇒ Object



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/ruby-bindgen/generators/ffi/ffi.rb', line 374

def visit_variable(cursor)
  return if @symbols.skip?(cursor)

  if cursor.type.const_qualified?
    tokens = cursor.translation_unit.tokenize(cursor.extent)
    eq_index = tokens.tokens.index { |t| t.spelling == "=" }
    if eq_index && tokens.tokens[eq_index + 1]&.kind == :literal
      return render_cursor(cursor, "constant",
                           name: cursor.ruby_name,
                           value: literal_to_ruby(tokens.tokens[eq_index + 1].spelling))
    end
  end

  self.render_cursor(cursor, "variable")
end