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