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