[][src]Crate ocaml_interop

Zinc-iron alloy coating is used in parts that need very good corrosion protection.

API IS CONSIDERED UNSTABLE AT THE MOMENT AND IS LIKELY TO CHANGE IN THE FUTURE

ocaml-interop is an OCaml<->Rust FFI with an emphasis on safety inspired by caml-oxide and ocaml-rs.

Table of Contents

How does it work

ocaml-interop, just like caml-oxide, encodes the invariants of OCaml's garbage collector into the rules of Rust's borrow checker. Any violation of these invariants results in a compilation error produced by Rust's borrow checker.

Usage

Rules

There are a few rules that have to be followed when calling into the OCaml runtime:

Rule 1: The OCaml runtime handle

To interact with the OCaml runtime (be it reading, mutating or allocating values, or to call functions) a reference to the OCaml runtime handle must be available. Any function that interacts with the OCaml runtime takes as a first argument a reference to the OCaml runtime handle.

Rule 2: Liveness of OCaml values and rooting

Rust references to OCaml values become stale after calls into the OCaml runtime and cannot be used again. This is enforced by Rust's borrow checker.

To have OCaml values survive across calls into the OCaml runtime, they have to be rooted, and then recovered from a root.

Rooting is only possible inside ocaml_frame! blocks, which initialize a list of root variables that can be used to root OCaml values.

Rule 3: Liveness and scope of OCaml roots

OCaml roots are only valid inside the ocaml_frame! that instantiated them, and cannot escape this scope.

Example (fails to compile):

let escape = ocaml_frame!(cr, (arg1_root), {
    let arg1 = arg1.to_ocaml(cr);
    let arg1_root = arg1_root.keep(arg1);
    let result = ocaml_function(cr, arg1_root, /* ..., argN */);
    let s: String = result.to_rust();
    // ...
    arg1_root
});

In the above example arg1_root cannot escape the ocaml_frame! scope, Rust's borrow checker will complain:

error[E0716]: temporary value dropped while borrowed
  --> src/lib.rs:64:14
   |
   |   let escape = ocaml_frame!(cr, (arg1_root), {
   |  _____------___^
   | |     |
   | |     borrow later stored here
   | |     let arg1 = arg1.to_ocaml(cr);
   | |     let arg1_root = arg1_root.keep(arg1);
   | |     let result = ocaml_function(cr, arg1_root, /* ..., argN */);
...  |
   | |     arg1_root
   | | });
   | |  ^
   | |  |
   | |__creates a temporary which is freed while still in use
   |    temporary value is freed at the end of this statement

A similar error would happen if a root-variable escaped the frame scope.

Converting between OCaml and Rust data

FromOCaml trait

The FromOCaml trait implements conversion from OCaml values into Rust values, using the from_ocaml function.

OCaml<T> values have a to_rust() method that is usually more convenient than Type::from_ocaml(ocaml_value), and works for any combination that implements the FromOCaml trait.

OCamlRef<T> values have a to_rust(cr) that needs an OCamlRuntime reference to be passed to it.

ToOCaml trait

The ToOCaml trait implements conversion from Rust values into OCaml values, using the to_ocaml method. It takes a single parameter that must be a &mut OCamlRuntime.

A more convenient way to convert Rust values into OCaml values is provided by the to_ocaml! macro that accepts a root variable as an optional third argument to return a root containing the value.

Calling convention

There are two possible calling conventions in regards to rooting, one with callee rooted arguments, and another with caller rooted arguments.

Callee rooted arguments calling convention

With this calling convention, values that are arguments to a function call are passed directly. Functions that receive arguments are responsible for rooting them. This is how OCaml's C API and ocaml-interop versions before 0.5.0 work.

Caller rooted arguments calling convention

With this calling convention, values that are arguments to a function call must be rooted by the caller. Then instead of the value, it is the root pointing to the value that is passed as an argument. This is how ocaml-interop works starting with version 0.5.0.

