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

Class Method Summary

Class Method Details

.load_exported_functions_from(header, *functions)

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 35

def self.load_exported_functions_from(header, *functions)
  File.foreach(File.expand_path("../../include/#{header}", __dir__)) 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+$/, "")) }

    # 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)

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 27

def self.resolve_type(type)
  type = type.strip
  type.end_with?("*") ? :pointer : type.delete_prefix("const ").to_sym
end