Skip to content

Commit

Permalink
const_prop_lint: Consider array length constant even if array is not
Browse files Browse the repository at this point in the history
  • Loading branch information
TheWastl committed Aug 5, 2022
1 parent f6f9d5e commit e4a4246
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
13 changes: 12 additions & 1 deletion compiler/rustc_mir_transform/src/const_prop_lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -501,12 +501,23 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
return None;
}

Rvalue::Len(len_place) => {
// To get the length of an array, we don't need to know the value.
let ty = len_place.ty(self.local_decls, self.tcx).ty;
if let &ty::Array(_, len) = ty.kind() {
return self.use_ecx(source_info, |this| {
let const_len = this.ecx.const_to_op(len, None)?;
let ecx_place = this.ecx.eval_place(place)?;
this.ecx.copy_op(&const_len, &ecx_place, /*allow_transmute*/ false)
});
}
}

// There's no other checking to do at this time.
Rvalue::Aggregate(..)
| Rvalue::Use(..)
| Rvalue::CopyForDeref(..)
| Rvalue::Repeat(..)
| Rvalue::Len(..)
| Rvalue::Cast(..)
| Rvalue::ShallowInitBox(..)
| Rvalue::Discriminant(..)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// build-fail
// Need to use build-fail because check doesn't run constant propagation.

fn main() {
let xs: [i32; 5] = [1, 2, 3, 4, 5];
let _ = &xs;
let _ = xs[7]; //~ ERROR this operation will panic at runtime
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
error: this operation will panic at runtime
--> $DIR/issue-98444-const-index-out-of-bounds.rs:7:13
|
LL | let _ = xs[7];
| ^^^^^ index out of bounds: the length is 5 but the index is 7
|
= note: `#[deny(unconditional_panic)]` on by default

error: aborting due to previous error

1 change: 1 addition & 0 deletions src/test/ui/consts/issue-65348.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// check-pass
#![allow(unconditional_panic)]

struct Generic<T>(T);

Expand Down

0 comments on commit e4a4246

Please sign in to comment.