When a Rust function is called from OCaml, it will receive arguments as OCamlRef<T> values, and when a OCaml function is called from Rust, arguments will be passed as OCamlRef<T> values.

OCaml exceptions

If an OCaml function called from Rust raises an exception, this will result in a panic.

OCaml functions meant to be called from Rust should not raise exceptions to signal errors, but instead return result or option values, which can then be mapped into Result and Option values in Rust.

Calling into OCaml from Rust

The following code defines two OCaml functions and registers them using the Callback.register mechanism:

let increment_bytes bytes first_n =
  let limit = (min (Bytes.length bytes) first_n) - 1 in
  for i = 0 to limit do
    let value = (Bytes.get_uint8 bytes i) + 1 in
    Bytes.set_uint8 bytes i value
  done;
  bytes

let twice x = 2 * x

let () =
  Callback.register "increment_bytes" increment_bytes;
  Callback.register "twice" twice

To be able to call these from Rust, there are a few things that need to be done:

  • The OCaml runtime has to be initialized. If the driving program is a Rust application, it has to be done explicitly by doing let runtime = OCamlRuntime::init(), but if the driving program is an OCaml application, this is not required.
  • Functions that were exported from the OCaml side with Callback.register have to be declared using the ocaml! macro.
  • Before the program exist, or once the OCaml runtime is not required anymore, it has to be de-initialized by calling the shutdown() method on the OCaml runtime handle.

Example

use ocaml_interop::{
    ocaml_frame, to_ocaml, FromOCaml, OCaml, OCamlRef, ToOCaml, OCamlRuntime
};

// To call an OCaml function, it first has to be declared inside an `ocaml!` macro block:
mod ocaml_funcs {
    use ocaml_interop::{ocaml, OCamlInt};

    ocaml! {
        // OCaml: `val increment_bytes: bytes -> int -> bytes`
        // registered with `Callback.register "increment_bytes" increment_bytes`
        pub fn increment_bytes(bytes: String, first_n: OCamlInt) -> String;
        // OCaml: `val twice: int -> int`
        // registered with `Callback.register "twice" twice`
        pub fn twice(num: OCamlInt) -> OCamlInt;
    }
}

