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