Skip to content

Commit ef6240a

Browse files
committedJun 12, 2019
Handle index out of bound errors during const eval without panic
1 parent 24ddd16 commit ef6240a

File tree

3 files changed

+36
-2
lines changed

3 files changed

+36
-2
lines changed
 

‎src/librustc_mir/interpret/place.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -348,8 +348,12 @@ where
348348
offsets[usize::try_from(field).unwrap()],
349349
layout::FieldPlacement::Array { stride, .. } => {
350350
let len = base.len(self)?;
351-
assert!(field < len, "Tried to access element {} of array/slice with length {}",
352-
field, len);
351+
if field >= len {
352+
// This can be violated because this runs during promotion on code where the
353+
// type system has not yet ensured that such things don't happen.
354+
debug!("Tried to access element {} of array/slice with length {}", field, len);
355+
return err!(BoundsCheck { len, index: field });
356+
}
353357
stride * field
354358
}
355359
layout::FieldPlacement::Union(count) => {
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+
}
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)