Skip to content

"this expression will panic at run-time" warnings can't be suppressed  #45850

@emilio

Description

@emilio

Here's a reduced test-case:

let a = [0u8; 2usize];
println!("{}", a[0]);
println!("{}", a[1]);

if a.len() == 3 {
    println!("{}", a[2]);
}

Now some background.

In Servo we generate large amounts of rust code using different systems. Today @upsuper was trying to generate shared code for two different structs that have different fields, let's simplify it as:

struct Foo {
    bar: [u8; 2],
}

struct Bar {
    bar: [u8; 3],
}

To generate shared code for both, he wanted to do something like:

let instance = ${var}; // Instance is either `Foo` or `Bar`, we'll expand this twice.
do_something_with(instance.bar[0]);
do_something_with(instance.bar[1]);
if instance.bar.len() == 3 {
    do_something_with(instance.bar[2]);
}

However, that generates an unsuppresable warning like:

^^^^ index out of bounds: the len is 2 but the index is 2

So it seems that Rust doesn't account for that code being unreachable in the Foo case.

In any case, being able to suppress that warning would've made this code straight-forward. Instead of that we probably need to work around it with something like:

#[inline(always)]
fn doit(a: &[u8]) {
    do_something_with(a[0]);
    do_something_with(a[1]);
    if a.len() == 3 {
        do_something_with(a[2]);
    }
}

doit(&instance.bar)

Which is not great.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions