@@ -74,7 +74,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessForEach {
74
74
&& let body = cx. tcx . hir_body ( body)
75
75
// Skip the lint if the body is not safe, so as not to suggest `for … in … unsafe {}`
76
76
// 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 ( _ ) , .. } , ..) )
78
78
{
79
79
let mut ret_collector = RetCollector :: default ( ) ;
80
80
ret_collector. visit_expr ( body. value ) ;
@@ -99,11 +99,21 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessForEach {
99
99
)
100
100
} ;
101
101
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
+
102
106
let sugg = format ! (
103
107
"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
+ }
107
117
) ;
108
118
109
119
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 {
116
126
}
117
127
}
118
128
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
+
119
143
/// This type plays two roles.
120
144
/// 1. Collect spans of `return` in the closure body.
121
145
/// 2. Detect use of `return` in `Loop` in the closure body.
0 commit comments