Skip to content

Commit 42c06fe

Browse files
estebankMark-Simulacrum
authored andcommitted
Handle index out of bound errors during const eval without panic
1 parent 2a335ef commit 42c06fe

File tree

3 files changed

+36
-2
lines changed

3 files changed

+36
-2
lines changed

src/librustc_mir/interpret/place.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -361,8 +361,12 @@ where
361361
offsets[usize::try_from(field).unwrap()],
362362
layout::FieldPlacement::Array { stride, .. } => {
363363
let len = base.len(self)?;
364-
assert!(field < len, "Tried to access element {} of array/slice with length {}",
365-
field, len);
364+
if field >= len {
365+
// This can be violated because this runs during promotion on code where the
366+
// type system has not yet ensured that such things don't happen.
367+
debug!("Tried to access element {} of array/slice with length {}", field, len);
368+
return err!(BoundsCheck { len, index: field });
369+
}
366370
stride * field
367371
}
368372
layout::FieldPlacement::Union(count) => {
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
fn main() {
2+
&{[1, 2, 3][4]};
3+
//~^ ERROR index out of bounds
4+
//~| ERROR reaching this expression at runtime will panic or abort
5+
//~| ERROR this expression will panic at runtime
6+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
error: index out of bounds: the len is 3 but the index is 4
2+
--> $DIR/array-literal-index-oob.rs:2:7
3+
|
4+
LL | &{[1, 2, 3][4]};
5+
| ^^^^^^^^^^^^
6+
|
7+
= note: #[deny(const_err)] on by default
8+
9+
error: this expression will panic at runtime
10+
--> $DIR/array-literal-index-oob.rs:2:5
11+
|
12+
LL | &{[1, 2, 3][4]};
13+
| ^^^^^^^^^^^^^^^ index out of bounds: the len is 3 but the index is 4
14+
15+
error: reaching this expression at runtime will panic or abort
16+
--> $DIR/array-literal-index-oob.rs:2:7
17+
|
18+
LL | &{[1, 2, 3][4]};
19+
| --^^^^^^^^^^^^-
20+
| |
21+
| index out of bounds: the len is 3 but the index is 4
22+
23+
error: aborting due to 3 previous errors
24+

0 commit comments

Comments
 (0)