Skip to content

Unreachable code is not borrow-checked #91377

Closed
@SNCPlay42

Description

@SNCPlay42

I tried this code:

fn main() {
    let a = 1;
    
    loop {}
        
    let z = &a;
    let x = &mut a;
    let y = &mut a;
    
    *x = 2;
    *y = 3;
    
    println!("{}", *z);
}

I expected this to fail to compile, since I create one immutable and two mutable borrows of an immutable variable that all have to be alive at once.

It's not unsound to accept this, since none of it is even codegened, but unreachable code is otherwise held to the same standards as reachable code (must type-check, etc.).

Instead, this code is accepted with only warnings:

warning: unreachable statement
 --> src/lib.rs:6:5
  |
4 |     loop {}
  |     ------- any code following this expression is unreachable
5 |         
6 |     let z = &a;
  |     ^^^^^^^^^^^ unreachable statement
  |
  = note: `#[warn(unreachable_code)]` on by default

warning: unused variable: `a`
 --> src/lib.rs:2:9
  |
2 |     let a = 1;
  |         ^ help: if this is intentional, prefix it with an underscore: `_a`
  |
  = note: `#[warn(unused_variables)]` on by default

warning: `playground` (lib) generated 2 warnings

On Rust 1.35 and before, this code was rejected in the 2015 edition (which used the old lexical borrowck).

@rustbot label regression-from-stable-to-stable

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerC-discussionCategory: Discussion or questions that doesn't represent real issues.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions