immunant / c2rust

Migrate C code to Rust
https://c2rust.com/
Other
3.79k stars 219 forks source link

`c2rust transpile`: When casting `bool`s to floats, go through the integral type `u8` #1030

Closed dgherzka closed 7 months ago

dgherzka commented 9 months ago

Previously, C code that cast bools to floating types, like this

#include <stdbool.h>

void cast_stuff(void) {
    bool b = true;
    float x15 = b;
}

would try to do so directly in Rust, like this

#[no_mangle]
pub unsafe extern "C" fn cast_stuff() {
    let mut b: bool = 1 as libc::c_int != 0;
    let mut x15: libc::c_float = b as libc::c_float;
}

which isn't allowed, resulting in errors like this

error[E0606]: casting `bool` as `f32` is invalid
  --> src/casts.rs:31:34
   |
31 |     let mut x15: libc::c_float = b as libc::c_float;
   |                                  ^^^^^^^^^^^^^^^^^^
   |
   = help: cast through an integer first

This fixes things by emitting this Rust instead by casting through the integral type u8:

#[no_mangle]
pub unsafe extern "C" fn cast_stuff() {
    let mut b: bool = 1 as libc::c_int != 0;
    let mut x15: libc::c_float = b as u8 as libc::c_float;
}
dgherzka commented 9 months ago

It wasn't clear to me whether this should be implemented as a new CastKind (BooleanToFloating) or treated as a special case of IntegralToFloating.

dgherzka commented 8 months ago

Hi @kkysen, pinging you because I see that you are a major contributor to this project. I apologize if you aren't the right person to talk to. What's the process for getting this reviewed? Thanks in advance!

dgherzka commented 8 months ago

Sorry for continuing to tag people, I just want to try one more time. @spernsteiner are you the right person to talk to? Please let me know if I should just abandon this.

kkysen commented 8 months ago

Hi @dgherzka! Sorry for taking a while to review this; I saw your ping but forgot to take a look. I'll review it now, and your other PRs and issues.