Skip to content

Commit e4a4246

Browse files
committed
const_prop_lint: Consider array length constant even if array is not
1 parent f6f9d5e commit e4a4246

File tree

4 files changed

+31
-1
lines changed

4 files changed

+31
-1
lines changed

compiler/rustc_mir_transform/src/const_prop_lint.rs

+12-1
Original file line numberDiff line numberDiff line change
@@ -501,12 +501,23 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
501501
return None;
502502
}
503503

504+
Rvalue::Len(len_place) => {
505+
// To get the length of an array, we don't need to know the value.
506+
let ty = len_place.ty(self.local_decls, self.tcx).ty;
507+
if let &ty::Array(_, len) = ty.kind() {
508+
return self.use_ecx(source_info, |this| {
509+
let const_len = this.ecx.const_to_op(len, None)?;
510+
let ecx_place = this.ecx.eval_place(place)?;
511+
this.ecx.copy_op(&const_len, &ecx_place, /*allow_transmute*/ false)
512+
});
513+
}
514+
}
515+
504516
// There's no other checking to do at this time.
505517
Rvalue::Aggregate(..)
506518
| Rvalue::Use(..)
507519
| Rvalue::CopyForDeref(..)
508520
| Rvalue::Repeat(..)
509-
| Rvalue::Len(..)
510521
| Rvalue::Cast(..)
511522
| Rvalue::ShallowInitBox(..)
512523
| Rvalue::Discriminant(..)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// build-fail
2+
// Need to use build-fail because check doesn't run constant propagation.
3+
4+
fn main() {
5+
let xs: [i32; 5] = [1, 2, 3, 4, 5];
6+
let _ = &xs;
7+
let _ = xs[7]; //~ ERROR this operation will panic at runtime
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: this operation will panic at runtime
2+
--> $DIR/issue-98444-const-index-out-of-bounds.rs:7:13
3+
|
4+
LL | let _ = xs[7];
5+
| ^^^^^ index out of bounds: the length is 5 but the index is 7
6+
|
7+
= note: `#[deny(unconditional_panic)]` on by default
8+
9+
error: aborting due to previous error
10+

src/test/ui/consts/issue-65348.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// check-pass
2+
#![allow(unconditional_panic)]
23

34
struct Generic<T>(T);
45

0 commit comments

Comments
 (0)