@@ -10,7 +10,7 @@ use rustc_data_structures::fx::FxIndexSet;
10
10
use rustc_hir:: intravisit:: { Visitor , walk_expr} ;
11
11
12
12
use rustc_errors:: Applicability ;
13
- use rustc_hir:: { AssignOpKind , Block , Expr , ExprKind , LetStmt , PatKind , QPath , Stmt , StmtKind } ;
13
+ use rustc_hir:: { AssignOpKind , Block , Expr , ExprKind , LetStmt , PatKind , Path , QPath , Stmt , StmtKind } ;
14
14
use rustc_lint:: { LateContext , LateLintPass , LintContext } ;
15
15
use rustc_middle:: ty;
16
16
use rustc_session:: declare_lint_pass;
@@ -350,12 +350,23 @@ impl<'tcx> IndexBinding<'_, 'tcx> {
350
350
format ! ( "{lhs_snippet}{rhs_snippet}" )
351
351
} ,
352
352
ExprKind :: Path ( QPath :: Resolved ( _, path) ) => {
353
- let init = self . cx . expr_or_init ( expr) ;
354
-
355
353
let Some ( first_segment) = path. segments . first ( ) else {
356
354
return String :: new ( ) ;
357
355
} ;
358
- if !self . suggest_span . contains ( init. span ) || !self . is_used_other_than_swapping ( first_segment. ident ) {
356
+
357
+ let init = self . cx . expr_or_init ( expr) ;
358
+
359
+ // We skip suggesting a variable binding in any of these cases:
360
+ // 1. Variable initialization is outside the suggestion span
361
+ // 2. Variable is inside the suggestion span but not used as an index or elsewhere later
362
+ // 3. Variable is inside the suggestion span and used as an index/elsewhere later, but its
363
+ // declaration is outside the suggestion span
364
+ if !self . suggest_span . contains ( init. span )
365
+ || !self . is_used_other_than_swapping ( first_segment. ident )
366
+ || self
367
+ . get_res_span ( expr)
368
+ . is_some_and ( |span| !self . suggest_span . contains ( span) )
369
+ {
359
370
return String :: new ( ) ;
360
371
}
361
372
@@ -371,6 +382,21 @@ impl<'tcx> IndexBinding<'_, 'tcx> {
371
382
}
372
383
}
373
384
385
+ fn get_res_span ( & self , expr : & ' tcx Expr < ' tcx > ) -> Option < Span > {
386
+ if let ExprKind :: Path ( QPath :: Resolved (
387
+ _,
388
+ Path {
389
+ res : rustc_hir:: def:: Res :: Local ( hir_id) ,
390
+ ..
391
+ } ,
392
+ ) ) = expr. kind
393
+ {
394
+ Some ( self . cx . tcx . hir_span ( * hir_id) )
395
+ } else {
396
+ None
397
+ }
398
+ }
399
+
374
400
fn is_used_other_than_swapping ( & mut self , idx_ident : Ident ) -> bool {
375
401
if Self :: is_used_slice_indexed ( self . swap1_idx , idx_ident)
376
402
|| Self :: is_used_slice_indexed ( self . swap2_idx , idx_ident)
0 commit comments