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