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