]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs
Auto merge of #106224 - bjorn3:staticlib_fixes, r=wesleywiser
[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().get_parent_node(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().get_parent_node(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_copied_or_cloned(
1018         &self,
1019         diag: &mut Diagnostic,
1020         expr: &hir::Expr<'_>,
1021         expr_ty: Ty<'tcx>,
1022         expected_ty: Ty<'tcx>,
1023     ) -> bool {
1024         let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; };
1025         let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; };
1026         if adt_def != expected_adt_def {
1027             return false;
1028         }
1029
1030         let mut suggest_copied_or_cloned = || {
1031             let expr_inner_ty = substs.type_at(0);
1032             let expected_inner_ty = expected_substs.type_at(0);
1033             if let ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind()
1034                 && self.can_eq(self.param_env, *ty, expected_inner_ty).is_ok()
1035             {
1036                 let def_path = self.tcx.def_path_str(adt_def.did());
1037                 if self.type_is_copy_modulo_regions(self.param_env, *ty, expr.span) {
1038                     diag.span_suggestion_verbose(
1039                         expr.span.shrink_to_hi(),
1040                         format!(
1041                             "use `{def_path}::copied` to copy the value inside the `{def_path}`"
1042                         ),
1043                         ".copied()",
1044                         Applicability::MachineApplicable,
1045                     );
1046                     return true;
1047                 } else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
1048                     && rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
1049                         self,
1050                         self.param_env,
1051                         *ty,
1052                         clone_did,
1053                         expr.span
1054                     )
1055                 {
1056                     diag.span_suggestion_verbose(
1057                         expr.span.shrink_to_hi(),
1058                         format!(
1059                             "use `{def_path}::cloned` to clone the value inside the `{def_path}`"
1060                         ),
1061                         ".cloned()",
1062                         Applicability::MachineApplicable,
1063                     );
1064                     return true;
1065                 }
1066             }
1067             false
1068         };
1069
1070         if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result)
1071             && adt_def.did() == result_did
1072             // Check that the error types are equal
1073             && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)).is_ok()
1074         {
1075             return suggest_copied_or_cloned();
1076         } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option)
1077             && adt_def.did() == option_did
1078         {
1079             return suggest_copied_or_cloned();
1080         }
1081
1082         false
1083     }
1084
1085     pub(crate) fn suggest_into(
1086         &self,
1087         diag: &mut Diagnostic,
1088         expr: &hir::Expr<'_>,
1089         expr_ty: Ty<'tcx>,
1090         expected_ty: Ty<'tcx>,
1091     ) -> bool {
1092         let expr = expr.peel_blocks();
1093
1094         // We have better suggestions for scalar interconversions...
1095         if expr_ty.is_scalar() && expected_ty.is_scalar() {
1096             return false;
1097         }
1098
1099         // Don't suggest turning a block into another type (e.g. `{}.into()`)
1100         if matches!(expr.kind, hir::ExprKind::Block(..)) {
1101             return false;
1102         }
1103
1104         // We'll later suggest `.as_ref` when noting the type error,
1105         // so skip if we will suggest that instead.
1106         if self.err_ctxt().should_suggest_as_ref(expected_ty, expr_ty).is_some() {
1107             return false;
1108         }
1109
1110         if let Some(into_def_id) = self.tcx.get_diagnostic_item(sym::Into)
1111             && self.predicate_must_hold_modulo_regions(&traits::Obligation::new(
1112                 self.tcx,
1113                 self.misc(expr.span),
1114                 self.param_env,
1115                 ty::Binder::dummy(self.tcx.mk_trait_ref(
1116                     into_def_id,
1117                     [expr_ty, expected_ty]
1118                 )),
1119             ))
1120         {
1121             let sugg = if expr.precedence().order() >= PREC_POSTFIX {
1122                 vec![(expr.span.shrink_to_hi(), ".into()".to_owned())]
1123             } else {
1124                 vec![(expr.span.shrink_to_lo(), "(".to_owned()), (expr.span.shrink_to_hi(), ").into()".to_owned())]
1125             };
1126             diag.multipart_suggestion(
1127                 format!("call `Into::into` on this expression to convert `{expr_ty}` into `{expected_ty}`"),
1128                 sugg,
1129                 Applicability::MaybeIncorrect
1130             );
1131             return true;
1132         }
1133
1134         false
1135     }
1136
1137     /// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
1138     pub(crate) fn suggest_option_to_bool(
1139         &self,
1140         diag: &mut Diagnostic,
1141         expr: &hir::Expr<'_>,
1142         expr_ty: Ty<'tcx>,
1143         expected_ty: Ty<'tcx>,
1144     ) -> bool {
1145         if !expected_ty.is_bool() {
1146             return false;
1147         }
1148
1149         let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { return false; };
1150         if !self.tcx.is_diagnostic_item(sym::Option, def.did()) {
1151             return false;
1152         }
1153
1154         let hir = self.tcx.hir();
1155         let cond_parent = hir.parent_iter(expr.hir_id).find(|(_, node)| {
1156             !matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(op, _, _), .. }) if op.node == hir::BinOpKind::And)
1157         });
1158         // Don't suggest:
1159         //     `let Some(_) = a.is_some() && b`
1160         //                     ++++++++++
1161         // since the user probably just misunderstood how `let else`
1162         // and `&&` work together.
1163         if let Some((_, hir::Node::Local(local))) = cond_parent
1164             && let hir::PatKind::Path(qpath) | hir::PatKind::TupleStruct(qpath, _, _) = &local.pat.kind
1165             && let hir::QPath::Resolved(None, path) = qpath
1166             && let Some(did) = path.res.opt_def_id()
1167                 .and_then(|did| self.tcx.opt_parent(did))
1168                 .and_then(|did| self.tcx.opt_parent(did))
1169             && self.tcx.is_diagnostic_item(sym::Option, did)
1170         {
1171             return false;
1172         }
1173
1174         diag.span_suggestion(
1175             expr.span.shrink_to_hi(),
1176             "use `Option::is_some` to test if the `Option` has a value",
1177             ".is_some()",
1178             Applicability::MachineApplicable,
1179         );
1180
1181         true
1182     }
1183
1184     /// Suggest wrapping the block in square brackets instead of curly braces
1185     /// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
1186     pub(crate) fn suggest_block_to_brackets(
1187         &self,
1188         diag: &mut Diagnostic,
1189         blk: &hir::Block<'_>,
1190         blk_ty: Ty<'tcx>,
1191         expected_ty: Ty<'tcx>,
1192     ) {
1193         if let ty::Slice(elem_ty) | ty::Array(elem_ty, _) = expected_ty.kind() {
1194             if self.can_coerce(blk_ty, *elem_ty)
1195                 && blk.stmts.is_empty()
1196                 && blk.rules == hir::BlockCheckMode::DefaultBlock
1197             {
1198                 let source_map = self.tcx.sess.source_map();
1199                 if let Ok(snippet) = source_map.span_to_snippet(blk.span) {
1200                     if snippet.starts_with('{') && snippet.ends_with('}') {
1201                         diag.multipart_suggestion_verbose(
1202                             "to create an array, use square brackets instead of curly braces",
1203                             vec![
1204                                 (
1205                                     blk.span
1206                                         .shrink_to_lo()
1207                                         .with_hi(rustc_span::BytePos(blk.span.lo().0 + 1)),
1208                                     "[".to_string(),
1209                                 ),
1210                                 (
1211                                     blk.span
1212                                         .shrink_to_hi()
1213                                         .with_lo(rustc_span::BytePos(blk.span.hi().0 - 1)),
1214                                     "]".to_string(),
1215                                 ),
1216                             ],
1217                             Applicability::MachineApplicable,
1218                         );
1219                     }
1220                 }
1221             }
1222         }
1223     }
1224
1225     #[instrument(skip(self, err))]
1226     pub(crate) fn suggest_floating_point_literal(
1227         &self,
1228         err: &mut Diagnostic,
1229         expr: &hir::Expr<'_>,
1230         expected_ty: Ty<'tcx>,
1231     ) -> bool {
1232         if !expected_ty.is_floating_point() {
1233             return false;
1234         }
1235         match expr.kind {
1236             ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [start, end], _) => {
1237                 err.span_suggestion_verbose(
1238                     start.span.shrink_to_hi().with_hi(end.span.lo()),
1239                     "remove the unnecessary `.` operator for a floating point literal",
1240                     '.',
1241                     Applicability::MaybeIncorrect,
1242                 );
1243                 true
1244             }
1245             ExprKind::Struct(QPath::LangItem(LangItem::RangeFrom, ..), [start], _) => {
1246                 err.span_suggestion_verbose(
1247                     expr.span.with_lo(start.span.hi()),
1248                     "remove the unnecessary `.` operator for a floating point literal",
1249                     '.',
1250                     Applicability::MaybeIncorrect,
1251                 );
1252                 true
1253             }
1254             ExprKind::Struct(QPath::LangItem(LangItem::RangeTo, ..), [end], _) => {
1255                 err.span_suggestion_verbose(
1256                     expr.span.until(end.span),
1257                     "remove the unnecessary `.` operator and add an integer part for a floating point literal",
1258                     "0.",
1259                     Applicability::MaybeIncorrect,
1260                 );
1261                 true
1262             }
1263             ExprKind::Lit(Spanned {
1264                 node: rustc_ast::LitKind::Int(lit, rustc_ast::LitIntType::Unsuffixed),
1265                 span,
1266             }) => {
1267                 let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) else { return false; };
1268                 if !(snippet.starts_with("0x") || snippet.starts_with("0X")) {
1269                     return false;
1270                 }
1271                 if snippet.len() <= 5 || !snippet.is_char_boundary(snippet.len() - 3) {
1272                     return false;
1273                 }
1274                 let (_, suffix) = snippet.split_at(snippet.len() - 3);
1275                 let value = match suffix {
1276                     "f32" => (lit - 0xf32) / (16 * 16 * 16),
1277                     "f64" => (lit - 0xf64) / (16 * 16 * 16),
1278                     _ => return false,
1279                 };
1280                 err.span_suggestions(
1281                     expr.span,
1282                     "rewrite this as a decimal floating point literal, or use `as` to turn a hex literal into a float",
1283                     [format!("0x{value:X} as {suffix}"), format!("{value}_{suffix}")],
1284                     Applicability::MaybeIncorrect,
1285                 );
1286                 true
1287             }
1288             _ => false,
1289         }
1290     }
1291
1292     pub(crate) fn suggest_associated_const(
1293         &self,
1294         err: &mut Diagnostic,
1295         expr: &hir::Expr<'_>,
1296         expected_ty: Ty<'tcx>,
1297     ) -> bool {
1298         let Some((DefKind::AssocFn, old_def_id)) = self.typeck_results.borrow().type_dependent_def(expr.hir_id) else {
1299             return false;
1300         };
1301         let old_item_name = self.tcx.item_name(old_def_id);
1302         let capitalized_name = Symbol::intern(&old_item_name.as_str().to_uppercase());
1303         if old_item_name == capitalized_name {
1304             return false;
1305         }
1306         let (item, segment) = match expr.kind {
1307             hir::ExprKind::Path(QPath::Resolved(
1308                 Some(ty),
1309                 hir::Path { segments: [segment], .. },
1310             ))
1311             | hir::ExprKind::Path(QPath::TypeRelative(ty, segment)) => {
1312                 let self_ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, ty);
1313                 if let Ok(pick) = self.probe_for_name(
1314                     Mode::Path,
1315                     Ident::new(capitalized_name, segment.ident.span),
1316                     IsSuggestion(true),
1317                     self_ty,
1318                     expr.hir_id,
1319                     ProbeScope::TraitsInScope,
1320                 ) {
1321                     (pick.item, segment)
1322                 } else {
1323                     return false;
1324                 }
1325             }
1326             hir::ExprKind::Path(QPath::Resolved(
1327                 None,
1328                 hir::Path { segments: [.., segment], .. },
1329             )) => {
1330                 // we resolved through some path that doesn't end in the item name,
1331                 // better not do a bad suggestion by accident.
1332                 if old_item_name != segment.ident.name {
1333                     return false;
1334                 }
1335                 if let Some(item) = self
1336                     .tcx
1337                     .associated_items(self.tcx.parent(old_def_id))
1338                     .filter_by_name_unhygienic(capitalized_name)
1339                     .next()
1340                 {
1341                     (*item, segment)
1342                 } else {
1343                     return false;
1344                 }
1345             }
1346             _ => return false,
1347         };
1348         if item.def_id == old_def_id || self.tcx.def_kind(item.def_id) != DefKind::AssocConst {
1349             // Same item
1350             return false;
1351         }
1352         let item_ty = self.tcx.type_of(item.def_id);
1353         // FIXME(compiler-errors): This check is *so* rudimentary
1354         if item_ty.needs_subst() {
1355             return false;
1356         }
1357         if self.can_coerce(item_ty, expected_ty) {
1358             err.span_suggestion_verbose(
1359                 segment.ident.span,
1360                 format!("try referring to the associated const `{capitalized_name}` instead",),
1361                 capitalized_name,
1362                 Applicability::MachineApplicable,
1363             );
1364             true
1365         } else {
1366             false
1367         }
1368     }
1369
1370     fn is_loop(&self, id: hir::HirId) -> bool {
1371         let node = self.tcx.hir().get(id);
1372         matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. }))
1373     }
1374
1375     fn is_local_statement(&self, id: hir::HirId) -> bool {
1376         let node = self.tcx.hir().get(id);
1377         matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. }))
1378     }
1379
1380     /// Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`,
1381     /// which is a side-effect of autoref.
1382     pub(crate) fn note_type_is_not_clone(
1383         &self,
1384         diag: &mut Diagnostic,
1385         expected_ty: Ty<'tcx>,
1386         found_ty: Ty<'tcx>,
1387         expr: &hir::Expr<'_>,
1388     ) {
1389         let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; };
1390         let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; };
1391         let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return };
1392         let results = self.typeck_results.borrow();
1393         // First, look for a `Clone::clone` call
1394         if segment.ident.name == sym::clone
1395             && results.type_dependent_def_id(expr.hir_id).map_or(
1396                 false,
1397                 |did| {
1398                     let assoc_item = self.tcx.associated_item(did);
1399                     assoc_item.container == ty::AssocItemContainer::TraitContainer
1400                         && assoc_item.container_id(self.tcx) == clone_trait_did
1401                 },
1402             )
1403             // If that clone call hasn't already dereferenced the self type (i.e. don't give this
1404             // diagnostic in cases where we have `(&&T).clone()` and we expect `T`).
1405             && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..)))
1406             // Check that we're in fact trying to clone into the expected type
1407             && self.can_coerce(*pointee_ty, expected_ty)
1408             && let trait_ref = ty::Binder::dummy(self.tcx.mk_trait_ref(clone_trait_did, [expected_ty]))
1409             // And the expected type doesn't implement `Clone`
1410             && !self.predicate_must_hold_considering_regions(&traits::Obligation::new(
1411                 self.tcx,
1412                 traits::ObligationCause::dummy(),
1413                 self.param_env,
1414                 trait_ref,
1415             ))
1416         {
1417             diag.span_note(
1418                 callee_expr.span,
1419                 &format!(
1420                     "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
1421                 ),
1422             );
1423             let owner = self.tcx.hir().enclosing_body_owner(expr.hir_id);
1424             if let ty::Param(param) = expected_ty.kind()
1425                 && let Some(generics) = self.tcx.hir().get_generics(owner)
1426             {
1427                 suggest_constraining_type_params(
1428                     self.tcx,
1429                     generics,
1430                     diag,
1431                     vec![(param.name.as_str(), "Clone", Some(clone_trait_did))].into_iter(),
1432                 );
1433             } else {
1434                 self.suggest_derive(diag, &[(trait_ref.to_predicate(self.tcx), None, None)]);
1435             }
1436         }
1437     }
1438
1439     /// A common error is to add an extra semicolon:
1440     ///
1441     /// ```compile_fail,E0308
1442     /// fn foo() -> usize {
1443     ///     22;
1444     /// }
1445     /// ```
1446     ///
1447     /// This routine checks if the final statement in a block is an
1448     /// expression with an explicit semicolon whose type is compatible
1449     /// with `expected_ty`. If so, it suggests removing the semicolon.
1450     pub(crate) fn consider_removing_semicolon(
1451         &self,
1452         blk: &'tcx hir::Block<'tcx>,
1453         expected_ty: Ty<'tcx>,
1454         err: &mut Diagnostic,
1455     ) -> bool {
1456         if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
1457             if let StatementAsExpression::NeedsBoxing = boxed {
1458                 err.span_suggestion_verbose(
1459                     span_semi,
1460                     "consider removing this semicolon and boxing the expression",
1461                     "",
1462                     Applicability::HasPlaceholders,
1463                 );
1464             } else {
1465                 err.span_suggestion_short(
1466                     span_semi,
1467                     "remove this semicolon to return this value",
1468                     "",
1469                     Applicability::MachineApplicable,
1470                 );
1471             }
1472             true
1473         } else {
1474             false
1475         }
1476     }
1477 }