├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── example ├── Cargo.toml ├── README.md ├── dune └── src │ ├── lib.rs │ ├── main.ml │ └── stubs.ml └── src ├── derive.rs ├── lib.rs └── stubs.rs /.gitignore: -------------------------------------------------------------------------------- 1 | **/target 2 | **/_build 3 | **/*.rs.bk 4 | Cargo.lock 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "derive-ocaml" 3 | version = "0.1.3" 4 | authors = ["joris giovannangeli "] 5 | license = "MIT" 6 | description = """ 7 | Custom derive and procedural macros for easy FFI with ocaml on top of the ocaml crate 8 | """ 9 | edition = "2018" 10 | categories = [ "external-ffi-bindings" ] 11 | keywords = [ "ocaml", "ffi", "derive" ] 12 | readme = "README.md" 13 | repository = "https://github.com/ahrefs/rust-ocaml-derive" 14 | homepage = "https://github.com/ahrefs/rust-ocaml-derive" 15 | 16 | 17 | [lib] 18 | proc-macro = true 19 | 20 | [features] 21 | default = [ "derive" ] 22 | 23 | # Implement custom derive for FromValue/ToValue ocaml traits 24 | derive = [ "synstructure" ] 25 | 26 | stubs = ["syn/full"] 27 | 28 | [dependencies] 29 | synstructure = { version = "0.12", optional = true } 30 | syn = "1.0" 31 | quote = "1.0" 32 | proc-macro2 = "1.0" 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright2018 Ahrefs Pte Ltd 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # derive-ocaml - Custom derive and procedural macros for easier ocaml <-> rust FFI 2 | 3 | *WARNING* this crate is very experimental 4 | 5 | derive-ocaml is based on top of [ocaml-rs](https://github.com/zshipko/ocaml-rs) and adds a custom derive macro for `FromValue` and `ToValue`. 6 | The macro supports structs, enums, and unboxed float records. 7 | 8 | On top of that it implements a nightly only procedural macro `ocaml-ffi` to ease the boilerplate of writing stubs functions. 9 | 10 | 11 | ``` 12 | #[derive(Debug, Default, ToValue, FromValue)] 13 | #[ocaml(floats_array)] 14 | pub struct Vec3 { 15 | x: f32, 16 | y: f32, 17 | z: f32, 18 | } 19 | 20 | #[ocaml_ffi] 21 | pub fn rust_add_vecs(l: Vec3, r: Vec3) -> Vec3 { 22 | l + r 23 | } 24 | ``` 25 | 26 | see `src/example/src/lib.rs` and `src/example/src/stubs.ml` for example 27 | -------------------------------------------------------------------------------- /example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "example_stubs" 3 | version = "0.1.0" 4 | authors = ["joris giovannangeli "] 5 | 6 | [dependencies] 7 | derive-ocaml = { version = "0.1.1", features= ["stubs", "derive"] } 8 | ocaml = "*" 9 | 10 | [lib] 11 | crate-type = ["staticlib"] 12 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # How to build and run 2 | 3 | ```bash 4 | dune build main.exe 5 | _build/default/main.exe 6 | ``` -------------------------------------------------------------------------------- /example/dune: -------------------------------------------------------------------------------- 1 | (include_subdirs unqualified) 2 | 3 | (rule 4 | (deps (source_tree .)) 5 | (targets libexample_stubs.a) 6 | (action (progn 7 | (run cargo build -Z unstable-options --out-dir . --target-dir ../rust --release) 8 | ))) 9 | 10 | (library 11 | (name stubs) 12 | (modules stubs) 13 | (self_build_stubs_archive (example)) 14 | (c_library_flags (-lpthread -lc -lm)) 15 | ) 16 | 17 | (executable 18 | 19 | (name main) 20 | (modules main) 21 | (libraries stubs) 22 | ) 23 | -------------------------------------------------------------------------------- /example/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![feature(proc_macro)] 2 | 3 | #[macro_use] 4 | extern crate derive_ocaml; 5 | #[macro_use] 6 | extern crate ocaml; 7 | 8 | use derive_ocaml::ocaml_ffi; 9 | use std::ops::Add; 10 | 11 | #[derive(Debug, Default, ToValue, FromValue)] 12 | #[ocaml(floats_array)] 13 | pub struct Vec3 { 14 | x: f32, 15 | y: f32, 16 | z: f32, 17 | } 18 | 19 | impl Add for Vec3 { 20 | type Output = Vec3; 21 | 22 | fn add(self, r: Self) -> Self::Output { 23 | let l = self; 24 | Vec3 { x: l.x + r.x, y: l.y + r.y, z: l.z + r.z } 25 | } 26 | } 27 | 28 | #[ocaml_ffi] 29 | pub fn rust_add_vecs(l: Vec3, r: Vec3) -> Vec3 { 30 | l + r 31 | } 32 | 33 | #[derive(FromValue, ToValue)] 34 | pub enum Unrolled { 35 | Empty, 36 | One(Item), 37 | Many(Vec), 38 | } 39 | 40 | #[derive(FromValue)] 41 | #[ocaml(unboxed)] 42 | pub struct Bound(usize); 43 | 44 | #[ocaml_ffi] 45 | pub fn rust_sum_vecs(vectors: Unrolled, max_items: Bound) -> Vec3 { 46 | use self::Unrolled::*; 47 | match vectors { 48 | Empty => Default::default(), 49 | One(vec) => vec, 50 | Many(vectors) => vectors.into_iter().take(max_items.0).fold(Default::default(), Vec3::add), 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /example/src/main.ml: -------------------------------------------------------------------------------- 1 | let _ = 2 | let open Stubs in 3 | let v1 = { x = 1.; y= 2.; z = 3. } in 4 | let v2 = { x = 4.; y= 5.; z = 6. } in 5 | let v3 = { x = 7.; y= 8.; z = 9. } in 6 | let v4 = add_vecs v1 v3 in 7 | let v5 = add_vecs v4 v2 in 8 | let sum = sum_vecs (Many [| v1; v2; v3; v4; v5 |]) { bound = 3 } in 9 | Printf.printf "[ %.2f; %.2f; %.2f ]\n" sum.x sum.y sum.z 10 | -------------------------------------------------------------------------------- /example/src/stubs.ml: -------------------------------------------------------------------------------- 1 | type vec3 = { 2 | x: float; 3 | y: float; 4 | z: float; 5 | } 6 | 7 | type bound = { 8 | bound: int; 9 | } [@@unboxed] 10 | 11 | type 'item unrolled = 12 | Empty 13 | | One of 'item 14 | | Many of 'item array 15 | 16 | external add_vecs : vec3 -> vec3 -> vec3 = "rust_add_vecs" 17 | external sum_vecs : vec3 unrolled -> bound -> vec3 = "rust_sum_vecs" 18 | -------------------------------------------------------------------------------- /src/derive.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2; 2 | use syn; 3 | use synstructure; 4 | 5 | #[derive(Default)] 6 | struct Attrs { 7 | unboxed: bool, 8 | floats: bool, 9 | } 10 | 11 | fn variant_attrs(attrs: &[syn::Attribute]) -> Attrs { 12 | fn is_ocaml(path: &syn::Path) -> bool { 13 | path.segments.len() == 1 14 | && path 15 | .segments 16 | .iter() 17 | .next() 18 | .map_or(false, |segment| segment.ident == "ocaml") 19 | } 20 | attrs 21 | .iter() 22 | .find(|attr| is_ocaml(&attr.path)) 23 | .map_or(Default::default(), |attr| { 24 | if let Ok(syn::Meta::List(ref list)) = attr.parse_meta() { 25 | list.nested 26 | .iter() 27 | .fold(Default::default(), |mut acc, meta| match meta { 28 | syn::NestedMeta::Meta(syn::Meta::Path(ref ident)) => 29 | if ident.is_ident("unboxed") { 30 | if acc.floats { 31 | panic!("in ocaml attrs a variant cannot be both float array and unboxed") 32 | } 33 | acc.unboxed = true; 34 | acc 35 | } else if ident.is_ident("floats_array") { 36 | if acc.unboxed { 37 | panic!("in ocaml attrs a variant cannot be both float array and unboxed") 38 | } 39 | acc.floats = true; 40 | acc 41 | } else { 42 | panic!("unexpected ocaml attribute parameter {:?}", ident) 43 | }, 44 | _ => panic!("unexpected ocaml attribute parameter"), 45 | }) 46 | } else { 47 | panic!("ocaml attribute must take a list of valid attributes in parentheses") 48 | } 49 | }) 50 | } 51 | 52 | pub fn tovalue_derive(s: synstructure::Structure) -> proc_macro2::TokenStream { 53 | let mut unit_tag = 0u8; 54 | let mut non_unit_tag = 0u8; 55 | let is_record_like = s.variants().len() == 1; 56 | let body = s.variants().iter().map(|variant| { 57 | let arity = variant.bindings().len(); 58 | let tag_ref = if arity > 0 { 59 | &mut non_unit_tag 60 | } else { 61 | &mut unit_tag 62 | }; 63 | let tag = *tag_ref; 64 | *tag_ref += 1; 65 | let attrs = variant_attrs(&variant.ast().attrs); 66 | if (attrs.floats || attrs.unboxed) && !is_record_like { 67 | panic!("ocaml cannot derive unboxed or float arrays for enums") 68 | } 69 | if arity == 0 { 70 | let init = quote!(value = ocaml::Value::i64(#tag as i64);); 71 | variant.fold(init, |_, _| quote!()) 72 | } else if attrs.floats { 73 | let mut idx = 0usize; 74 | let init = quote!( 75 | value = ocaml::Value::alloc(#arity, ocaml::Tag::DoubleArray); 76 | ); 77 | variant.fold(init, |acc, b| { 78 | let i = idx; 79 | idx += 1; 80 | quote!(#acc; ocaml::Array::from(value.clone()).set_double(#i, *#b as f64).unwrap();) 81 | }) 82 | } else if attrs.unboxed { 83 | if variant.bindings().len() > 1 { 84 | panic!("ocaml cannot unboxed record with multiple fields") 85 | } 86 | variant.each(|field| quote!(value = #field.to_value())) 87 | } else { 88 | let mut idx = 0usize; 89 | let ghost = (0..arity) 90 | .into_iter() 91 | .map(|idx| quote!(value.store_field(#idx, ocaml::value::UNIT))); 92 | let init = quote!( 93 | value = ocaml::Value::alloc(#arity, ocaml::Tag::new(#tag)); 94 | #(#ghost);*; 95 | ); 96 | variant.fold(init, |acc, b| { 97 | let i = idx; 98 | idx += 1; 99 | quote!(#acc value.store_field(#i, #b.to_value());) 100 | }) 101 | } 102 | }); 103 | s.gen_impl(quote! { 104 | extern crate ocaml; 105 | gen unsafe impl ocaml::ToValue for @Self { 106 | fn to_value(&self) -> ocaml::Value { 107 | unsafe { 108 | ::ocaml::caml_body!{ | |, , { 109 | match *self { 110 | #(#body),* 111 | } 112 | }}; 113 | return value 114 | } 115 | } 116 | } 117 | }) 118 | } 119 | 120 | pub fn fromvalue_derive(s: synstructure::Structure) -> proc_macro2::TokenStream { 121 | let mut unit_tag = 0u8; 122 | let mut non_unit_tag = 0u8; 123 | let is_record_like = s.variants().len() == 1; 124 | let attrs = if is_record_like { 125 | variant_attrs(s.variants()[0].ast().attrs) 126 | } else { 127 | Attrs::default() 128 | }; 129 | let body = s.variants().iter().map(|variant| { 130 | let arity = variant.bindings().len(); 131 | let tag_ref = if arity > 0 { 132 | &mut non_unit_tag 133 | } else { 134 | &mut unit_tag 135 | }; 136 | let attrs = variant_attrs(&variant.ast().attrs); 137 | if (attrs.floats || attrs.unboxed) && !is_record_like { 138 | panic!("ocaml cannot derive unboxed records or float arrays for enums") 139 | } 140 | let tag = *tag_ref; 141 | *tag_ref += 1; 142 | let is_block = arity != 0; 143 | if attrs.unboxed { 144 | if arity > 1 { 145 | panic!("ocaml cannot derive unboxed records with several fields") 146 | } 147 | variant.construct(|_, _| quote!(ocaml::FromValue::from_value(value))) 148 | } else { 149 | let construct = variant.construct(|field, idx| { 150 | if attrs.floats { 151 | let ty = &field.ty; 152 | quote!(ocaml::Array::from(value.clone()).get_double(#idx).unwrap() as #ty) 153 | } else { 154 | quote!(ocaml::FromValue::from_value(value.field(#idx))) 155 | } 156 | }); 157 | quote!((#is_block, #tag) => { 158 | #construct 159 | } 160 | ) 161 | } 162 | }); 163 | if attrs.unboxed { 164 | s.gen_impl(quote! { 165 | extern crate ocaml; 166 | gen unsafe impl ocaml::FromValue for @Self { 167 | fn fromm_value(value: ocaml::Value) -> Self { 168 | #(#body),* 169 | } 170 | } 171 | }) 172 | } else { 173 | let tag = if !attrs.floats { 174 | quote!(match value.tag() { 175 | ocaml::Tag::Tag(tag) => tag, 176 | ocaml::Tag::Zero => 0, 177 | _ => panic!( 178 | "ocaml ffi: trying to convert a non structural value to a structure/enum" 179 | ), 180 | }) 181 | } else { 182 | quote!({ 183 | if value.tag() != ocaml::Tag::DoubleArray { 184 | panic!("ocaml ffi: trying to convert a value which is not a double array to an unboxed record") 185 | }; 186 | 0 187 | }) 188 | }; 189 | s.gen_impl(quote! { 190 | extern crate ocaml; 191 | gen unsafe impl ocaml::FromValue for @Self { 192 | fn from_value(value: ocaml::Value) -> Self { 193 | let is_block = value.is_block(); 194 | let tag = if !is_block { value.i32_val() as u8 } else { #tag }; 195 | match (is_block, tag) { 196 | #(#body),* 197 | _ => panic!("ocaml ffi: received unknown variant while trying to convert ocaml structure/enum to rust"), 198 | } 199 | } 200 | } 201 | }) 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "stubs")] 2 | extern crate proc_macro; 3 | extern crate proc_macro2; 4 | extern crate quote; 5 | extern crate syn; 6 | 7 | #[cfg(feature = "stubs")] 8 | mod stubs; 9 | 10 | #[cfg(feature = "stubs")] 11 | #[proc_macro_attribute] 12 | pub fn ocaml_ffi( 13 | attribute: proc_macro::TokenStream, 14 | function: proc_macro::TokenStream, 15 | ) -> proc_macro::TokenStream { 16 | stubs::ocaml(attribute, function) 17 | } 18 | 19 | #[cfg(feature = "derive")] 20 | #[macro_use] 21 | extern crate synstructure; 22 | 23 | #[cfg(feature = "derive")] 24 | mod derive; 25 | 26 | #[cfg(feature = "derive")] 27 | decl_derive!([ToValue, attributes(ocaml)] => derive::tovalue_derive); 28 | #[cfg(feature = "derive")] 29 | decl_derive!([FromValue, attributes(ocaml)] => derive::fromvalue_derive); 30 | -------------------------------------------------------------------------------- /src/stubs.rs: -------------------------------------------------------------------------------- 1 | use proc_macro::TokenStream; 2 | use proc_macro2; 3 | use proc_macro2::Ident; 4 | use syn::{self, *}; 5 | 6 | struct OcamlParam { 7 | ident: Option, 8 | typ: Type, 9 | } 10 | 11 | fn args_to_rust_vars<'a>( 12 | args: &'a [OcamlParam], 13 | ) -> impl 'a + Iterator { 14 | args.iter().filter_map(|arg| match arg.ident { 15 | None => None, 16 | Some(ref ident) => { 17 | let typ = &arg.typ; 18 | Some(quote!( <#typ as ::ocaml::FromValue>::from_value(#ident))) 19 | } 20 | }) 21 | } 22 | 23 | fn args_names<'a>(args: &'a [OcamlParam]) -> impl 'a + Iterator { 24 | args.iter() 25 | .filter_map(|arg| arg.ident.as_ref().map(|ident| quote!(#ident))) 26 | } 27 | 28 | pub fn ocaml(_attribute: TokenStream, function: TokenStream) -> TokenStream { 29 | let ItemFn { 30 | sig, 31 | block, 32 | attrs, 33 | vis, 34 | .. 35 | } = match syn::parse(function).expect("failed to parse tokens as a function") { 36 | Item::Fn(item) => item, 37 | _ => panic!("#[ocaml] can only be applied to functions"), 38 | }; 39 | match vis { 40 | syn::Visibility::Public(_) => (), 41 | _ => panic!("#[ocaml] functions must be public"), 42 | }; 43 | let syn::Signature { 44 | ident, 45 | inputs, 46 | output, 47 | variadic, 48 | generics, 49 | fn_token, 50 | .. 51 | } = { sig }; 52 | 53 | if !generics.params.is_empty() { 54 | panic!("#[ocaml] functions must not have generics") 55 | } 56 | if variadic.is_some() { 57 | panic!("#[ocaml] functions must not be variadic") 58 | } 59 | 60 | let args = inputs 61 | .iter() 62 | .enumerate() 63 | .map(|(i, input)| { 64 | match *input { 65 | FnArg::Receiver(_) => panic!("#[ocaml] can only be applied to plain functions, methods are not supported at argument {}", i), 66 | FnArg::Typed(syn::PatType { 67 | ref pat, 68 | ref ty, 69 | .. 70 | }) => { 71 | match **pat { 72 | Pat::Ident(syn::PatIdent { 73 | ref ident, 74 | by_ref: None, 75 | subpat: None, 76 | .. 77 | }) => { 78 | let typ = *ty.clone(); 79 | OcamlParam { ident: Some(ident.clone()), typ } 80 | }, 81 | Pat::Wild (_) => { let typ = *ty.clone(); OcamlParam { ident: None, typ }}, 82 | _ => panic!("#[ocaml] only supports simple argument patterns at argument {}", i), 83 | } 84 | }, 85 | } 86 | }) 87 | .collect::>(); 88 | 89 | let where_clause = &generics.where_clause; 90 | let (returns, return_ty, rust_ty) = match output { 91 | rust_ty @ ReturnType::Type(_, _) => ( 92 | true, 93 | quote!( -> ::ocaml::core::mlvalues::Value), 94 | quote!(#rust_ty), 95 | ), 96 | ReturnType::Default => (false, quote!(), quote!()), 97 | }; 98 | let params = args_names(&args).collect::>(); 99 | let rust_code = { 100 | let inputs = inputs.clone(); 101 | // Generate an internal function so that ? and return properly works 102 | quote!( 103 | #[inline(always)] 104 | fn internal( #inputs ) #rust_ty { 105 | #block 106 | } 107 | ) 108 | }; 109 | let arguments = args_to_rust_vars(&args); 110 | let body = if returns { 111 | quote!( 112 | #rust_code 113 | ::ocaml::caml_body!{ | #(#params), * |, , { 114 | let rust_val = internal(#(#arguments),*); 115 | return_value = ::ocaml::ToValue::to_value(&rust_val); 116 | } 117 | }; 118 | return ::ocaml::core::mlvalues::Value::from(return_value); 119 | ) 120 | } else { 121 | quote!( 122 | #rust_code 123 | ::ocaml::caml_body!{ | #(#params), * |, @code { 124 | internal(#(#arguments),*); 125 | }}; 126 | return 127 | ) 128 | }; 129 | let inputs = args.iter().map(|arg| match arg.ident { 130 | Some(ref ident) => quote! { mut #ident: ::ocaml::core::mlvalues::Value }, 131 | None => quote! { _: ::ocaml::core::mlvalues::Value }, 132 | }); 133 | 134 | let output = quote! { 135 | #[no_mangle] 136 | #[allow(unused_mut)] 137 | #(#attrs)* 138 | pub unsafe extern #fn_token #ident (#(#inputs),*) #return_ty #where_clause { 139 | #body 140 | } 141 | }; 142 | output.into() 143 | } 144 | --------------------------------------------------------------------------------