123456789_123456789_123456789_123456789_123456789_

Module: Prism::LibRubyParser

Do not use. This module is for internal use only.
Relationships & Source Files
Namespace Children
Classes:
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, FFI::Library
Defined in: lib/prism/ffi.rb

Constant Summary

Class Method Summary

Class Method Details

.load_exported_functions_from(header, *functions, callbacks)

Read through the given header file and find the declaration of each of the given functions. For each one, define a function with the same name and signature as the C function.

[ GitHub ]

  
# File 'lib/prism/ffi.rb', line 48

def self.load_exported_functions_from(header, *functions, callbacks)
  File.foreach("#{INCLUDE_DIR}/#{header}") do |line|
    # We only want to attempt to load exported functions.
    next unless line.start_with?("PRISM_EXPORTED_FUNCTION ")

    # We only want to load the functions that we are interested in.
    next unless functions.any? { |function| line.include?(function) }

    # Parse the function declaration.
    unless /^PRISM_EXPORTED_FUNCTION (?<return_type>.+) (?<name>\w)\((?<arg_types>.)\);$/ =~ line
      raise "Could not parse #{line}"
    end

    # Delete the function from the list of functions we are looking for to
    # mark it as having been found.
    functions.delete(name)

    # Split up the argument types into an array, ensure we handle the case
    # where there are no arguments (by explicit void).
    arg_types = arg_types.split(",").map(&:strip)
    arg_types = [] if arg_types == %w[void]

    # Resolve the type of the argument by dropping the name of the argument
    # first if it is present.
    arg_types.map! { |type| resolve_type(type.sub(/\w+$/, ""), callbacks) }

    # Attach the function using the FFI library.
    attach_function name, arg_types, resolve_type(return_type, [])
  end

  # If we didn't find all of the functions, raise an error.
  raise "Could not find functions #{functions.inspect}" unless functions.empty?
end

.resolve_type(type, callbacks)

Convert a native C type declaration into a symbol that FFI understands. For example:

const char * -> :pointer
bool         -> :bool
size_t       -> :size_t
void         -> :void
[ GitHub ]

  
# File 'lib/prism/ffi.rb', line 34

def self.resolve_type(type, callbacks)
  type = type.strip

  if !type.end_with?("*")
    type.delete_prefix("const ").to_sym
  else
    type = type.delete_suffix("*").rstrip
    callbacks.include?(type.to_sym) ? type.to_sym : :pointer
  end
end