@@ -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 } ;
@@ -89,12 +89,14 @@ declare_clippy_lint! {
89
89
impl_lint_pass ! ( IndexingSlicing => [ INDEXING_SLICING , OUT_OF_BOUNDS_INDEXING ] ) ;
90
90
91
91
pub struct IndexingSlicing {
92
+ allow_indexing_slicing_in_tests : bool ,
92
93
suppress_restriction_lint_in_const : bool ,
93
94
}
94
95
95
96
impl IndexingSlicing {
96
97
pub fn new ( conf : & ' static Conf ) -> Self {
97
98
Self {
99
+ allow_indexing_slicing_in_tests : conf. allow_indexing_slicing_in_tests ,
98
100
suppress_restriction_lint_in_const : conf. suppress_restriction_lint_in_const ,
99
101
}
100
102
}
@@ -115,6 +117,7 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
115
117
{
116
118
let note = "the suggestion might not be applicable in constant blocks" ;
117
119
let ty = cx. typeck_results ( ) . expr_ty ( array) . peel_refs ( ) ;
120
+ let allowed_in_tests = self . allow_indexing_slicing_in_tests && is_in_test ( cx. tcx , expr. hir_id ) ;
118
121
if let Some ( range) = higher:: Range :: hir ( index) {
119
122
// Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..]
120
123
if let ty:: Array ( _, s) = ty. kind ( ) {
@@ -164,6 +167,10 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
164
167
( None , None ) => return , // [..] is ok.
165
168
} ;
166
169
170
+ if allowed_in_tests {
171
+ return ;
172
+ }
173
+
167
174
span_lint_and_then ( cx, INDEXING_SLICING , expr. span , "slicing may panic" , |diag| {
168
175
diag. help ( help_msg) ;
169
176
@@ -202,6 +209,10 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
202
209
}
203
210
}
204
211
212
+ if allowed_in_tests {
213
+ return ;
214
+ }
215
+
205
216
span_lint_and_then ( cx, INDEXING_SLICING , expr. span , "indexing may panic" , |diag| {
206
217
diag. help ( "consider using `.get(n)` or `.get_mut(n)` instead" ) ;
207
218
0 commit comments