@@ -74,7 +74,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessForEach {
7474 && let body = cx. tcx . hir_body ( body)
7575 // Skip the lint if the body is not safe, so as not to suggest `for … in … unsafe {}`
7676 // and suggesting `for … in … { unsafe { } }` is a little ugly.
77- && let ExprKind :: Block ( Block { rules : BlockCheckMode :: DefaultBlock , .. } , ..) = body . value . kind
77+ && ! matches ! ( body . value . kind , ExprKind :: Block ( Block { rules: BlockCheckMode :: UnsafeBlock ( _ ) , .. } , ..) )
7878 {
7979 let mut ret_collector = RetCollector :: default ( ) ;
8080 ret_collector. visit_expr ( body. value ) ;
@@ -99,11 +99,21 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessForEach {
9999 )
100100 } ;
101101
102+ let body_param_sugg = snippet_with_applicability ( cx, body. params [ 0 ] . pat . span , ".." , & mut applicability) ;
103+ let for_each_rev_sugg = snippet_with_applicability ( cx, for_each_recv. span , ".." , & mut applicability) ;
104+ let body_value_sugg = snippet_with_applicability ( cx, body. value . span , ".." , & mut applicability) ;
105+
102106 let sugg = format ! (
103107 "for {} in {} {}" ,
104- snippet_with_applicability( cx, body. params[ 0 ] . pat. span, ".." , & mut applicability) ,
105- snippet_with_applicability( cx, for_each_recv. span, ".." , & mut applicability) ,
106- snippet_with_applicability( cx, body. value. span, ".." , & mut applicability) ,
108+ body_param_sugg,
109+ for_each_rev_sugg,
110+ match body. value. kind {
111+ ExprKind :: Block ( block, _) if is_let_desugar( block) => {
112+ format!( "{{ {body_value_sugg} }}" )
113+ } ,
114+ ExprKind :: Block ( _, _) => body_value_sugg. to_string( ) ,
115+ _ => format!( "{{ {body_value_sugg}; }}" ) ,
116+ }
107117 ) ;
108118
109119 span_lint_and_then ( cx, NEEDLESS_FOR_EACH , stmt. span , "needless use of `for_each`" , |diag| {
@@ -116,6 +126,20 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessForEach {
116126 }
117127}
118128
129+ /// Check if the block is a desugared `_ = expr` statement.
130+ fn is_let_desugar ( block : & Block < ' _ > ) -> bool {
131+ matches ! (
132+ block,
133+ Block {
134+ stmts: [ Stmt {
135+ kind: StmtKind :: Let ( _) ,
136+ ..
137+ } , ] ,
138+ ..
139+ }
140+ )
141+ }
142+
119143/// This type plays two roles.
120144/// 1. Collect spans of `return` in the closure body.
121145/// 2. Detect use of `return` in `Loop` in the closure body.
0 commit comments