rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
96.92k stars 12.53k forks source link

rustc since 1.36 accepts invalid code after return #130433

Open shao-hua-li opened 3 days ago

shao-hua-li commented 3 days ago

Code

I tried this code:

fn foo() -> u8 {
    return 0;
    let a: u8 = 1;
    a = 2; // error: second write to an immutable variable
    return a;
}
fn main() -> () {
    println!("{}", foo());
}

rustc-1.35 rejects the code and says:

error[E0384]: cannot assign twice to immutable variable `a`
 --> <source>:4:5
  |
3 |     let a: u8 = 1;
  |         - first assignment to `a`
4 |     a = 2;
  |     ^^^^^ cannot assign twice to immutable variable

Current rustc accepts the code

I acknowledge that the invalid write happens in a dead region, but still report it as all rustc versions reject the following code:

fn foo() -> u8 {
    if true {
        return 0;
    }
    let a: u8 = 1;
    a = 2; // error: second write to an immutable variable
    return a;
}
fn main() -> () {
    println!("{}", foo());
}
compiler-errors commented 3 days ago

This is due to the fact that assignment and move analysis is performed on MIR, which doesn't have those post-return statements.

I don't consider this to be a bug, since the code is truly unreachable.