hs_bindgen_attribute/
lib.rs1#![forbid(unsafe_code)]
23#![cfg_attr(DIAGNOSTICS, feature(proc_macro_diagnostic))]
24
25use proc_macro::TokenStream;
26use std::{fs, path::Path, sync::Mutex};
27
28mod haskell;
29mod reflexive;
30mod rust;
31mod toml;
32
33#[proc_macro_attribute]
34pub fn hs_bindgen(attrs: TokenStream, input: TokenStream) -> TokenStream {
35 let mut output = input.clone();
36 let item_fn: syn::ItemFn = syn::parse(input)
37 .expect("failed to parse as Rust code the content of `#[hs_bindgen]` macro");
38
39 let (signature, extern_c_wrapper) = rust::generate(attrs, item_fn);
41
42 static SIGNATURES: Mutex<Vec<haskell::Signature>> = Mutex::new(vec![]);
44 let signatures = &mut *SIGNATURES.lock().unwrap();
45 signatures.push(signature);
46
47 let module = toml::config()
49 .default
50 .expect("your `hsbindgen.toml` file should contain a `default` field");
51 let cargo_manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
52 .expect("environment variable `CARGO_MANIFEST_DIR` must be set");
53 let path = Path::new(&cargo_manifest_dir).join(format!("src/{}.hs", module));
54 fs::write(&path, haskell::template(&module, signatures))
55 .unwrap_or_else(|_| panic!("fail to write `{}` file", path.display()));
56
57 output.extend(extern_c_wrapper);
58 output
59}