@@ -2,7 +2,7 @@ use clippy_config::Conf;
22use clippy_utils:: consts:: { ConstEvalCtxt , Constant } ;
33use clippy_utils:: diagnostics:: { span_lint, span_lint_and_then} ;
44use 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 } ;
66use rustc_ast:: ast:: RangeLimits ;
77use rustc_hir:: { Expr , ExprKind } ;
88use rustc_lint:: { LateContext , LateLintPass } ;
@@ -89,12 +89,14 @@ declare_clippy_lint! {
8989impl_lint_pass ! ( IndexingSlicing => [ INDEXING_SLICING , OUT_OF_BOUNDS_INDEXING ] ) ;
9090
9191pub struct IndexingSlicing {
92+ allow_indexing_slicing_in_tests : bool ,
9293 suppress_restriction_lint_in_const : bool ,
9394}
9495
9596impl IndexingSlicing {
9697 pub fn new ( conf : & ' static Conf ) -> Self {
9798 Self {
99+ allow_indexing_slicing_in_tests : conf. allow_indexing_slicing_in_tests ,
98100 suppress_restriction_lint_in_const : conf. suppress_restriction_lint_in_const ,
99101 }
100102 }
@@ -115,6 +117,7 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
115117 {
116118 let note = "the suggestion might not be applicable in constant blocks" ;
117119 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 ) ;
118121 if let Some ( range) = higher:: Range :: hir ( index) {
119122 // Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..]
120123 if let ty:: Array ( _, s) = ty. kind ( ) {
@@ -164,6 +167,10 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
164167 ( None , None ) => return , // [..] is ok.
165168 } ;
166169
170+ if allowed_in_tests {
171+ return ;
172+ }
173+
167174 span_lint_and_then ( cx, INDEXING_SLICING , expr. span , "slicing may panic" , |diag| {
168175 diag. help ( help_msg) ;
169176
@@ -202,6 +209,10 @@ impl<'tcx> LateLintPass<'tcx> for IndexingSlicing {
202209 }
203210 }
204211
212+ if allowed_in_tests {
213+ return ;
214+ }
215+
205216 span_lint_and_then ( cx, INDEXING_SLICING , expr. span , "indexing may panic" , |diag| {
206217 diag. help ( "consider using `.get(n)` or `.get_mut(n)` instead" ) ;
207218
0 commit comments