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