Repository: immunant/c2rust (language: rust)

Issue:
Casting bool to pointer type results in invalid Rust
The fix should be the same as #1030, but presumably with something like `size_t` as the intermediate type.

(Why, you might ask, would anyone ever do this in real code. The answer is that C doesn't have generics, so projects will have, say, a single hash table type with `void *` values, and store booleans in it by casting.)


Discussion / hints:
This code reproduces this bug:
```C
#include <stdbool.h>

void f(bool b) {
    void* x = (void*)b;
}
```
It gets translated to:
```rust
#[no_mangle]
pub unsafe extern "C" fn f(mut b: bool) {
    let mut x: *mut libc::c_void = b as *mut libc::c_void;
}
```
which does not compile (E0606).

Fix patch:
diff --git a/c2rust-transpile/src/translator/mod.rs b/c2rust-transpile/src/translator/mod.rs
index 10ba422ee2..91b79a274a 100644
--- a/c2rust-transpile/src/translator/mod.rs
+++ b/c2rust-transpile/src/translator/mod.rs
@@ -4282,6 +4282,13 @@ impl<'c> Translation<'c> {
                             target_ty,
                         )))
                     })
+                } else if target_ty_ctype.is_pointer() && source_ty_kind.is_bool() {
+                    val.and_then(|x| {
+                        Ok(WithStmts::new_val(mk().cast_expr(
+                            mk().cast_expr(x, mk().path_ty(vec!["libc", "size_t"])),
+                            target_ty,
+                        )))
+                    })
                 } else {
                     // Other numeric casts translate to Rust `as` casts,
                     // unless the cast is to a function pointer then use `transmute`.


Test patch:
diff --git a/tests/casts/src/casts.c b/tests/casts/src/casts.c
index 1222683017..f881e46314 100644
--- a/tests/casts/src/casts.c
+++ b/tests/casts/src/casts.c
@@ -30,4 +30,5 @@ void cast_stuff(void) {
 
         bool b = true;
         float x15 = b;
+        void* x16 = (void*)b;
 }