fn increment_bytes(
    cr: &mut OCamlRuntime,
    bytes1: String,
    bytes2: String,
    first_n: usize,
) -> (String, String) {
    // Any calls into the OCaml runtime takes as input a `&mut` reference to an `OCamlRuntime`
    // value that is obtained as the result of initializing the OCaml runtime.
    // If rooting of OCaml values is needed, a new frame has to be opened by using the
    // `ocaml_frame!` macro.
    // The first argument to the macro is a reference to an `OCamlRuntime`, followed by a
    // list of "root variables" (more on this later). The last argument
    // is the block of code that will run inside that frame.
    ocaml_frame!(cr, (bytes1_root, bytes2_root), {
        // The `ToOCaml` trait provides the `to_ocaml` method to convert Rust
        // values into OCaml values.
        let ocaml_bytes1: OCaml<String> = bytes1.to_ocaml(cr);

        // `ocaml_bytes1` is going to be referenced later, but there calls into the
        // OCaml runtime that perform allocations happening before this value is used again.
        // Those calls into the OCaml runtime invalidate this reference, so it has to be
        // kept alive somehow. To do so, `bytes1_root.keep(ocaml_bytes1)` is used.
        // `bytes1_root` is one of the "root variables" that were declared when opening
        // this frame.
        // Each "root variable" reserves space for a reference that will be tracked by the GC.
        // A root variable's `root_var.keep(value)` method returns
        // an value-containing root that is going to be valid during the scope of
        // the current `ocaml_frame!` block. Later `cr.get(value_root)` can be used
        // to recover the original OCaml value.
        let bytes1_root: OCamlRef<String> = bytes1_root.keep(ocaml_bytes1);

        // Same as above. Here the convenience macro [`to_ocaml!`] is used.
        // It works like `value.to_ocaml(cr)`, but has an optional third argument that
        // can be a root variable to perform the rooting.
        // This variation returns an `OCamlRef` value instead of an `OCaml` one.
        let bytes2_root = to_ocaml!(cr, bytes2, bytes2_root);

        // Rust `i64` integers can be converted into OCaml fixnums with `OCaml::of_i64`
        // and `OCaml::of_i64_unchecked`.
        // Such conversion doesn't require any allocation on the OCaml side, and doesn't
        // invalidate other `OCaml<T>` values.
        let ocaml_first_n = unsafe { OCaml::of_i64_unchecked(first_n as i64) };

        // Any OCaml function (declared above in a `ocaml!` block) can be called as a regular
        // Rust function, by passing a `&mut OCamlRuntime` as the first argument, followed by
        // the rest of the arguments declared for that function.
        // Arguments to these functions must be references to roots: `OCamlRef<T>`
        let result1 = ocaml_funcs::increment_bytes(
            cr,             // &mut OCamlRuntime
            bytes1_root,    // OCamlRef<String>
            // Immediate OCaml values, such as ints and books have an as_value_ref() method
            // that can be used to simulate rooting.
            &ocaml_first_n, // OCamlRef<OCamlInt>
        );

        // Perform the conversion of the OCaml result value into a
        // Rust value while the reference is still valid because the
        // call that follows will invalidate it.
        // Alternatively, the result of `rootvar.keep(result1)` could be used
        // to be able to reference the value later through an `OCamlRef` value.
        let new_bytes1: String = result1.to_rust();
        let result2 = ocaml_funcs::increment_bytes(
            cr,
            bytes2_root,
            &ocaml_first_n,
        );

        // The `FromOCaml` trait provides the `from_ocaml` method to convert from
        // OCaml values into OCaml values. Unlike the `to_ocaml` method, it doesn't
        // require a GC handle argument, because no allocation is performed by the
        // OCaml runtime when converting into Rust values.
        // A more convenient alternative, is to use the `to_rust` method as
        // above when `result1` was converted.
        (new_bytes1, String::from_ocaml(result2))
    })
}

fn twice(cr: &mut OCamlRuntime, num: usize) -> usize {
    ocaml_frame!(cr, (num_root), {
        let ocaml_num = unsafe { OCaml::of_i64_unchecked(num as i64) };
        let num_root = num_root.keep(ocaml_num);
        let result = ocaml_funcs::twice(cr, num_root);
        i64::from_ocaml(result) as usize
    })
}

fn entry_point() {
    // IMPORTANT: the OCaml runtime has to be initialized first.
    let mut cr = OCamlRuntime::init();
    // `cr` is the OCaml runtime handle, must be passed to any function
    // that interacts with the OCaml runtime.
    let first_n = twice(&mut cr, 5);
    let bytes1 = "000000000000000".to_owned();
    let bytes2 = "aaaaaaaaaaaaaaa".to_owned();
    println!("Bytes1 before: {}", bytes1);
    println!("Bytes2 before: {}", bytes2);
    let (result1, result2) = increment_bytes(&mut cr, bytes1, bytes2, first_n);
    println!("Bytes1 after: {}", result1);
    println!("Bytes2 after: {}", result2);
    // `OCamlRuntime`'s `Drop` implementation will pefrorm the necessary cleanup
    // to shutdown the OCaml runtime.
}

Calling into Rust from OCaml

To be able to call a Rust function from OCaml, it has to be defined in a way that exposes it to OCaml. This can be done with the ocaml_export! macro.

Example

use ocaml_interop::{
    to_ocaml, ocaml_export, ocaml_frame, FromOCaml, OCamlInt, OCaml, OCamlBytes,
    OCamlRef, ToOCaml,
};

