Rollup merge of #61598 - estebank:const-idx, r=oli-obk
Handle index out of bound errors during const eval without panic Fix #61595
This commit is contained in:
commit
a0d05150c9
3 changed files with 36 additions and 2 deletions
|
@ -348,8 +348,12 @@ where
|
||||||
offsets[usize::try_from(field).unwrap()],
|
offsets[usize::try_from(field).unwrap()],
|
||||||
layout::FieldPlacement::Array { stride, .. } => {
|
layout::FieldPlacement::Array { stride, .. } => {
|
||||||
let len = base.len(self)?;
|
let len = base.len(self)?;
|
||||||
assert!(field < len, "Tried to access element {} of array/slice with length {}",
|
if field >= len {
|
||||||
field, len);
|
// This can be violated because this runs during promotion on code where the
|
||||||
|
// type system has not yet ensured that such things don't happen.
|
||||||
|
debug!("Tried to access element {} of array/slice with length {}", field, len);
|
||||||
|
return err!(BoundsCheck { len, index: field });
|
||||||
|
}
|
||||||
stride * field
|
stride * field
|
||||||
}
|
}
|
||||||
layout::FieldPlacement::Union(count) => {
|
layout::FieldPlacement::Union(count) => {
|
||||||
|
|
6
src/test/ui/consts/array-literal-index-oob.rs
Normal file
6
src/test/ui/consts/array-literal-index-oob.rs
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
fn main() {
|
||||||
|
&{[1, 2, 3][4]};
|
||||||
|
//~^ ERROR index out of bounds
|
||||||
|
//~| ERROR reaching this expression at runtime will panic or abort
|
||||||
|
//~| ERROR this expression will panic at runtime
|
||||||
|
}
|
24
src/test/ui/consts/array-literal-index-oob.stderr
Normal file
24
src/test/ui/consts/array-literal-index-oob.stderr
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
error: index out of bounds: the len is 3 but the index is 4
|
||||||
|
--> $DIR/array-literal-index-oob.rs:2:7
|
||||||
|
|
|
||||||
|
LL | &{[1, 2, 3][4]};
|
||||||
|
| ^^^^^^^^^^^^
|
||||||
|
|
|
||||||
|
= note: #[deny(const_err)] on by default
|
||||||
|
|
||||||
|
error: this expression will panic at runtime
|
||||||
|
--> $DIR/array-literal-index-oob.rs:2:5
|
||||||
|
|
|
||||||
|
LL | &{[1, 2, 3][4]};
|
||||||
|
| ^^^^^^^^^^^^^^^ index out of bounds: the len is 3 but the index is 4
|
||||||
|
|
||||||
|
error: reaching this expression at runtime will panic or abort
|
||||||
|
--> $DIR/array-literal-index-oob.rs:2:7
|
||||||
|
|
|
||||||
|
LL | &{[1, 2, 3][4]};
|
||||||
|
| --^^^^^^^^^^^^-
|
||||||
|
| |
|
||||||
|
| index out of bounds: the len is 3 but the index is 4
|
||||||
|
|
||||||
|
error: aborting due to 3 previous errors
|
||||||
|
|
Loading…
Reference in a new issue