]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/demand.rs
7379e75963f532b5d6642b27d2b025b6cb739b30
[rust.git] / compiler / rustc_hir_typeck / src / demand.rs
1 use crate::FnCtxt;
2 use rustc_ast::util::parser::PREC_POSTFIX;
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_errors::MultiSpan;
5 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
6 use rustc_hir as hir;
7 use rustc_hir::def::CtorKind;
8 use rustc_hir::intravisit::Visitor;
9 use rustc_hir::lang_items::LangItem;
10 use rustc_hir::{is_range_literal, Node};
11 use rustc_infer::infer::InferOk;
12 use rustc_middle::lint::in_external_macro;
13 use rustc_middle::middle::stability::EvalResult;
14 use rustc_middle::ty::adjustment::AllowTwoPhase;
15 use rustc_middle::ty::error::{ExpectedFound, TypeError};
16 use rustc_middle::ty::fold::{BottomUpFolder, TypeFolder};
17 use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
18 use rustc_middle::ty::relate::TypeRelation;
19 use rustc_middle::ty::{self, Article, AssocItem, Ty, TypeAndMut, TypeVisitable};
20 use rustc_span::symbol::{sym, Symbol};
21 use rustc_span::{BytePos, Span};
22 use rustc_trait_selection::infer::InferCtxtExt as _;
23 use rustc_trait_selection::traits::error_reporting::method_chain::CollectAllMismatches;
24 use rustc_trait_selection::traits::ObligationCause;
25
26 use super::method::probe;
27
28 use std::cmp::min;
29 use std::iter;
30
31 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
32     pub fn emit_type_mismatch_suggestions(
33         &self,
34         err: &mut Diagnostic,
35         expr: &hir::Expr<'tcx>,
36         expr_ty: Ty<'tcx>,
37         expected: Ty<'tcx>,
38         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
39         error: Option<TypeError<'tcx>>,
40     ) {
41         if expr_ty == expected {
42             return;
43         }
44
45         self.annotate_alternative_method_deref(err, expr, error);
46
47         // Use `||` to give these suggestions a precedence
48         let suggested = self.suggest_missing_parentheses(err, expr)
49             || self.suggest_remove_last_method_call(err, expr, expected)
50             || self.suggest_associated_const(err, expr, expected)
51             || self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr)
52             || self.suggest_option_to_bool(err, expr, expr_ty, expected)
53             || self.suggest_compatible_variants(err, expr, expected, expr_ty)
54             || self.suggest_non_zero_new_unwrap(err, expr, expected, expr_ty)
55             || self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty)
56             || self.suggest_no_capture_closure(err, expected, expr_ty)
57             || self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty)
58             || self.suggest_block_to_brackets_peeling_refs(err, expr, expr_ty, expected)
59             || self.suggest_copied_or_cloned(err, expr, expr_ty, expected)
60             || self.suggest_clone_for_ref(err, expr, expr_ty, expected)
61             || self.suggest_into(err, expr, expr_ty, expected)
62             || self.suggest_floating_point_literal(err, expr, expected)
63             || self.note_result_coercion(err, expr, expected, expr_ty);
64         if !suggested {
65             self.point_at_expr_source_of_inferred_type(err, expr, expr_ty, expected);
66         }
67     }
68
69     pub fn emit_coerce_suggestions(
70         &self,
71         err: &mut Diagnostic,
72         expr: &hir::Expr<'tcx>,
73         expr_ty: Ty<'tcx>,
74         expected: Ty<'tcx>,
75         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
76         error: Option<TypeError<'tcx>>,
77     ) {
78         if expr_ty == expected {
79             return;
80         }
81
82         self.annotate_expected_due_to_let_ty(err, expr, error);
83         self.emit_type_mismatch_suggestions(err, expr, expr_ty, expected, expected_ty_expr, error);
84         self.note_type_is_not_clone(err, expected, expr_ty, expr);
85         self.note_internal_mutation_in_method(err, expr, expected, expr_ty);
86         self.check_for_range_as_method_call(err, expr, expr_ty, expected);
87         self.check_for_binding_assigned_block_without_tail_expression(err, expr, expr_ty, expected);
88         self.check_wrong_return_type_due_to_generic_arg(err, expr, expr_ty);
89     }
90
91     /// Requires that the two types unify, and prints an error message if
92     /// they don't.
93     pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
94         if let Some(mut e) = self.demand_suptype_diag(sp, expected, actual) {
95             e.emit();
96         }
97     }
98
99     pub fn demand_suptype_diag(
100         &self,
101         sp: Span,
102         expected: Ty<'tcx>,
103         actual: Ty<'tcx>,
104     ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
105         self.demand_suptype_with_origin(&self.misc(sp), expected, actual)
106     }
107
108     #[instrument(skip(self), level = "debug")]
109     pub fn demand_suptype_with_origin(
110         &self,
111         cause: &ObligationCause<'tcx>,
112         expected: Ty<'tcx>,
113         actual: Ty<'tcx>,
114     ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
115         match self.at(cause, self.param_env).sup(expected, actual) {
116             Ok(InferOk { obligations, value: () }) => {
117                 self.register_predicates(obligations);
118                 None
119             }
120             Err(e) => Some(self.err_ctxt().report_mismatched_types(&cause, expected, actual, e)),
121         }
122     }
123
124     pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
125         if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
126             err.emit();
127         }
128     }
129
130     pub fn demand_eqtype_diag(
131         &self,
132         sp: Span,
133         expected: Ty<'tcx>,
134         actual: Ty<'tcx>,
135     ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
136         self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
137     }
138
139     pub fn demand_eqtype_with_origin(
140         &self,
141         cause: &ObligationCause<'tcx>,
142         expected: Ty<'tcx>,
143         actual: Ty<'tcx>,
144     ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
145         match self.at(cause, self.param_env).eq(expected, actual) {
146             Ok(InferOk { obligations, value: () }) => {
147                 self.register_predicates(obligations);
148                 None
149             }
150             Err(e) => Some(self.err_ctxt().report_mismatched_types(cause, expected, actual, e)),
151         }
152     }
153
154     pub fn demand_coerce(
155         &self,
156         expr: &hir::Expr<'tcx>,
157         checked_ty: Ty<'tcx>,
158         expected: Ty<'tcx>,
159         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
160         allow_two_phase: AllowTwoPhase,
161     ) -> Ty<'tcx> {
162         let (ty, err) =
163             self.demand_coerce_diag(expr, checked_ty, expected, expected_ty_expr, allow_two_phase);
164         if let Some(mut err) = err {
165             err.emit();
166         }
167         ty
168     }
169
170     /// Checks that the type of `expr` can be coerced to `expected`.
171     ///
172     /// N.B., this code relies on `self.diverges` to be accurate. In particular, assignments to `!`
173     /// will be permitted if the diverges flag is currently "always".
174     #[instrument(level = "debug", skip(self, expr, expected_ty_expr, allow_two_phase))]
175     pub fn demand_coerce_diag(
176         &self,
177         expr: &hir::Expr<'tcx>,
178         checked_ty: Ty<'tcx>,
179         expected: Ty<'tcx>,
180         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
181         allow_two_phase: AllowTwoPhase,
182     ) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>) {
183         let expected = self.resolve_vars_with_obligations(expected);
184
185         let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase, None) {
186             Ok(ty) => return (ty, None),
187             Err(e) => e,
188         };
189
190         self.set_tainted_by_errors(self.tcx.sess.delay_span_bug(
191             expr.span,
192             "`TypeError` when attempting coercion but no error emitted",
193         ));
194         let expr = expr.peel_drop_temps();
195         let cause = self.misc(expr.span);
196         let expr_ty = self.resolve_vars_with_obligations(checked_ty);
197         let mut err = self.err_ctxt().report_mismatched_types(&cause, expected, expr_ty, e);
198
199         let is_insufficiently_polymorphic =
200             matches!(e, TypeError::RegionsInsufficientlyPolymorphic(..));
201
202         // FIXME(#73154): For now, we do leak check when coercing function
203         // pointers in typeck, instead of only during borrowck. This can lead
204         // to these `RegionsInsufficientlyPolymorphic` errors that aren't helpful.
205         if !is_insufficiently_polymorphic {
206             self.emit_coerce_suggestions(
207                 &mut err,
208                 expr,
209                 expr_ty,
210                 expected,
211                 expected_ty_expr,
212                 Some(e),
213             );
214         }
215
216         (expected, Some(err))
217     }
218
219     pub fn point_at_expr_source_of_inferred_type(
220         &self,
221         err: &mut Diagnostic,
222         expr: &hir::Expr<'_>,
223         found: Ty<'tcx>,
224         expected: Ty<'tcx>,
225     ) -> bool {
226         let map = self.tcx.hir();
227
228         let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind else { return false; };
229         let [hir::PathSegment { ident, args: None, .. }] = p.segments else { return false; };
230         let hir::def::Res::Local(hir_id) = p.res else { return false; };
231         let Some(hir::Node::Pat(pat)) = map.find(hir_id) else { return false; };
232         let Some(hir::Node::Local(hir::Local {
233             ty: None,
234             init: Some(init),
235             ..
236         })) = map.find_parent(pat.hir_id) else { return false; };
237         let Some(ty) = self.node_ty_opt(init.hir_id) else { return false; };
238         if ty.is_closure() || init.span.overlaps(expr.span) || pat.span.from_expansion() {
239             return false;
240         }
241
242         // Locate all the usages of the relevant binding.
243         struct FindExprs<'hir> {
244             hir_id: hir::HirId,
245             uses: Vec<&'hir hir::Expr<'hir>>,
246         }
247         impl<'v> Visitor<'v> for FindExprs<'v> {
248             fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
249                 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = ex.kind
250                     && let hir::def::Res::Local(hir_id) = path.res
251                     && hir_id == self.hir_id
252                 {
253                     self.uses.push(ex);
254                 }
255                 hir::intravisit::walk_expr(self, ex);
256             }
257         }
258
259         let mut expr_finder = FindExprs { hir_id, uses: vec![] };
260         let id = map.get_parent_item(hir_id);
261         let hir_id: hir::HirId = id.into();
262
263         let Some(node) = map.find(hir_id) else { return false; };
264         let Some(body_id) = node.body_id() else { return false; };
265         let body = map.body(body_id);
266         expr_finder.visit_expr(body.value);
267         // Hack to make equality checks on types with inference variables and regions useful.
268         let mut eraser = BottomUpFolder {
269             tcx: self.tcx,
270             lt_op: |_| self.tcx.lifetimes.re_erased,
271             ct_op: |c| c,
272             ty_op: |t| match *t.kind() {
273                 ty::Infer(ty::TyVar(vid)) => self.tcx.mk_ty_infer(ty::TyVar(self.root_var(vid))),
274                 ty::Infer(ty::IntVar(_)) => {
275                     self.tcx.mk_ty_infer(ty::IntVar(ty::IntVid { index: 0 }))
276                 }
277                 ty::Infer(ty::FloatVar(_)) => {
278                     self.tcx.mk_ty_infer(ty::FloatVar(ty::FloatVid { index: 0 }))
279                 }
280                 _ => t,
281             },
282         };
283         let mut prev = eraser.fold_ty(ty);
284         let mut prev_span = None;
285
286         for binding in expr_finder.uses {
287             // In every expression where the binding is referenced, we will look at that
288             // expression's type and see if it is where the incorrect found type was fully
289             // "materialized" and point at it. We will also try to provide a suggestion there.
290             if let Some(hir::Node::Expr(expr)
291             | hir::Node::Stmt(hir::Stmt {
292                 kind: hir::StmtKind::Expr(expr) | hir::StmtKind::Semi(expr),
293                 ..
294             })) = &map.find_parent(binding.hir_id)
295                 && let hir::ExprKind::MethodCall(segment, rcvr, args, _span) = expr.kind
296                 && rcvr.hir_id == binding.hir_id
297                 && let Some(def_id) = self.typeck_results.borrow().type_dependent_def_id(expr.hir_id)
298             {
299                 // We special case methods, because they can influence inference through the
300                 // call's arguments and we can provide a more explicit span.
301                 let sig = self.tcx.fn_sig(def_id);
302                 let def_self_ty = sig.input(0).skip_binder();
303                 let rcvr_ty = self.node_ty(rcvr.hir_id);
304                 // Get the evaluated type *after* calling the method call, so that the influence
305                 // of the arguments can be reflected in the receiver type. The receiver
306                 // expression has the type *before* theis analysis is done.
307                 let ty = match self.lookup_probe_for_diagnostic(
308                     segment.ident,
309                     rcvr_ty,
310                     expr,
311                     probe::ProbeScope::TraitsInScope,
312                     None,
313                 ) {
314                     Ok(pick) => pick.self_ty,
315                     Err(_) => rcvr_ty,
316                 };
317                 // Remove one layer of references to account for `&mut self` and
318                 // `&self`, so that we can compare it against the binding.
319                 let (ty, def_self_ty) = match (ty.kind(), def_self_ty.kind()) {
320                     (ty::Ref(_, ty, a), ty::Ref(_, self_ty, b)) if a == b => (*ty, *self_ty),
321                     _ => (ty, def_self_ty),
322                 };
323                 let mut param_args = FxHashMap::default();
324                 let mut param_expected = FxHashMap::default();
325                 let mut param_found = FxHashMap::default();
326                 if self.can_eq(self.param_env, ty, found).is_ok() {
327                     // We only point at the first place where the found type was inferred.
328                     for (i, param_ty) in sig.inputs().skip_binder().iter().skip(1).enumerate() {
329                         if def_self_ty.contains(*param_ty) && let ty::Param(_) = param_ty.kind() {
330                             // We found an argument that references a type parameter in `Self`,
331                             // so we assume that this is the argument that caused the found
332                             // type, which we know already because of `can_eq` above was first
333                             // inferred in this method call.
334                             let arg = &args[i];
335                             let arg_ty = self.node_ty(arg.hir_id);
336                             err.span_label(
337                                 arg.span,
338                                 &format!(
339                                     "this is of type `{arg_ty}`, which causes `{ident}` to be \
340                                      inferred as `{ty}`",
341                                 ),
342                             );
343                             param_args.insert(param_ty, (arg, arg_ty));
344                         }
345                     }
346                 }
347
348                 // Here we find, for a type param `T`, the type that `T` is in the current
349                 // method call *and* in the original expected type. That way, we can see if we
350                 // can give any structured suggestion for the function argument.
351                 let mut c = CollectAllMismatches {
352                     infcx: &self.infcx,
353                     param_env: self.param_env,
354                     errors: vec![],
355                 };
356                 let _ = c.relate(def_self_ty, ty);
357                 for error in c.errors {
358                     if let TypeError::Sorts(error) = error {
359                         param_found.insert(error.expected, error.found);
360                     }
361                 }
362                 c.errors = vec![];
363                 let _ = c.relate(def_self_ty, expected);
364                 for error in c.errors {
365                     if let TypeError::Sorts(error) = error {
366                         param_expected.insert(error.expected, error.found);
367                     }
368                 }
369                 for (param, (arg, arg_ty)) in param_args.iter() {
370                     let Some(expected) = param_expected.get(param) else { continue; };
371                     let Some(found) = param_found.get(param) else { continue; };
372                     if self.can_eq(self.param_env, *arg_ty, *found).is_err() { continue; }
373                     self.emit_coerce_suggestions(err, arg, *found, *expected, None, None);
374                 }
375
376                 let ty = eraser.fold_ty(ty);
377                 if ty.references_error() {
378                     break;
379                 }
380                 if ty != prev
381                     && param_args.is_empty()
382                     && self.can_eq(self.param_env, ty, found).is_ok()
383                 {
384                     // We only point at the first place where the found type was inferred.
385                     err.span_label(
386                         segment.ident.span,
387                         with_forced_trimmed_paths!(format!(
388                             "here the type of `{ident}` is inferred to be `{ty}`",
389                         )),
390                     );
391                     break;
392                 } else if !param_args.is_empty() {
393                     break;
394                 }
395                 prev = ty;
396             } else {
397                 let ty = eraser.fold_ty(self.node_ty(binding.hir_id));
398                 if ty.references_error() {
399                     break;
400                 }
401                 if ty != prev
402                     && let Some(span) = prev_span
403                     && self.can_eq(self.param_env, ty, found).is_ok()
404                 {
405                     // We only point at the first place where the found type was inferred.
406                     // We use the *previous* span because if the type is known *here* it means
407                     // it was *evaluated earlier*. We don't do this for method calls because we
408                     // evaluate the method's self type eagerly, but not in any other case.
409                     err.span_label(
410                         span,
411                         with_forced_trimmed_paths!(format!(
412                             "here the type of `{ident}` is inferred to be `{ty}`",
413                         )),
414                     );
415                     break;
416                 }
417                 prev = ty;
418             }
419             if binding.hir_id == expr.hir_id {
420                 // Do not look at expressions that come after the expression we were originally
421                 // evaluating and had a type error.
422                 break;
423             }
424             prev_span = Some(binding.span);
425         }
426         true
427     }
428
429     fn annotate_expected_due_to_let_ty(
430         &self,
431         err: &mut Diagnostic,
432         expr: &hir::Expr<'_>,
433         error: Option<TypeError<'tcx>>,
434     ) {
435         let parent = self.tcx.hir().parent_id(expr.hir_id);
436         match (self.tcx.hir().find(parent), error) {
437             (Some(hir::Node::Local(hir::Local { ty: Some(ty), init: Some(init), .. })), _)
438                 if init.hir_id == expr.hir_id =>
439             {
440                 // Point at `let` assignment type.
441                 err.span_label(ty.span, "expected due to this");
442             }
443             (
444                 Some(hir::Node::Expr(hir::Expr {
445                     kind: hir::ExprKind::Assign(lhs, rhs, _), ..
446                 })),
447                 Some(TypeError::Sorts(ExpectedFound { expected, .. })),
448             ) if rhs.hir_id == expr.hir_id && !expected.is_closure() => {
449                 // We ignore closures explicitly because we already point at them elsewhere.
450                 // Point at the assigned-to binding.
451                 let mut primary_span = lhs.span;
452                 let mut secondary_span = lhs.span;
453                 let mut post_message = "";
454                 match lhs.kind {
455                     hir::ExprKind::Path(hir::QPath::Resolved(
456                         None,
457                         hir::Path {
458                             res:
459                                 hir::def::Res::Def(
460                                     hir::def::DefKind::Static(_) | hir::def::DefKind::Const,
461                                     def_id,
462                                 ),
463                             ..
464                         },
465                     )) => {
466                         if let Some(hir::Node::Item(hir::Item {
467                             ident,
468                             kind: hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..),
469                             ..
470                         })) = self.tcx.hir().get_if_local(*def_id)
471                         {
472                             primary_span = ty.span;
473                             secondary_span = ident.span;
474                             post_message = " type";
475                         }
476                     }
477                     hir::ExprKind::Path(hir::QPath::Resolved(
478                         None,
479                         hir::Path { res: hir::def::Res::Local(hir_id), .. },
480                     )) => {
481                         if let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(*hir_id) {
482                             primary_span = pat.span;
483                             secondary_span = pat.span;
484                             match self.tcx.hir().find_parent(pat.hir_id) {
485                                 Some(hir::Node::Local(hir::Local { ty: Some(ty), .. })) => {
486                                     primary_span = ty.span;
487                                     post_message = " type";
488                                 }
489                                 Some(hir::Node::Local(hir::Local { init: Some(init), .. })) => {
490                                     primary_span = init.span;
491                                     post_message = " value";
492                                 }
493                                 Some(hir::Node::Param(hir::Param { ty_span, .. })) => {
494                                     primary_span = *ty_span;
495                                     post_message = " parameter type";
496                                 }
497                                 _ => {}
498                             }
499                         }
500                     }
501                     _ => {}
502                 }
503
504                 if primary_span != secondary_span
505                     && self
506                         .tcx
507                         .sess
508                         .source_map()
509                         .is_multiline(secondary_span.shrink_to_hi().until(primary_span))
510                 {
511                     // We are pointing at the binding's type or initializer value, but it's pattern
512                     // is in a different line, so we point at both.
513                     err.span_label(secondary_span, "expected due to the type of this binding");
514                     err.span_label(primary_span, &format!("expected due to this{post_message}"));
515                 } else if post_message == "" {
516                     // We are pointing at either the assignment lhs or the binding def pattern.
517                     err.span_label(primary_span, "expected due to the type of this binding");
518                 } else {
519                     // We are pointing at the binding's type or initializer value.
520                     err.span_label(primary_span, &format!("expected due to this{post_message}"));
521                 }
522
523                 if !lhs.is_syntactic_place_expr() {
524                     // We already emitted E0070 "invalid left-hand side of assignment", so we
525                     // silence this.
526                     err.downgrade_to_delayed_bug();
527                 }
528             }
529             (
530                 Some(hir::Node::Expr(hir::Expr {
531                     kind: hir::ExprKind::Binary(_, lhs, rhs), ..
532                 })),
533                 Some(TypeError::Sorts(ExpectedFound { expected, .. })),
534             ) if rhs.hir_id == expr.hir_id
535                 && self.typeck_results.borrow().expr_ty_adjusted_opt(lhs) == Some(expected) =>
536             {
537                 err.span_label(lhs.span, &format!("expected because this is `{expected}`"));
538             }
539             _ => {}
540         }
541     }
542
543     fn annotate_alternative_method_deref(
544         &self,
545         err: &mut Diagnostic,
546         expr: &hir::Expr<'_>,
547         error: Option<TypeError<'tcx>>,
548     ) {
549         let parent = self.tcx.hir().parent_id(expr.hir_id);
550         let Some(TypeError::Sorts(ExpectedFound { expected, .. })) = error else {return;};
551         let Some(hir::Node::Expr(hir::Expr {
552                     kind: hir::ExprKind::Assign(lhs, rhs, _), ..
553                 })) = self.tcx.hir().find(parent) else {return; };
554         if rhs.hir_id != expr.hir_id || expected.is_closure() {
555             return;
556         }
557         let hir::ExprKind::Unary(hir::UnOp::Deref, deref) = lhs.kind else { return; };
558         let hir::ExprKind::MethodCall(path, base, args, _) = deref.kind else { return; };
559         let Some(self_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(base) else { return; };
560
561         let Ok(pick) = self
562             .lookup_probe_for_diagnostic(
563                 path.ident,
564                 self_ty,
565                 deref,
566                 probe::ProbeScope::TraitsInScope,
567                 None,
568             ) else {
569                 return;
570             };
571         let in_scope_methods = self.probe_for_name_many(
572             probe::Mode::MethodCall,
573             path.ident,
574             Some(expected),
575             probe::IsSuggestion(true),
576             self_ty,
577             deref.hir_id,
578             probe::ProbeScope::TraitsInScope,
579         );
580         let other_methods_in_scope: Vec<_> =
581             in_scope_methods.iter().filter(|c| c.item.def_id != pick.item.def_id).collect();
582
583         let all_methods = self.probe_for_name_many(
584             probe::Mode::MethodCall,
585             path.ident,
586             Some(expected),
587             probe::IsSuggestion(true),
588             self_ty,
589             deref.hir_id,
590             probe::ProbeScope::AllTraits,
591         );
592         let suggestions: Vec<_> = all_methods
593             .into_iter()
594             .filter(|c| c.item.def_id != pick.item.def_id)
595             .map(|c| {
596                 let m = c.item;
597                 let substs = ty::InternalSubsts::for_item(self.tcx, m.def_id, |param, _| {
598                     self.var_for_def(deref.span, param)
599                 });
600                 vec![
601                     (
602                         deref.span.until(base.span),
603                         format!(
604                             "{}({}",
605                             with_no_trimmed_paths!(
606                                 self.tcx.def_path_str_with_substs(m.def_id, substs,)
607                             ),
608                             match self.tcx.fn_sig(m.def_id).input(0).skip_binder().kind() {
609                                 ty::Ref(_, _, hir::Mutability::Mut) => "&mut ",
610                                 ty::Ref(_, _, _) => "&",
611                                 _ => "",
612                             },
613                         ),
614                     ),
615                     match &args[..] {
616                         [] => (base.span.shrink_to_hi().with_hi(deref.span.hi()), ")".to_string()),
617                         [first, ..] => (base.span.between(first.span), ", ".to_string()),
618                     },
619                 ]
620             })
621             .collect();
622         if suggestions.is_empty() {
623             return;
624         }
625         let mut path_span: MultiSpan = path.ident.span.into();
626         path_span.push_span_label(
627             path.ident.span,
628             with_no_trimmed_paths!(format!(
629                 "refers to `{}`",
630                 self.tcx.def_path_str(pick.item.def_id),
631             )),
632         );
633         let container_id = pick.item.container_id(self.tcx);
634         let container = with_no_trimmed_paths!(self.tcx.def_path_str(container_id));
635         for def_id in pick.import_ids {
636             let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
637             path_span.push_span_label(
638                 self.tcx.hir().span(hir_id),
639                 format!("`{container}` imported here"),
640             );
641         }
642         let tail = with_no_trimmed_paths!(match &other_methods_in_scope[..] {
643             [] => return,
644             [candidate] => format!(
645                 "the method of the same name on {} `{}`",
646                 match candidate.kind {
647                     probe::CandidateKind::InherentImplCandidate(..) => "the inherent impl for",
648                     _ => "trait",
649                 },
650                 self.tcx.def_path_str(candidate.item.container_id(self.tcx))
651             ),
652             [.., last] if other_methods_in_scope.len() < 5 => {
653                 format!(
654                     "the methods of the same name on {} and `{}`",
655                     other_methods_in_scope[..other_methods_in_scope.len() - 1]
656                         .iter()
657                         .map(|c| format!(
658                             "`{}`",
659                             self.tcx.def_path_str(c.item.container_id(self.tcx))
660                         ))
661                         .collect::<Vec<String>>()
662                         .join(", "),
663                     self.tcx.def_path_str(last.item.container_id(self.tcx))
664                 )
665             }
666             _ => format!(
667                 "the methods of the same name on {} other traits",
668                 other_methods_in_scope.len()
669             ),
670         });
671         err.span_note(
672             path_span,
673             &format!(
674                 "the `{}` call is resolved to the method in `{container}`, shadowing {tail}",
675                 path.ident,
676             ),
677         );
678         if suggestions.len() > other_methods_in_scope.len() {
679             err.note(&format!(
680                 "additionally, there are {} other available methods that aren't in scope",
681                 suggestions.len() - other_methods_in_scope.len()
682             ));
683         }
684         err.multipart_suggestions(
685             &format!(
686                 "you might have meant to call {}; you can use the fully-qualified path to call {} \
687                  explicitly",
688                 if suggestions.len() == 1 {
689                     "the other method"
690                 } else {
691                     "one of the other methods"
692                 },
693                 if suggestions.len() == 1 { "it" } else { "one of them" },
694             ),
695             suggestions,
696             Applicability::MaybeIncorrect,
697         );
698     }
699
700     pub(crate) fn note_result_coercion(
701         &self,
702         err: &mut Diagnostic,
703         expr: &hir::Expr<'tcx>,
704         expected: Ty<'tcx>,
705         found: Ty<'tcx>,
706     ) -> bool {
707         let ty::Adt(e, substs_e) = expected.kind() else { return false; };
708         let ty::Adt(f, substs_f) = found.kind() else { return false; };
709         if e.did() != f.did() {
710             return false;
711         }
712         if Some(e.did()) != self.tcx.get_diagnostic_item(sym::Result) {
713             return false;
714         }
715         let map = self.tcx.hir();
716         if let Some(hir::Node::Expr(expr)) = map.find_parent(expr.hir_id)
717             && let hir::ExprKind::Ret(_) = expr.kind
718         {
719             // `return foo;`
720         } else if map.get_return_block(expr.hir_id).is_some() {
721             // Function's tail expression.
722         } else {
723             return false;
724         }
725         let e = substs_e.type_at(1);
726         let f = substs_f.type_at(1);
727         if self
728             .infcx
729             .type_implements_trait(
730                 self.tcx.get_diagnostic_item(sym::Into).unwrap(),
731                 [f, e],
732                 self.param_env,
733             )
734             .must_apply_modulo_regions()
735         {
736             err.multipart_suggestion(
737                 "use `?` to coerce and return an appropriate `Err`, and wrap the resulting value \
738                  in `Ok` so the expression remains of type `Result`",
739                 vec![
740                     (expr.span.shrink_to_lo(), "Ok(".to_string()),
741                     (expr.span.shrink_to_hi(), "?)".to_string()),
742                 ],
743                 Applicability::MaybeIncorrect,
744             );
745             return true;
746         }
747         false
748     }
749
750     /// If the expected type is an enum (Issue #55250) with any variants whose
751     /// sole field is of the found type, suggest such variants. (Issue #42764)
752     fn suggest_compatible_variants(
753         &self,
754         err: &mut Diagnostic,
755         expr: &hir::Expr<'_>,
756         expected: Ty<'tcx>,
757         expr_ty: Ty<'tcx>,
758     ) -> bool {
759         if let ty::Adt(expected_adt, substs) = expected.kind() {
760             if let hir::ExprKind::Field(base, ident) = expr.kind {
761                 let base_ty = self.typeck_results.borrow().expr_ty(base);
762                 if self.can_eq(self.param_env, base_ty, expected).is_ok()
763                     && let Some(base_span) = base.span.find_ancestor_inside(expr.span)
764                 {
765                     err.span_suggestion_verbose(
766                         expr.span.with_lo(base_span.hi()),
767                         format!("consider removing the tuple struct field `{ident}`"),
768                         "",
769                         Applicability::MaybeIncorrect,
770                     );
771                     return true;
772                 }
773             }
774
775             // If the expression is of type () and it's the return expression of a block,
776             // we suggest adding a separate return expression instead.
777             // (To avoid things like suggesting `Ok(while .. { .. })`.)
778             if expr_ty.is_unit() {
779                 let mut id = expr.hir_id;
780                 let mut parent;
781
782                 // Unroll desugaring, to make sure this works for `for` loops etc.
783                 loop {
784                     parent = self.tcx.hir().parent_id(id);
785                     if let Some(parent_span) = self.tcx.hir().opt_span(parent) {
786                         if parent_span.find_ancestor_inside(expr.span).is_some() {
787                             // The parent node is part of the same span, so is the result of the
788                             // same expansion/desugaring and not the 'real' parent node.
789                             id = parent;
790                             continue;
791                         }
792                     }
793                     break;
794                 }
795
796                 if let Some(hir::Node::Block(&hir::Block {
797                     span: block_span, expr: Some(e), ..
798                 })) = self.tcx.hir().find(parent)
799                 {
800                     if e.hir_id == id {
801                         if let Some(span) = expr.span.find_ancestor_inside(block_span) {
802                             let return_suggestions = if self
803                                 .tcx
804                                 .is_diagnostic_item(sym::Result, expected_adt.did())
805                             {
806                                 vec!["Ok(())"]
807                             } else if self.tcx.is_diagnostic_item(sym::Option, expected_adt.did()) {
808                                 vec!["None", "Some(())"]
809                             } else {
810                                 return false;
811                             };
812                             if let Some(indent) =
813                                 self.tcx.sess.source_map().indentation_before(span.shrink_to_lo())
814                             {
815                                 // Add a semicolon, except after `}`.
816                                 let semicolon =
817                                     match self.tcx.sess.source_map().span_to_snippet(span) {
818                                         Ok(s) if s.ends_with('}') => "",
819                                         _ => ";",
820                                     };
821                                 err.span_suggestions(
822                                     span.shrink_to_hi(),
823                                     "try adding an expression at the end of the block",
824                                     return_suggestions
825                                         .into_iter()
826                                         .map(|r| format!("{semicolon}\n{indent}{r}")),
827                                     Applicability::MaybeIncorrect,
828                                 );
829                             }
830                             return true;
831                         }
832                     }
833                 }
834             }
835
836             let compatible_variants: Vec<(String, _, _, Option<String>)> = expected_adt
837                 .variants()
838                 .iter()
839                 .filter(|variant| {
840                     variant.fields.len() == 1
841                 })
842                 .filter_map(|variant| {
843                     let sole_field = &variant.fields[0];
844
845                     let field_is_local = sole_field.did.is_local();
846                     let field_is_accessible =
847                         sole_field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
848                         // Skip suggestions for unstable public fields (for example `Pin::pointer`)
849                         && matches!(self.tcx.eval_stability(sole_field.did, None, expr.span, None), EvalResult::Allow | EvalResult::Unmarked);
850
851                     if !field_is_local && !field_is_accessible {
852                         return None;
853                     }
854
855                     let note_about_variant_field_privacy = (field_is_local && !field_is_accessible)
856                         .then(|| " (its field is private, but it's local to this crate and its privacy can be changed)".to_string());
857
858                     let sole_field_ty = sole_field.ty(self.tcx, substs);
859                     if self.can_coerce(expr_ty, sole_field_ty) {
860                         let variant_path =
861                             with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
862                         // FIXME #56861: DRYer prelude filtering
863                         if let Some(path) = variant_path.strip_prefix("std::prelude::")
864                             && let Some((_, path)) = path.split_once("::")
865                         {
866                             return Some((path.to_string(), variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy));
867                         }
868                         Some((variant_path, variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy))
869                     } else {
870                         None
871                     }
872                 })
873                 .collect();
874
875             let suggestions_for = |variant: &_, ctor_kind, field_name| {
876                 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
877                     Some(ident) => format!("{ident}: "),
878                     None => String::new(),
879                 };
880
881                 let (open, close) = match ctor_kind {
882                     Some(CtorKind::Fn) => ("(".to_owned(), ")"),
883                     None => (format!(" {{ {field_name}: "), " }"),
884
885                     // unit variants don't have fields
886                     Some(CtorKind::Const) => unreachable!(),
887                 };
888
889                 // Suggest constructor as deep into the block tree as possible.
890                 // This fixes https://github.com/rust-lang/rust/issues/101065,
891                 // and also just helps make the most minimal suggestions.
892                 let mut expr = expr;
893                 while let hir::ExprKind::Block(block, _) = &expr.kind
894                     && let Some(expr_) = &block.expr
895                 {
896                     expr = expr_
897                 }
898
899                 vec![
900                     (expr.span.shrink_to_lo(), format!("{prefix}{variant}{open}")),
901                     (expr.span.shrink_to_hi(), close.to_owned()),
902                 ]
903             };
904
905             match &compatible_variants[..] {
906                 [] => { /* No variants to format */ }
907                 [(variant, ctor_kind, field_name, note)] => {
908                     // Just a single matching variant.
909                     err.multipart_suggestion_verbose(
910                         &format!(
911                             "try wrapping the expression in `{variant}`{note}",
912                             note = note.as_deref().unwrap_or("")
913                         ),
914                         suggestions_for(&**variant, *ctor_kind, *field_name),
915                         Applicability::MaybeIncorrect,
916                     );
917                     return true;
918                 }
919                 _ => {
920                     // More than one matching variant.
921                     err.multipart_suggestions(
922                         &format!(
923                             "try wrapping the expression in a variant of `{}`",
924                             self.tcx.def_path_str(expected_adt.did())
925                         ),
926                         compatible_variants.into_iter().map(
927                             |(variant, ctor_kind, field_name, _)| {
928                                 suggestions_for(&variant, ctor_kind, field_name)
929                             },
930                         ),
931                         Applicability::MaybeIncorrect,
932                     );
933                     return true;
934                 }
935             }
936         }
937
938         false
939     }
940
941     fn suggest_non_zero_new_unwrap(
942         &self,
943         err: &mut Diagnostic,
944         expr: &hir::Expr<'_>,
945         expected: Ty<'tcx>,
946         expr_ty: Ty<'tcx>,
947     ) -> bool {
948         let tcx = self.tcx;
949         let (adt, unwrap) = match expected.kind() {
950             // In case Option<NonZero*> is wanted, but * is provided, suggest calling new
951             ty::Adt(adt, substs) if tcx.is_diagnostic_item(sym::Option, adt.did()) => {
952                 // Unwrap option
953                 let ty::Adt(adt, _) = substs.type_at(0).kind() else { return false; };
954
955                 (adt, "")
956             }
957             // In case NonZero* is wanted, but * is provided also add `.unwrap()` to satisfy types
958             ty::Adt(adt, _) => (adt, ".unwrap()"),
959             _ => return false,
960         };
961
962         let map = [
963             (sym::NonZeroU8, tcx.types.u8),
964             (sym::NonZeroU16, tcx.types.u16),
965             (sym::NonZeroU32, tcx.types.u32),
966             (sym::NonZeroU64, tcx.types.u64),
967             (sym::NonZeroU128, tcx.types.u128),
968             (sym::NonZeroI8, tcx.types.i8),
969             (sym::NonZeroI16, tcx.types.i16),
970             (sym::NonZeroI32, tcx.types.i32),
971             (sym::NonZeroI64, tcx.types.i64),
972             (sym::NonZeroI128, tcx.types.i128),
973         ];
974
975         let Some((s, _)) = map
976             .iter()
977             .find(|&&(s, t)| self.tcx.is_diagnostic_item(s, adt.did()) && self.can_coerce(expr_ty, t))
978             else { return false; };
979
980         let path = self.tcx.def_path_str(adt.non_enum_variant().def_id);
981
982         err.multipart_suggestion(
983             format!("consider calling `{s}::new`"),
984             vec![
985                 (expr.span.shrink_to_lo(), format!("{path}::new(")),
986                 (expr.span.shrink_to_hi(), format!("){unwrap}")),
987             ],
988             Applicability::MaybeIncorrect,
989         );
990
991         true
992     }
993
994     pub fn get_conversion_methods(
995         &self,
996         span: Span,
997         expected: Ty<'tcx>,
998         checked_ty: Ty<'tcx>,
999         hir_id: hir::HirId,
1000     ) -> Vec<AssocItem> {
1001         let methods = self.probe_for_return_type(
1002             span,
1003             probe::Mode::MethodCall,
1004             expected,
1005             checked_ty,
1006             hir_id,
1007             |m| {
1008                 self.has_only_self_parameter(m)
1009                     && self
1010                         .tcx
1011                         // This special internal attribute is used to permit
1012                         // "identity-like" conversion methods to be suggested here.
1013                         //
1014                         // FIXME (#46459 and #46460): ideally
1015                         // `std::convert::Into::into` and `std::borrow:ToOwned` would
1016                         // also be `#[rustc_conversion_suggestion]`, if not for
1017                         // method-probing false-positives and -negatives (respectively).
1018                         //
1019                         // FIXME? Other potential candidate methods: `as_ref` and
1020                         // `as_mut`?
1021                         .has_attr(m.def_id, sym::rustc_conversion_suggestion)
1022             },
1023         );
1024
1025         methods
1026     }
1027
1028     /// This function checks whether the method is not static and does not accept other parameters than `self`.
1029     fn has_only_self_parameter(&self, method: &AssocItem) -> bool {
1030         match method.kind {
1031             ty::AssocKind::Fn => {
1032                 method.fn_has_self_parameter
1033                     && self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1
1034             }
1035             _ => false,
1036         }
1037     }
1038
1039     /// Identify some cases where `as_ref()` would be appropriate and suggest it.
1040     ///
1041     /// Given the following code:
1042     /// ```compile_fail,E0308
1043     /// struct Foo;
1044     /// fn takes_ref(_: &Foo) {}
1045     /// let ref opt = Some(Foo);
1046     ///
1047     /// opt.map(|param| takes_ref(param));
1048     /// ```
1049     /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
1050     ///
1051     /// It only checks for `Option` and `Result` and won't work with
1052     /// ```ignore (illustrative)
1053     /// opt.map(|param| { takes_ref(param) });
1054     /// ```
1055     fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Span, &'static str, String)> {
1056         let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.kind else {
1057             return None;
1058         };
1059
1060         let hir::def::Res::Local(local_id) = path.res else {
1061             return None;
1062         };
1063
1064         let local_parent = self.tcx.hir().parent_id(local_id);
1065         let Some(Node::Param(hir::Param { hir_id: param_hir_id, .. })) = self.tcx.hir().find(local_parent) else {
1066             return None;
1067         };
1068
1069         let param_parent = self.tcx.hir().parent_id(*param_hir_id);
1070         let Some(Node::Expr(hir::Expr {
1071             hir_id: expr_hir_id,
1072             kind: hir::ExprKind::Closure(hir::Closure { fn_decl: closure_fn_decl, .. }),
1073             ..
1074         })) = self.tcx.hir().find(param_parent) else {
1075             return None;
1076         };
1077
1078         let expr_parent = self.tcx.hir().parent_id(*expr_hir_id);
1079         let hir = self.tcx.hir().find(expr_parent);
1080         let closure_params_len = closure_fn_decl.inputs.len();
1081         let (
1082             Some(Node::Expr(hir::Expr {
1083                 kind: hir::ExprKind::MethodCall(method_path, receiver, ..),
1084                 ..
1085             })),
1086             1,
1087         ) = (hir, closure_params_len) else {
1088             return None;
1089         };
1090
1091         let self_ty = self.typeck_results.borrow().expr_ty(receiver);
1092         let name = method_path.ident.name;
1093         let is_as_ref_able = match self_ty.peel_refs().kind() {
1094             ty::Adt(def, _) => {
1095                 (self.tcx.is_diagnostic_item(sym::Option, def.did())
1096                     || self.tcx.is_diagnostic_item(sym::Result, def.did()))
1097                     && (name == sym::map || name == sym::and_then)
1098             }
1099             _ => false,
1100         };
1101         match (is_as_ref_able, self.sess().source_map().span_to_snippet(method_path.ident.span)) {
1102             (true, Ok(src)) => {
1103                 let suggestion = format!("as_ref().{}", src);
1104                 Some((method_path.ident.span, "consider using `as_ref` instead", suggestion))
1105             }
1106             _ => None,
1107         }
1108     }
1109
1110     pub(crate) fn maybe_get_struct_pattern_shorthand_field(
1111         &self,
1112         expr: &hir::Expr<'_>,
1113     ) -> Option<Symbol> {
1114         let hir = self.tcx.hir();
1115         let local = match expr {
1116             hir::Expr {
1117                 kind:
1118                     hir::ExprKind::Path(hir::QPath::Resolved(
1119                         None,
1120                         hir::Path {
1121                             res: hir::def::Res::Local(_),
1122                             segments: [hir::PathSegment { ident, .. }],
1123                             ..
1124                         },
1125                     )),
1126                 ..
1127             } => Some(ident),
1128             _ => None,
1129         }?;
1130
1131         match hir.find_parent(expr.hir_id)? {
1132             Node::ExprField(field) => {
1133                 if field.ident.name == local.name && field.is_shorthand {
1134                     return Some(local.name);
1135                 }
1136             }
1137             _ => {}
1138         }
1139
1140         None
1141     }
1142
1143     /// If the given `HirId` corresponds to a block with a trailing expression, return that expression
1144     pub(crate) fn maybe_get_block_expr(
1145         &self,
1146         expr: &hir::Expr<'tcx>,
1147     ) -> Option<&'tcx hir::Expr<'tcx>> {
1148         match expr {
1149             hir::Expr { kind: hir::ExprKind::Block(block, ..), .. } => block.expr,
1150             _ => None,
1151         }
1152     }
1153
1154     /// Returns whether the given expression is an `else if`.
1155     pub(crate) fn is_else_if_block(&self, expr: &hir::Expr<'_>) -> bool {
1156         if let hir::ExprKind::If(..) = expr.kind {
1157             let parent_id = self.tcx.hir().parent_id(expr.hir_id);
1158             if let Some(Node::Expr(hir::Expr {
1159                 kind: hir::ExprKind::If(_, _, Some(else_expr)),
1160                 ..
1161             })) = self.tcx.hir().find(parent_id)
1162             {
1163                 return else_expr.hir_id == expr.hir_id;
1164             }
1165         }
1166         false
1167     }
1168
1169     /// This function is used to determine potential "simple" improvements or users' errors and
1170     /// provide them useful help. For example:
1171     ///
1172     /// ```compile_fail,E0308
1173     /// fn some_fn(s: &str) {}
1174     ///
1175     /// let x = "hey!".to_owned();
1176     /// some_fn(x); // error
1177     /// ```
1178     ///
1179     /// No need to find every potential function which could make a coercion to transform a
1180     /// `String` into a `&str` since a `&` would do the trick!
1181     ///
1182     /// In addition of this check, it also checks between references mutability state. If the
1183     /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
1184     /// `&mut`!".
1185     pub fn check_ref(
1186         &self,
1187         expr: &hir::Expr<'tcx>,
1188         checked_ty: Ty<'tcx>,
1189         expected: Ty<'tcx>,
1190     ) -> Option<(
1191         Span,
1192         String,
1193         String,
1194         Applicability,
1195         bool, /* verbose */
1196         bool, /* suggest `&` or `&mut` type annotation */
1197     )> {
1198         let sess = self.sess();
1199         let sp = expr.span;
1200
1201         // If the span is from an external macro, there's no suggestion we can make.
1202         if in_external_macro(sess, sp) {
1203             return None;
1204         }
1205
1206         let sm = sess.source_map();
1207
1208         let replace_prefix = |s: &str, old: &str, new: &str| {
1209             s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
1210         };
1211
1212         // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
1213         let expr = expr.peel_drop_temps();
1214
1215         match (&expr.kind, expected.kind(), checked_ty.kind()) {
1216             (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (exp.kind(), check.kind()) {
1217                 (&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
1218                     if let hir::ExprKind::Lit(_) = expr.kind
1219                         && let Ok(src) = sm.span_to_snippet(sp)
1220                         && replace_prefix(&src, "b\"", "\"").is_some()
1221                     {
1222                                 let pos = sp.lo() + BytePos(1);
1223                                 return Some((
1224                                     sp.with_hi(pos),
1225                                     "consider removing the leading `b`".to_string(),
1226                                     String::new(),
1227                                     Applicability::MachineApplicable,
1228                                     true,
1229                                     false,
1230                                 ));
1231                             }
1232                         }
1233                 (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
1234                     if let hir::ExprKind::Lit(_) = expr.kind
1235                         && let Ok(src) = sm.span_to_snippet(sp)
1236                         && replace_prefix(&src, "\"", "b\"").is_some()
1237                     {
1238                                 return Some((
1239                                     sp.shrink_to_lo(),
1240                                     "consider adding a leading `b`".to_string(),
1241                                     "b".to_string(),
1242                                     Applicability::MachineApplicable,
1243                                     true,
1244                                     false,
1245                                 ));
1246                     }
1247                 }
1248                 _ => {}
1249             },
1250             (_, &ty::Ref(_, _, mutability), _) => {
1251                 // Check if it can work when put into a ref. For example:
1252                 //
1253                 // ```
1254                 // fn bar(x: &mut i32) {}
1255                 //
1256                 // let x = 0u32;
1257                 // bar(&x); // error, expected &mut
1258                 // ```
1259                 let ref_ty = match mutability {
1260                     hir::Mutability::Mut => {
1261                         self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
1262                     }
1263                     hir::Mutability::Not => {
1264                         self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
1265                     }
1266                 };
1267                 if self.can_coerce(ref_ty, expected) {
1268                     let mut sugg_sp = sp;
1269                     if let hir::ExprKind::MethodCall(ref segment, receiver, args, _) = expr.kind {
1270                         let clone_trait =
1271                             self.tcx.require_lang_item(LangItem::Clone, Some(segment.ident.span));
1272                         if args.is_empty()
1273                             && self.typeck_results.borrow().type_dependent_def_id(expr.hir_id).map(
1274                                 |did| {
1275                                     let ai = self.tcx.associated_item(did);
1276                                     ai.trait_container(self.tcx) == Some(clone_trait)
1277                                 },
1278                             ) == Some(true)
1279                             && segment.ident.name == sym::clone
1280                         {
1281                             // If this expression had a clone call when suggesting borrowing
1282                             // we want to suggest removing it because it'd now be unnecessary.
1283                             sugg_sp = receiver.span;
1284                         }
1285                     }
1286
1287                     if let hir::ExprKind::Unary(hir::UnOp::Deref, ref inner) = expr.kind
1288                         && let Some(1) = self.deref_steps(expected, checked_ty) {
1289                         // We have `*&T`, check if what was expected was `&T`.
1290                         // If so, we may want to suggest removing a `*`.
1291                         sugg_sp = sugg_sp.with_hi(inner.span.lo());
1292                         return Some((
1293                             sugg_sp,
1294                             "consider removing deref here".to_string(),
1295                             "".to_string(),
1296                             Applicability::MachineApplicable,
1297                             true,
1298                             false,
1299                         ));
1300                     }
1301
1302                     if let Ok(src) = sm.span_to_snippet(sugg_sp) {
1303                         let needs_parens = match expr.kind {
1304                             // parenthesize if needed (Issue #46756)
1305                             hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true,
1306                             // parenthesize borrows of range literals (Issue #54505)
1307                             _ if is_range_literal(expr) => true,
1308                             _ => false,
1309                         };
1310
1311                         if let Some(sugg) = self.can_use_as_ref(expr) {
1312                             return Some((
1313                                 sugg.0,
1314                                 sugg.1.to_string(),
1315                                 sugg.2,
1316                                 Applicability::MachineApplicable,
1317                                 false,
1318                                 false,
1319                             ));
1320                         }
1321
1322                         let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
1323                             Some(ident) => format!("{ident}: "),
1324                             None => String::new(),
1325                         };
1326
1327                         if let Some(hir::Node::Expr(hir::Expr {
1328                             kind: hir::ExprKind::Assign(..),
1329                             ..
1330                         })) = self.tcx.hir().find_parent(expr.hir_id)
1331                         {
1332                             if mutability.is_mut() {
1333                                 // Suppressing this diagnostic, we'll properly print it in `check_expr_assign`
1334                                 return None;
1335                             }
1336                         }
1337
1338                         let sugg_expr = if needs_parens { format!("({src})") } else { src };
1339                         return Some((
1340                             sp,
1341                             format!("consider {}borrowing here", mutability.mutably_str()),
1342                             format!("{prefix}{}{sugg_expr}", mutability.ref_prefix_str()),
1343                             Applicability::MachineApplicable,
1344                             false,
1345                             false,
1346                         ));
1347                     }
1348                 }
1349             }
1350             (
1351                 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
1352                 _,
1353                 &ty::Ref(_, checked, _),
1354             ) if self.can_sub(self.param_env, checked, expected).is_ok() => {
1355                 // We have `&T`, check if what was expected was `T`. If so,
1356                 // we may want to suggest removing a `&`.
1357                 if sm.is_imported(expr.span) {
1358                     // Go through the spans from which this span was expanded,
1359                     // and find the one that's pointing inside `sp`.
1360                     //
1361                     // E.g. for `&format!("")`, where we want the span to the
1362                     // `format!()` invocation instead of its expansion.
1363                     if let Some(call_span) =
1364                         iter::successors(Some(expr.span), |s| s.parent_callsite())
1365                             .find(|&s| sp.contains(s))
1366                         && sm.is_span_accessible(call_span)
1367                     {
1368                         return Some((
1369                             sp.with_hi(call_span.lo()),
1370                             "consider removing the borrow".to_string(),
1371                             String::new(),
1372                             Applicability::MachineApplicable,
1373                             true,
1374                             true
1375                         ));
1376                     }
1377                     return None;
1378                 }
1379                 if sp.contains(expr.span)
1380                     && sm.is_span_accessible(expr.span)
1381                 {
1382                     return Some((
1383                         sp.with_hi(expr.span.lo()),
1384                         "consider removing the borrow".to_string(),
1385                         String::new(),
1386                         Applicability::MachineApplicable,
1387                         true,
1388                         true,
1389                     ));
1390                 }
1391             }
1392             (
1393                 _,
1394                 &ty::RawPtr(TypeAndMut { ty: ty_b, mutbl: mutbl_b }),
1395                 &ty::Ref(_, ty_a, mutbl_a),
1396             ) => {
1397                 if let Some(steps) = self.deref_steps(ty_a, ty_b)
1398                     // Only suggest valid if dereferencing needed.
1399                     && steps > 0
1400                     // The pointer type implements `Copy` trait so the suggestion is always valid.
1401                     && let Ok(src) = sm.span_to_snippet(sp)
1402                 {
1403                     let derefs = "*".repeat(steps);
1404                     let old_prefix = mutbl_a.ref_prefix_str();
1405                     let new_prefix = mutbl_b.ref_prefix_str().to_owned() + &derefs;
1406
1407                     let suggestion = replace_prefix(&src, old_prefix, &new_prefix).map(|_| {
1408                         // skip `&` or `&mut ` if both mutabilities are mutable
1409                         let lo = sp.lo() + BytePos(min(old_prefix.len(), mutbl_b.ref_prefix_str().len()) as _);
1410                         // skip `&` or `&mut `
1411                         let hi = sp.lo() + BytePos(old_prefix.len() as _);
1412                         let sp = sp.with_lo(lo).with_hi(hi);
1413
1414                         (
1415                             sp,
1416                             format!("{}{derefs}", if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" }),
1417                             if mutbl_b <= mutbl_a { Applicability::MachineApplicable } else { Applicability::MaybeIncorrect }
1418                         )
1419                     });
1420
1421                     if let Some((span, src, applicability)) = suggestion {
1422                         return Some((
1423                             span,
1424                             "consider dereferencing".to_string(),
1425                             src,
1426                             applicability,
1427                             true,
1428                             false,
1429                         ));
1430                     }
1431                 }
1432             }
1433             _ if sp == expr.span => {
1434                 if let Some(mut steps) = self.deref_steps(checked_ty, expected) {
1435                     let mut expr = expr.peel_blocks();
1436                     let mut prefix_span = expr.span.shrink_to_lo();
1437                     let mut remove = String::new();
1438
1439                     // Try peeling off any existing `&` and `&mut` to reach our target type
1440                     while steps > 0 {
1441                         if let hir::ExprKind::AddrOf(_, mutbl, inner) = expr.kind {
1442                             // If the expression has `&`, removing it would fix the error
1443                             prefix_span = prefix_span.with_hi(inner.span.lo());
1444                             expr = inner;
1445                             remove.push_str(mutbl.ref_prefix_str());
1446                             steps -= 1;
1447                         } else {
1448                             break;
1449                         }
1450                     }
1451                     // If we've reached our target type with just removing `&`, then just print now.
1452                     if steps == 0 && !remove.trim().is_empty() {
1453                         return Some((
1454                             prefix_span,
1455                             format!("consider removing the `{}`", remove.trim()),
1456                             String::new(),
1457                             // Do not remove `&&` to get to bool, because it might be something like
1458                             // { a } && b, which we have a separate fixup suggestion that is more
1459                             // likely correct...
1460                             if remove.trim() == "&&" && expected == self.tcx.types.bool {
1461                                 Applicability::MaybeIncorrect
1462                             } else {
1463                                 Applicability::MachineApplicable
1464                             },
1465                             true,
1466                             false,
1467                         ));
1468                     }
1469
1470                     // For this suggestion to make sense, the type would need to be `Copy`,
1471                     // or we have to be moving out of a `Box<T>`
1472                     if self.type_is_copy_modulo_regions(self.param_env, expected, sp)
1473                         // FIXME(compiler-errors): We can actually do this if the checked_ty is
1474                         // `steps` layers of boxes, not just one, but this is easier and most likely.
1475                         || (checked_ty.is_box() && steps == 1)
1476                     {
1477                         let deref_kind = if checked_ty.is_box() {
1478                             "unboxing the value"
1479                         } else if checked_ty.is_region_ptr() {
1480                             "dereferencing the borrow"
1481                         } else {
1482                             "dereferencing the type"
1483                         };
1484
1485                         // Suggest removing `&` if we have removed any, otherwise suggest just
1486                         // dereferencing the remaining number of steps.
1487                         let message = if remove.is_empty() {
1488                             format!("consider {deref_kind}")
1489                         } else {
1490                             format!(
1491                                 "consider removing the `{}` and {} instead",
1492                                 remove.trim(),
1493                                 deref_kind
1494                             )
1495                         };
1496
1497                         let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
1498                             Some(ident) => format!("{ident}: "),
1499                             None => String::new(),
1500                         };
1501
1502                         let (span, suggestion) = if self.is_else_if_block(expr) {
1503                             // Don't suggest nonsense like `else *if`
1504                             return None;
1505                         } else if let Some(expr) = self.maybe_get_block_expr(expr) {
1506                             // prefix should be empty here..
1507                             (expr.span.shrink_to_lo(), "*".to_string())
1508                         } else {
1509                             (prefix_span, format!("{}{}", prefix, "*".repeat(steps)))
1510                         };
1511                         if suggestion.trim().is_empty() {
1512                             return None;
1513                         }
1514
1515                         return Some((
1516                             span,
1517                             message,
1518                             suggestion,
1519                             Applicability::MachineApplicable,
1520                             true,
1521                             false,
1522                         ));
1523                     }
1524                 }
1525             }
1526             _ => {}
1527         }
1528         None
1529     }
1530
1531     pub fn check_for_cast(
1532         &self,
1533         err: &mut Diagnostic,
1534         expr: &hir::Expr<'_>,
1535         checked_ty: Ty<'tcx>,
1536         expected_ty: Ty<'tcx>,
1537         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
1538     ) -> bool {
1539         if self.tcx.sess.source_map().is_imported(expr.span) {
1540             // Ignore if span is from within a macro.
1541             return false;
1542         }
1543
1544         let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) else {
1545             return false;
1546         };
1547
1548         // If casting this expression to a given numeric type would be appropriate in case of a type
1549         // mismatch.
1550         //
1551         // We want to minimize the amount of casting operations that are suggested, as it can be a
1552         // lossy operation with potentially bad side effects, so we only suggest when encountering
1553         // an expression that indicates that the original type couldn't be directly changed.
1554         //
1555         // For now, don't suggest casting with `as`.
1556         let can_cast = false;
1557
1558         let mut sugg = vec![];
1559
1560         if let Some(hir::Node::ExprField(field)) = self.tcx.hir().find_parent(expr.hir_id) {
1561             // `expr` is a literal field for a struct, only suggest if appropriate
1562             if field.is_shorthand {
1563                 // This is a field literal
1564                 sugg.push((field.ident.span.shrink_to_lo(), format!("{}: ", field.ident)));
1565             } else {
1566                 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
1567                 return false;
1568             }
1569         };
1570
1571         if let hir::ExprKind::Call(path, args) = &expr.kind
1572             && let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
1573                 (&path.kind, args.len())
1574             // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
1575             && let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
1576                 (&base_ty.kind, path_segment.ident.name)
1577         {
1578             if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
1579                 match ident.name {
1580                     sym::i128
1581                     | sym::i64
1582                     | sym::i32
1583                     | sym::i16
1584                     | sym::i8
1585                     | sym::u128
1586                     | sym::u64
1587                     | sym::u32
1588                     | sym::u16
1589                     | sym::u8
1590                     | sym::isize
1591                     | sym::usize
1592                         if base_ty_path.segments.len() == 1 =>
1593                     {
1594                         return false;
1595                     }
1596                     _ => {}
1597                 }
1598             }
1599         }
1600
1601         let msg = format!(
1602             "you can convert {} `{}` to {} `{}`",
1603             checked_ty.kind().article(),
1604             checked_ty,
1605             expected_ty.kind().article(),
1606             expected_ty,
1607         );
1608         let cast_msg = format!(
1609             "you can cast {} `{}` to {} `{}`",
1610             checked_ty.kind().article(),
1611             checked_ty,
1612             expected_ty.kind().article(),
1613             expected_ty,
1614         );
1615         let lit_msg = format!(
1616             "change the type of the numeric literal from `{checked_ty}` to `{expected_ty}`",
1617         );
1618
1619         let close_paren = if expr.precedence().order() < PREC_POSTFIX {
1620             sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1621             ")"
1622         } else {
1623             ""
1624         };
1625
1626         let mut cast_suggestion = sugg.clone();
1627         cast_suggestion.push((expr.span.shrink_to_hi(), format!("{close_paren} as {expected_ty}")));
1628         let mut into_suggestion = sugg.clone();
1629         into_suggestion.push((expr.span.shrink_to_hi(), format!("{close_paren}.into()")));
1630         let mut suffix_suggestion = sugg.clone();
1631         suffix_suggestion.push((
1632             if matches!(
1633                 (&expected_ty.kind(), &checked_ty.kind()),
1634                 (ty::Int(_) | ty::Uint(_), ty::Float(_))
1635             ) {
1636                 // Remove fractional part from literal, for example `42.0f32` into `42`
1637                 let src = src.trim_end_matches(&checked_ty.to_string());
1638                 let len = src.split('.').next().unwrap().len();
1639                 expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
1640             } else {
1641                 let len = src.trim_end_matches(&checked_ty.to_string()).len();
1642                 expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
1643             },
1644             if expr.precedence().order() < PREC_POSTFIX {
1645                 // Readd `)`
1646                 format!("{expected_ty})")
1647             } else {
1648                 expected_ty.to_string()
1649             },
1650         ));
1651         let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
1652             if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
1653         };
1654         let is_negative_int =
1655             |expr: &hir::Expr<'_>| matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::Neg, ..));
1656         let is_uint = |ty: Ty<'_>| matches!(ty.kind(), ty::Uint(..));
1657
1658         let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id);
1659
1660         let suggest_fallible_into_or_lhs_from =
1661             |err: &mut Diagnostic, exp_to_found_is_fallible: bool| {
1662                 // If we know the expression the expected type is derived from, we might be able
1663                 // to suggest a widening conversion rather than a narrowing one (which may
1664                 // panic). For example, given x: u8 and y: u32, if we know the span of "x",
1665                 //   x > y
1666                 // can be given the suggestion "u32::from(x) > y" rather than
1667                 // "x > y.try_into().unwrap()".
1668                 let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
1669                     self.tcx
1670                         .sess
1671                         .source_map()
1672                         .span_to_snippet(expr.span)
1673                         .ok()
1674                         .map(|src| (expr, src))
1675                 });
1676                 let (msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
1677                     (lhs_expr_and_src, exp_to_found_is_fallible)
1678                 {
1679                     let msg = format!(
1680                         "you can convert `{lhs_src}` from `{expected_ty}` to `{checked_ty}`, matching the type of `{src}`",
1681                     );
1682                     let suggestion = vec![
1683                         (lhs_expr.span.shrink_to_lo(), format!("{checked_ty}::from(")),
1684                         (lhs_expr.span.shrink_to_hi(), ")".to_string()),
1685                     ];
1686                     (msg, suggestion)
1687                 } else {
1688                     let msg = format!("{msg} and panic if the converted value doesn't fit");
1689                     let mut suggestion = sugg.clone();
1690                     suggestion.push((
1691                         expr.span.shrink_to_hi(),
1692                         format!("{close_paren}.try_into().unwrap()"),
1693                     ));
1694                     (msg, suggestion)
1695                 };
1696                 err.multipart_suggestion_verbose(
1697                     &msg,
1698                     suggestion,
1699                     Applicability::MachineApplicable,
1700                 );
1701             };
1702
1703         let suggest_to_change_suffix_or_into =
1704             |err: &mut Diagnostic,
1705              found_to_exp_is_fallible: bool,
1706              exp_to_found_is_fallible: bool| {
1707                 let exp_is_lhs =
1708                     expected_ty_expr.map(|e| self.tcx.hir().is_lhs(e.hir_id)).unwrap_or(false);
1709
1710                 if exp_is_lhs {
1711                     return;
1712                 }
1713
1714                 let always_fallible = found_to_exp_is_fallible
1715                     && (exp_to_found_is_fallible || expected_ty_expr.is_none());
1716                 let msg = if literal_is_ty_suffixed(expr) {
1717                     &lit_msg
1718                 } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
1719                     // We now know that converting either the lhs or rhs is fallible. Before we
1720                     // suggest a fallible conversion, check if the value can never fit in the
1721                     // expected type.
1722                     let msg = format!("`{src}` cannot fit into type `{expected_ty}`");
1723                     err.note(&msg);
1724                     return;
1725                 } else if in_const_context {
1726                     // Do not recommend `into` or `try_into` in const contexts.
1727                     return;
1728                 } else if found_to_exp_is_fallible {
1729                     return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
1730                 } else {
1731                     &msg
1732                 };
1733                 let suggestion = if literal_is_ty_suffixed(expr) {
1734                     suffix_suggestion.clone()
1735                 } else {
1736                     into_suggestion.clone()
1737                 };
1738                 err.multipart_suggestion_verbose(msg, suggestion, Applicability::MachineApplicable);
1739             };
1740
1741         match (&expected_ty.kind(), &checked_ty.kind()) {
1742             (ty::Int(exp), ty::Int(found)) => {
1743                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1744                 {
1745                     (Some(exp), Some(found)) if exp < found => (true, false),
1746                     (Some(exp), Some(found)) if exp > found => (false, true),
1747                     (None, Some(8 | 16)) => (false, true),
1748                     (Some(8 | 16), None) => (true, false),
1749                     (None, _) | (_, None) => (true, true),
1750                     _ => (false, false),
1751                 };
1752                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1753                 true
1754             }
1755             (ty::Uint(exp), ty::Uint(found)) => {
1756                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1757                 {
1758                     (Some(exp), Some(found)) if exp < found => (true, false),
1759                     (Some(exp), Some(found)) if exp > found => (false, true),
1760                     (None, Some(8 | 16)) => (false, true),
1761                     (Some(8 | 16), None) => (true, false),
1762                     (None, _) | (_, None) => (true, true),
1763                     _ => (false, false),
1764                 };
1765                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1766                 true
1767             }
1768             (&ty::Int(exp), &ty::Uint(found)) => {
1769                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1770                 {
1771                     (Some(exp), Some(found)) if found < exp => (false, true),
1772                     (None, Some(8)) => (false, true),
1773                     _ => (true, true),
1774                 };
1775                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1776                 true
1777             }
1778             (&ty::Uint(exp), &ty::Int(found)) => {
1779                 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1780                 {
1781                     (Some(exp), Some(found)) if found > exp => (true, false),
1782                     (Some(8), None) => (true, false),
1783                     _ => (true, true),
1784                 };
1785                 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1786                 true
1787             }
1788             (ty::Float(exp), ty::Float(found)) => {
1789                 if found.bit_width() < exp.bit_width() {
1790                     suggest_to_change_suffix_or_into(err, false, true);
1791                 } else if literal_is_ty_suffixed(expr) {
1792                     err.multipart_suggestion_verbose(
1793                         &lit_msg,
1794                         suffix_suggestion,
1795                         Applicability::MachineApplicable,
1796                     );
1797                 } else if can_cast {
1798                     // Missing try_into implementation for `f64` to `f32`
1799                     err.multipart_suggestion_verbose(
1800                         &format!("{cast_msg}, producing the closest possible value"),
1801                         cast_suggestion,
1802                         Applicability::MaybeIncorrect, // lossy conversion
1803                     );
1804                 }
1805                 true
1806             }
1807             (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
1808                 if literal_is_ty_suffixed(expr) {
1809                     err.multipart_suggestion_verbose(
1810                         &lit_msg,
1811                         suffix_suggestion,
1812                         Applicability::MachineApplicable,
1813                     );
1814                 } else if can_cast {
1815                     // Missing try_into implementation for `{float}` to `{integer}`
1816                     err.multipart_suggestion_verbose(
1817                         &format!("{msg}, rounding the float towards zero"),
1818                         cast_suggestion,
1819                         Applicability::MaybeIncorrect, // lossy conversion
1820                     );
1821                 }
1822                 true
1823             }
1824             (ty::Float(exp), ty::Uint(found)) => {
1825                 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
1826                 if exp.bit_width() > found.bit_width().unwrap_or(256) {
1827                     err.multipart_suggestion_verbose(
1828                         &format!(
1829                             "{msg}, producing the floating point representation of the integer",
1830                         ),
1831                         into_suggestion,
1832                         Applicability::MachineApplicable,
1833                     );
1834                 } else if literal_is_ty_suffixed(expr) {
1835                     err.multipart_suggestion_verbose(
1836                         &lit_msg,
1837                         suffix_suggestion,
1838                         Applicability::MachineApplicable,
1839                     );
1840                 } else {
1841                     // Missing try_into implementation for `{integer}` to `{float}`
1842                     err.multipart_suggestion_verbose(
1843                         &format!(
1844                             "{cast_msg}, producing the floating point representation of the integer, \
1845                                  rounded if necessary",
1846                         ),
1847                         cast_suggestion,
1848                         Applicability::MaybeIncorrect, // lossy conversion
1849                     );
1850                 }
1851                 true
1852             }
1853             (ty::Float(exp), ty::Int(found)) => {
1854                 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
1855                 if exp.bit_width() > found.bit_width().unwrap_or(256) {
1856                     err.multipart_suggestion_verbose(
1857                         &format!(
1858                             "{}, producing the floating point representation of the integer",
1859                             &msg,
1860                         ),
1861                         into_suggestion,
1862                         Applicability::MachineApplicable,
1863                     );
1864                 } else if literal_is_ty_suffixed(expr) {
1865                     err.multipart_suggestion_verbose(
1866                         &lit_msg,
1867                         suffix_suggestion,
1868                         Applicability::MachineApplicable,
1869                     );
1870                 } else {
1871                     // Missing try_into implementation for `{integer}` to `{float}`
1872                     err.multipart_suggestion_verbose(
1873                         &format!(
1874                             "{}, producing the floating point representation of the integer, \
1875                                 rounded if necessary",
1876                             &msg,
1877                         ),
1878                         cast_suggestion,
1879                         Applicability::MaybeIncorrect, // lossy conversion
1880                     );
1881                 }
1882                 true
1883             }
1884             (
1885                 &ty::Uint(ty::UintTy::U32 | ty::UintTy::U64 | ty::UintTy::U128)
1886                 | &ty::Int(ty::IntTy::I32 | ty::IntTy::I64 | ty::IntTy::I128),
1887                 &ty::Char,
1888             ) => {
1889                 err.multipart_suggestion_verbose(
1890                     &format!("{cast_msg}, since a `char` always occupies 4 bytes"),
1891                     cast_suggestion,
1892                     Applicability::MachineApplicable,
1893                 );
1894                 true
1895             }
1896             _ => false,
1897         }
1898     }
1899
1900     /// Identify when the user has written `foo..bar()` instead of `foo.bar()`.
1901     pub fn check_for_range_as_method_call(
1902         &self,
1903         err: &mut Diagnostic,
1904         expr: &hir::Expr<'tcx>,
1905         checked_ty: Ty<'tcx>,
1906         expected_ty: Ty<'tcx>,
1907     ) {
1908         if !hir::is_range_literal(expr) {
1909             return;
1910         }
1911         let hir::ExprKind::Struct(
1912             hir::QPath::LangItem(LangItem::Range, ..),
1913             [start, end],
1914             _,
1915         ) = expr.kind else { return; };
1916         let parent = self.tcx.hir().parent_id(expr.hir_id);
1917         if let Some(hir::Node::ExprField(_)) = self.tcx.hir().find(parent) {
1918             // Ignore `Foo { field: a..Default::default() }`
1919             return;
1920         }
1921         let mut expr = end.expr;
1922         let mut expectation = Some(expected_ty);
1923         while let hir::ExprKind::MethodCall(_, rcvr, ..) = expr.kind {
1924             // Getting to the root receiver and asserting it is a fn call let's us ignore cases in
1925             // `tests/ui/methods/issues/issue-90315.stderr`.
1926             expr = rcvr;
1927             // If we have more than one layer of calls, then the expected ty
1928             // cannot guide the method probe.
1929             expectation = None;
1930         }
1931         let hir::ExprKind::Call(method_name, _) = expr.kind else { return; };
1932         let ty::Adt(adt, _) = checked_ty.kind() else { return; };
1933         if self.tcx.lang_items().range_struct() != Some(adt.did()) {
1934             return;
1935         }
1936         if let ty::Adt(adt, _) = expected_ty.kind()
1937             && self.tcx.lang_items().range_struct() == Some(adt.did())
1938         {
1939             return;
1940         }
1941         // Check if start has method named end.
1942         let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = method_name.kind else { return; };
1943         let [hir::PathSegment { ident, .. }] = p.segments else { return; };
1944         let self_ty = self.typeck_results.borrow().expr_ty(start.expr);
1945         let Ok(_pick) = self.lookup_probe_for_diagnostic(
1946             *ident,
1947             self_ty,
1948             expr,
1949             probe::ProbeScope::AllTraits,
1950             expectation,
1951         ) else { return; };
1952         let mut sugg = ".";
1953         let mut span = start.expr.span.between(end.expr.span);
1954         if span.lo() + BytePos(2) == span.hi() {
1955             // There's no space between the start, the range op and the end, suggest removal which
1956             // will be more noticeable than the replacement of `..` with `.`.
1957             span = span.with_lo(span.lo() + BytePos(1));
1958             sugg = "";
1959         }
1960         err.span_suggestion_verbose(
1961             span,
1962             "you likely meant to write a method call instead of a range",
1963             sugg,
1964             Applicability::MachineApplicable,
1965         );
1966     }
1967
1968     /// Identify when the type error is because `()` is found in a binding that was assigned a
1969     /// block without a tail expression.
1970     fn check_for_binding_assigned_block_without_tail_expression(
1971         &self,
1972         err: &mut Diagnostic,
1973         expr: &hir::Expr<'_>,
1974         checked_ty: Ty<'tcx>,
1975         expected_ty: Ty<'tcx>,
1976     ) {
1977         if !checked_ty.is_unit() {
1978             return;
1979         }
1980         let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { return; };
1981         let hir::def::Res::Local(hir_id) = path.res else { return; };
1982         let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else {
1983             return;
1984         };
1985         let Some(hir::Node::Local(hir::Local {
1986             ty: None,
1987             init: Some(init),
1988             ..
1989         })) = self.tcx.hir().find_parent(pat.hir_id) else { return; };
1990         let hir::ExprKind::Block(block, None) = init.kind else { return; };
1991         if block.expr.is_some() {
1992             return;
1993         }
1994         let [.., stmt] = block.stmts else {
1995             err.span_label(block.span, "this empty block is missing a tail expression");
1996             return;
1997         };
1998         let hir::StmtKind::Semi(tail_expr) = stmt.kind else { return; };
1999         let Some(ty) = self.node_ty_opt(tail_expr.hir_id) else { return; };
2000         if self.can_eq(self.param_env, expected_ty, ty).is_ok() {
2001             err.span_suggestion_short(
2002                 stmt.span.with_lo(tail_expr.span.hi()),
2003                 "remove this semicolon",
2004                 "",
2005                 Applicability::MachineApplicable,
2006             );
2007         } else {
2008             err.span_label(block.span, "this block is missing a tail expression");
2009         }
2010     }
2011
2012     fn check_wrong_return_type_due_to_generic_arg(
2013         &self,
2014         err: &mut Diagnostic,
2015         expr: &hir::Expr<'_>,
2016         checked_ty: Ty<'tcx>,
2017     ) {
2018         let Some(hir::Node::Expr(parent_expr)) = self.tcx.hir().find_parent(expr.hir_id) else { return; };
2019         enum CallableKind {
2020             Function,
2021             Method,
2022             Constructor,
2023         }
2024         let mut maybe_emit_help = |def_id: hir::def_id::DefId,
2025                                    callable: rustc_span::symbol::Ident,
2026                                    args: &[hir::Expr<'_>],
2027                                    kind: CallableKind| {
2028             let arg_idx = args.iter().position(|a| a.hir_id == expr.hir_id).unwrap();
2029             let fn_ty = self.tcx.bound_type_of(def_id).0;
2030             if !fn_ty.is_fn() {
2031                 return;
2032             }
2033             let fn_sig = fn_ty.fn_sig(self.tcx).skip_binder();
2034             let Some(&arg) = fn_sig.inputs().get(arg_idx + if matches!(kind, CallableKind::Method) { 1 } else { 0 }) else { return; };
2035             if matches!(arg.kind(), ty::Param(_))
2036                 && fn_sig.output().contains(arg)
2037                 && self.node_ty(args[arg_idx].hir_id) == checked_ty
2038             {
2039                 let mut multi_span: MultiSpan = parent_expr.span.into();
2040                 multi_span.push_span_label(
2041                     args[arg_idx].span,
2042                     format!(
2043                         "this argument influences the {} of `{}`",
2044                         if matches!(kind, CallableKind::Constructor) {
2045                             "type"
2046                         } else {
2047                             "return type"
2048                         },
2049                         callable
2050                     ),
2051                 );
2052                 err.span_help(
2053                     multi_span,
2054                     format!(
2055                         "the {} `{}` due to the type of the argument passed",
2056                         match kind {
2057                             CallableKind::Function => "return type of this call is",
2058                             CallableKind::Method => "return type of this call is",
2059                             CallableKind::Constructor => "type constructed contains",
2060                         },
2061                         checked_ty
2062                     ),
2063                 );
2064             }
2065         };
2066         match parent_expr.kind {
2067             hir::ExprKind::Call(fun, args) => {
2068                 let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = fun.kind else { return; };
2069                 let hir::def::Res::Def(kind, def_id) = path.res else { return; };
2070                 let callable_kind = if matches!(kind, hir::def::DefKind::Ctor(_, _)) {
2071                     CallableKind::Constructor
2072                 } else {
2073                     CallableKind::Function
2074                 };
2075                 maybe_emit_help(def_id, path.segments[0].ident, args, callable_kind);
2076             }
2077             hir::ExprKind::MethodCall(method, _receiver, args, _span) => {
2078                 let Some(def_id) = self.typeck_results.borrow().type_dependent_def_id(parent_expr.hir_id) else { return; };
2079                 maybe_emit_help(def_id, method.ident, args, CallableKind::Method)
2080             }
2081             _ => return,
2082         }
2083     }
2084 }