Skip to content

Compile time error detection failing #98408

Closed
@lkurcak

Description

@lkurcak

Running the example at https://doc.rust-lang.org/rust-by-example/primitives/array.html, simplified here:

fn analyze_slice(slice: &[i32]) {
    println!("first element of the slice: {}", slice[0]);
    println!("the slice has {} elements", slice.len());
}

fn main() {
    let xs: [i32; 5] = [1, 2, 3, 4, 5];
    
    analyze_slice(&xs);
    
    // Out of bound indexing causes compile error
    println!("{}", xs[5]);
}

produces a runtime error ("panic"):

thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 5', src/main.rs:38:20
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

but the comment suggests that the compiler should be able to detect this out of bounds array access.

An anonymous user from https://boards.4channel.org/g/thread/87459430 wrote this regarding the issue (excerpt):

compiler/rustc_mir_transform/src/const_prop_lint.rs in the compiler implements this lint. This part is the culprit:

// Do not try creating references (#67862)
Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
    trace!("skipping AddressOf | Ref for {:?}", place);

    // This may be creating mutable references or immutable references to cells.
    // If that happens, the pointed to value could be mutated via that reference.
    // Since we aren't tracking references, the const propagator loses track of what
    // value the local has right now.
    // Thus, all locals that have their reference taken
    // must not take part in propagation.
    Self::remove_const(&mut self.ecx, place.local);

    return None;
}

It references this bug: #67862
Fixed by this PR: #68170
The analysis runs your code at compile time, but taking a reference to xs halts it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions