Skip to content

Commit 6b67c46

Browse files
committed
Compute array length from type for unconditional panic.
1 parent 14f303b commit 6b67c46

File tree

3 files changed

+27
-7
lines changed

3 files changed

+27
-7
lines changed

compiler/rustc_mir_transform/src/known_panics_lint.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -600,13 +600,15 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
600600
}
601601

602602
Len(place) => {
603-
let len = match self.get_const(place)? {
604-
Value::Immediate(src) => src.len(&self.ecx).discard_err()?,
605-
Value::Aggregate { fields, .. } => fields.len() as u64,
606-
Value::Uninit => match place.ty(self.local_decls(), self.tcx).ty.kind() {
607-
ty::Array(_, n) => n.try_eval_target_usize(self.tcx, self.param_env)?,
608-
_ => return None,
609-
},
603+
let len = if let ty::Array(_, n) = place.ty(self.local_decls(), self.tcx).ty.kind()
604+
{
605+
n.try_eval_target_usize(self.tcx, self.param_env)?
606+
} else {
607+
match self.get_const(place)? {
608+
Value::Immediate(src) => src.len(&self.ecx).discard_err()?,
609+
Value::Aggregate { fields, .. } => fields.len() as u64,
610+
Value::Uninit => return None,
611+
}
610612
};
611613
ImmTy::from_scalar(Scalar::from_target_usize(len, self), layout).into()
612614
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
//@ build-fail
2+
3+
fn main() {
4+
// MIR encodes this as a reborrow from a promoted constant.
5+
// But the array lenth can still be gotten from the type.
6+
let slice = &[0, 1];
7+
let _ = slice[2]; //~ ERROR: this operation will panic at runtime [unconditional_panic]
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: this operation will panic at runtime
2+
--> $DIR/unconditional_panic_promoted.rs:7:13
3+
|
4+
LL | let _ = slice[2];
5+
| ^^^^^^^^ index out of bounds: the length is 2 but the index is 2
6+
|
7+
= note: `#[deny(unconditional_panic)]` on by default
8+
9+
error: aborting due to 1 previous error
10+

0 commit comments

Comments
 (0)