Skip to content

Commit d403a4a

Browse files
committed
Handle macros with avoidable_slice_indexing lint
1 parent c7ac557 commit d403a4a

File tree

3 files changed

+52
-1
lines changed

3 files changed

+52
-1
lines changed

clippy_lints/src/avoidable_slice_indexing.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use clippy_utils::consts::{constant, Constant};
22
use clippy_utils::diagnostics::span_lint_and_then;
33
use clippy_utils::higher::IfLet;
44
use clippy_utils::ty::implements_trait;
5-
use clippy_utils::{is_lint_allowed, meets_msrv, msrvs};
5+
use clippy_utils::{in_macro, is_expn_of, is_lint_allowed, meets_msrv, msrvs};
66
use if_chain::if_chain;
77
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
88
use rustc_errors::Applicability;
@@ -69,6 +69,7 @@ impl_lint_pass!(AvoidableSliceIndexing => [AVOIDABLE_SLICE_INDEXING]);
6969
impl LateLintPass<'_> for AvoidableSliceIndexing {
7070
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
7171
if_chain! {
72+
if !in_macro(expr.span) || is_expn_of(expr.span, "if_chain").is_some();
7273
if let Some(IfLet {let_pat, if_then, ..}) = IfLet::hir(cx, expr);
7374
if !is_lint_allowed(cx, AVOIDABLE_SLICE_INDEXING, expr.hir_id);
7475
if meets_msrv(self.msrv.as_ref(), &msrvs::SLICE_PATTERNS);
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#![deny(clippy::avoidable_slice_indexing)]
2+
3+
extern crate if_chain;
4+
use if_chain::if_chain;
5+
6+
macro_rules! if_let_slice_macro {
7+
() => {
8+
// This would normally be linted
9+
let slice: Option<&[u32]> = Some(&[1, 2, 3]);
10+
if let Some(slice) = slice {
11+
println!("{}", slice[0]);
12+
}
13+
};
14+
}
15+
16+
fn main() {
17+
// Don't lint this
18+
if_let_slice_macro!();
19+
20+
// Do lint this
21+
if_chain! {
22+
let slice: Option<&[u32]> = Some(&[1, 2, 3]);
23+
if let Some(slice) = slice;
24+
then {
25+
println!("{}", slice[0]);
26+
}
27+
}
28+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
error: this slice can be deconstructured to avoid indexing
2+
--> $DIR/slice_indexing_in_macro.rs:24:21
3+
|
4+
LL | if let Some(slice) = slice;
5+
| ^^^^^
6+
|
7+
note: the lint level is defined here
8+
--> $DIR/slice_indexing_in_macro.rs:1:9
9+
|
10+
LL | #![deny(clippy::avoidable_slice_indexing)]
11+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
12+
help: try destructing the slice with a pattern here
13+
|
14+
LL | if let Some([slice_0, ..]) = slice;
15+
| ~~~~~~~~~~~~~
16+
help: and replacing the index expressions here
17+
|
18+
LL | println!("{}", slice_0);
19+
| ~~~~~~~
20+
21+
error: aborting due to previous error
22+

0 commit comments

Comments
 (0)