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