Skip to content

Commit

Permalink
const_eval: 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 Jul 22, 2022
1 parent aa01891 commit c5b1678
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 3 deletions.
12 changes: 9 additions & 3 deletions compiler/rustc_const_eval/src/interpret/step.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use rustc_middle::mir;
use rustc_middle::mir::interpret::{InterpResult, Scalar};
use rustc_middle::ty;
use rustc_middle::ty::layout::LayoutOf;

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

Len(place) => {
let src = self.eval_place(place)?;
let mplace = self.force_allocation(&src)?;
let len = mplace.len(self)?;
self.write_scalar(Scalar::from_machine_usize(len, self), &dest)?;
if let &ty::Array(_, len) = src.layout.ty.kind() {
let len = self.const_to_op(len, Some(dest.layout))?;
self.copy_op(&len, &dest, /*allow_transmute*/ false)?;
} else {
let mplace = self.force_allocation(&src)?;
let len = mplace.len(self)?;
self.write_scalar(Scalar::from_machine_usize(len, self), &dest)?;
}
}

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

Please sign in to comment.