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