]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs
Rollup merge of #103876 - oli-obk:tait_implications, r=lcnr
[rust.git] / compiler / rustc_hir_typeck / src / fn_ctxt / suggestions.rs
1 use super::FnCtxt;
2
3 use crate::errors::{AddReturnTypeSuggestion, ExpectedReturnTypeLabel};
4 use rustc_ast::util::parser::{ExprPrecedence, PREC_POSTFIX};
5 use rustc_errors::{Applicability, Diagnostic, MultiSpan};
6 use rustc_hir as hir;
7 use rustc_hir::def::{CtorOf, DefKind};
8 use rustc_hir::lang_items::LangItem;
9 use rustc_hir::{
10     Expr, ExprKind, GenericBound, Node, Path, QPath, Stmt, StmtKind, TyKind, WherePredicate,
11 };
12 use rustc_hir_analysis::astconv::AstConv;
13 use rustc_infer::infer::{self, TyCtxtInferExt};
14 use rustc_infer::traits::{self, StatementAsExpression};
15 use rustc_middle::lint::in_external_macro;
16 use rustc_middle::ty::{self, Binder, DefIdTree, IsSuggestable, ToPredicate, Ty};
17 use rustc_session::errors::ExprParenthesesNeeded;
18 use rustc_span::symbol::sym;
19 use rustc_span::Span;
20 use rustc_trait_selection::infer::InferCtxtExt;
21 use rustc_trait_selection::traits::error_reporting::DefIdOrName;
22 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
23
24 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25     pub(crate) fn body_fn_sig(&self) -> Option<ty::FnSig<'tcx>> {
26         self.typeck_results
27             .borrow()
28             .liberated_fn_sigs()
29             .get(self.tcx.hir().get_parent_node(self.body_id))
30             .copied()
31     }
32
33     pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
34         err.span_suggestion_short(
35             span.shrink_to_hi(),
36             "consider using a semicolon here",
37             ";",
38             Applicability::MachineApplicable,
39         );
40     }
41
42     /// On implicit return expressions with mismatched types, provides the following suggestions:
43     ///
44     /// - Points out the method's return type as the reason for the expected type.
45     /// - Possible missing semicolon.
46     /// - Possible missing return type if the return type is the default, and not `fn main()`.
47     pub fn suggest_mismatched_types_on_tail(
48         &self,
49         err: &mut Diagnostic,
50         expr: &'tcx hir::Expr<'tcx>,
51         expected: Ty<'tcx>,
52         found: Ty<'tcx>,
53         blk_id: hir::HirId,
54     ) -> bool {
55         let expr = expr.peel_drop_temps();
56         self.suggest_missing_semicolon(err, expr, expected, false);
57         let mut pointing_at_return_type = false;
58         if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
59             let fn_id = self.tcx.hir().get_return_block(blk_id).unwrap();
60             pointing_at_return_type = self.suggest_missing_return_type(
61                 err,
62                 &fn_decl,
63                 expected,
64                 found,
65                 can_suggest,
66                 fn_id,
67             );
68             self.suggest_missing_break_or_return_expr(
69                 err, expr, &fn_decl, expected, found, blk_id, fn_id,
70             );
71         }
72         pointing_at_return_type
73     }
74
75     /// When encountering an fn-like type, try accessing the output of the type
76     /// and suggesting calling it if it satisfies a predicate (i.e. if the
77     /// output has a method or a field):
78     /// ```compile_fail,E0308
79     /// fn foo(x: usize) -> usize { x }
80     /// let x: usize = foo;  // suggest calling the `foo` function: `foo(42)`
81     /// ```
82     pub(crate) fn suggest_fn_call(
83         &self,
84         err: &mut Diagnostic,
85         expr: &hir::Expr<'_>,
86         found: Ty<'tcx>,
87         can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
88     ) -> bool {
89         let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(expr, found)
90             else { return false; };
91         if can_satisfy(output) {
92             let (sugg_call, mut applicability) = match inputs.len() {
93                 0 => ("".to_string(), Applicability::MachineApplicable),
94                 1..=4 => (
95                     inputs
96                         .iter()
97                         .map(|ty| {
98                             if ty.is_suggestable(self.tcx, false) {
99                                 format!("/* {ty} */")
100                             } else {
101                                 "/* value */".to_string()
102                             }
103                         })
104                         .collect::<Vec<_>>()
105                         .join(", "),
106                     Applicability::HasPlaceholders,
107                 ),
108                 _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
109             };
110
111             let msg = match def_id_or_name {
112                 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
113                     DefKind::Ctor(CtorOf::Struct, _) => "construct this tuple struct".to_string(),
114                     DefKind::Ctor(CtorOf::Variant, _) => "construct this tuple variant".to_string(),
115                     kind => format!("call this {}", kind.descr(def_id)),
116                 },
117                 DefIdOrName::Name(name) => format!("call this {name}"),
118             };
119
120             let sugg = match expr.kind {
121                 hir::ExprKind::Call(..)
122                 | hir::ExprKind::Path(..)
123                 | hir::ExprKind::Index(..)
124                 | hir::ExprKind::Lit(..) => {
125                     vec![(expr.span.shrink_to_hi(), format!("({sugg_call})"))]
126                 }
127                 hir::ExprKind::Closure { .. } => {
128                     // Might be `{ expr } || { bool }`
129                     applicability = Applicability::MaybeIncorrect;
130                     vec![
131                         (expr.span.shrink_to_lo(), "(".to_string()),
132                         (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
133                     ]
134                 }
135                 _ => {
136                     vec![
137                         (expr.span.shrink_to_lo(), "(".to_string()),
138                         (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
139                     ]
140                 }
141             };
142
143             err.multipart_suggestion_verbose(
144                 format!("use parentheses to {msg}"),
145                 sugg,
146                 applicability,
147             );
148             return true;
149         }
150         false
151     }
152
153     /// Extracts information about a callable type for diagnostics. This is a
154     /// heuristic -- it doesn't necessarily mean that a type is always callable,
155     /// because the callable type must also be well-formed to be called.
156     pub(in super::super) fn extract_callable_info(
157         &self,
158         expr: &Expr<'_>,
159         found: Ty<'tcx>,
160     ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
161         // Autoderef is useful here because sometimes we box callables, etc.
162         let Some((def_id_or_name, output, inputs)) = self.autoderef(expr.span, found).silence_errors().find_map(|(found, _)| {
163             match *found.kind() {
164                 ty::FnPtr(fn_sig) =>
165                     Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())),
166                 ty::FnDef(def_id, _) => {
167                     let fn_sig = found.fn_sig(self.tcx);
168                     Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
169                 }
170                 ty::Closure(def_id, substs) => {
171                     let fn_sig = substs.as_closure().sig();
172                     Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..])))
173                 }
174                 ty::Opaque(def_id, substs) => {
175                     self.tcx.bound_item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| {
176                         if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
177                         && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
178                         // args tuple will always be substs[1]
179                         && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
180                         {
181                             Some((
182                                 DefIdOrName::DefId(def_id),
183                                 pred.kind().rebind(proj.term.ty().unwrap()),
184                                 pred.kind().rebind(args.as_slice()),
185                             ))
186                         } else {
187                             None
188                         }
189                     })
190                 }
191                 ty::Dynamic(data, _, ty::Dyn) => {
192                     data.iter().find_map(|pred| {
193                         if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
194                         && Some(proj.item_def_id) == self.tcx.lang_items().fn_once_output()
195                         // for existential projection, substs are shifted over by 1
196                         && let ty::Tuple(args) = proj.substs.type_at(0).kind()
197                         {
198                             Some((
199                                 DefIdOrName::Name("trait object"),
200                                 pred.rebind(proj.term.ty().unwrap()),
201                                 pred.rebind(args.as_slice()),
202                             ))
203                         } else {
204                             None
205                         }
206                     })
207                 }
208                 ty::Param(param) => {
209                     let def_id = self.tcx.generics_of(self.body_id.owner).type_param(&param, self.tcx).def_id;
210                     self.tcx.predicates_of(self.body_id.owner).predicates.iter().find_map(|(pred, _)| {
211                         if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = pred.kind().skip_binder()
212                         && Some(proj.projection_ty.item_def_id) == self.tcx.lang_items().fn_once_output()
213                         && proj.projection_ty.self_ty() == found
214                         // args tuple will always be substs[1]
215                         && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind()
216                         {
217                             Some((
218                                 DefIdOrName::DefId(def_id),
219                                 pred.kind().rebind(proj.term.ty().unwrap()),
220                                 pred.kind().rebind(args.as_slice()),
221                             ))
222                         } else {
223                             None
224                         }
225                     })
226                 }
227                 _ => None,
228             }
229         }) else { return None; };
230
231         let output = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, output);
232         let inputs = inputs
233             .skip_binder()
234             .iter()
235             .map(|ty| {
236                 self.replace_bound_vars_with_fresh_vars(
237                     expr.span,
238                     infer::FnCall,
239                     inputs.rebind(*ty),
240                 )
241             })
242             .collect();
243
244         // We don't want to register any extra obligations, which should be
245         // implied by wf, but also because that would possibly result in
246         // erroneous errors later on.
247         let infer::InferOk { value: output, obligations: _ } =
248             self.normalize_associated_types_in_as_infer_ok(expr.span, output);
249
250         if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
251     }
252
253     pub fn suggest_two_fn_call(
254         &self,
255         err: &mut Diagnostic,
256         lhs_expr: &'tcx hir::Expr<'tcx>,
257         lhs_ty: Ty<'tcx>,
258         rhs_expr: &'tcx hir::Expr<'tcx>,
259         rhs_ty: Ty<'tcx>,
260         can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool,
261     ) -> bool {
262         let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_expr, lhs_ty)
263             else { return false; };
264         let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_expr, rhs_ty)
265             else { return false; };
266
267         if can_satisfy(lhs_output_ty, rhs_output_ty) {
268             let mut sugg = vec![];
269             let mut applicability = Applicability::MachineApplicable;
270
271             for (expr, inputs) in [(lhs_expr, lhs_inputs), (rhs_expr, rhs_inputs)] {
272                 let (sugg_call, this_applicability) = match inputs.len() {
273                     0 => ("".to_string(), Applicability::MachineApplicable),
274                     1..=4 => (
275                         inputs
276                             .iter()
277                             .map(|ty| {
278                                 if ty.is_suggestable(self.tcx, false) {
279                                     format!("/* {ty} */")
280                                 } else {
281                                     "/* value */".to_string()
282                                 }
283                             })
284                             .collect::<Vec<_>>()
285                             .join(", "),
286                         Applicability::HasPlaceholders,
287                     ),
288                     _ => ("/* ... */".to_string(), Applicability::HasPlaceholders),
289                 };
290
291                 applicability = applicability.max(this_applicability);
292
293                 match expr.kind {
294                     hir::ExprKind::Call(..)
295                     | hir::ExprKind::Path(..)
296                     | hir::ExprKind::Index(..)
297                     | hir::ExprKind::Lit(..) => {
298                         sugg.extend([(expr.span.shrink_to_hi(), format!("({sugg_call})"))]);
299                     }
300                     hir::ExprKind::Closure { .. } => {
301                         // Might be `{ expr } || { bool }`
302                         applicability = Applicability::MaybeIncorrect;
303                         sugg.extend([
304                             (expr.span.shrink_to_lo(), "(".to_string()),
305                             (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
306                         ]);
307                     }
308                     _ => {
309                         sugg.extend([
310                             (expr.span.shrink_to_lo(), "(".to_string()),
311                             (expr.span.shrink_to_hi(), format!(")({sugg_call})")),
312                         ]);
313                     }
314                 }
315             }
316
317             err.multipart_suggestion_verbose(
318                 format!("use parentheses to call these"),
319                 sugg,
320                 applicability,
321             );
322
323             true
324         } else {
325             false
326         }
327     }
328
329     pub fn suggest_deref_ref_or_into(
330         &self,
331         err: &mut Diagnostic,
332         expr: &hir::Expr<'tcx>,
333         expected: Ty<'tcx>,
334         found: Ty<'tcx>,
335         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
336     ) -> bool {
337         let expr = expr.peel_blocks();
338         if let Some((sp, msg, suggestion, applicability, verbose, annotation)) =
339             self.check_ref(expr, found, expected)
340         {
341             if verbose {
342                 err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
343             } else {
344                 err.span_suggestion(sp, &msg, suggestion, applicability);
345             }
346             if annotation {
347                 let suggest_annotation = match expr.peel_drop_temps().kind {
348                     hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, _) => mutbl.ref_prefix_str(),
349                     _ => return true,
350                 };
351                 let mut tuple_indexes = Vec::new();
352                 let mut expr_id = expr.hir_id;
353                 for (parent_id, node) in self.tcx.hir().parent_iter(expr.hir_id) {
354                     match node {
355                         Node::Expr(&Expr { kind: ExprKind::Tup(subs), .. }) => {
356                             tuple_indexes.push(
357                                 subs.iter()
358                                     .enumerate()
359                                     .find(|(_, sub_expr)| sub_expr.hir_id == expr_id)
360                                     .unwrap()
361                                     .0,
362                             );
363                             expr_id = parent_id;
364                         }
365                         Node::Local(local) => {
366                             if let Some(mut ty) = local.ty {
367                                 while let Some(index) = tuple_indexes.pop() {
368                                     match ty.kind {
369                                         TyKind::Tup(tys) => ty = &tys[index],
370                                         _ => return true,
371                                     }
372                                 }
373                                 let annotation_span = ty.span;
374                                 err.span_suggestion(
375                                     annotation_span.with_hi(annotation_span.lo()),
376                                     "alternatively, consider changing the type annotation",
377                                     suggest_annotation,
378                                     Applicability::MaybeIncorrect,
379                                 );
380                             }
381                             break;
382                         }
383                         _ => break,
384                     }
385                 }
386             }
387             return true;
388         } else if self.suggest_else_fn_with_closure(err, expr, found, expected) {
389             return true;
390         } else if self.suggest_fn_call(err, expr, found, |output| self.can_coerce(output, expected))
391             && let ty::FnDef(def_id, ..) = &found.kind()
392             && let Some(sp) = self.tcx.hir().span_if_local(*def_id)
393         {
394             err.span_label(sp, format!("{found} defined here"));
395             return true;
396         } else if self.check_for_cast(err, expr, found, expected, expected_ty_expr) {
397             return true;
398         } else {
399             let methods = self.get_conversion_methods(expr.span, expected, found, expr.hir_id);
400             if !methods.is_empty() {
401                 let mut suggestions = methods.iter()
402                     .filter_map(|conversion_method| {
403                         let receiver_method_ident = expr.method_ident();
404                         if let Some(method_ident) = receiver_method_ident
405                             && method_ident.name == conversion_method.name
406                         {
407                             return None // do not suggest code that is already there (#53348)
408                         }
409
410                         let method_call_list = [sym::to_vec, sym::to_string];
411                         let mut sugg = if let ExprKind::MethodCall(receiver_method, ..) = expr.kind
412                             && receiver_method.ident.name == sym::clone
413                             && method_call_list.contains(&conversion_method.name)
414                             // If receiver is `.clone()` and found type has one of those methods,
415                             // we guess that the user wants to convert from a slice type (`&[]` or `&str`)
416                             // to an owned type (`Vec` or `String`).  These conversions clone internally,
417                             // so we remove the user's `clone` call.
418                         {
419                             vec![(
420                                 receiver_method.ident.span,
421                                 conversion_method.name.to_string()
422                             )]
423                         } else if expr.precedence().order()
424                             < ExprPrecedence::MethodCall.order()
425                         {
426                             vec![
427                                 (expr.span.shrink_to_lo(), "(".to_string()),
428                                 (expr.span.shrink_to_hi(), format!(").{}()", conversion_method.name)),
429                             ]
430                         } else {
431                             vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method.name))]
432                         };
433                         let struct_pat_shorthand_field = self.maybe_get_struct_pattern_shorthand_field(expr);
434                         if let Some(name) = struct_pat_shorthand_field {
435                             sugg.insert(
436                                 0,
437                                 (expr.span.shrink_to_lo(), format!("{}: ", name)),
438                             );
439                         }
440                         Some(sugg)
441                     })
442                     .peekable();
443                 if suggestions.peek().is_some() {
444                     err.multipart_suggestions(
445                         "try using a conversion method",
446                         suggestions,
447                         Applicability::MaybeIncorrect,
448                     );
449                     return true;
450                 }
451             } else if let ty::Adt(found_adt, found_substs) = found.kind()
452                 && self.tcx.is_diagnostic_item(sym::Option, found_adt.did())
453                 && let ty::Adt(expected_adt, expected_substs) = expected.kind()
454                 && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did())
455                 && let ty::Ref(_, inner_ty, _) = expected_substs.type_at(0).kind()
456                 && inner_ty.is_str()
457             {
458                 let ty = found_substs.type_at(0);
459                 let mut peeled = ty;
460                 let mut ref_cnt = 0;
461                 while let ty::Ref(_, inner, _) = peeled.kind() {
462                     peeled = *inner;
463                     ref_cnt += 1;
464                 }
465                 if let ty::Adt(adt, _) = peeled.kind()
466                     && Some(adt.did()) == self.tcx.lang_items().string()
467                 {
468                     err.span_suggestion_verbose(
469                         expr.span.shrink_to_hi(),
470                         "try converting the passed type into a `&str`",
471                         format!(".map(|x| &*{}x)", "*".repeat(ref_cnt)),
472                         Applicability::MaybeIncorrect,
473                     );
474                     return true;
475                 }
476             }
477         }
478
479         false
480     }
481
482     /// When encountering the expected boxed value allocated in the stack, suggest allocating it
483     /// in the heap by calling `Box::new()`.
484     pub(in super::super) fn suggest_boxing_when_appropriate(
485         &self,
486         err: &mut Diagnostic,
487         expr: &hir::Expr<'_>,
488         expected: Ty<'tcx>,
489         found: Ty<'tcx>,
490     ) -> bool {
491         if self.tcx.hir().is_inside_const_context(expr.hir_id) {
492             // Do not suggest `Box::new` in const context.
493             return false;
494         }
495         if !expected.is_box() || found.is_box() {
496             return false;
497         }
498         let boxed_found = self.tcx.mk_box(found);
499         if self.can_coerce(boxed_found, expected) {
500             err.multipart_suggestion(
501                 "store this in the heap by calling `Box::new`",
502                 vec![
503                     (expr.span.shrink_to_lo(), "Box::new(".to_string()),
504                     (expr.span.shrink_to_hi(), ")".to_string()),
505                 ],
506                 Applicability::MachineApplicable,
507             );
508             err.note(
509                 "for more on the distinction between the stack and the heap, read \
510                  https://doc.rust-lang.org/book/ch15-01-box.html, \
511                  https://doc.rust-lang.org/rust-by-example/std/box.html, and \
512                  https://doc.rust-lang.org/std/boxed/index.html",
513             );
514             true
515         } else {
516             false
517         }
518     }
519
520     /// When encountering a closure that captures variables, where a FnPtr is expected,
521     /// suggest a non-capturing closure
522     pub(in super::super) fn suggest_no_capture_closure(
523         &self,
524         err: &mut Diagnostic,
525         expected: Ty<'tcx>,
526         found: Ty<'tcx>,
527     ) -> bool {
528         if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
529             if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
530                 // Report upto four upvars being captured to reduce the amount error messages
531                 // reported back to the user.
532                 let spans_and_labels = upvars
533                     .iter()
534                     .take(4)
535                     .map(|(var_hir_id, upvar)| {
536                         let var_name = self.tcx.hir().name(*var_hir_id).to_string();
537                         let msg = format!("`{}` captured here", var_name);
538                         (upvar.span, msg)
539                     })
540                     .collect::<Vec<_>>();
541
542                 let mut multi_span: MultiSpan =
543                     spans_and_labels.iter().map(|(sp, _)| *sp).collect::<Vec<_>>().into();
544                 for (sp, label) in spans_and_labels {
545                     multi_span.push_span_label(sp, label);
546                 }
547                 err.span_note(
548                     multi_span,
549                     "closures can only be coerced to `fn` types if they do not capture any variables"
550                 );
551                 return true;
552             }
553         }
554         false
555     }
556
557     /// When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.
558     #[instrument(skip(self, err))]
559     pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
560         &self,
561         err: &mut Diagnostic,
562         expr: &hir::Expr<'_>,
563         expected: Ty<'tcx>,
564         found: Ty<'tcx>,
565     ) -> bool {
566         // Handle #68197.
567
568         if self.tcx.hir().is_inside_const_context(expr.hir_id) {
569             // Do not suggest `Box::new` in const context.
570             return false;
571         }
572         let pin_did = self.tcx.lang_items().pin_type();
573         // This guards the `unwrap` and `mk_box` below.
574         if pin_did.is_none() || self.tcx.lang_items().owned_box().is_none() {
575             return false;
576         }
577         let box_found = self.tcx.mk_box(found);
578         let pin_box_found = self.tcx.mk_lang_item(box_found, LangItem::Pin).unwrap();
579         let pin_found = self.tcx.mk_lang_item(found, LangItem::Pin).unwrap();
580         match expected.kind() {
581             ty::Adt(def, _) if Some(def.did()) == pin_did => {
582                 if self.can_coerce(pin_box_found, expected) {
583                     debug!("can coerce {:?} to {:?}, suggesting Box::pin", pin_box_found, expected);
584                     match found.kind() {
585                         ty::Adt(def, _) if def.is_box() => {
586                             err.help("use `Box::pin`");
587                         }
588                         _ => {
589                             err.multipart_suggestion(
590                                 "you need to pin and box this expression",
591                                 vec![
592                                     (expr.span.shrink_to_lo(), "Box::pin(".to_string()),
593                                     (expr.span.shrink_to_hi(), ")".to_string()),
594                                 ],
595                                 Applicability::MaybeIncorrect,
596                             );
597                         }
598                     }
599                     true
600                 } else if self.can_coerce(pin_found, expected) {
601                     match found.kind() {
602                         ty::Adt(def, _) if def.is_box() => {
603                             err.help("use `Box::pin`");
604                             true
605                         }
606                         _ => false,
607                     }
608                 } else {
609                     false
610                 }
611             }
612             ty::Adt(def, _) if def.is_box() && self.can_coerce(box_found, expected) => {
613                 // Check if the parent expression is a call to Pin::new.  If it
614                 // is and we were expecting a Box, ergo Pin<Box<expected>>, we
615                 // can suggest Box::pin.
616                 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
617                 let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else {
618                     return false;
619                 };
620                 match fn_name.kind {
621                     ExprKind::Path(QPath::TypeRelative(
622                         hir::Ty {
623                             kind: TyKind::Path(QPath::Resolved(_, Path { res: recv_ty, .. })),
624                             ..
625                         },
626                         method,
627                     )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => {
628                         err.span_suggestion(
629                             fn_name.span,
630                             "use `Box::pin` to pin and box this expression",
631                             "Box::pin",
632                             Applicability::MachineApplicable,
633                         );
634                         true
635                     }
636                     _ => false,
637                 }
638             }
639             _ => false,
640         }
641     }
642
643     /// A common error is to forget to add a semicolon at the end of a block, e.g.,
644     ///
645     /// ```compile_fail,E0308
646     /// # fn bar_that_returns_u32() -> u32 { 4 }
647     /// fn foo() {
648     ///     bar_that_returns_u32()
649     /// }
650     /// ```
651     ///
652     /// This routine checks if the return expression in a block would make sense on its own as a
653     /// statement and the return type has been left as default or has been specified as `()`. If so,
654     /// it suggests adding a semicolon.
655     ///
656     /// If the expression is the expression of a closure without block (`|| expr`), a
657     /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
658     pub fn suggest_missing_semicolon(
659         &self,
660         err: &mut Diagnostic,
661         expression: &'tcx hir::Expr<'tcx>,
662         expected: Ty<'tcx>,
663         needs_block: bool,
664     ) {
665         if expected.is_unit() {
666             // `BlockTailExpression` only relevant if the tail expr would be
667             // useful on its own.
668             match expression.kind {
669                 ExprKind::Call(..)
670                 | ExprKind::MethodCall(..)
671                 | ExprKind::Loop(..)
672                 | ExprKind::If(..)
673                 | ExprKind::Match(..)
674                 | ExprKind::Block(..)
675                     if expression.can_have_side_effects()
676                         // If the expression is from an external macro, then do not suggest
677                         // adding a semicolon, because there's nowhere to put it.
678                         // See issue #81943.
679                         && !in_external_macro(self.tcx.sess, expression.span) =>
680                 {
681                     if needs_block {
682                         err.multipart_suggestion(
683                             "consider using a semicolon here",
684                             vec![
685                                 (expression.span.shrink_to_lo(), "{ ".to_owned()),
686                                 (expression.span.shrink_to_hi(), "; }".to_owned()),
687                             ],
688                             Applicability::MachineApplicable,
689                         );
690                     } else {
691                         err.span_suggestion(
692                             expression.span.shrink_to_hi(),
693                             "consider using a semicolon here",
694                             ";",
695                             Applicability::MachineApplicable,
696                         );
697                     }
698                 }
699                 _ => (),
700             }
701         }
702     }
703
704     /// A possible error is to forget to add a return type that is needed:
705     ///
706     /// ```compile_fail,E0308
707     /// # fn bar_that_returns_u32() -> u32 { 4 }
708     /// fn foo() {
709     ///     bar_that_returns_u32()
710     /// }
711     /// ```
712     ///
713     /// This routine checks if the return type is left as default, the method is not part of an
714     /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return
715     /// type.
716     pub(in super::super) fn suggest_missing_return_type(
717         &self,
718         err: &mut Diagnostic,
719         fn_decl: &hir::FnDecl<'_>,
720         expected: Ty<'tcx>,
721         found: Ty<'tcx>,
722         can_suggest: bool,
723         fn_id: hir::HirId,
724     ) -> bool {
725         let found =
726             self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
727         // Only suggest changing the return type for methods that
728         // haven't set a return type at all (and aren't `fn main()` or an impl).
729         match &fn_decl.output {
730             &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
731                 // `fn main()` must return `()`, do not suggest changing return type
732                 err.subdiagnostic(ExpectedReturnTypeLabel::Unit { span });
733                 return true;
734             }
735             &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
736                 if found.is_suggestable(self.tcx, false) {
737                     err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() });
738                     return true;
739                 } else if let ty::Closure(_, substs) = found.kind()
740                     // FIXME(compiler-errors): Get better at printing binders...
741                     && let closure = substs.as_closure()
742                     && closure.sig().is_suggestable(self.tcx, false)
743                 {
744                     err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: closure.print_as_impl_trait().to_string() });
745                     return true;
746                 } else {
747                     // FIXME: if `found` could be `impl Iterator` we should suggest that.
748                     err.subdiagnostic(AddReturnTypeSuggestion::MissingHere { span });
749                     return true
750                 }
751             }
752             &hir::FnRetTy::Return(ref ty) => {
753                 // Only point to return type if the expected type is the return type, as if they
754                 // are not, the expectation must have been caused by something else.
755                 debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind);
756                 let span = ty.span;
757                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
758                 debug!("suggest_missing_return_type: return type {:?}", ty);
759                 debug!("suggest_missing_return_type: expected type {:?}", ty);
760                 let bound_vars = self.tcx.late_bound_vars(fn_id);
761                 let ty = Binder::bind_with_vars(ty, bound_vars);
762                 let ty = self.normalize_associated_types_in(span, ty);
763                 let ty = self.tcx.erase_late_bound_regions(ty);
764                 if self.can_coerce(expected, ty) {
765                     err.subdiagnostic(ExpectedReturnTypeLabel::Other { span, expected });
766                     self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
767                     return true;
768                 }
769             }
770             _ => {}
771         }
772         false
773     }
774
775     /// check whether the return type is a generic type with a trait bound
776     /// only suggest this if the generic param is not present in the arguments
777     /// if this is true, hint them towards changing the return type to `impl Trait`
778     /// ```compile_fail,E0308
779     /// fn cant_name_it<T: Fn() -> u32>() -> T {
780     ///     || 3
781     /// }
782     /// ```
783     fn try_suggest_return_impl_trait(
784         &self,
785         err: &mut Diagnostic,
786         expected: Ty<'tcx>,
787         found: Ty<'tcx>,
788         fn_id: hir::HirId,
789     ) {
790         // Only apply the suggestion if:
791         //  - the return type is a generic parameter
792         //  - the generic param is not used as a fn param
793         //  - the generic param has at least one bound
794         //  - the generic param doesn't appear in any other bounds where it's not the Self type
795         // Suggest:
796         //  - Changing the return type to be `impl <all bounds>`
797
798         debug!("try_suggest_return_impl_trait, expected = {:?}, found = {:?}", expected, found);
799
800         let ty::Param(expected_ty_as_param) = expected.kind() else { return };
801
802         let fn_node = self.tcx.hir().find(fn_id);
803
804         let Some(hir::Node::Item(hir::Item {
805             kind:
806                 hir::ItemKind::Fn(
807                     hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. },
808                     hir::Generics { params, predicates, .. },
809                     _body_id,
810                 ),
811             ..
812         })) = fn_node else { return };
813
814         if params.get(expected_ty_as_param.index as usize).is_none() {
815             return;
816         };
817
818         // get all where BoundPredicates here, because they are used in to cases below
819         let where_predicates = predicates
820             .iter()
821             .filter_map(|p| match p {
822                 WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
823                     bounds,
824                     bounded_ty,
825                     ..
826                 }) => {
827                     // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below)
828                     let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, bounded_ty);
829                     Some((ty, bounds))
830                 }
831                 _ => None,
832             })
833             .map(|(ty, bounds)| match ty.kind() {
834                 ty::Param(param_ty) if param_ty == expected_ty_as_param => Ok(Some(bounds)),
835                 // check whether there is any predicate that contains our `T`, like `Option<T>: Send`
836                 _ => match ty.contains(expected) {
837                     true => Err(()),
838                     false => Ok(None),
839                 },
840             })
841             .collect::<Result<Vec<_>, _>>();
842
843         let Ok(where_predicates) = where_predicates else { return };
844
845         // now get all predicates in the same types as the where bounds, so we can chain them
846         let predicates_from_where =
847             where_predicates.iter().flatten().flat_map(|bounds| bounds.iter());
848
849         // extract all bounds from the source code using their spans
850         let all_matching_bounds_strs = predicates_from_where
851             .filter_map(|bound| match bound {
852                 GenericBound::Trait(_, _) => {
853                     self.tcx.sess.source_map().span_to_snippet(bound.span()).ok()
854                 }
855                 _ => None,
856             })
857             .collect::<Vec<String>>();
858
859         if all_matching_bounds_strs.len() == 0 {
860             return;
861         }
862
863         let all_bounds_str = all_matching_bounds_strs.join(" + ");
864
865         let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| {
866                 let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, param);
867                 matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param)
868             });
869
870         if ty_param_used_in_fn_params {
871             return;
872         }
873
874         err.span_suggestion(
875             fn_return.span(),
876             "consider using an impl return type",
877             format!("impl {}", all_bounds_str),
878             Applicability::MaybeIncorrect,
879         );
880     }
881
882     pub(in super::super) fn suggest_missing_break_or_return_expr(
883         &self,
884         err: &mut Diagnostic,
885         expr: &'tcx hir::Expr<'tcx>,
886         fn_decl: &hir::FnDecl<'_>,
887         expected: Ty<'tcx>,
888         found: Ty<'tcx>,
889         id: hir::HirId,
890         fn_id: hir::HirId,
891     ) {
892         if !expected.is_unit() {
893             return;
894         }
895         let found = self.resolve_vars_with_obligations(found);
896
897         let in_loop = self.is_loop(id)
898             || self.tcx.hir().parent_iter(id).any(|(parent_id, _)| self.is_loop(parent_id));
899
900         let in_local_statement = self.is_local_statement(id)
901             || self
902                 .tcx
903                 .hir()
904                 .parent_iter(id)
905                 .any(|(parent_id, _)| self.is_local_statement(parent_id));
906
907         if in_loop && in_local_statement {
908             err.multipart_suggestion(
909                 "you might have meant to break the loop with this value",
910                 vec![
911                     (expr.span.shrink_to_lo(), "break ".to_string()),
912                     (expr.span.shrink_to_hi(), ";".to_string()),
913                 ],
914                 Applicability::MaybeIncorrect,
915             );
916             return;
917         }
918
919         if let hir::FnRetTy::Return(ty) = fn_decl.output {
920             let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
921             let bound_vars = self.tcx.late_bound_vars(fn_id);
922             let ty = self.tcx.erase_late_bound_regions(Binder::bind_with_vars(ty, bound_vars));
923             let ty = self.normalize_associated_types_in(expr.span, ty);
924             let ty = match self.tcx.asyncness(fn_id.owner) {
925                 hir::IsAsync::Async => {
926                     let infcx = self.tcx.infer_ctxt().build();
927                     infcx.get_impl_future_output_ty(ty).unwrap_or_else(|| {
928                         span_bug!(
929                             fn_decl.output.span(),
930                             "failed to get output type of async function"
931                         )
932                     })
933                 }
934                 hir::IsAsync::NotAsync => ty,
935             };
936             if self.can_coerce(found, ty) {
937                 err.multipart_suggestion(
938                     "you might have meant to return this value",
939                     vec![
940                         (expr.span.shrink_to_lo(), "return ".to_string()),
941                         (expr.span.shrink_to_hi(), ";".to_string()),
942                     ],
943                     Applicability::MaybeIncorrect,
944                 );
945             }
946         }
947     }
948
949     pub(in super::super) fn suggest_missing_parentheses(
950         &self,
951         err: &mut Diagnostic,
952         expr: &hir::Expr<'_>,
953     ) -> bool {
954         let sp = self.tcx.sess.source_map().start_point(expr.span);
955         if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) {
956             // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
957             err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
958             true
959         } else {
960             false
961         }
962     }
963
964     /// Given an expression type mismatch, peel any `&` expressions until we get to
965     /// a block expression, and then suggest replacing the braces with square braces
966     /// if it was possibly mistaken array syntax.
967     pub(crate) fn suggest_block_to_brackets_peeling_refs(
968         &self,
969         diag: &mut Diagnostic,
970         mut expr: &hir::Expr<'_>,
971         mut expr_ty: Ty<'tcx>,
972         mut expected_ty: Ty<'tcx>,
973     ) -> bool {
974         loop {
975             match (&expr.kind, expr_ty.kind(), expected_ty.kind()) {
976                 (
977                     hir::ExprKind::AddrOf(_, _, inner_expr),
978                     ty::Ref(_, inner_expr_ty, _),
979                     ty::Ref(_, inner_expected_ty, _),
980                 ) => {
981                     expr = *inner_expr;
982                     expr_ty = *inner_expr_ty;
983                     expected_ty = *inner_expected_ty;
984                 }
985                 (hir::ExprKind::Block(blk, _), _, _) => {
986                     self.suggest_block_to_brackets(diag, *blk, expr_ty, expected_ty);
987                     break true;
988                 }
989                 _ => break false,
990             }
991         }
992     }
993
994     pub(crate) fn suggest_copied_or_cloned(
995         &self,
996         diag: &mut Diagnostic,
997         expr: &hir::Expr<'_>,
998         expr_ty: Ty<'tcx>,
999         expected_ty: Ty<'tcx>,
1000     ) -> bool {
1001         let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; };
1002         let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; };
1003         if adt_def != expected_adt_def {
1004             return false;
1005         }
1006
1007         let mut suggest_copied_or_cloned = || {
1008             let expr_inner_ty = substs.type_at(0);
1009             let expected_inner_ty = expected_substs.type_at(0);
1010             if let ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind()
1011                 && self.can_eq(self.param_env, *ty, expected_inner_ty).is_ok()
1012             {
1013                 let def_path = self.tcx.def_path_str(adt_def.did());
1014                 if self.type_is_copy_modulo_regions(self.param_env, *ty, expr.span) {
1015                     diag.span_suggestion_verbose(
1016                         expr.span.shrink_to_hi(),
1017                         format!(
1018                             "use `{def_path}::copied` to copy the value inside the `{def_path}`"
1019                         ),
1020                         ".copied()",
1021                         Applicability::MachineApplicable,
1022                     );
1023                     return true;
1024                 } else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
1025                     && rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
1026                         self,
1027                         self.param_env,
1028                         *ty,
1029                         clone_did,
1030                         expr.span
1031                     )
1032                 {
1033                     diag.span_suggestion_verbose(
1034                         expr.span.shrink_to_hi(),
1035                         format!(
1036                             "use `{def_path}::cloned` to clone the value inside the `{def_path}`"
1037                         ),
1038                         ".cloned()",
1039                         Applicability::MachineApplicable,
1040                     );
1041                     return true;
1042                 }
1043             }
1044             false
1045         };
1046
1047         if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result)
1048             && adt_def.did() == result_did
1049             // Check that the error types are equal
1050             && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)).is_ok()
1051         {
1052             return suggest_copied_or_cloned();
1053         } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option)
1054             && adt_def.did() == option_did
1055         {
1056             return suggest_copied_or_cloned();
1057         }
1058
1059         false
1060     }
1061
1062     pub(crate) fn suggest_into(
1063         &self,
1064         diag: &mut Diagnostic,
1065         expr: &hir::Expr<'_>,
1066         expr_ty: Ty<'tcx>,
1067         expected_ty: Ty<'tcx>,
1068     ) -> bool {
1069         let expr = expr.peel_blocks();
1070
1071         // We have better suggestions for scalar interconversions...
1072         if expr_ty.is_scalar() && expected_ty.is_scalar() {
1073             return false;
1074         }
1075
1076         // Don't suggest turning a block into another type (e.g. `{}.into()`)
1077         if matches!(expr.kind, hir::ExprKind::Block(..)) {
1078             return false;
1079         }
1080
1081         // We'll later suggest `.as_ref` when noting the type error,
1082         // so skip if we will suggest that instead.
1083         if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1084             return false;
1085         }
1086
1087         if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1088             && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1089                 self.tcx,
1090                 self.misc(expr.span),
1091                 self.param_env,
1092                 ty::Binder::dummy(self.tcx.mk_trait_ref(
1093                     into_def_id,
1094                     [expr_ty, expected_ty]
1095                 )),
1096             ))
1097         {
1098             let sugg = if expr.precedence().order() >= PREC_POSTFIX {
1099                 vec![(expr.span.shrink_to_hi(), ".into()".to_owned())]
1100             } else {
1101                 vec![(expr.span.shrink_to_lo(), "(".to_owned()), (expr.span.shrink_to_hi(), ").into()".to_owned())]
1102             };
1103             diag.multipart_suggestion(
1104                 format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1105                 sugg,
1106                 Applicability::MaybeIncorrect
1107             );
1108             return true;
1109         }
1110
1111         false
1112     }
1113
1114     /// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
1115     pub(crate) fn suggest_option_to_bool(
1116         &self,
1117         diag: &mut Diagnostic,
1118         expr: &hir::Expr<'_>,
1119         expr_ty: Ty<'tcx>,
1120         expected_ty: Ty<'tcx>,
1121     ) -> bool {
1122         if !expected_ty.is_bool() {
1123             return false;
1124         }
1125
1126         let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { return false; };
1127         if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1128             return false;
1129         }
1130
1131         let hir = self.tcx.hir();
1132         let cond_parent = hir.parent_iter(expr.hir_id).skip_while(|(_, node)| {
1133             matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. }) if op.node == hir::BinOpKind::And)
1134         }).next();
1135         // Don't suggest:
1136         //     `let Some(_) = a.is_some() && b`
1137         //                     ++++++++++
1138         // since the user probably just misunderstood how `let else`
1139         // and `&&` work together.
1140         if let Some((_, hir::Node::Local(local))) = cond_parent
1141             && let hir::PatKind::Path(qpath) | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1142             && let hir::QPath::Resolved(None, path) = qpath
1143             && let Some(did) = path.res.opt_def_id()
1144                 .and_then(|did| self.tcx.opt_parent(did))
1145                 .and_then(|did| self.tcx.opt_parent(did))
1146             && self.tcx.is_diagnostic_item(sym::Option, did)
1147         {
1148             return false;
1149         }
1150
1151         diag.span_suggestion(
1152             expr.span.shrink_to_hi(),
1153             "use `Option::is_some` to test if the `Option` has a value",
1154             ".is_some()",
1155             Applicability::MachineApplicable,
1156         );
1157
1158         true
1159     }
1160
1161     /// Suggest wrapping the block in square brackets instead of curly braces
1162     /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1163     pub(crate) fn suggest_block_to_brackets(
1164         &self,
1165         diag: &mut Diagnostic,
1166         blk: &hir::Block<'_>,
1167         blk_ty: Ty<'tcx>,
1168         expected_ty: Ty<'tcx>,
1169     ) {
1170         if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1171             if self.can_coerce(blk_ty, *elem_ty)
1172                 && blk.stmts.is_empty()
1173                 && blk.rules == hir::BlockCheckMode::DefaultBlock
1174             {
1175                 let source_map = self.tcx.sess.source_map();
1176                 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
1177                     if snippet.starts_with('{') && snippet.ends_with('}') {
1178                         diag.multipart_suggestion_verbose(
1179                             "to create an array, use square brackets instead of curly braces",
1180                             vec![
1181                                 (
1182                                     blk.span
1183                                         .shrink_to_lo()
1184                                         .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1185                                     "[".to_string(),
1186                                 ),
1187                                 (
1188                                     blk.span
1189                                         .shrink_to_hi()
1190                                         .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1191                                     "]".to_string(),
1192                                 ),
1193                             ],
1194                             Applicability::MachineApplicable,
1195                         );
1196                     }
1197                 }
1198             }
1199         }
1200     }
1201
1202     #[instrument(skip(self, err))]
1203     pub(crate) fn suggest_floating_point_literal(
1204         &self,
1205         err: &mut Diagnostic,
1206         expr: &hir::Expr<'_>,
1207         expected_ty: Ty<'tcx>,
1208     ) -> bool {
1209         if !expected_ty.is_floating_point() {
1210             return false;
1211         }
1212         match expr.kind {
1213             ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [start, end], _) => {
1214                 err.span_suggestion_verbose(
1215                     start.span.shrink_to_hi().with_hi(end.span.lo()),
1216                     "remove the unnecessary `.` operator for a floating point literal",
1217                     '.',
1218                     Applicability::MaybeIncorrect,
1219                 );
1220                 true
1221             }
1222             ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, ..), [start], _) => {
1223                 err.span_suggestion_verbose(
1224                     expr.span.with_lo(start.span.hi()),
1225                     "remove the unnecessary `.` operator for a floating point literal",
1226                     '.',
1227                     Applicability::MaybeIncorrect,
1228                 );
1229                 true
1230             }
1231             ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, ..), [end], _) => {
1232                 err.span_suggestion_verbose(
1233                     expr.span.until(end.span),
1234                     "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1235                     "0.",
1236                     Applicability::MaybeIncorrect,
1237                 );
1238                 true
1239             }
1240             _ => false,
1241         }
1242     }
1243
1244     fn is_loop(&self, id: hir::HirId) -> bool {
1245         let node = self.tcx.hir().get(id);
1246         matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1247     }
1248
1249     fn is_local_statement(&self, id: hir::HirId) -> bool {
1250         let node = self.tcx.hir().get(id);
1251         matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
1252     }
1253
1254     /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1255     /// which is a side-effect of autoref.
1256     pub(crate) fn note_type_is_not_clone(
1257         &self,
1258         diag: &mut Diagnostic,
1259         expected_ty: Ty<'tcx>,
1260         found_ty: Ty<'tcx>,
1261         expr: &hir::Expr<'_>,
1262     ) {
1263         let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; };
1264         let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
1265         let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1266         let results = self.typeck_results.borrow();
1267         // First, look for a `Clone::clone` call
1268         if segment.ident.name == sym::clone
1269             && results.type_dependent_def_id(expr.hir_id).map_or(
1270                 false,
1271                 |did| {
1272                     let assoc_item = self.tcx.associated_item(did);
1273                     assoc_item.container == ty::AssocItemContainer::TraitContainer
1274                         && assoc_item.container_id(self.tcx) == clone_trait_did
1275                 },
1276             )
1277             // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1278             // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1279             && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1280             // Check that we're in fact trying to clone into the expected type
1281             && self.can_coerce(*pointee_ty, expected_ty)
1282             // And the expected type doesn't implement `Clone`
1283             && !self.predicate_must_hold_considering_regions(&traits::Obligation {
1284                 cause: traits::ObligationCause::dummy(),
1285                 param_env: self.param_env,
1286                 recursion_depth: 0,
1287                 predicate: ty::Binder::dummy(ty::TraitRef {
1288                     def_id: clone_trait_did,
1289                     substs: self.tcx.mk_substs([expected_ty.into()].iter()),
1290                 })
1291                 .without_const()
1292                 .to_predicate(self.tcx),
1293             })
1294         {
1295             diag.span_note(
1296                 callee_expr.span,
1297                 &format!(
1298                     "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1299                 ),
1300             );
1301         }
1302     }
1303
1304     /// A common error is to add an extra semicolon:
1305     ///
1306     /// ```compile_fail,E0308
1307     /// fn foo() -> usize {
1308     ///     22;
1309     /// }
1310     /// ```
1311     ///
1312     /// This routine checks if the final statement in a block is an
1313     /// expression with an explicit semicolon whose type is compatible
1314     /// with `expected_ty`. If so, it suggests removing the semicolon.
1315     pub(crate) fn consider_removing_semicolon(
1316         &self,
1317         blk: &'tcx hir::Block<'tcx>,
1318         expected_ty: Ty<'tcx>,
1319         err: &mut Diagnostic,
1320     ) -> bool {
1321         if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
1322             if let StatementAsExpression::NeedsBoxing = boxed {
1323                 err.span_suggestion_verbose(
1324                     span_semi,
1325                     "consider removing this semicolon and boxing the expression",
1326                     "",
1327                     Applicability::HasPlaceholders,
1328                 );
1329             } else {
1330                 err.span_suggestion_short(
1331                     span_semi,
1332                     "remove this semicolon to return this value",
1333                     "",
1334                     Applicability::MachineApplicable,
1335                 );
1336             }
1337             true
1338         } else {
1339             false
1340         }
1341     }
1342 }