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