immunant / c2rust

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

rewriter: do not add hypothetical lifetimes to structs with type alias fields that gain a hypothetical parameter #957

Open aneksteind opened 1 year ago

aneksteind commented 1 year ago
type MyPtr = *mut i32;

struct MyPtrStruct {
    x: MyPtr
}

gets rewritten to

type MyPtr = *mut i32;

struct MyPtrStruct<'h1> {
    x: MyPtr
}
aneksteind commented 1 year ago

@spernsteiner what are your thoughts on this one?

spernsteiner commented 1 year ago

I'm a little surprised by that rewriting - rewrite::ty usually unfolds type aliases if it needs to rewrite underneath them, so I would expect it to produce x: &'h1 i32 instead.

It might be nice for readability if we treated type aliases more like structs and produced a rewrite like type MyPtr<'h2> = &'h2 i32;. But this would be more difficult to implement because type aliases are already unfolded at the MIR level (for example, the type of x would be TyKind::RawPtr), which makes it hard to tell where a given alias is actually used. Also, we'd need to decide what to do about the case where some uses of MyPtr need to become &i32 while others need to become &mut i32.

aneksteind commented 1 year ago

Why does the transpiler generate type aliases at all?

kkysen commented 1 year ago

Why does the transpiler generate type aliases at all?

It generates them for C typedefs.

kkysen commented 1 year ago

Also, we'd need to decide what to do about the case where some uses of MyPtr need to become &i32 while others need to become &mut i32.

If there are cases like this, I think we should ignore/write through the typedef/type alias. C typdefs are often not written const-correctly.

aneksteind commented 1 year ago

I wonder if there is a case for delaying the type alias generation until after the semantics of the types and their permissions have been nailed down. We could then generate something like Alias and AliasMut

spernsteiner commented 1 year ago

Yes, I think our approach to preserving aliases would have to be to split them into multiple variants depending on what underlying types we want.