immunant / c2rust

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

analyze: when rewriting, omit unused hypothetical regions #997

Closed spernsteiner closed 11 months ago

spernsteiner commented 1 year ago

Sometimes, we add hypothetical regions to a type, but the rewriting we choose for the field types results in those region parameters going unused:

struct S {
    ptr: *mut u8,
}

#[c2rust_analyze_test::fixed_signature]
unsafe fn f(x: *mut *mut u8) {}

unsafe fn g(s: *mut S) {
    f(ptr::addr_of_mut!((*s).ptr));
}

Rewritten output:

struct S<'h0> {
    ptr: *mut u8,
}

#[c2rust_analyze_test::fixed_signature]
unsafe fn f(x: *mut *mut u8) {}

unsafe fn g(s: &(S)) {
    f(core::ptr::addr_of!(*&mut ((*s).ptr)).cast_mut());
}

Here, we add a hypothetical region param 'h0 to S for it to use in the type of ptr, but we end up leaving ptr as a raw pointer type, which doesn't need a region. This causes rustc to report an error: "parameter 'h0 is never used". We would have similar issues if we chose to rewrite ptr into Box or Rc.

We need a postprocessing pass that can examine the rewrites (TypeDescs) for ADT field types and decide which of the hypothetical regions params should actually be emitted during rewriting.

aneksteind commented 1 year ago

@spernsteiner i'm happy to take this one once i'm done with other tasks, if you want to re-assign to me

spernsteiner commented 1 year ago

I self-assigned this first because it's the most immediate blocker for being able to filter exactly what gets rewritten (currently lifetimes are always added) and I plan to start on it immediately, and second because I'd like to get a better understanding of how exactly lifetime parameters are handled at the moment, since we'll need to extend that sometime soon to work with functions and possibly lifetime bounds (as in 'a: 'b).

aneksteind commented 1 year ago

Sounds good, and as an FYI I've been working on lifetimes in functions