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