Skip to content

Commit 31236a4

Browse files
fix[missing_asserts_for_indexing]: ignore asserts after indexing
1 parent 8178530 commit 31236a4

File tree

3 files changed

+37
-9
lines changed

3 files changed

+37
-9
lines changed

clippy_lints/src/missing_asserts_for_indexing.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -244,14 +244,16 @@ fn check_index<'hir>(cx: &LateContext<'_>, expr: &'hir Expr<'hir>, map: &mut Uni
244244
assert_span,
245245
slice,
246246
} => {
247-
*entry = IndexEntry::AssertWithIndex {
248-
highest_index: index,
249-
asserted_len: *asserted_len,
250-
assert_span: *assert_span,
251-
slice,
252-
indexes: vec![expr.span],
253-
comparison: *comparison,
254-
};
247+
if slice.span.lo() > assert_span.lo() {
248+
*entry = IndexEntry::AssertWithIndex {
249+
highest_index: index,
250+
asserted_len: *asserted_len,
251+
assert_span: *assert_span,
252+
slice,
253+
indexes: vec![expr.span],
254+
comparison: *comparison,
255+
};
256+
}
255257
},
256258
IndexEntry::IndexWithoutAssert {
257259
highest_index, indexes, ..
@@ -287,6 +289,7 @@ fn check_assert<'hir>(cx: &LateContext<'_>, expr: &'hir Expr<'hir>, map: &mut Un
287289
indexes,
288290
slice,
289291
} = entry
292+
&& expr.span.lo() <= slice.span.lo()
290293
{
291294
*entry = IndexEntry::AssertWithIndex {
292295
highest_index: *highest_index,

tests/ui/missing_asserts_for_indexing_unfixable.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,10 @@ pub fn issue11856(values: &[i32]) -> usize {
7373
ascending.len()
7474
}
7575

76+
fn assert_after_indexing(v1: &[u8]) {
77+
let _ = v1[1] + v1[2];
78+
//~^ ERROR: indexing into a slice multiple times without an `assert`
79+
assert!(v1.len() > 2);
80+
}
81+
7682
fn main() {}

tests/ui/missing_asserts_for_indexing_unfixable.stderr

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,5 +180,24 @@ LL | let _ = x[0] + x[1];
180180
| ^^^^
181181
= note: asserting the length before indexing will elide bounds checks
182182

183-
error: aborting due to 8 previous errors
183+
error: indexing into a slice multiple times without an `assert`
184+
--> tests/ui/missing_asserts_for_indexing_unfixable.rs:77:13
185+
|
186+
LL | let _ = v1[1] + v1[2];
187+
| ^^^^^^^^^^^^^
188+
|
189+
= help: consider asserting the length before indexing: `assert!(v1.len() > 2);`
190+
note: slice indexed here
191+
--> tests/ui/missing_asserts_for_indexing_unfixable.rs:77:13
192+
|
193+
LL | let _ = v1[1] + v1[2];
194+
| ^^^^^
195+
note: slice indexed here
196+
--> tests/ui/missing_asserts_for_indexing_unfixable.rs:77:21
197+
|
198+
LL | let _ = v1[1] + v1[2];
199+
| ^^^^^
200+
= note: asserting the length before indexing will elide bounds checks
201+
202+
error: aborting due to 9 previous errors
184203

0 commit comments

Comments
 (0)