@@ -2,7 +2,7 @@ use super::autoderef::Autoderef;
2
2
use super :: method:: MethodCallee ;
3
3
use super :: { Expectation , FnCtxt , Needs , TupleArgumentsFlag } ;
4
4
5
- use errors:: Applicability ;
5
+ use errors:: { Applicability , DiagnosticBuilder } ;
6
6
use hir:: def:: Def ;
7
7
use hir:: def_id:: { DefId , LOCAL_CRATE } ;
8
8
use rustc:: ty:: adjustment:: { Adjust , Adjustment , AllowTwoPhase , AutoBorrow , AutoBorrowMutability } ;
@@ -232,6 +232,32 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
232
232
None
233
233
}
234
234
235
+ /// Give appropriate suggestion when encountering `||{/* not callable */}()`, where the
236
+ /// likely intention is to call the closure, suggest `(||{})()`. (#55851)
237
+ fn identify_bad_closure_def_and_call (
238
+ & self ,
239
+ err : & mut DiagnosticBuilder < ' a > ,
240
+ hir_id : hir:: HirId ,
241
+ callee_node : & hir:: ExprKind ,
242
+ callee_span : Span ,
243
+ ) {
244
+ let hir_id = self . tcx . hir ( ) . get_parent_node_by_hir_id ( hir_id) ;
245
+ let parent_node = self . tcx . hir ( ) . get_by_hir_id ( hir_id) ;
246
+ if let (
247
+ hir:: Node :: Expr ( hir:: Expr { node : hir:: ExprKind :: Closure ( _, _, _, sp, ..) , .. } ) ,
248
+ hir:: ExprKind :: Block ( ..) ,
249
+ ) = ( parent_node, callee_node) {
250
+ let start = sp. shrink_to_lo ( ) ;
251
+ let end = self . tcx . sess . source_map ( ) . next_point ( callee_span) ;
252
+ err. multipart_suggestion (
253
+ "if you meant to create this closure and immediately call it, surround the \
254
+ closure with parenthesis",
255
+ vec ! [ ( start, "(" . to_string( ) ) , ( end, ")" . to_string( ) ) ] ,
256
+ Applicability :: MaybeIncorrect ,
257
+ ) ;
258
+ }
259
+ }
260
+
235
261
fn confirm_builtin_call (
236
262
& self ,
237
263
call_expr : & hir:: Expr ,
@@ -268,6 +294,13 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
268
294
}
269
295
) ;
270
296
297
+ self . identify_bad_closure_def_and_call (
298
+ & mut err,
299
+ call_expr. hir_id ,
300
+ & callee. node ,
301
+ callee. span ,
302
+ ) ;
303
+
271
304
if let Some ( ref path) = unit_variant {
272
305
err. span_suggestion (
273
306
call_expr. span ,
0 commit comments