]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/fn_ctxt/suggestions.rs
Rollup merge of #93813 - xldenis:public-mir-passes, r=wesleywiser
[rust.git] / compiler / rustc_typeck / src / check / fn_ctxt / suggestions.rs
1 use super::FnCtxt;
2 use crate::astconv::AstConv;
3
4 use rustc_ast::util::parser::ExprPrecedence;
5 use rustc_span::{self, MultiSpan, Span};
6
7 use rustc_errors::{Applicability, DiagnosticBuilder};
8 use rustc_hir as hir;
9 use rustc_hir::def::{CtorOf, DefKind};
10 use rustc_hir::lang_items::LangItem;
11 use rustc_hir::{Expr, ExprKind, ItemKind, Node, Path, QPath, Stmt, StmtKind, TyKind};
12 use rustc_infer::infer::{self, TyCtxtInferExt};
13 use rustc_middle::lint::in_external_macro;
14 use rustc_middle::ty::{self, Binder, Ty};
15 use rustc_span::symbol::{kw, sym};
16
17 use rustc_middle::ty::subst::GenericArgKind;
18 use std::iter;
19
20 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
21     pub(in super::super) fn suggest_semicolon_at_end(
22         &self,
23         span: Span,
24         err: &mut DiagnosticBuilder<'_>,
25     ) {
26         err.span_suggestion_short(
27             span.shrink_to_hi(),
28             "consider using a semicolon here",
29             ";".to_string(),
30             Applicability::MachineApplicable,
31         );
32     }
33
34     /// On implicit return expressions with mismatched types, provides the following suggestions:
35     ///
36     /// - Points out the method's return type as the reason for the expected type.
37     /// - Possible missing semicolon.
38     /// - Possible missing return type if the return type is the default, and not `fn main()`.
39     pub fn suggest_mismatched_types_on_tail(
40         &self,
41         err: &mut DiagnosticBuilder<'_>,
42         expr: &'tcx hir::Expr<'tcx>,
43         expected: Ty<'tcx>,
44         found: Ty<'tcx>,
45         blk_id: hir::HirId,
46     ) -> bool {
47         let expr = expr.peel_drop_temps();
48         // If the expression is from an external macro, then do not suggest
49         // adding a semicolon, because there's nowhere to put it.
50         // See issue #81943.
51         if expr.can_have_side_effects() && !in_external_macro(self.tcx.sess, expr.span) {
52             self.suggest_missing_semicolon(err, expr, expected);
53         }
54         let mut pointing_at_return_type = false;
55         if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
56             let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
57             pointing_at_return_type = self.suggest_missing_return_type(
58                 err,
59                 &fn_decl,
60                 expected,
61                 found,
62                 can_suggest,
63                 fn_id,
64             );
65             self.suggest_missing_break_or_return_expr(
66                 err, expr, &fn_decl, expected, found, blk_id, fn_id,
67             );
68         }
69         pointing_at_return_type
70     }
71
72     /// When encountering an fn-like ctor that needs to unify with a value, check whether calling
73     /// the ctor would successfully solve the type mismatch and if so, suggest it:
74     /// ```
75     /// fn foo(x: usize) -> usize { x }
76     /// let x: usize = foo;  // suggest calling the `foo` function: `foo(42)`
77     /// ```
78     fn suggest_fn_call(
79         &self,
80         err: &mut DiagnosticBuilder<'_>,
81         expr: &hir::Expr<'_>,
82         expected: Ty<'tcx>,
83         found: Ty<'tcx>,
84     ) -> bool {
85         let hir = self.tcx.hir();
86         let (def_id, sig) = match *found.kind() {
87             ty::FnDef(def_id, _) => (def_id, found.fn_sig(self.tcx)),
88             ty::Closure(def_id, substs) => (def_id, substs.as_closure().sig()),
89             _ => return false,
90         };
91
92         let sig = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, sig).0;
93         let sig = self.normalize_associated_types_in(expr.span, sig);
94         if self.can_coerce(sig.output(), expected) {
95             let (mut sugg_call, applicability) = if sig.inputs().is_empty() {
96                 (String::new(), Applicability::MachineApplicable)
97             } else {
98                 ("...".to_string(), Applicability::HasPlaceholders)
99             };
100             let mut msg = "call this function";
101             match hir.get_if_local(def_id) {
102                 Some(
103                     Node::Item(hir::Item { kind: ItemKind::Fn(.., body_id), .. })
104                     | Node::ImplItem(hir::ImplItem {
105                         kind: hir::ImplItemKind::Fn(_, body_id), ..
106                     })
107                     | Node::TraitItem(hir::TraitItem {
108                         kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Provided(body_id)),
109                         ..
110                     }),
111                 ) => {
112                     let body = hir.body(*body_id);
113                     sugg_call = body
114                         .params
115                         .iter()
116                         .map(|param| match &param.pat.kind {
117                             hir::PatKind::Binding(_, _, ident, None)
118                                 if ident.name != kw::SelfLower =>
119                             {
120                                 ident.to_string()
121                             }
122                             _ => "_".to_string(),
123                         })
124                         .collect::<Vec<_>>()
125                         .join(", ");
126                 }
127                 Some(Node::Expr(hir::Expr {
128                     kind: ExprKind::Closure(_, _, body_id, _, _),
129                     span: full_closure_span,
130                     ..
131                 })) => {
132                     if *full_closure_span == expr.span {
133                         return false;
134                     }
135                     msg = "call this closure";
136                     let body = hir.body(*body_id);
137                     sugg_call = body
138                         .params
139                         .iter()
140                         .map(|param| match &param.pat.kind {
141                             hir::PatKind::Binding(_, _, ident, None)
142                                 if ident.name != kw::SelfLower =>
143                             {
144                                 ident.to_string()
145                             }
146                             _ => "_".to_string(),
147                         })
148                         .collect::<Vec<_>>()
149                         .join(", ");
150                 }
151                 Some(Node::Ctor(hir::VariantData::Tuple(fields, _))) => {
152                     sugg_call = fields.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
153                     match def_id.as_local().map(|def_id| hir.def_kind(def_id)) {
154                         Some(DefKind::Ctor(hir::def::CtorOf::Variant, _)) => {
155                             msg = "instantiate this tuple variant";
156                         }
157                         Some(DefKind::Ctor(CtorOf::Struct, _)) => {
158                             msg = "instantiate this tuple struct";
159                         }
160                         _ => {}
161                     }
162                 }
163                 Some(Node::ForeignItem(hir::ForeignItem {
164                     kind: hir::ForeignItemKind::Fn(_, idents, _),
165                     ..
166                 })) => {
167                     sugg_call = idents
168                         .iter()
169                         .map(|ident| {
170                             if ident.name != kw::SelfLower {
171                                 ident.to_string()
172                             } else {
173                                 "_".to_string()
174                             }
175                         })
176                         .collect::<Vec<_>>()
177                         .join(", ")
178                 }
179                 Some(Node::TraitItem(hir::TraitItem {
180                     kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Required(idents)),
181                     ..
182                 })) => {
183                     sugg_call = idents
184                         .iter()
185                         .map(|ident| {
186                             if ident.name != kw::SelfLower {
187                                 ident.to_string()
188                             } else {
189                                 "_".to_string()
190                             }
191                         })
192                         .collect::<Vec<_>>()
193                         .join(", ")
194                 }
195                 _ => {}
196             }
197             err.span_suggestion_verbose(
198                 expr.span.shrink_to_hi(),
199                 &format!("use parentheses to {}", msg),
200                 format!("({})", sugg_call),
201                 applicability,
202             );
203             return true;
204         }
205         false
206     }
207
208     pub fn suggest_deref_ref_or_into(
209         &self,
210         err: &mut DiagnosticBuilder<'_>,
211         expr: &hir::Expr<'tcx>,
212         expected: Ty<'tcx>,
213         found: Ty<'tcx>,
214         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
215     ) {
216         let expr = expr.peel_blocks();
217         if let Some((sp, msg, suggestion, applicability, verbose)) =
218             self.check_ref(expr, found, expected)
219         {
220             if verbose {
221                 err.span_suggestion_verbose(sp, msg, suggestion, applicability);
222             } else {
223                 err.span_suggestion(sp, msg, suggestion, applicability);
224             }
225         } else if let (ty::FnDef(def_id, ..), true) =
226             (&found.kind(), self.suggest_fn_call(err, expr, expected, found))
227         {
228             if let Some(sp) = self.tcx.hir().span_if_local(*def_id) {
229                 let sp = self.sess().source_map().guess_head_span(sp);
230                 err.span_label(sp, &format!("{} defined here", found));
231             }
232         } else if !self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
233             let is_struct_pat_shorthand_field =
234                 self.maybe_get_struct_pattern_shorthand_field(expr).is_some();
235             let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
236             if !methods.is_empty() {
237                 if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr.span) {
238                     let mut suggestions = iter::zip(iter::repeat(&expr_text), &methods)
239                         .filter_map(|(receiver, method)| {
240                             let method_call = format!(".{}()", method.name);
241                             if receiver.ends_with(&method_call) {
242                                 None // do not suggest code that is already there (#53348)
243                             } else {
244                                 let method_call_list = [".to_vec()", ".to_string()"];
245                                 let mut sugg = if receiver.ends_with(".clone()")
246                                     && method_call_list.contains(&method_call.as_str())
247                                 {
248                                     let max_len = receiver.rfind('.').unwrap();
249                                     vec![(
250                                         expr.span,
251                                         format!("{}{}", &receiver[..max_len], method_call),
252                                     )]
253                                 } else {
254                                     if expr.precedence().order()
255                                         < ExprPrecedence::MethodCall.order()
256                                     {
257                                         vec![
258                                             (expr.span.shrink_to_lo(), "(".to_string()),
259                                             (expr.span.shrink_to_hi(), format!("){}", method_call)),
260                                         ]
261                                     } else {
262                                         vec![(expr.span.shrink_to_hi(), method_call)]
263                                     }
264                                 };
265                                 if is_struct_pat_shorthand_field {
266                                     sugg.insert(
267                                         0,
268                                         (expr.span.shrink_to_lo(), format!("{}: ", receiver)),
269                                     );
270                                 }
271                                 Some(sugg)
272                             }
273                         })
274                         .peekable();
275                     if suggestions.peek().is_some() {
276                         err.multipart_suggestions(
277                             "try using a conversion method",
278                             suggestions,
279                             Applicability::MaybeIncorrect,
280                         );
281                     }
282                 }
283             } else if found.to_string().starts_with("Option<")
284                 && expected.to_string() == "Option<&str>"
285             {
286                 if let ty::Adt(_def, subst) = found.kind() {
287                     if subst.len() != 0 {
288                         if let GenericArgKind::Type(ty) = subst[0].unpack() {
289                             let peeled = ty.peel_refs().to_string();
290                             if peeled == "String" {
291                                 let ref_cnt = ty.to_string().len() - peeled.len();
292                                 let result = format!(".map(|x| &*{}x)", "*".repeat(ref_cnt));
293                                 err.span_suggestion_verbose(
294                                     expr.span.shrink_to_hi(),
295                                     "try converting the passed type into a `&str`",
296                                     result,
297                                     Applicability::MaybeIncorrect,
298                                 );
299                             }
300                         }
301                     }
302                 }
303             }
304         }
305     }
306
307     /// When encountering the expected boxed value allocated in the stack, suggest allocating it
308     /// in the heap by calling `Box::new()`.
309     pub(in super::super) fn suggest_boxing_when_appropriate(
310         &self,
311         err: &mut DiagnosticBuilder<'_>,
312         expr: &hir::Expr<'_>,
313         expected: Ty<'tcx>,
314         found: Ty<'tcx>,
315     ) {
316         if self.tcx.hir().is_inside_const_context(expr.hir_id) {
317             // Do not suggest `Box::new` in const context.
318             return;
319         }
320         if !expected.is_box() || found.is_box() {
321             return;
322         }
323         let boxed_found = self.tcx.mk_box(found);
324         if self.can_coerce(boxed_found, expected) {
325             err.multipart_suggestion(
326                 "store this in the heap by calling `Box::new`",
327                 vec![
328                     (expr.span.shrink_to_lo(), "Box::new(".to_string()),
329                     (expr.span.shrink_to_hi(), ")".to_string()),
330                 ],
331                 Applicability::MachineApplicable,
332             );
333             err.note(
334                 "for more on the distinction between the stack and the heap, read \
335                  https://doc.rust-lang.org/book/ch15-01-box.html, \
336                  https://doc.rust-lang.org/rust-by-example/std/box.html, and \
337                  https://doc.rust-lang.org/std/boxed/index.html",
338             );
339         }
340     }
341
342     /// When encountering a closure that captures variables, where a FnPtr is expected,
343     /// suggest a non-capturing closure
344     pub(in super::super) fn suggest_no_capture_closure(
345         &self,
346         err: &mut DiagnosticBuilder<'_>,
347         expected: Ty<'tcx>,
348         found: Ty<'tcx>,
349     ) {
350         if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
351             if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
352                 // Report upto four upvars being captured to reduce the amount error messages
353                 // reported back to the user.
354                 let spans_and_labels = upvars
355                     .iter()
356                     .take(4)
357                     .map(|(var_hir_id, upvar)| {
358                         let var_name = self.tcx.hir().name(*var_hir_id).to_string();
359                         let msg = format!("`{}` captured here", var_name);
360                         (upvar.span, msg)
361                     })
362                     .collect::<Vec<_>>();
363
364                 let mut multi_span: MultiSpan =
365                     spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
366                 for (sp, label) in spans_and_labels {
367                     multi_span.push_span_label(sp, label);
368                 }
369                 err.span_note(
370                     multi_span,
371                     "closures can only be coerced to `fn` types if they do not capture any variables"
372                 );
373             }
374         }
375     }
376
377     /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
378     #[instrument(skip(self, err))]
379     pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
380         &self,
381         err: &mut DiagnosticBuilder<'_>,
382         expr: &hir::Expr<'_>,
383         expected: Ty<'tcx>,
384         found: Ty<'tcx>,
385     ) -> bool {
386         // Handle #68197.
387
388         if self.tcx.hir().is_inside_const_context(expr.hir_id) {
389             // Do not suggest `Box::new` in const context.
390             return false;
391         }
392         let pin_did = self.tcx.lang_items().pin_type();
393         // This guards the `unwrap` and `mk_box` below.
394         if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
395             return false;
396         }
397         let box_found = self.tcx.mk_box(found);
398         let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
399         let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
400         match expected.kind() {
401             ty::Adt(def, _) if Some(def.did) == pin_did => {
402                 if self.can_coerce(pin_box_found, expected) {
403                     debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
404                     match found.kind() {
405                         ty::Adt(def, _) if def.is_box() => {
406                             err.help("use `Box::pin`");
407                         }
408                         _ => {
409                             err.multipart_suggestion(
410                                 "you need to pin and box this expression",
411                                 vec![
412                                     (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
413                                     (expr.span.shrink_to_hi(), ")".to_string()),
414                                 ],
415                                 Applicability::MaybeIncorrect,
416                             );
417                         }
418                     }
419                     true
420                 } else if self.can_coerce(pin_found, expected) {
421                     match found.kind() {
422                         ty::Adt(def, _) if def.is_box() => {
423                             err.help("use `Box::pin`");
424                             true
425                         }
426                         _ => false,
427                     }
428                 } else {
429                     false
430                 }
431             }
432             ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
433                 // Check if the parent expression is a call to Pin::new.  If it
434                 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
435                 // can suggest Box::pin.
436                 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
437                 let fn_name = match self.tcx.hir().find(parent) {
438                     Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) => fn_name,
439                     _ => return false,
440                 };
441                 match fn_name.kind {
442                     ExprKind::Path(QPath::TypeRelative(
443                         hir::Ty {
444                             kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
445                             ..
446                         },
447                         method,
448                     )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
449                         err.span_suggestion(
450                             fn_name.span,
451                             "use `Box::pin` to pin and box this expression",
452                             "Box::pin".to_string(),
453                             Applicability::MachineApplicable,
454                         );
455                         true
456                     }
457                     _ => false,
458                 }
459             }
460             _ => false,
461         }
462     }
463
464     /// A common error is to forget to add a semicolon at the end of a block, e.g.,
465     ///
466     /// ```
467     /// fn foo() {
468     ///     bar_that_returns_u32()
469     /// }
470     /// ```
471     ///
472     /// This routine checks if the return expression in a block would make sense on its own as a
473     /// statement and the return type has been left as default or has been specified as `()`. If so,
474     /// it suggests adding a semicolon.
475     fn suggest_missing_semicolon(
476         &self,
477         err: &mut DiagnosticBuilder<'_>,
478         expression: &'tcx hir::Expr<'tcx>,
479         expected: Ty<'tcx>,
480     ) {
481         if expected.is_unit() {
482             // `BlockTailExpression` only relevant if the tail expr would be
483             // useful on its own.
484             match expression.kind {
485                 ExprKind::Call(..)
486                 | ExprKind::MethodCall(..)
487                 | ExprKind::Loop(..)
488                 | ExprKind::If(..)
489                 | ExprKind::Match(..)
490                 | ExprKind::Block(..)
491                     if expression.can_have_side_effects() =>
492                 {
493                     err.span_suggestion(
494                         expression.span.shrink_to_hi(),
495                         "consider using a semicolon here",
496                         ";".to_string(),
497                         Applicability::MachineApplicable,
498                     );
499                 }
500                 _ => (),
501             }
502         }
503     }
504
505     /// A possible error is to forget to add a return type that is needed:
506     ///
507     /// ```
508     /// fn foo() {
509     ///     bar_that_returns_u32()
510     /// }
511     /// ```
512     ///
513     /// This routine checks if the return type is left as default, the method is not part of an
514     /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
515     /// type.
516     pub(in super::super) fn suggest_missing_return_type(
517         &self,
518         err: &mut DiagnosticBuilder<'_>,
519         fn_decl: &hir::FnDecl<'_>,
520         expected: Ty<'tcx>,
521         found: Ty<'tcx>,
522         can_suggest: bool,
523         fn_id: hir::HirId,
524     ) -> bool {
525         // Only suggest changing the return type for methods that
526         // haven't set a return type at all (and aren't `fn main()` or an impl).
527         match (&fn_decl.output, found.is_suggestable(), can_suggest, expected.is_unit()) {
528             (&hir::FnRetTy::DefaultReturn(span), true, true, true) => {
529                 err.span_suggestion(
530                     span,
531                     "try adding a return type",
532                     format!("-> {} ", self.resolve_vars_with_obligations(found)),
533                     Applicability::MachineApplicable,
534                 );
535                 true
536             }
537             (&hir::FnRetTy::DefaultReturn(span), false, true, true) => {
538                 err.span_label(span, "possibly return type missing here?");
539                 true
540             }
541             (&hir::FnRetTy::DefaultReturn(span), _, false, true) => {
542                 // `fn main()` must return `()`, do not suggest changing return type
543                 err.span_label(span, "expected `()` because of default return type");
544                 true
545             }
546             // expectation was caused by something else, not the default return
547             (&hir::FnRetTy::DefaultReturn(_), _, _, false) => false,
548             (&hir::FnRetTy::Return(ref ty), _, _, _) => {
549                 // Only point to return type if the expected type is the return type, as if they
550                 // are not, the expectation must have been caused by something else.
551                 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
552                 let sp = ty.span;
553                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
554                 debug!("suggest_missing_return_type: return type {:?}", ty);
555                 debug!("suggest_missing_return_type: expected type {:?}", ty);
556                 let bound_vars = self.tcx.late_bound_vars(fn_id);
557                 let ty = Binder::bind_with_vars(ty, bound_vars);
558                 let ty = self.normalize_associated_types_in(sp, ty);
559                 let ty = self.tcx.erase_late_bound_regions(ty);
560                 if self.can_coerce(expected, ty) {
561                     err.span_label(sp, format!("expected `{}` because of return type", expected));
562                     return true;
563                 }
564                 false
565             }
566         }
567     }
568
569     pub(in super::super) fn suggest_missing_break_or_return_expr(
570         &self,
571         err: &mut DiagnosticBuilder<'_>,
572         expr: &'tcx hir::Expr<'tcx>,
573         fn_decl: &hir::FnDecl<'_>,
574         expected: Ty<'tcx>,
575         found: Ty<'tcx>,
576         id: hir::HirId,
577         fn_id: hir::HirId,
578     ) {
579         if !expected.is_unit() {
580             return;
581         }
582         let found = self.resolve_vars_with_obligations(found);
583
584         let in_loop = self.is_loop(id)
585             || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
586
587         let in_local_statement = self.is_local_statement(id)
588             || self
589                 .tcx
590                 .hir()
591                 .parent_iter(id)
592                 .any(|(parent_id, _)| self.is_local_statement(parent_id));
593
594         if in_loop && in_local_statement {
595             err.multipart_suggestion(
596                 "you might have meant to break the loop with this value",
597                 vec![
598                     (expr.span.shrink_to_lo(), "break ".to_string()),
599                     (expr.span.shrink_to_hi(), ";".to_string()),
600                 ],
601                 Applicability::MaybeIncorrect,
602             );
603             return;
604         }
605
606         if let hir::FnRetTy::Return(ty) = fn_decl.output {
607             let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
608             let bound_vars = self.tcx.late_bound_vars(fn_id);
609             let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
610             let ty = self.normalize_associated_types_in(expr.span, ty);
611             let ty = match self.tcx.asyncness(fn_id.owner) {
612                 hir::IsAsync::Async => self
613                     .tcx
614                     .infer_ctxt()
615                     .enter(|infcx| {
616                         infcx.get_impl_future_output_ty(ty).unwrap_or_else(|| {
617                             span_bug!(
618                                 fn_decl.output.span(),
619                                 "failed to get output type of async function"
620                             )
621                         })
622                     })
623                     .skip_binder(),
624                 hir::IsAsync::NotAsync => ty,
625             };
626             if self.can_coerce(found, ty) {
627                 err.multipart_suggestion(
628                     "you might have meant to return this value",
629                     vec![
630                         (expr.span.shrink_to_lo(), "return ".to_string()),
631                         (expr.span.shrink_to_hi(), ";".to_string()),
632                     ],
633                     Applicability::MaybeIncorrect,
634                 );
635             }
636         }
637     }
638
639     pub(in super::super) fn suggest_missing_parentheses(
640         &self,
641         err: &mut DiagnosticBuilder<'_>,
642         expr: &hir::Expr<'_>,
643     ) {
644         let sp = self.tcx.sess.source_map().start_point(expr.span);
645         if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
646             // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
647             self.tcx.sess.parse_sess.expr_parentheses_needed(err, *sp);
648         }
649     }
650
651     fn is_loop(&self, id: hir::HirId) -> bool {
652         let node = self.tcx.hir().get(id);
653         matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
654     }
655
656     fn is_local_statement(&self, id: hir::HirId) -> bool {
657         let node = self.tcx.hir().get(id);
658         matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
659     }
660 }