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