Skip to main content

rust_anything/
codegen_c.rs

1//! C ABI bridge: drop-in `extern "C"` replacements with the original names and signatures.
2//!
3//! The port is safe Rust over C's ABI types (`c_int`, `usize`, `f64`, ...), with each
4//! `const char *` as `Option<&[u8]>` (`None` for `NULL`). `lib.rs` is the only place with
5//! `unsafe`: reading C strings, and exporting unmangled symbols.
6
7use 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
17/// The ABI type of a C scalar, as Rust spells it.
18fn 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    if any_string {
92        out.push_str(
93            "use std::ffi::{CStr, c_char};\n\npub mod port;\n\n\
94             /// A `const char *` argument as bytes; `None` for `NULL`.\n\
95             fn c_str<'a>(ptr: *const c_char) -> Option<&'a [u8]> {\n    if ptr.is_null() {\n        return None;\n    }\n\
96             \x20   // SAFETY: the C API takes NUL-terminated strings that stay valid for the call;\n\
97             \x20   // NULL is handled above.\n    Some(unsafe { CStr::from_ptr(ptr) }.to_bytes())\n}\n",
98        );
99    } else {
100        out.push_str("pub mod port;\n");
101    }
102    for f in &m.exports {
103        let params: Vec<String> = f
104            .params
105            .iter()
106            .map(|p| {
107                let ty = if is_string(p) {
108                    "*const c_char".to_string()
109                } else {
110                    abi(p.native_type.as_deref().unwrap_or("int"))
111                };
112                format!("{}: {ty}", p.name)
113            })
114            .collect();
115        let args: Vec<String> = f
116            .params
117            .iter()
118            .map(|p| {
119                if is_string(p) {
120                    format!("c_str({})", p.name)
121                } else {
122                    p.name.clone()
123                }
124            })
125            .collect();
126        let ret = ret_type(f).map(|r| format!(" -> {r}")).unwrap_or_default();
127        let prototype = f.prototype.as_deref().unwrap_or(&f.name);
128        let _ = writeln!(
129            out,
130            "\n/// `{prototype}` (`{}:{}`).\n\
131             #[cfg(not(feature = \"shadow\"))]\n\
132             // SAFETY: exported under the C name it replaces: link it instead of the original object.\n\
133             #[unsafe(no_mangle)]\npub extern \"C\" fn {name}({params}){ret} {{\n    port::{name}({args})\n}}\n\n\
134             /// `{name}` as `rust_anything_{name}`, for shadow builds beside the original.\n\
135             // SAFETY: a name no C code defines.\n\
136             #[unsafe(no_mangle)]\npub extern \"C\" fn rust_anything_{name}({params}){ret} {{\n    port::{name}({args})\n}}",
137            f.file,
138            f.line,
139            name = f.name,
140            params = params.join(", "),
141            args = args.join(", "),
142        );
143    }
144    out
145}
146
147/// `include/<lib>.h`: the prototypes, and the `rust_anything_` aliases.
148pub fn header(m: &Manifest) -> String {
149    let guard = format!("{}_H", m.lib_name().to_uppercase());
150    let mut out = format!(
151        "/* C API of the Rust port of `{}`, generated by rust-anything. */\n#ifndef {guard}\n#define {guard}\n\n\
152         #include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <sys/types.h>\n\n",
153        m.unit
154    );
155    for f in &m.exports {
156        let _ = writeln!(out, "{};", f.prototype.as_deref().unwrap_or(&f.name));
157    }
158    out.push_str("\n/* The same functions under `rust_anything_` names, for shadow runs. */\n");
159    for f in &m.exports {
160        let prototype = f.prototype.as_deref().unwrap_or(&f.name);
161        let _ = writeln!(
162            out,
163            "{};",
164            prototype.replacen(
165                &format!("{}(", f.name),
166                &format!("rust_anything_{}(", f.name),
167                1
168            )
169        );
170    }
171    let _ = writeln!(out, "\n#endif /* {guard} */");
172    out
173}
174
175/// A C shadow file: each function calls the original (compiled renamed) and the Rust port.
176pub fn shadow_c(m: &Manifest) -> String {
177    let mut out = String::from(
178        "/* Generated by rust-anything: runs the C original and the Rust port side by side.\n\
179         *\n * Build: compile the original sources with `-D<name>=<name>__original` for each function\n\
180         * below (see `shadow/flags.txt`), then link this file, those objects and the Rust library.\n\
181         * Build the Rust library with `cargo build --release --features shadow`, so it exports only the\n\
182         * `rust_anything_` names. Callers get the original's results; differences are counted and reported\n\
183         * on stderr.\n */\n\
184         #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\
185         long rust_anything_shadow_calls = 0;\nlong rust_anything_shadow_mismatches = 0;\n\n",
186    );
187    for f in &m.exports {
188        let prototype = f.prototype.as_deref().unwrap_or(&f.name);
189        let original = prototype.replacen(
190            &format!("{}(", f.name),
191            &format!("{}__original(", f.name),
192            1,
193        );
194        let rust = prototype.replacen(
195            &format!("{}(", f.name),
196            &format!("rust_anything_{}(", f.name),
197            1,
198        );
199        let args = f
200            .params
201            .iter()
202            .map(|p| p.name.as_str())
203            .collect::<Vec<_>>()
204            .join(", ");
205        let _ = writeln!(out, "{original};\n{rust};\n");
206        if f.native_return.as_deref() == Some("void") {
207            let _ = writeln!(
208                out,
209                "{prototype} {{\n    {name}__original({args});\n    rust_anything_{name}({args});\n}}\n",
210                name = f.name
211            );
212        } else {
213            let ret = f.native_return.as_deref().unwrap_or("int");
214            let _ = writeln!(
215                out,
216                "{prototype} {{\n    {ret} expected = {name}__original({args});\n    {ret} actual = rust_anything_{name}({args});\n\
217                 \x20   rust_anything_shadow_calls++;\n    if (memcmp(&expected, &actual, sizeof expected) != 0) {{\n\
218                 \x20       rust_anything_shadow_mismatches++;\n        if (rust_anything_shadow_mismatches <= 10)\n\
219                 \x20           fprintf(stderr, \"[rust-anything] mismatch in {name}\\n\");\n    }}\n    return expected;\n}}\n",
220                name = f.name
221            );
222        }
223    }
224    out
225}
226
227/// `-D` flags that rename the originals for a shadow build.
228pub fn shadow_flags(m: &Manifest) -> String {
229    m.exports
230        .iter()
231        .map(|f| format!("-D{0}={0}__original", f.name))
232        .collect::<Vec<_>>()
233        .join(" ")
234        + "\n"
235}
236
237pub fn cargo_toml(m: &Manifest) -> String {
238    format!(
239        "[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
240         description = \"Rust port of `{}`, generated by rust-anything\"\n\n\
241         [lib]\ncrate-type = [\"cdylib\", \"staticlib\", \"rlib\"]\n\n\
242         [features]\n# Export only the `rust_anything_` names, to link beside the original C code.\nshadow = []\n\n[dependencies]\n\n\
243         [profile.release]\nlto = true\n\n[lints.clippy]\nall = {{ level = \"warn\", priority = -1 }}\n",
244        m.crate_name, m.unit
245    )
246}