1use 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
14#[derive(Clone, Copy, PartialEq, Eq, Debug)]
16pub enum CKind {
17 Scalar,
18 Str,
20 Bytes,
22 Buffer,
24 Len(usize),
26 Out,
28 Struct,
30 OutPtr(usize),
32}
33
34#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct CStruct {
37 pub c_name: String,
39 pub fields: Vec<(String, String)>,
41}
42
43impl CStruct {
44 pub fn rust_name(&self) -> &str {
46 self.c_name
47 .strip_prefix("struct ")
48 .unwrap_or(&self.c_name)
49 .trim()
50 }
51}
52
53pub fn c_struct(ts_type: &str) -> Option<CStruct> {
55 let (c_name, fields) = ts_type.strip_prefix("struct:")?.split_once(':')?;
56 let fields = fields
57 .split(',')
58 .map(|f| {
59 let (ty, name) = f.trim().rsplit_once(' ')?;
60 Some((ty.to_string(), name.to_string()))
61 })
62 .collect::<Option<Vec<_>>>()?;
63 Some(CStruct {
64 c_name: c_name.to_string(),
65 fields,
66 })
67}
68
69pub fn structs(m: &Manifest) -> Vec<CStruct> {
71 let mut out: Vec<CStruct> = Vec::new();
72 for f in &m.exports {
73 for ts in f
74 .params
75 .iter()
76 .map(|p| p.ts_type.as_str())
77 .chain([f.returns.as_str()])
78 {
79 if let Some(s) = c_struct(ts)
80 && !out.iter().any(|o| o.c_name == s.c_name)
81 {
82 out.push(s);
83 }
84 }
85 }
86 out
87}
88
89pub fn c_struct_defs(m: &Manifest) -> String {
91 let mut out = String::new();
92 for s in structs(m) {
93 let fields: String = s
94 .fields
95 .iter()
96 .map(|(ty, name)| format!(" {ty} {name};"))
97 .collect();
98 if s.c_name.starts_with("struct ") {
99 let _ = writeln!(out, "{} {{{fields} }};", s.c_name);
100 } else {
101 let _ = writeln!(out, "typedef struct {{{fields} }} {};", s.c_name);
102 }
103 }
104 out
105}
106
107fn rust_struct(s: &CStruct) -> String {
109 let fields: String = s
110 .fields
111 .iter()
112 .map(|(ty, name)| format!(" pub {}: {},\n", ident(name), abi(ty)))
113 .collect();
114 let name = s.rust_name();
115 let mut allow = Vec::new();
116 if !name.starts_with(|c: char| c.is_ascii_uppercase()) || name.contains('_') {
117 allow.push("non_camel_case_types");
118 }
119 if s.fields
120 .iter()
121 .any(|(_, n)| n.chars().any(|c| c.is_ascii_uppercase()))
122 {
123 allow.push("non_snake_case");
124 }
125 let allow = if allow.is_empty() {
126 String::new()
127 } else {
128 format!("#[allow({})]\n", allow.join(", "))
129 };
130 format!(
131 "\n/// `{}` as C lays it out: passed and returned by value.\n#[repr(C)]\n\
132 #[derive(Clone, Copy, Debug, Default, PartialEq)]\n{allow}pub struct {name} {{\n{fields}}}\n",
133 s.c_name,
134 )
135}
136
137pub fn kind(p: &Param) -> CKind {
138 match p.ts_type.as_str() {
139 "string" => CKind::Str,
140 "bytes" => CKind::Bytes,
141 "buffer" => CKind::Buffer,
142 "out" => CKind::Out,
143 t if t.starts_with("struct:") => CKind::Struct,
144 t => {
145 if let Some(i) = t.strip_prefix("outptr:").and_then(|i| i.parse().ok()) {
146 return CKind::OutPtr(i);
147 }
148 t.strip_prefix("len:")
149 .and_then(|i| i.parse().ok())
150 .map_or(CKind::Scalar, CKind::Len)
151 }
152 }
153}
154
155pub fn returns_into(f: &ExportedFn) -> Option<usize> {
157 f.returns.strip_prefix("ptr:").and_then(|i| i.parse().ok())
158}
159
160pub fn writes(f: &ExportedFn) -> bool {
162 f.params
163 .iter()
164 .any(|p| matches!(kind(p), CKind::Buffer | CKind::Out | CKind::OutPtr(_)))
165}
166
167fn abi(c_type: &str) -> String {
169 scalar(c_type).map_or_else(|| "()".to_string(), |(_, _, abi, _)| abi.to_string())
170}
171
172pub fn pointee(c_type: &str) -> String {
174 c_type
175 .trim_end_matches(['*', ' '])
176 .split_whitespace()
177 .filter(|w| *w != "const")
178 .collect::<Vec<_>>()
179 .join(" ")
180}
181
182fn pointee_abi(c_type: &str) -> String {
184 match pointee(c_type).as_str() {
185 "void" => "std::ffi::c_void".into(),
186 "char" => "std::ffi::c_char".into(),
187 other => abi(other),
188 }
189}
190
191fn native(p: &Param) -> &str {
192 p.native_type.as_deref().unwrap_or("int")
193}
194
195const KEYWORDS: &[&str] = &[
196 "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for",
197 "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
198 "static", "struct", "trait", "true", "type", "unsafe", "use", "where", "while", "async",
199 "await", "dyn", "abstract", "become", "box", "do", "final", "macro", "override", "priv",
200 "typeof", "unsized", "virtual", "yield", "try", "gen",
201];
202
203fn ident(name: &str) -> String {
205 if KEYWORDS.contains(&name) {
206 format!("r#{name}")
207 } else {
208 name.to_string()
209 }
210}
211
212fn ret_type(f: &ExportedFn) -> Option<String> {
213 if let Some(s) = c_struct(&f.returns) {
214 return Some(format!("crate::{}", s.rust_name()));
215 }
216 let r = f.native_return.as_deref().unwrap_or("void");
217 if r.contains('*') {
218 return Some(format!("*mut {}", pointee_abi(r)));
219 }
220 (r != "void").then(|| abi(r))
221}
222
223fn inner(c_type: &str) -> String {
225 c_type
226 .trim_end()
227 .strip_suffix('*')
228 .unwrap_or(c_type)
229 .trim_end()
230 .to_string()
231}
232
233pub fn c_decl(c_type: &str, name: &str) -> String {
235 let stars = c_type.matches('*').count();
236 let base = c_type.trim_end_matches(['*', ' ']);
237 if stars == 0 {
238 format!("{base} {name}")
239 } else {
240 format!("{base} {}{name}", "*".repeat(stars))
241 }
242}
243
244pub fn c_prototype(f: &ExportedFn, name: &str) -> String {
247 let params: Vec<String> = f
248 .params
249 .iter()
250 .map(|p| c_decl(native(p), &p.name))
251 .collect();
252 let params = if params.is_empty() {
253 "void".to_string()
254 } else {
255 params.join(", ")
256 };
257 c_decl(
258 f.native_return.as_deref().unwrap_or("void"),
259 &format!("{name}({params})"),
260 )
261}
262
263pub fn port_rs(m: &Manifest) -> String {
264 let mut out = format!(
265 "//! The Rust port of `{}`: safe Rust; `lib.rs` exports each function under its C name.\n//!\n\
266 //! Replace each `unimplemented!` with the port of the C function. C has no error channel:\n\
267 //! return what the C code returns, and never panic (a panic aborts at the C boundary).\n\n\
268 #![forbid(unsafe_code)]\n",
269 m.unit
270 );
271 for f in &m.exports {
272 let shown: Vec<&Param> = f
273 .params
274 .iter()
275 .filter(|p| !matches!(kind(p), CKind::Len(_)))
276 .collect();
277 let params: Vec<String> = shown
278 .iter()
279 .map(|p| {
280 let ty = match kind(p) {
281 CKind::Str => "Option<&[u8]>".to_string(),
282 CKind::Bytes => "&[u8]".to_string(),
283 CKind::Buffer => "&mut [u8]".to_string(),
284 CKind::Out => format!("Option<&mut {}>", abi(&pointee(native(p)))),
285 CKind::Struct => c_struct(&p.ts_type)
286 .map_or_else(|| "()".into(), |s| format!("crate::{}", s.rust_name())),
287 CKind::OutPtr(_) => "Option<&mut Option<usize>>".to_string(),
288 CKind::Scalar | CKind::Len(_) => abi(native(p)),
289 };
290 format!("{}: {ty}", ident(&p.name))
291 })
292 .collect();
293 let ret = if returns_into(f).is_some() {
294 " -> Option<usize>".to_string()
295 } else {
296 ret_type(f).map(|r| format!(" -> {r}")).unwrap_or_default()
297 };
298 out.push('\n');
299 let _ = writeln!(
300 out,
301 "/// Port of `{}` (`{}:{}`).",
302 f.prototype.as_deref().unwrap_or(&f.name),
303 f.file,
304 f.line
305 );
306 for p in &shown {
307 let doc = match kind(p) {
308 CKind::Str => "the bytes of the C string, without its NUL; `None` for `NULL`.",
309 CKind::Bytes => "the bytes the C code reads, as long as its length parameter says.",
310 CKind::Buffer => {
311 "the buffer the C code writes, as long as its size parameter says (a negative \
312 size is empty)."
313 }
314 CKind::Out => "the value behind the pointer; `None` for `NULL`.",
315 CKind::OutPtr(i) => {
316 let _ = writeln!(
317 out,
318 "///\n/// `{}`: the pointer behind it, as the offset into `{}` it points to \
319 (`None` for `NULL`); the outer `None` is a `NULL` `{}`.",
320 p.name,
321 f.params[i].name,
322 native(p)
323 );
324 continue;
325 }
326 _ => continue,
327 };
328 let _ = writeln!(out, "///\n/// `{}`: {doc}", p.name);
329 }
330 if let Some(i) = returns_into(f) {
331 let _ = writeln!(
332 out,
333 "///\n/// Returns the offset into `{}` that the C function's pointer points to; `None` for `NULL`.",
334 f.params[i].name
335 );
336 }
337 let _ = writeln!(out, "pub fn {}({}){ret} {{", f.name, params.join(", "));
338 let names: Vec<String> = shown
339 .iter()
340 .map(|p| format!("&{}", ident(&p.name)))
341 .collect();
342 match names.len() {
343 0 => {}
344 1 => {
345 let _ = writeln!(out, " let _ = {};", names[0]);
346 }
347 _ => {
348 let _ = writeln!(out, " let _ = ({});", names.join(", "));
349 }
350 }
351 let _ = writeln!(
352 out,
353 " unimplemented!(\"port `{}` from {}\")\n}}",
354 f.name, f.file
355 );
356 }
357 out
358}
359
360fn lazy(port: &crate::codegen::PortApi, f: &ExportedFn, p: &Param) -> bool {
363 kind(p) == CKind::Str
364 && port
365 .functions
366 .iter()
367 .find(|g| g.rust_name.trim_start_matches("r#") == f.name)
368 .and_then(|g| g.params.iter().find(|(name, _)| *name == ident(&p.name)))
369 .is_some_and(|(_, ty)| ty.contains("CChars"))
370}
371
372const C_CHARS: &str = r#"
374/// A `const char *` read one byte at a time up to its NUL, without measuring it first: for ports
375/// where `strlen` would cost more than the work (`av_strcasecmp` on short words). A port opts in
376/// by typing the parameter `Option<crate::CChars<'_>>`; `rust-anything refresh` then passes it.
377#[derive(Clone, Debug)]
378pub struct CChars<'a> {
379 ptr: std::ptr::NonNull<std::ffi::c_char>,
380 life: std::marker::PhantomData<&'a std::ffi::CStr>,
381}
382
383impl<'a> CChars<'a> {
384 /// The bytes of `s`, for calling a port from Rust.
385 pub fn new(s: &'a std::ffi::CStr) -> Self {
386 Self {
387 ptr: std::ptr::NonNull::from(s).cast(),
388 life: std::marker::PhantomData,
389 }
390 }
391
392 /// The next byte without moving past it; `0` at the end.
393 pub fn peek(&self) -> u8 {
394 // SAFETY: `ptr` points into a NUL-terminated string valid for `'a`, at or before its NUL.
395 unsafe { *self.ptr.as_ptr() as u8 }
396 }
397
398 /// The rest of the string as a slice, without its NUL (this measures it).
399 pub fn to_bytes(&self) -> &'a [u8] {
400 // SAFETY: as in `peek`; the rest of the string is itself NUL-terminated.
401 unsafe { std::ffi::CStr::from_ptr(self.ptr.as_ptr()) }.to_bytes()
402 }
403}
404
405impl Iterator for CChars<'_> {
406 type Item = u8;
407
408 fn next(&mut self) -> Option<u8> {
409 let b = self.peek();
410 if b == 0 {
411 return None;
412 }
413 // SAFETY: `b` is not the NUL, so the next byte is still inside the string.
414 self.ptr = unsafe { self.ptr.add(1) };
415 Some(b)
416 }
417}
418
419impl std::iter::FusedIterator for CChars<'_> {}
420"#;
421
422pub fn lib_rs(m: &Manifest, port: &str) -> String {
423 let port = crate::codegen::parse_port(port);
424 let all = || m.exports.iter().flat_map(|f| f.params.iter().map(kind));
425 let any_lazy = m
426 .exports
427 .iter()
428 .any(|f| f.params.iter().any(|p| lazy(&port, f, p)));
429 let any_measured = m.exports.iter().any(|f| {
430 f.params
431 .iter()
432 .any(|p| kind(p) == CKind::Str && !lazy(&port, f, p))
433 });
434 let any_string = all().any(|k| k == CKind::Str);
435 let any_bytes = all().any(|k| k == CKind::Bytes);
436 let any_buffer = all().any(|k| k == CKind::Buffer);
437 let any_out = all().any(|k| k == CKind::Out);
438 let any_outptr = all().any(|k| matches!(k, CKind::OutPtr(_)));
439 let any_len = all().any(|k| matches!(k, CKind::Len(_)));
440 let mut out = format!(
441 "//! C ABI for `{}`: drop-in replacements with the original names and signatures, generated\n\
442 //! by rust-anything from `rust-anything.json`. All of the crate's `unsafe` code lives in this file.\n\n",
443 m.unit
444 );
445 out.push_str("pub mod port;\n");
446 for s in structs(m) {
447 out.push_str(&rust_struct(&s));
448 }
449 if any_string {
450 out.push_str("\nuse std::ffi::c_char;\n");
451 }
452 if any_lazy {
453 out.push_str(C_CHARS);
454 }
455 if any_string || any_bytes || any_buffer || any_out || any_outptr || any_len {
456 out.push_str("\nmod __rust_anything_c_abi {\n");
457 if any_lazy {
458 out.push_str(
459 r#" /// A `const char *` argument read as the port goes; `None` for `NULL`.
460 pub(super) fn c_chars<'a>(ptr: *const std::ffi::c_char) -> Option<super::CChars<'a>> {
461 std::ptr::NonNull::new(ptr.cast_mut()).map(|ptr| super::CChars {
462 ptr,
463 life: std::marker::PhantomData,
464 })
465 }
466"#,
467 );
468 }
469 if any_measured {
470 out.push_str(
471 r#" use std::ffi::{CStr, c_char};
472
473 /// A `const char *` argument as bytes; `None` for `NULL`.
474 pub(super) fn c_str<'a>(ptr: *const c_char) -> Option<&'a [u8]> {
475 if ptr.is_null() {
476 return None;
477 }
478
479 // SAFETY: the C API takes NUL-terminated strings that stay valid for the call;
480 // NULL is handled above.
481 Some(unsafe { CStr::from_ptr(ptr) }.to_bytes())
482 }
483"#,
484 );
485 }
486 if any_bytes {
487 out.push_str(
488 r#"
489 /// A `const` byte pointer and its length as a slice; empty for `NULL` or a zero length.
490 pub(super) fn bytes<'a>(ptr: *const u8, len: usize) -> &'a [u8] {
491 if ptr.is_null() || len == 0 {
492 return &[];
493 }
494
495 // SAFETY: the C API passes `len` readable bytes at `ptr` that stay valid for the call;
496 // NULL is handled above.
497 unsafe { std::slice::from_raw_parts(ptr, len) }
498 }
499"#,
500 );
501 }
502 if any_buffer {
503 out.push_str(
504 r#"
505 /// A writable byte pointer and its size as a slice; empty for `NULL` or a zero size.
506 pub(super) fn bytes_mut<'a>(ptr: *mut u8, len: usize) -> &'a mut [u8] {
507 if ptr.is_null() || len == 0 {
508 return &mut [];
509 }
510
511 // SAFETY: the C API passes `len` writable bytes at `ptr`, used by nothing else during the
512 // call; NULL is handled above.
513 unsafe { std::slice::from_raw_parts_mut(ptr, len) }
514 }
515"#,
516 );
517 }
518 if any_out {
519 out.push_str(
520 r#"
521 /// A pointer to one value as a reference; `None` for `NULL`.
522 pub(super) fn out<'a, T>(ptr: *mut T) -> Option<&'a mut T> {
523 // SAFETY: the C API passes NULL or a valid, aligned pointer used by nothing else
524 // during the call.
525 unsafe { ptr.as_mut() }
526 }
527"#,
528 );
529 }
530 if any_outptr {
531 out.push_str(
532 r#"
533 /// Where the pointer behind `slot` points, as an offset from `base`: `None` for a `NULL`
534 /// `slot`, `Some(None)` when it holds `NULL`.
535 pub(super) fn offset_in<T>(slot: *mut *const T, base: *const u8) -> Option<Option<usize>> {
536 // SAFETY: the C API passes NULL or a valid, aligned pointer to a pointer, used by nothing
537 // else during the call; NULL is handled by `as_ref`.
538 let target = unsafe { slot.as_ref() }?;
539 Some((!target.is_null()).then(|| target.addr().wrapping_sub(base.addr())))
540 }
541
542 /// Points the pointer behind `slot` at `offset` bytes into `base` (`NULL` for `None`); a
543 /// `NULL` `slot` is left alone.
544 pub(super) fn set_offset<T>(slot: *mut *const T, base: *const u8, offset: Option<Option<usize>>) {
545 // SAFETY: as in `offset_in`.
546 if let (Some(target), Some(offset)) = (unsafe { slot.as_mut() }, offset) {
547 *target = offset.map_or(std::ptr::null(), |o| base.wrapping_add(o).cast());
548 }
549 }
550"#,
551 );
552 }
553 if any_len {
554 out.push_str(
555 r#"
556 /// A C length as `usize`; a negative length is zero.
557 pub(super) fn len<T: TryInto<usize>>(n: T) -> usize {
558 n.try_into().unwrap_or(0)
559 }
560"#,
561 );
562 }
563 out.push_str("}\n");
564 }
565 for f in &m.exports {
566 let params: Vec<String> = f
567 .params
568 .iter()
569 .map(|p| {
570 let ty = match kind(p) {
571 CKind::Str => "*const c_char".to_string(),
572 CKind::Bytes => format!("*const {}", pointee_abi(native(p))),
573 CKind::Buffer => format!("*mut {}", pointee_abi(native(p))),
574 CKind::Out => format!("*mut {}", abi(&pointee(native(p)))),
575 CKind::Struct => c_struct(&p.ts_type)
576 .map_or_else(|| "()".into(), |s| s.rust_name().to_string()),
577 CKind::OutPtr(_) => format!("*mut *const {}", pointee_abi(&inner(native(p)))),
578 CKind::Scalar | CKind::Len(_) => abi(native(p)),
579 };
580 format!("{}: {ty}", ident(&p.name))
581 })
582 .collect();
583 let len_of = |i: usize| -> String {
584 f.params
585 .iter()
586 .find(|p| kind(p) == CKind::Len(i))
587 .map_or_else(
588 || "0".to_string(),
589 |p| format!("crate::__rust_anything_c_abi::len({})", ident(&p.name)),
590 )
591 };
592 let args: Vec<String> = f
593 .params
594 .iter()
595 .enumerate()
596 .filter_map(|(i, p)| {
597 let name = ident(&p.name);
598 Some(match kind(p) {
599 CKind::Str if lazy(&port, f, p) => {
600 format!("crate::__rust_anything_c_abi::c_chars({name})")
601 }
602 CKind::Str => format!("crate::__rust_anything_c_abi::c_str({name})"),
603 CKind::Bytes => format!(
604 "crate::__rust_anything_c_abi::bytes({name}.cast::<u8>(), {})",
605 len_of(i)
606 ),
607 CKind::Buffer => format!(
608 "crate::__rust_anything_c_abi::bytes_mut({name}.cast::<u8>(), {})",
609 len_of(i)
610 ),
611 CKind::Out => format!("crate::__rust_anything_c_abi::out({name})"),
612 CKind::OutPtr(_) => format!("{}_offset.as_mut()", p.name),
613 CKind::Len(_) => return None,
614 CKind::Struct | CKind::Scalar => name,
615 })
616 })
617 .collect();
618 let ret = ret_type(f).map(|r| format!(" -> {r}")).unwrap_or_default();
619 let call = format!("port::{}({})", f.name, args.join(", "));
620 let body = match returns_into(f) {
621 Some(i) => {
622 let target = ident(&f.params[i].name);
623 let cast = if kind(&f.params[i]) == CKind::Buffer {
624 target
625 } else {
626 format!("{target}.cast_mut()")
627 };
628 let ret_ptr = ret_type(f).unwrap_or_default();
629 format!(
630 "match {call} {{\n Some(offset) => {cast}.cast::<u8>().wrapping_add(offset).cast(),\n \
631 None => std::ptr::null_mut::<{}>(),\n }}",
632 ret_ptr.trim_start_matches("*mut ")
633 )
634 }
635 None => call,
636 };
637 let outptrs: Vec<(String, String)> = f
638 .params
639 .iter()
640 .filter_map(|p| match kind(p) {
641 CKind::OutPtr(i) => {
642 let base = ident(&f.params[i].name);
643 let base = if kind(&f.params[i]) == CKind::Buffer {
644 format!("{base}.cast::<u8>().cast_const()")
645 } else {
646 format!("{base}.cast::<u8>()")
647 };
648 Some((ident(&p.name), base))
649 }
650 _ => None,
651 })
652 .collect();
653 let body = if outptrs.is_empty() {
654 body
655 } else {
656 let before: String = outptrs
657 .iter()
658 .map(|(name, base)| {
659 format!(
660 "let mut {}_offset = crate::__rust_anything_c_abi::offset_in({name}, {base});\n ",
661 name.trim_start_matches("r#")
662 )
663 })
664 .collect();
665 let after: String = outptrs
666 .iter()
667 .map(|(name, base)| {
668 format!(
669 "\n crate::__rust_anything_c_abi::set_offset({name}, {base}, {}_offset);",
670 name.trim_start_matches("r#")
671 )
672 })
673 .collect();
674 if ret_type(f).is_some() {
675 format!("{before}let result = {body};{after}\n result")
676 } else {
677 format!("{before}{body};{after}")
678 }
679 };
680 let prototype = f.prototype.as_deref().unwrap_or(&f.name);
681 let _ = writeln!(
682 out,
683 "\n/// `{prototype}` (`{}:{}`).\n\
684 #[cfg(not(feature = \"shadow\"))]\n\
685 // SAFETY: exported under the C name it replaces: link it instead of the original object.\n\
686 #[unsafe(no_mangle)]\npub extern \"C\" fn {name}({params}){ret} {{\n {body}\n}}\n\n\
687 /// `{name}` as `rust_anything_{name}`, for shadow builds beside the original.\n\
688 // SAFETY: a name no C code defines.\n\
689 #[unsafe(no_mangle)]\npub extern \"C\" fn rust_anything_{name}({params}){ret} {{\n {body}\n}}",
690 f.file,
691 f.line,
692 name = f.name,
693 params = params.join(", "),
694 );
695 }
696 out
697}
698
699pub fn header(m: &Manifest) -> String {
701 let guard = format!("{}_H", m.lib_name().to_uppercase());
702 let mut out = format!(
703 "/* C API of the Rust port of `{}`, generated by rust-anything. */\n#ifndef {guard}\n#define {guard}\n\n\
704 #include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <sys/types.h>\n\n",
705 m.unit
706 );
707 let defs = c_struct_defs(m);
708 if !defs.is_empty() {
709 let _ = writeln!(out, "{defs}");
710 }
711 for f in &m.exports {
712 let _ = writeln!(out, "{};", c_prototype(f, &f.name));
713 }
714 out.push_str("\n/* The same functions under `rust_anything_` names, for shadow runs. */\n");
715 for f in &m.exports {
716 let _ = writeln!(
717 out,
718 "{};",
719 c_prototype(f, &format!("rust_anything_{}", f.name))
720 );
721 }
722 let _ = writeln!(out, "\n#endif /* {guard} */");
723 out
724}
725
726fn c_len_of(f: &ExportedFn, i: usize) -> String {
728 f.params
729 .iter()
730 .find(|p| kind(p) == CKind::Len(i))
731 .map_or_else(
732 || "0".to_string(),
733 |p| format!("({0} > 0 ? (size_t){0} : 0)", p.name),
734 )
735}
736
737pub fn shadow_c(m: &Manifest) -> String {
741 let mut out = String::from(
742 "/* Generated by rust-anything: runs the C original and the Rust port side by side.\n\
743 *\n * Build: compile the original sources with `-D<name>=<name>__original` for each function\n\
744 * below (see `shadow/flags.txt`), then link this file, those objects and the Rust library.\n\
745 * Build the Rust library with `cargo build --release --features shadow`, so it exports only the\n\
746 * `rust_anything_` names. Callers get the original's results; differences are counted and reported\n\
747 * on stderr.\n */\n\
748 #include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/types.h>\n\n\
749 long rust_anything_shadow_calls = 0;\nlong rust_anything_shadow_mismatches = 0;\n\n",
750 );
751 let defs = c_struct_defs(m);
752 if !defs.is_empty() {
753 let _ = writeln!(out, "{defs}");
754 }
755 for f in &m.exports {
756 let prototype = c_prototype(f, &f.name);
757 let _ = writeln!(
758 out,
759 "{};\n{};\n",
760 c_prototype(f, &format!("{}__original", f.name)),
761 c_prototype(f, &format!("rust_anything_{}", f.name))
762 );
763 let mut before = String::new();
764 let mut after = String::new();
765 let mut rust_args = Vec::new();
766 for (i, p) in f.params.iter().enumerate() {
767 match kind(p) {
768 CKind::Buffer => {
769 let len = c_len_of(f, i);
770 let _ = writeln!(
771 before,
772 " size_t len_{n} = {len};\n unsigned char *copy_{n} = len_{n} ? malloc(len_{n}) : NULL;\n \
773 if (copy_{n}) memcpy(copy_{n}, {n}, len_{n});",
774 n = p.name
775 );
776 let _ = writeln!(
777 after,
778 " if (copy_{n} && memcmp(copy_{n}, {n}, len_{n}) != 0) differ = 1;\n free(copy_{n});",
779 n = p.name
780 );
781 rust_args.push(format!("({})copy_{}", native(p), p.name));
782 }
783 CKind::Out => {
784 let ty = pointee(native(p));
785 let _ = writeln!(before, " {ty} copy_{n} = {n} ? *{n} : 0;", n = p.name);
786 let _ = writeln!(
787 after,
788 " if ({n} && memcmp(©_{n}, {n}, sizeof copy_{n}) != 0) differ = 1;",
789 n = p.name
790 );
791 rust_args.push(format!("{n} ? ©_{n} : NULL", n = p.name));
792 }
793 CKind::OutPtr(t) => {
794 let target = &f.params[t];
795 let base = if kind(target) == CKind::Buffer {
796 format!("copy_{}", target.name)
797 } else {
798 target.name.clone()
799 };
800 let _ = writeln!(
801 before,
802 " {} = {n} ? *{n} : NULL;",
803 c_decl(&inner(native(p)), &format!("copy_{}", p.name)),
804 n = p.name
805 );
806 let _ = writeln!(
807 after,
808 " if ({n} && ((*{n} == NULL) != (copy_{n} == NULL) || (*{n} && (const char *)*{n} - (const char *){t} != (const char *)copy_{n} - (const char *){base}))) differ = 1;",
809 n = p.name,
810 t = target.name
811 );
812 rust_args.push(format!("{n} ? ©_{n} : NULL", n = p.name));
813 }
814 _ => rust_args.push(p.name.clone()),
815 }
816 }
817 let args = f
818 .params
819 .iter()
820 .map(|p| p.name.as_str())
821 .collect::<Vec<_>>()
822 .join(", ");
823 let rust_args = rust_args.join(", ");
824 let void = f.native_return.as_deref() == Some("void");
825 let ret = f.native_return.as_deref().unwrap_or("int");
826 let compare_ret = match returns_into(f) {
827 _ if void => String::new(),
828 Some(i) => {
829 let target = &f.params[i];
830 let base = if kind(target) == CKind::Buffer {
831 format!("(const char *)copy_{}", target.name)
832 } else {
833 format!("(const char *){}", target.name)
834 };
835 format!(
836 " if ((expected == NULL) != (actual == NULL) || (expected && (const char *)expected - (const char *){} != (const char *)actual - {base})) differ = 1;\n",
837 target.name
838 )
839 }
840 None => match c_struct(&f.returns) {
841 Some(s) => s
842 .fields
843 .iter()
844 .map(|(_, n)| {
845 format!(
846 " if (memcmp(&expected.{n}, &actual.{n}, sizeof expected.{n}) != 0) differ = 1;\n"
847 )
848 })
849 .collect(),
850 None => {
851 " if (memcmp(&expected, &actual, sizeof expected) != 0) differ = 1;\n".into()
852 }
853 },
854 };
855 let (call_original, call_rust, give) = if void {
856 (
857 format!(" {}__original({args});\n", f.name),
858 format!(" rust_anything_{}({rust_args});\n", f.name),
859 String::new(),
860 )
861 } else {
862 (
863 format!(
864 " {} = {}__original({args});\n",
865 c_decl(ret, "expected"),
866 f.name
867 ),
868 format!(
869 " {} = rust_anything_{}({rust_args});\n",
870 c_decl(ret, "actual"),
871 f.name
872 ),
873 " return expected;\n".to_string(),
874 )
875 };
876 let _ = writeln!(
877 out,
878 "{prototype} {{\n int differ = 0;\n{before}{call_original}{call_rust}{compare_ret}{after}\
879 \x20 rust_anything_shadow_calls++;\n if (differ) {{\n\
880 \x20 rust_anything_shadow_mismatches++;\n if (rust_anything_shadow_mismatches <= 10)\n\
881 \x20 fprintf(stderr, \"[rust-anything] mismatch in {name}\\n\");\n }}\n{give}}}\n",
882 name = f.name
883 );
884 }
885 out
886}
887
888pub fn shadow_flags(m: &Manifest) -> String {
890 m.exports
891 .iter()
892 .map(|f| format!("-D{0}={0}__original", f.name))
893 .collect::<Vec<_>>()
894 .join(" ")
895 + "\n"
896}
897
898pub fn cargo_toml(m: &Manifest) -> String {
899 format!(
900 "[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2024\"\nrust-version = \"{MIN_RUST}\"\npublish = false\n\
901 description = \"Rust port of `{}`, generated by rust-anything\"\n\n\
902 [lib]\ncrate-type = [\"cdylib\", \"staticlib\", \"rlib\"]\n\n\
903 [features]\n# Export only the `rust_anything_` names, to link beside the original C code.\nshadow = []\n\n[dependencies]\n\n\
904 [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",
905 m.crate_name, m.unit
906 )
907}