@@ -2,7 +2,7 @@ use clippy_config::Conf;
2
2
use clippy_utils:: consts:: { ConstEvalCtxt , Constant } ;
3
3
use clippy_utils:: diagnostics:: { span_lint, span_lint_and_then} ;
4
4
use clippy_utils:: ty:: { deref_chain, get_adt_inherent_method} ;
5
- use clippy_utils:: { higher, is_from_proc_macro} ;
5
+ use clippy_utils:: { higher, is_from_proc_macro, is_in_test } ;
6
6
use rustc_ast:: ast:: RangeLimits ;
7
7
use rustc_hir:: { Expr , ExprKind } ;
8
8
use rustc_lint:: { LateContext , LateLintPass } ;
@@ -96,12 +96,14 @@ declare_clippy_lint! {
96
96
impl_lint_pass ! ( IndexingSlicing => [ INDEXING_SLICING , OUT_OF_BOUNDS_INDEXING ] ) ;
97
97
98
98
pub struct IndexingSlicing {
99
+ allow_indexing_slicing_in_tests : bool ,
99
100
suppress_restriction_lint_in_const : bool ,
100
101
}
101
102
102
103
impl IndexingSlicing {
103
104
pub fn new ( conf : & ' static Conf ) -> Self {
104
105
Self {
106
+ allow_indexing_slicing_in_tests : conf. allow_indexing_slicing_in_tests ,
105
107
suppress_restriction_lint_in_const : conf. suppress_restriction_lint_in_const ,
106
108
}
107
109
}
@@ -122,6 +124,7 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
122
124
{
123
125
let note = "the suggestion might not be applicable in constant blocks" ;
124
126
let ty = cx. typeck_results ( ) . expr_ty ( array) . peel_refs ( ) ;
127
+ let allowed_in_tests = self . allow_indexing_slicing_in_tests && is_in_test ( cx. tcx , expr. hir_id ) ;
125
128
if let Some ( range) = higher:: Range :: hir ( index) {
126
129
// Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..]
127
130
if let ty:: Array ( _, s) = ty. kind ( ) {
@@ -171,6 +174,10 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
171
174
( None , None ) => return , // [..] is ok.
172
175
} ;
173
176
177
+ if allowed_in_tests {
178
+ return ;
179
+ }
180
+
174
181
span_lint_and_then ( cx, INDEXING_SLICING , expr. span , "slicing may panic" , |diag| {
175
182
diag. help ( help_msg) ;
176
183
@@ -209,6 +216,10 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
209
216
}
210
217
}
211
218
219
+ if allowed_in_tests {
220
+ return ;
221
+ }
222
+
212
223
span_lint_and_then ( cx, INDEXING_SLICING , expr. span , "indexing may panic" , |diag| {
213
224
diag. help ( "consider using `.get(n)` or `.get_mut(n)` instead" ) ;
214
225
0 commit comments