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