1use std::fmt::Write as _;
8
9use crate::bridge::Manifest;
10use crate::lang::c::scalar;
11use crate::ts::exports::{ExportedFn, Param};
12
13fn is_string(p: &Param) -> bool {
14 p.ts_type == "string"
15}
16
17fn abi(c_type: &str) -> String {
19 scalar(c_type).map_or_else(|| "()".to_string(), |(_, _, abi, _)| abi.to_string())
20}
21
22fn ret_type(f: &ExportedFn) -> Option<String> {
23 let r = f.native_return.as_deref().unwrap_or("void");
24 (r != "void").then(|| abi(r))
25}
26
27pub fn port_rs(m: &Manifest) -> String {
28 let mut out = format!(
29 "//! The Rust port of `{}`: safe Rust; `lib.rs` exports each function under its C name.\n//!\n\
30 //! Replace each `unimplemented!` with the port of the C function. C has no error channel:\n\
31 //! return what the C code returns, and never panic (a panic aborts at the C boundary).\n\n\
32 #![forbid(unsafe_code)]\n",
33 m.unit
34 );
35 for f in &m.exports {
36 let params: Vec<String> = f
37 .params
38 .iter()
39 .map(|p| {
40 let ty = if is_string(p) {
41 "Option<&[u8]>".to_string()
42 } else {
43 abi(p.native_type.as_deref().unwrap_or("int"))
44 };
45 format!("{}: {ty}", p.name)
46 })
47 .collect();
48 let ret = ret_type(f).map(|r| format!(" -> {r}")).unwrap_or_default();
49 out.push('\n');
50 let _ = writeln!(
51 out,
52 "/// Port of `{}` (`{}:{}`).",
53 f.prototype.as_deref().unwrap_or(&f.name),
54 f.file,
55 f.line
56 );
57 for p in f.params.iter().filter(|p| is_string(p)) {
58 let _ = writeln!(
59 out,
60 "///\n/// `{}`: the bytes of the C string, without its NUL; `None` for `NULL`.",
61 p.name
62 );
63 }
64 let _ = writeln!(out, "pub fn {}({}){ret} {{", f.name, params.join(", "));
65 let names: Vec<String> = f.params.iter().map(|p| format!("&{}", p.name)).collect();
66 match names.len() {
67 0 => {}
68 1 => {
69 let _ = writeln!(out, " let _ = {};", names[0]);
70 }
71 _ => {
72 let _ = writeln!(out, " let _ = ({});", names.join(", "));
73 }
74 }
75 let _ = writeln!(
76 out,
77 " unimplemented!(\"port `{}` from {}\")\n}}",
78 f.name, f.file
79 );
80 }
81 out
82}
83
84pub fn lib_rs(m: &Manifest) -> String {
85 let any_string = m.exports.iter().any(|f| f.params.iter().any(is_string));
86 let mut out = format!(
87 "//! C ABI for `{}`: drop-in replacements with the original names and signatures, generated\n\
88 //! by rust-anything from `rust-anything.json`. All of the crate's `unsafe` code lives in this file.\n\n",
89 m.unit
90 );
91 out.push_str("pub mod port;\n");
92 if any_string {
93 out.push_str(
94 r#"
95use std::ffi::c_char;
96
97mod __rust_anything_c_abi {
98 use std::ffi::{CStr, c_char};
99
100 /// A `const char *` argument as bytes; `None` for `NULL`.
101 pub(super) fn c_str<'a>(ptr: *const c_char) -> Option<&'a [u8]> {
102 if ptr.is_null() {
103 return None;
104 }
105
106 // SAFETY: the C API takes NUL-terminated strings that stay valid for the call;
107 // NULL is handled above.
108 Some(unsafe { CStr::from_ptr(ptr) }.to_bytes())
109 }
110}
111"#,
112 );
113 }
114 for f in &m.exports {
115 let params: Vec<String> = f
116 .params
117 .iter()
118 .map(|p| {
119 let ty = if is_string(p) {
120 "*const c_char".to_string()
121 } else {
122 abi(p.native_type.as_deref().unwrap_or("int"))
123 };
124 format!("{}: {ty}", p.name)
125 })
126 .collect();
127 let args: Vec<String> = f
128 .params
129 .iter()
130 .map(|p| {
131 if is_string(p) {
132 format!("crate::__rust_anything_c_abi::c_str({})", p.name)
133 } else {
134 p.name.clone()
135 }
136 })
137 .collect();
138 let ret = ret_type(f).map(|r| format!(" -> {r}")).unwrap_or_default();
139 let prototype = f.prototype.as_deref().unwrap_or(&f.name);
140 let _ = writeln!(
141 out,
142 "\n/// `{prototype}` (`{}:{}`).\n\
143 #[cfg(not(feature = \"shadow\"))]\n\
144 // SAFETY: exported under the C name it replaces: link it instead of the original object.\n\
145 #[unsafe(no_mangle)]\npub extern \"C\" fn {name}({params}){ret} {{\n port::{name}({args})\n}}\n\n\
146 /// `{name}` as `rust_anything_{name}`, for shadow builds beside the original.\n\
147 // SAFETY: a name no C code defines.\n\
148 #[unsafe(no_mangle)]\npub extern \"C\" fn rust_anything_{name}({params}){ret} {{\n port::{name}({args})\n}}",
149 f.file,
150 f.line,
151 name = f.name,
152 params = params.join(", "),
153 args = args.join(", "),
154 );
155 }
156 out
157}
158
159pub fn header(m: &Manifest) -> String {
161 let guard = format!("{}_H", m.lib_name().to_uppercase());
162 let mut out = format!(
163 "/* C API of the Rust port of `{}`, generated by rust-anything. */\n#ifndef {guard}\n#define {guard}\n\n\
164 #include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <sys/types.h>\n\n",
165 m.unit
166 );
167 for f in &m.exports {
168 let _ = writeln!(out, "{};", f.prototype.as_deref().unwrap_or(&f.name));
169 }
170 out.push_str("\n/* The same functions under `rust_anything_` names, for shadow runs. */\n");
171 for f in &m.exports {
172 let prototype = f.prototype.as_deref().unwrap_or(&f.name);
173 let _ = writeln!(
174 out,
175 "{};",
176 prototype.replacen(
177 &format!("{}(", f.name),
178 &format!("rust_anything_{}(", f.name),
179 1
180 )
181 );
182 }
183 let _ = writeln!(out, "\n#endif /* {guard} */");
184 out
185}
186
187pub fn shadow_c(m: &Manifest) -> String {
189 let mut out = String::from(
190 "/* Generated by rust-anything: runs the C original and the Rust port side by side.\n\
191 *\n * Build: compile the original sources with `-D<name>=<name>__original` for each function\n\
192 * below (see `shadow/flags.txt`), then link this file, those objects and the Rust library.\n\
193 * Build the Rust library with `cargo build --release --features shadow`, so it exports only the\n\
194 * `rust_anything_` names. Callers get the original's results; differences are counted and reported\n\
195 * on stderr.\n */\n\
196 #include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/types.h>\n\n\
197 long rust_anything_shadow_calls = 0;\nlong rust_anything_shadow_mismatches = 0;\n\n",
198 );
199 for f in &m.exports {
200 let prototype = f.prototype.as_deref().unwrap_or(&f.name);
201 let original = prototype.replacen(
202 &format!("{}(", f.name),
203 &format!("{}__original(", f.name),
204 1,
205 );
206 let rust = prototype.replacen(
207 &format!("{}(", f.name),
208 &format!("rust_anything_{}(", f.name),
209 1,
210 );
211 let args = f
212 .params
213 .iter()
214 .map(|p| p.name.as_str())
215 .collect::<Vec<_>>()
216 .join(", ");
217 let _ = writeln!(out, "{original};\n{rust};\n");
218 if f.native_return.as_deref() == Some("void") {
219 let _ = writeln!(
220 out,
221 "{prototype} {{\n {name}__original({args});\n rust_anything_{name}({args});\n}}\n",
222 name = f.name
223 );
224 } else {
225 let ret = f.native_return.as_deref().unwrap_or("int");
226 let _ = writeln!(
227 out,
228 "{prototype} {{\n {ret} expected = {name}__original({args});\n {ret} actual = rust_anything_{name}({args});\n\
229 \x20 rust_anything_shadow_calls++;\n if (memcmp(&expected, &actual, sizeof expected) != 0) {{\n\
230 \x20 rust_anything_shadow_mismatches++;\n if (rust_anything_shadow_mismatches <= 10)\n\
231 \x20 fprintf(stderr, \"[rust-anything] mismatch in {name}\\n\");\n }}\n return expected;\n}}\n",
232 name = f.name
233 );
234 }
235 }
236 out
237}
238
239pub fn shadow_flags(m: &Manifest) -> String {
241 m.exports
242 .iter()
243 .map(|f| format!("-D{0}={0}__original", f.name))
244 .collect::<Vec<_>>()
245 .join(" ")
246 + "\n"
247}
248
249pub fn cargo_toml(m: &Manifest) -> String {
250 format!(
251 "[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
252 description = \"Rust port of `{}`, generated by rust-anything\"\n\n\
253 [lib]\ncrate-type = [\"cdylib\", \"staticlib\", \"rlib\"]\n\n\
254 [features]\n# Export only the `rust_anything_` names, to link beside the original C code.\nshadow = []\n\n[dependencies]\n\n\
255 [profile.release]\nlto = true\n\n[lints.clippy]\nall = {{ level = \"warn\", priority = -1 }}\n",
256 m.crate_name, m.unit
257 )
258}