Skip to content

Commit 1546cc4

Browse files
committed
Fix ICE in OUT_OF_BOUNDS_INDEXING with ranges
1 parent 893d6e8 commit 1546cc4

File tree

2 files changed

+22
-11
lines changed

2 files changed

+22
-11
lines changed

src/array_indexing.rs

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ impl LateLintPass for ArrayIndexing {
8383
eval_const_expr_partial(cx.tcx, end, ExprTypeChecked, None)).map(|v| v.ok());
8484

8585
if let Some((start, end)) = to_const_range(start, end, range.limits, size) {
86-
if start >= size || end >= size {
86+
if start > size || end > size {
8787
utils::span_lint(cx,
8888
OUT_OF_BOUNDS_INDEXING,
8989
e.span,
@@ -109,14 +109,11 @@ impl LateLintPass for ArrayIndexing {
109109
}
110110
}
111111

112-
/// Returns an option containing a tuple with the start and end (exclusive) of the range
113-
///
114-
/// Note: we assume the start and the end of the range are unsigned, since array slicing
115-
/// works only on usize
112+
/// Returns an option containing a tuple with the start and end (exclusive) of the range.
116113
fn to_const_range(start: Option<Option<ConstVal>>,
117-
end: Option<Option<ConstVal>>,
118-
limits: RangeLimits,
119-
array_size: ConstInt)
114+
end: Option<Option<ConstVal>>,
115+
limits: RangeLimits,
116+
array_size: ConstInt)
120117
-> Option<(ConstInt, ConstInt)> {
121118
let start = match start {
122119
Some(Some(ConstVal::Integral(x))) => x,
@@ -127,13 +124,13 @@ fn to_const_range(start: Option<Option<ConstVal>>,
127124
let end = match end {
128125
Some(Some(ConstVal::Integral(x))) => {
129126
if limits == RangeLimits::Closed {
130-
x
127+
(x + ConstInt::Infer(1)).expect("such a big array is not realistic")
131128
} else {
132-
(x - ConstInt::Infer(1)).expect("x > 0")
129+
x
133130
}
134131
}
135132
Some(_) => return None,
136-
None => (array_size - ConstInt::Infer(1)).expect("array_size > 0"),
133+
None => array_size
137134
};
138135

139136
Some((start, end))

tests/compile-fail/array_indexing.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ fn main() {
1616
&x[0...4]; //~ERROR: range is out of bounds
1717
&x[..];
1818
&x[1..];
19+
&x[4..];
20+
&x[5..]; //~ERROR: range is out of bounds
1921
&x[..4];
2022
&x[..5]; //~ERROR: range is out of bounds
2123

@@ -24,4 +26,16 @@ fn main() {
2426
&y[1..2]; //~ERROR: slicing may panic
2527
&y[..];
2628
&y[0...4]; //~ERROR: slicing may panic
29+
30+
let empty: [i8; 0] = [];
31+
empty[0]; //~ERROR: const index is out of bounds
32+
&empty[1..5]; //~ERROR: range is out of bounds
33+
&empty[0...4]; //~ERROR: range is out of bounds
34+
&empty[..];
35+
&empty[0..];
36+
&empty[0..0];
37+
&empty[0...0]; //~ERROR: range is out of bounds
38+
&empty[..0];
39+
&empty[1..]; //~ERROR: range is out of bounds
40+
&empty[..4]; //~ERROR: range is out of bounds
2741
}

0 commit comments

Comments
 (0)