Skip to content

Commit e642406

Browse files
fix[missing_asserts_for_indexing]: ignore asserts after indexing
1 parent ad05bc0 commit e642406

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
@@ -68,4 +68,10 @@ pub fn issue11856(values: &[i32]) -> usize {
6868
ascending.len()
6969
}
7070

71+
fn assert_after_indexing(v1: &[u8]) {
72+
let _ = v1[1] + v1[2];
73+
//~^ ERROR: indexing into a slice multiple times without an `assert`
74+
assert!(v1.len() > 2);
75+
}
76+
7177
fn main() {}

tests/ui/missing_asserts_for_indexing_unfixable.stderr

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

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

0 commit comments

Comments
 (0)