Skip to main content

rust_anything/
codegen_ffi.rs

1//! The JSON bridge for Go, Ruby and Java: the port is plain Rust over serde types, and one
2//! dispatcher takes a function name and its arguments as JSON and answers
3//! `{"ok": value}`, `{"error": message}` or `{"panic": message}`.
4//!
5//! Go and Ruby reach the dispatcher through two C functions, `rust_anything_call` and
6//! `rust_anything_free`; Java through one JNI method. The language side is a generated wrapper with
7//! the original names and signatures, so callers do not change.
8
9use crate::MIN_RUST;
10use std::fmt::Write as _;
11
12use crate::bridge::Manifest;
13use crate::codegen::{PortApi, PortFn};
14use crate::lang::Lang;
15
16/// How a wrapper class or package names the JNI entry point: `rust-anything.<Lib>Native`.
17pub fn java_native_class(m: &Manifest) -> String {
18    let mut out = String::new();
19    for part in m.lib_name().split('_') {
20        let mut chars = part.chars();
21        if let Some(first) = chars.next() {
22            out.extend(first.to_uppercase());
23            out.push_str(chars.as_str());
24        }
25    }
26    format!("{out}Native")
27}
28
29fn arg_expr(f: &PortFn, i: usize) -> String {
30    match f.params[i].1.as_str() {
31        "f64" => format!("num(args, {i})?"),
32        "Option<f64>" => format!("opt_num(args, {i})?"),
33        "Vec<f64>" => format!("num_vec(args, {i})?"),
34        _ => format!("arg(args, {i})?"),
35    }
36}
37
38fn out_expr(f: &PortFn) -> &'static str {
39    match f.ret.as_str() {
40        "f64" => "out_num(out)",
41        "Option<f64>" => "out.map_or(Value::Null, out_num)",
42        "Vec<f64>" => "Value::Array(out.into_iter().map(out_num).collect())",
43        "()" => "Value::Null",
44        _ => "serde_json::to_value(out).map_err(|e| e.to_string())?",
45    }
46}
47
48pub fn lib_rs(m: &Manifest, api: &PortApi) -> String {
49    let mut arms = String::new();
50    for f in &api.functions {
51        let args: Vec<String> = (0..f.params.len()).map(|i| arg_expr(f, i)).collect();
52        let call = format!("port::{}({})", f.rust_name, args.join(", "));
53        let call = if f.fallible { format!("{call}?") } else { call };
54        let binding = if f.ret == "()" {
55            "let () ="
56        } else {
57            "let out ="
58        };
59        let _ = writeln!(
60            arms,
61            "        \"{name}\" => {{\n            {binding} {call};\n            Ok({out})\n        }}",
62            name = f.js_name,
63            out = out_expr(f),
64        );
65    }
66    let entry = if matches!(m.language, Lang::Java | Lang::Kotlin) {
67        format!(
68            r#"
69/// `static native String call(String name, String args)` of `rustanything.{class}`.
70// SAFETY: the JNI symbol name of that method; nothing else defines it.
71#[unsafe(no_mangle)]
72pub extern "system" fn Java_rustanything_{mangled}_call<'local>(
73    mut env: jni::JNIEnv<'local>,
74    _class: jni::objects::JClass<'local>,
75    name: jni::objects::JString<'local>,
76    args: jni::objects::JString<'local>,
77) -> jni::sys::jstring {{
78    let read = |env: &mut jni::JNIEnv<'local>, s: &jni::objects::JString<'local>| -> String {{
79        env.get_string(s).map(Into::into).unwrap_or_default()
80    }};
81    let name = read(&mut env, &name);
82    let args = read(&mut env, &args);
83    env.new_string(call_json(&name, &args))
84        .map_or(std::ptr::null_mut(), jni::objects::JString::into_raw)
85}}
86"#,
87            class = java_native_class(m),
88            mangled = crate::codegen_java::mangle_jni_component(&java_native_class(m)),
89        )
90    } else {
91        r#"
92/// The C entry point: `char *rust_anything_call(const char *name, const char *args)`. Free the
93/// answer with `rust_anything_free`.
94///
95/// # Safety
96///
97/// `name` and `args` must be NUL-terminated strings, valid for the call.
98// SAFETY: exported unmangled under a name only rust-anything defines.
99#[unsafe(no_mangle)]
100// SAFETY: callers uphold the contract under `# Safety`.
101pub unsafe extern "C" fn rust_anything_call(name: *const c_char, args: *const c_char) -> *mut c_char {
102    let text = |ptr: *const c_char| -> String {
103        if ptr.is_null() {
104            return String::new();
105        }
106        // SAFETY: the caller passes NUL-terminated strings that live for the call (see above).
107        unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned()
108    };
109    let answer = call_json(&text(name), &text(args));
110    // A JSON text never contains NUL: serde_json escapes it as \u0000.
111    CString::new(answer).map_or(std::ptr::null_mut(), CString::into_raw)
112}
113
114/// Frees an answer of `rust_anything_call`.
115///
116/// # Safety
117///
118/// `ptr` must come from `rust_anything_call` and not be freed before; NULL is ignored.
119// SAFETY: exported unmangled under a name only rust-anything defines.
120#[unsafe(no_mangle)]
121// SAFETY: callers uphold the contract under `# Safety`.
122pub unsafe extern "C" fn rust_anything_free(ptr: *mut c_char) {
123    if !ptr.is_null() {
124        // SAFETY: `ptr` was made by `CString::into_raw` in `rust_anything_call` (see above).
125        drop(unsafe { CString::from_raw(ptr) });
126    }
127}
128"#
129        .to_string()
130    };
131    let imports = if matches!(m.language, Lang::Java | Lang::Kotlin) {
132        "use serde_json::{Value, json};\n"
133    } else {
134        "use std::ffi::{CStr, CString, c_char};\n\nuse serde_json::{Value, json};\n"
135    };
136    format!(
137        r#"//! The {lang} bridge for `{unit}`, generated by rust-anything from `src/port.rs`: a JSON
138//! dispatcher over the port, and its entry point. Regenerate with `rust-anything refresh`.
139
140{imports}
141pub mod port;
142
143/// Argument `i`, decoded from JSON into the port's parameter type.
144fn arg<T: serde::de::DeserializeOwned>(args: &[Value], i: usize) -> Result<T, String> {{
145    serde_json::from_value(args.get(i).cloned().unwrap_or(Value::Null))
146        .map_err(|e| format!("argument {{i}}: {{e}}"))
147}}
148
149/// A float argument: JSON has no NaN or infinities, so they arrive as `{{"$num": "NaN"}}`.
150#[allow(dead_code)]
151fn num(args: &[Value], i: usize) -> Result<f64, String> {{
152    match args.get(i) {{
153        Some(Value::Object(o)) => match o.get("$num").and_then(Value::as_str) {{
154            Some("NaN") => Ok(f64::NAN),
155            Some("Infinity") => Ok(f64::INFINITY),
156            Some("-Infinity") => Ok(f64::NEG_INFINITY),
157            Some("-0") => Ok(-0.0),
158            _ => Err(format!("argument {{i}}: not a number")),
159        }},
160        _ => arg(args, i),
161    }}
162}}
163
164#[allow(dead_code)]
165fn num_vec(args: &[Value], i: usize) -> Result<Vec<f64>, String> {{
166    match args.get(i) {{
167        Some(Value::Array(items)) => (0..items.len()).map(|j| num(items, j)).collect(),
168        _ => arg(args, i),
169    }}
170}}
171
172#[allow(dead_code)]
173fn opt_num(args: &[Value], i: usize) -> Result<Option<f64>, String> {{
174    match args.get(i) {{
175        None | Some(Value::Null) => Ok(None),
176        Some(_) => num(args, i).map(Some),
177    }}
178}}
179
180#[allow(dead_code)]
181fn out_num(x: f64) -> Value {{
182    if x.is_nan() {{
183        json!({{"$num": "NaN"}})
184    }} else if x.is_infinite() {{
185        json!({{"$num": if x > 0.0 {{ "Infinity" }} else {{ "-Infinity" }}}})
186    }} else if x == 0.0 && x.is_sign_negative() {{
187        json!({{"$num": "-0"}})
188    }} else {{
189        json!(x)
190    }}
191}}
192
193fn dispatch(name: &str, args: &[Value]) -> Result<Value, String> {{
194    match name {{
195{arms}        _ => Err(format!("no function `{{name}}`")),
196    }}
197}}
198
199/// Runs `name` on the JSON array `args`; never unwinds into the caller.
200pub fn call_json(name: &str, args: &str) -> String {{
201    let result = std::panic::catch_unwind(|| {{
202        let args: Vec<Value> = serde_json::from_str(args).map_err(|e| e.to_string())?;
203        dispatch(name, &args)
204    }});
205    match result {{
206        Ok(Ok(value)) => json!({{"ok": value}}),
207        Ok(Err(message)) => json!({{"error": message}}),
208        Err(panic) => {{
209            let message = panic
210                .downcast_ref::<&str>()
211                .map(ToString::to_string)
212                .or_else(|| panic.downcast_ref::<String>().cloned())
213                .unwrap_or_else(|| "panic".into());
214            json!({{"panic": message}})
215        }}
216    }}
217    .to_string()
218}}
219{entry}"#,
220        lang = m.language.name(),
221        unit = m.unit,
222    )
223}
224
225pub fn cargo_toml(m: &Manifest) -> String {
226    let (crate_types, extra) = match m.language {
227        Lang::Java | Lang::Kotlin => ("\"cdylib\", \"rlib\"", "jni = \"0.21\"\n"),
228        Lang::Go => ("\"cdylib\", \"rlib\"", ""),
229        _ => ("\"cdylib\", \"staticlib\", \"rlib\"", ""),
230    };
231    // Ruby hashes and Java's LinkedHashMap keep insertion order; Go's encoder sorts map keys.
232    // `float_roundtrip`: the default float parser can be off by one ULP.
233    let serde_json = if m.language == Lang::Go {
234        "serde_json = { version = \"1\", features = [\"float_roundtrip\"] }\n"
235    } else {
236        "serde_json = { version = \"1\", features = [\"preserve_order\", \"float_roundtrip\"] }\n"
237    };
238    format!(
239        "[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2024\"\nrust-version = \"{MIN_RUST}\"\npublish = false\n\
240         description = \"Rust port of `{}`, generated by rust-anything\"\n\n\
241         [lib]\ncrate-type = [{crate_types}]\n\n[dependencies]\nserde = {{ version = \"1\", features = [\"derive\"] }}\n\
242         {serde_json}{extra}\n[profile.release]\nlto = true\n\n[lints.clippy]\nall = {{ level = \"warn\", priority = -1 }}\n\n[lints.rust]\nunused_lifetimes = \"warn\"\ntrivial_numeric_casts = \"warn\"\n",
243        m.crate_name, m.unit
244    )
245}