// `ocaml_export` expands the function definitions by adding `pub` visibility and
// the required `#[no_mangle]` and `extern` declarations. It also takes care of
// acquiring the OCaml runtime handle and binding it to the name provided as
// the first parameter of the function.
ocaml_export! {
    // The first parameter is a name to which the GC frame handle will be bound to.
    // The remaining parameters must have type `OCamlRef<T>`, and the return
    // value `OCaml<T>`.
    fn rust_twice(cr, num: OCamlRef<OCamlInt>) -> OCaml<OCamlInt> {
        let num: i64 = num.to_rust(cr);
        unsafe { OCaml::of_i64_unchecked(num * 2) }
    }

    fn rust_increment_bytes(
        cr,
        bytes: OCamlRef<OCamlBytes>,
        first_n: OCamlRef<OCamlInt>,
    ) -> OCaml<OCamlBytes> {
        let first_n: i64 = first_n.to_rust(cr);
        let first_n = first_n as usize;
        let mut vec: Vec<u8> = bytes.to_rust(cr);

        for i in 0..first_n {
            vec[i] += 1;
        }

        to_ocaml!(cr, vec)
    }
}

Then in OCaml, these functions can be referred to in the same way as C functions:

external rust_twice: int -> int = "rust_twice"
external rust_increment_bytes: bytes -> int -> bytes = "rust_increment_bytes"

Macros

impl_conv_ocaml_record

Implements conversion between a Rust struct and an OCaml record.

impl_conv_ocaml_variant

Implements conversion between a Rust enum and an OCaml variant.

impl_from_ocaml_polymorphic_variant

Implements FromOCaml for mapping an OCaml variant into a Rust enum.

impl_from_ocaml_record

Implements FromOCaml for mapping an OCaml record into a Rust record.

impl_from_ocaml_variant

Implements FromOCaml for mapping an OCaml variant into a Rust enum.

impl_to_ocaml_record

Implements ToOCaml for mapping a Rust record into an OCaml record.

impl_to_ocaml_variant

Implements ToOCaml for mapping a Rust enum into an OCaml variant.

ocaml

Declares OCaml functions.

ocaml_alloc_record

Allocates an OCaml record built from a Rust record

ocaml_alloc_tagged_block

Allocates an OCaml memory block tagged with the specified value.

ocaml_alloc_variant

Allocates an OCaml variant, mapped from a Rust enum.

ocaml_export

Defines Rust functions callable from OCaml.

ocaml_frame

Opens a new frame inside of which OCaml values can be rooted to have them tracked by the GC.

ocaml_unpack_polymorphic_variant

Unpacks an OCaml polymorphic variant and maps it into a Rust enum.

ocaml_unpack_record

Unpacks an OCaml record into a Rust record

ocaml_unpack_variant

Unpacks an OCaml variant and maps it into a Rust enum.

to_ocaml

Converts Rust values into OCaml values.

Structs

OCaml

Representation of OCaml values.

OCamlBytes

OCaml<OCamlBytes> is a reference to an OCaml bytes value.

OCamlException

An OCaml exception value.

OCamlFloat

OCaml<OCamlFloat> is a reference to an OCaml float (boxed float) value.

OCamlInt32

OCaml<OCamlInt32> is a reference to an OCaml Int32.t (boxed int32) value.

OCamlInt64

OCaml<OCamlInt64> is a reference to an OCaml Int64.t (boxed int64) value.

OCamlList

OCaml<OCamlList<T>> is a reference to an OCaml list containing values of type T.

OCamlRuntime

OCaml runtime handle.

Traits

FromOCaml

Implements conversion from OCaml values into Rust values.

ToOCaml

Implements conversion from Rust values into OCaml values.

Type Definitions

OCamlFn1

OCaml function that accepts one argument.

OCamlFn2

OCaml function that accepts two arguments.

OCamlFn3

OCaml function that accepts three arguments.

OCamlFn4

OCaml function that accepts four arguments.

OCamlFn5

OCaml function that accepts five arguments.

OCamlInt

OCaml<OCamlInt> is an OCaml integer (tagged and unboxed) value.

OCamlRef

An OCamlRef<T> is a reference to a location containing a OCaml<T> value.

RawOCaml

OCaml value type