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