Skip to content

Commit c5b1678

Browse files
committed
const_eval: Consider array length constant even if array is not
1 parent aa01891 commit c5b1678

File tree

4 files changed

+28
-3
lines changed

4 files changed

+28
-3
lines changed

compiler/rustc_const_eval/src/interpret/step.rs

+9-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
55
use rustc_middle::mir;
66
use rustc_middle::mir::interpret::{InterpResult, Scalar};
7+
use rustc_middle::ty;
78
use rustc_middle::ty::layout::LayoutOf;
89

910
use super::{InterpCx, Machine};
@@ -251,9 +252,14 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
251252

252253
Len(place) => {
253254
let src = self.eval_place(place)?;
254-
let mplace = self.force_allocation(&src)?;
255-
let len = mplace.len(self)?;
256-
self.write_scalar(Scalar::from_machine_usize(len, self), &dest)?;
255+
if let &ty::Array(_, len) = src.layout.ty.kind() {
256+
let len = self.const_to_op(len, Some(dest.layout))?;
257+
self.copy_op(&len, &dest, /*allow_transmute*/ false)?;
258+
} else {
259+
let mplace = self.force_allocation(&src)?;
260+
let len = mplace.len(self)?;
261+
self.write_scalar(Scalar::from_machine_usize(len, self), &dest)?;
262+
}
257263
}
258264

259265
AddressOf(_, place) | Ref(_, _, place) => {
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)