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