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