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