You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When translating C code with a const variable, c2rust incorrectly generates a mutable static mut variable in Rust. This behavior is inconsistent with the immutability semantics of const in C.
Source C code
#include<stdio.h>constintx=1;
intmain() {
printf("Value of x: %d\n", x);
// x=5; // this is compile error in Creturn0;
}
Translated Rust Code
#[no_mangle]pubstaticmut x: libc::c_int = 1as libc::c_int;unsafefnmain_0() -> libc::c_int{printf(b"Value of x: %d\n\0"as*constu8as*const libc::c_char, x);// x=5; // this line is okay here as x is declared as mutablereturn0as libc::c_int;}
In the original C code, x is declared as const, meaning it is immutable. However, c2rust generates static mut x, which makes x mutable in Rust. This is incorrect and violates the immutability semantics of the original C code.
I think this line creates the problem as it forcefully makes all static contexts mutable!
// Force mutability due to the potential for raw pointers occurring in the type// and because we may be assigning to these variables in the external initializerletmut static_def = static_def.span(span).mutbl();
Before this, the mutbl for static context ctf.static_ is ignored here
The reason for this is a bit complex. consts in C that contain pointers have to be translated as static muts because internal raw pointers are not allowed in consts in Rust. So we'd have to detect which cases can be const and which ones have to be static muts, which isn't trivial (though we should do it). What's allowed in consts and static muts has been changing and under discussion recently, so we also want to keep that in mind as well.
Description
When translating C code with a
const
variable,c2rust
incorrectly generates a mutablestatic mut
variable in Rust. This behavior is inconsistent with the immutability semantics ofconst
in C.Source C code
Translated Rust Code
In the original C code,
x
is declared asconst
, meaning it is immutable. However, c2rust generatesstatic mut x
, which makesx
mutable in Rust. This is incorrect and violates the immutability semantics of the original C code.Expected Declaration
The text was updated successfully, but these errors were encountered: