2 use rustc_ast::util::parser::PREC_POSTFIX;
3 use rustc_errors::MultiSpan;
4 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
6 use rustc_hir::def::CtorKind;
7 use rustc_hir::lang_items::LangItem;
8 use rustc_hir::{is_range_literal, Node};
9 use rustc_infer::infer::InferOk;
10 use rustc_middle::lint::in_external_macro;
11 use rustc_middle::middle::stability::EvalResult;
12 use rustc_middle::ty::adjustment::AllowTwoPhase;
13 use rustc_middle::ty::error::{ExpectedFound, TypeError};
14 use rustc_middle::ty::print::with_no_trimmed_paths;
15 use rustc_middle::ty::{self, Article, AssocItem, Ty, TypeAndMut};
16 use rustc_span::symbol::{sym, Symbol};
17 use rustc_span::{BytePos, Span};
18 use rustc_trait_selection::infer::InferCtxtExt as _;
19 use rustc_trait_selection::traits::ObligationCause;
21 use super::method::probe;
26 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
27 pub fn emit_type_mismatch_suggestions(
30 expr: &hir::Expr<'tcx>,
33 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
34 error: Option<TypeError<'tcx>>,
36 if expr_ty == expected {
40 self.annotate_alternative_method_deref(err, expr, error);
42 // Use `||` to give these suggestions a precedence
43 let _ = self.suggest_missing_parentheses(err, expr)
44 || self.suggest_remove_last_method_call(err, expr, expected)
45 || self.suggest_associated_const(err, expr, expected)
46 || self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr)
47 || self.suggest_option_to_bool(err, expr, expr_ty, expected)
48 || self.suggest_compatible_variants(err, expr, expected, expr_ty)
49 || self.suggest_non_zero_new_unwrap(err, expr, expected, expr_ty)
50 || self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty)
51 || self.suggest_no_capture_closure(err, expected, expr_ty)
52 || self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty)
53 || self.suggest_block_to_brackets_peeling_refs(err, expr, expr_ty, expected)
54 || self.suggest_copied_or_cloned(err, expr, expr_ty, expected)
55 || self.suggest_into(err, expr, expr_ty, expected)
56 || self.suggest_floating_point_literal(err, expr, expected);
59 pub fn emit_coerce_suggestions(
62 expr: &hir::Expr<'tcx>,
65 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
66 error: Option<TypeError<'tcx>>,
68 if expr_ty == expected {
72 self.annotate_expected_due_to_let_ty(err, expr, error);
73 self.emit_type_mismatch_suggestions(err, expr, expr_ty, expected, expected_ty_expr, error);
74 self.note_type_is_not_clone(err, expected, expr_ty, expr);
75 self.note_need_for_fn_pointer(err, expected, expr_ty);
76 self.note_internal_mutation_in_method(err, expr, expected, expr_ty);
77 self.check_for_range_as_method_call(err, expr, expr_ty, expected);
80 /// Requires that the two types unify, and prints an error message if
82 pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
83 if let Some(mut e) = self.demand_suptype_diag(sp, expected, actual) {
88 pub fn demand_suptype_diag(
93 ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
94 self.demand_suptype_with_origin(&self.misc(sp), expected, actual)
97 #[instrument(skip(self), level = "debug")]
98 pub fn demand_suptype_with_origin(
100 cause: &ObligationCause<'tcx>,
103 ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
104 match self.at(cause, self.param_env).sup(expected, actual) {
105 Ok(InferOk { obligations, value: () }) => {
106 self.register_predicates(obligations);
109 Err(e) => Some(self.err_ctxt().report_mismatched_types(&cause, expected, actual, e)),
113 pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
114 if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
119 pub fn demand_eqtype_diag(
124 ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
125 self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
128 pub fn demand_eqtype_with_origin(
130 cause: &ObligationCause<'tcx>,
133 ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
134 match self.at(cause, self.param_env).eq(expected, actual) {
135 Ok(InferOk { obligations, value: () }) => {
136 self.register_predicates(obligations);
139 Err(e) => Some(self.err_ctxt().report_mismatched_types(cause, expected, actual, e)),
143 pub fn demand_coerce(
145 expr: &hir::Expr<'tcx>,
146 checked_ty: Ty<'tcx>,
148 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
149 allow_two_phase: AllowTwoPhase,
152 self.demand_coerce_diag(expr, checked_ty, expected, expected_ty_expr, allow_two_phase);
153 if let Some(mut err) = err {
159 /// Checks that the type of `expr` can be coerced to `expected`.
161 /// N.B., this code relies on `self.diverges` to be accurate. In particular, assignments to `!`
162 /// will be permitted if the diverges flag is currently "always".
163 #[instrument(level = "debug", skip(self, expr, expected_ty_expr, allow_two_phase))]
164 pub fn demand_coerce_diag(
166 expr: &hir::Expr<'tcx>,
167 checked_ty: Ty<'tcx>,
169 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
170 allow_two_phase: AllowTwoPhase,
171 ) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>) {
172 let expected = self.resolve_vars_with_obligations(expected);
174 let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase, None) {
175 Ok(ty) => return (ty, None),
179 self.set_tainted_by_errors(self.tcx.sess.delay_span_bug(
181 "`TypeError` when attempting coercion but no error emitted",
183 let expr = expr.peel_drop_temps();
184 let cause = self.misc(expr.span);
185 let expr_ty = self.resolve_vars_with_obligations(checked_ty);
186 let mut err = self.err_ctxt().report_mismatched_types(&cause, expected, expr_ty, e);
188 let is_insufficiently_polymorphic =
189 matches!(e, TypeError::RegionsInsufficientlyPolymorphic(..));
191 // FIXME(#73154): For now, we do leak check when coercing function
192 // pointers in typeck, instead of only during borrowck. This can lead
193 // to these `RegionsInsufficientlyPolymorphic` errors that aren't helpful.
194 if !is_insufficiently_polymorphic {
195 self.emit_coerce_suggestions(
205 (expected, Some(err))
208 fn annotate_expected_due_to_let_ty(
210 err: &mut Diagnostic,
211 expr: &hir::Expr<'_>,
212 error: Option<TypeError<'tcx>>,
214 let parent = self.tcx.hir().parent_id(expr.hir_id);
215 match (self.tcx.hir().find(parent), error) {
216 (Some(hir::Node::Local(hir::Local { ty: Some(ty), init: Some(init), .. })), _)
217 if init.hir_id == expr.hir_id =>
219 // Point at `let` assignment type.
220 err.span_label(ty.span, "expected due to this");
223 Some(hir::Node::Expr(hir::Expr {
224 kind: hir::ExprKind::Assign(lhs, rhs, _), ..
226 Some(TypeError::Sorts(ExpectedFound { expected, .. })),
227 ) if rhs.hir_id == expr.hir_id && !expected.is_closure() => {
228 // We ignore closures explicitly because we already point at them elsewhere.
229 // Point at the assigned-to binding.
230 let mut primary_span = lhs.span;
231 let mut secondary_span = lhs.span;
232 let mut post_message = "";
234 hir::ExprKind::Path(hir::QPath::Resolved(
239 hir::def::DefKind::Static(_) | hir::def::DefKind::Const,
245 if let Some(hir::Node::Item(hir::Item {
247 kind: hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..),
249 })) = self.tcx.hir().get_if_local(*def_id)
251 primary_span = ty.span;
252 secondary_span = ident.span;
253 post_message = " type";
256 hir::ExprKind::Path(hir::QPath::Resolved(
258 hir::Path { res: hir::def::Res::Local(hir_id), .. },
260 if let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(*hir_id) {
261 primary_span = pat.span;
262 secondary_span = pat.span;
263 match self.tcx.hir().find_parent(pat.hir_id) {
264 Some(hir::Node::Local(hir::Local { ty: Some(ty), .. })) => {
265 primary_span = ty.span;
266 post_message = " type";
268 Some(hir::Node::Local(hir::Local { init: Some(init), .. })) => {
269 primary_span = init.span;
270 post_message = " value";
272 Some(hir::Node::Param(hir::Param { ty_span, .. })) => {
273 primary_span = *ty_span;
274 post_message = " parameter type";
283 if primary_span != secondary_span
288 .is_multiline(secondary_span.shrink_to_hi().until(primary_span))
290 // We are pointing at the binding's type or initializer value, but it's pattern
291 // is in a different line, so we point at both.
292 err.span_label(secondary_span, "expected due to the type of this binding");
293 err.span_label(primary_span, &format!("expected due to this{post_message}"));
294 } else if post_message == "" {
295 // We are pointing at either the assignment lhs or the binding def pattern.
296 err.span_label(primary_span, "expected due to the type of this binding");
298 // We are pointing at the binding's type or initializer value.
299 err.span_label(primary_span, &format!("expected due to this{post_message}"));
302 if !lhs.is_syntactic_place_expr() {
303 // We already emitted E0070 "invalid left-hand side of assignment", so we
305 err.downgrade_to_delayed_bug();
309 Some(hir::Node::Expr(hir::Expr {
310 kind: hir::ExprKind::Binary(_, lhs, rhs), ..
312 Some(TypeError::Sorts(ExpectedFound { expected, .. })),
313 ) if rhs.hir_id == expr.hir_id
314 && self.typeck_results.borrow().expr_ty_adjusted_opt(lhs) == Some(expected) =>
316 err.span_label(lhs.span, &format!("expected because this is `{expected}`"));
322 fn annotate_alternative_method_deref(
324 err: &mut Diagnostic,
325 expr: &hir::Expr<'_>,
326 error: Option<TypeError<'tcx>>,
328 let parent = self.tcx.hir().parent_id(expr.hir_id);
329 let Some(TypeError::Sorts(ExpectedFound { expected, .. })) = error else {return;};
330 let Some(hir::Node::Expr(hir::Expr {
331 kind: hir::ExprKind::Assign(lhs, rhs, _), ..
332 })) = self.tcx.hir().find(parent) else {return; };
333 if rhs.hir_id != expr.hir_id || expected.is_closure() {
336 let hir::ExprKind::Unary(hir::UnOp::Deref, deref) = lhs.kind else { return; };
337 let hir::ExprKind::MethodCall(path, base, args, _) = deref.kind else { return; };
338 let Some(self_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(base) else { return; };
342 probe::Mode::MethodCall,
344 probe::IsSuggestion(true),
347 probe::ProbeScope::TraitsInScope,
351 let in_scope_methods = self.probe_for_name_many(
352 probe::Mode::MethodCall,
354 probe::IsSuggestion(true),
357 probe::ProbeScope::TraitsInScope,
359 let other_methods_in_scope: Vec<_> =
360 in_scope_methods.iter().filter(|c| c.item.def_id != pick.item.def_id).collect();
362 let all_methods = self.probe_for_name_many(
363 probe::Mode::MethodCall,
365 probe::IsSuggestion(true),
368 probe::ProbeScope::AllTraits,
370 let suggestions: Vec<_> = all_methods
372 .filter(|c| c.item.def_id != pick.item.def_id)
375 let substs = ty::InternalSubsts::for_item(self.tcx, m.def_id, |param, _| {
376 self.var_for_def(deref.span, param)
380 deref.span.until(base.span),
383 with_no_trimmed_paths!(
384 self.tcx.def_path_str_with_substs(m.def_id, substs,)
386 match self.tcx.fn_sig(m.def_id).input(0).skip_binder().kind() {
387 ty::Ref(_, _, hir::Mutability::Mut) => "&mut ",
388 ty::Ref(_, _, _) => "&",
394 [] => (base.span.shrink_to_hi().with_hi(deref.span.hi()), ")".to_string()),
395 [first, ..] => (base.span.between(first.span), ", ".to_string()),
400 if suggestions.is_empty() {
403 let mut path_span: MultiSpan = path.ident.span.into();
404 path_span.push_span_label(
406 with_no_trimmed_paths!(format!(
408 self.tcx.def_path_str(pick.item.def_id),
411 let container_id = pick.item.container_id(self.tcx);
412 let container = with_no_trimmed_paths!(self.tcx.def_path_str(container_id));
413 for def_id in pick.import_ids {
414 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
415 path_span.push_span_label(
416 self.tcx.hir().span(hir_id),
417 format!("`{container}` imported here"),
420 let tail = with_no_trimmed_paths!(match &other_methods_in_scope[..] {
422 [candidate] => format!(
423 "the method of the same name on {} `{}`",
424 match candidate.kind {
425 probe::CandidateKind::InherentImplCandidate(..) => "the inherent impl for",
428 self.tcx.def_path_str(candidate.item.container_id(self.tcx))
430 [.., last] if other_methods_in_scope.len() < 5 => {
432 "the methods of the same name on {} and `{}`",
433 other_methods_in_scope[..other_methods_in_scope.len() - 1]
437 self.tcx.def_path_str(c.item.container_id(self.tcx))
439 .collect::<Vec<String>>()
441 self.tcx.def_path_str(last.item.container_id(self.tcx))
445 "the methods of the same name on {} other traits",
446 other_methods_in_scope.len()
452 "the `{}` call is resolved to the method in `{container}`, shadowing {tail}",
456 if suggestions.len() > other_methods_in_scope.len() {
458 "additionally, there are {} other available methods that aren't in scope",
459 suggestions.len() - other_methods_in_scope.len()
462 err.multipart_suggestions(
464 "you might have meant to call {}; you can use the fully-qualified path to call {} \
466 if suggestions.len() == 1 {
469 "one of the other methods"
471 if suggestions.len() == 1 { "it" } else { "one of them" },
474 Applicability::MaybeIncorrect,
478 /// If the expected type is an enum (Issue #55250) with any variants whose
479 /// sole field is of the found type, suggest such variants. (Issue #42764)
480 fn suggest_compatible_variants(
482 err: &mut Diagnostic,
483 expr: &hir::Expr<'_>,
487 if let ty::Adt(expected_adt, substs) = expected.kind() {
488 if let hir::ExprKind::Field(base, ident) = expr.kind {
489 let base_ty = self.typeck_results.borrow().expr_ty(base);
490 if self.can_eq(self.param_env, base_ty, expected).is_ok()
491 && let Some(base_span) = base.span.find_ancestor_inside(expr.span)
493 err.span_suggestion_verbose(
494 expr.span.with_lo(base_span.hi()),
495 format!("consider removing the tuple struct field `{ident}`"),
497 Applicability::MaybeIncorrect,
503 // If the expression is of type () and it's the return expression of a block,
504 // we suggest adding a separate return expression instead.
505 // (To avoid things like suggesting `Ok(while .. { .. })`.)
506 if expr_ty.is_unit() {
507 let mut id = expr.hir_id;
510 // Unroll desugaring, to make sure this works for `for` loops etc.
512 parent = self.tcx.hir().parent_id(id);
513 if let Some(parent_span) = self.tcx.hir().opt_span(parent) {
514 if parent_span.find_ancestor_inside(expr.span).is_some() {
515 // The parent node is part of the same span, so is the result of the
516 // same expansion/desugaring and not the 'real' parent node.
524 if let Some(hir::Node::Block(&hir::Block {
525 span: block_span, expr: Some(e), ..
526 })) = self.tcx.hir().find(parent)
529 if let Some(span) = expr.span.find_ancestor_inside(block_span) {
530 let return_suggestions = if self
532 .is_diagnostic_item(sym::Result, expected_adt.did())
535 } else if self.tcx.is_diagnostic_item(sym::Option, expected_adt.did()) {
536 vec!["None", "Some(())"]
540 if let Some(indent) =
541 self.tcx.sess.source_map().indentation_before(span.shrink_to_lo())
543 // Add a semicolon, except after `}`.
545 match self.tcx.sess.source_map().span_to_snippet(span) {
546 Ok(s) if s.ends_with('}') => "",
549 err.span_suggestions(
551 "try adding an expression at the end of the block",
554 .map(|r| format!("{semicolon}\n{indent}{r}")),
555 Applicability::MaybeIncorrect,
564 let compatible_variants: Vec<(String, _, _, Option<String>)> = expected_adt
568 variant.fields.len() == 1
570 .filter_map(|variant| {
571 let sole_field = &variant.fields[0];
573 let field_is_local = sole_field.did.is_local();
574 let field_is_accessible =
575 sole_field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
576 // Skip suggestions for unstable public fields (for example `Pin::pointer`)
577 && matches!(self.tcx.eval_stability(sole_field.did, None, expr.span, None), EvalResult::Allow | EvalResult::Unmarked);
579 if !field_is_local && !field_is_accessible {
583 let note_about_variant_field_privacy = (field_is_local && !field_is_accessible)
584 .then(|| " (its field is private, but it's local to this crate and its privacy can be changed)".to_string());
586 let sole_field_ty = sole_field.ty(self.tcx, substs);
587 if self.can_coerce(expr_ty, sole_field_ty) {
589 with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
590 // FIXME #56861: DRYer prelude filtering
591 if let Some(path) = variant_path.strip_prefix("std::prelude::")
592 && let Some((_, path)) = path.split_once("::")
594 return Some((path.to_string(), variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy));
596 Some((variant_path, variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy))
603 let suggestions_for = |variant: &_, ctor_kind, field_name| {
604 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
605 Some(ident) => format!("{ident}: "),
606 None => String::new(),
609 let (open, close) = match ctor_kind {
610 Some(CtorKind::Fn) => ("(".to_owned(), ")"),
611 None => (format!(" {{ {field_name}: "), " }"),
613 // unit variants don't have fields
614 Some(CtorKind::Const) => unreachable!(),
617 // Suggest constructor as deep into the block tree as possible.
618 // This fixes https://github.com/rust-lang/rust/issues/101065,
619 // and also just helps make the most minimal suggestions.
621 while let hir::ExprKind::Block(block, _) = &expr.kind
622 && let Some(expr_) = &block.expr
628 (expr.span.shrink_to_lo(), format!("{prefix}{variant}{open}")),
629 (expr.span.shrink_to_hi(), close.to_owned()),
633 match &compatible_variants[..] {
634 [] => { /* No variants to format */ }
635 [(variant, ctor_kind, field_name, note)] => {
636 // Just a single matching variant.
637 err.multipart_suggestion_verbose(
639 "try wrapping the expression in `{variant}`{note}",
640 note = note.as_deref().unwrap_or("")
642 suggestions_for(&**variant, *ctor_kind, *field_name),
643 Applicability::MaybeIncorrect,
648 // More than one matching variant.
649 err.multipart_suggestions(
651 "try wrapping the expression in a variant of `{}`",
652 self.tcx.def_path_str(expected_adt.did())
654 compatible_variants.into_iter().map(
655 |(variant, ctor_kind, field_name, _)| {
656 suggestions_for(&variant, ctor_kind, field_name)
659 Applicability::MaybeIncorrect,
669 fn suggest_non_zero_new_unwrap(
671 err: &mut Diagnostic,
672 expr: &hir::Expr<'_>,
677 let (adt, unwrap) = match expected.kind() {
678 // In case Option<NonZero*> is wanted, but * is provided, suggest calling new
679 ty::Adt(adt, substs) if tcx.is_diagnostic_item(sym::Option, adt.did()) => {
681 let ty::Adt(adt, _) = substs.type_at(0).kind() else { return false; };
685 // In case NonZero* is wanted, but * is provided also add `.unwrap()` to satisfy types
686 ty::Adt(adt, _) => (adt, ".unwrap()"),
691 (sym::NonZeroU8, tcx.types.u8),
692 (sym::NonZeroU16, tcx.types.u16),
693 (sym::NonZeroU32, tcx.types.u32),
694 (sym::NonZeroU64, tcx.types.u64),
695 (sym::NonZeroU128, tcx.types.u128),
696 (sym::NonZeroI8, tcx.types.i8),
697 (sym::NonZeroI16, tcx.types.i16),
698 (sym::NonZeroI32, tcx.types.i32),
699 (sym::NonZeroI64, tcx.types.i64),
700 (sym::NonZeroI128, tcx.types.i128),
703 let Some((s, _)) = map
705 .find(|&&(s, t)| self.tcx.is_diagnostic_item(s, adt.did()) && self.can_coerce(expr_ty, t))
706 else { return false; };
708 let path = self.tcx.def_path_str(adt.non_enum_variant().def_id);
710 err.multipart_suggestion(
711 format!("consider calling `{s}::new`"),
713 (expr.span.shrink_to_lo(), format!("{path}::new(")),
714 (expr.span.shrink_to_hi(), format!("){unwrap}")),
716 Applicability::MaybeIncorrect,
722 pub fn get_conversion_methods(
726 checked_ty: Ty<'tcx>,
728 ) -> Vec<AssocItem> {
729 let methods = self.probe_for_return_type(
731 probe::Mode::MethodCall,
736 self.has_only_self_parameter(m)
739 // This special internal attribute is used to permit
740 // "identity-like" conversion methods to be suggested here.
742 // FIXME (#46459 and #46460): ideally
743 // `std::convert::Into::into` and `std::borrow:ToOwned` would
744 // also be `#[rustc_conversion_suggestion]`, if not for
745 // method-probing false-positives and -negatives (respectively).
747 // FIXME? Other potential candidate methods: `as_ref` and
749 .has_attr(m.def_id, sym::rustc_conversion_suggestion)
756 /// This function checks whether the method is not static and does not accept other parameters than `self`.
757 fn has_only_self_parameter(&self, method: &AssocItem) -> bool {
759 ty::AssocKind::Fn => {
760 method.fn_has_self_parameter
761 && self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1
767 /// Identify some cases where `as_ref()` would be appropriate and suggest it.
769 /// Given the following code:
770 /// ```compile_fail,E0308
772 /// fn takes_ref(_: &Foo) {}
773 /// let ref opt = Some(Foo);
775 /// opt.map(|param| takes_ref(param));
777 /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
779 /// It only checks for `Option` and `Result` and won't work with
780 /// ```ignore (illustrative)
781 /// opt.map(|param| { takes_ref(param) });
783 fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Span, &'static str, String)> {
784 let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.kind else {
788 let hir::def::Res::Local(local_id) = path.res else {
792 let local_parent = self.tcx.hir().parent_id(local_id);
793 let Some(Node::Param(hir::Param { hir_id: param_hir_id, .. })) = self.tcx.hir().find(local_parent) else {
797 let param_parent = self.tcx.hir().parent_id(*param_hir_id);
798 let Some(Node::Expr(hir::Expr {
800 kind: hir::ExprKind::Closure(hir::Closure { fn_decl: closure_fn_decl, .. }),
802 })) = self.tcx.hir().find(param_parent) else {
806 let expr_parent = self.tcx.hir().parent_id(*expr_hir_id);
807 let hir = self.tcx.hir().find(expr_parent);
808 let closure_params_len = closure_fn_decl.inputs.len();
810 Some(Node::Expr(hir::Expr {
811 kind: hir::ExprKind::MethodCall(method_path, receiver, ..),
815 ) = (hir, closure_params_len) else {
819 let self_ty = self.typeck_results.borrow().expr_ty(receiver);
820 let name = method_path.ident.name;
821 let is_as_ref_able = match self_ty.peel_refs().kind() {
823 (self.tcx.is_diagnostic_item(sym::Option, def.did())
824 || self.tcx.is_diagnostic_item(sym::Result, def.did()))
825 && (name == sym::map || name == sym::and_then)
829 match (is_as_ref_able, self.sess().source_map().span_to_snippet(method_path.ident.span)) {
831 let suggestion = format!("as_ref().{}", src);
832 Some((method_path.ident.span, "consider using `as_ref` instead", suggestion))
838 pub(crate) fn maybe_get_struct_pattern_shorthand_field(
840 expr: &hir::Expr<'_>,
841 ) -> Option<Symbol> {
842 let hir = self.tcx.hir();
843 let local = match expr {
846 hir::ExprKind::Path(hir::QPath::Resolved(
849 res: hir::def::Res::Local(_),
850 segments: [hir::PathSegment { ident, .. }],
859 match hir.find_parent(expr.hir_id)? {
860 Node::ExprField(field) => {
861 if field.ident.name == local.name && field.is_shorthand {
862 return Some(local.name);
871 /// If the given `HirId` corresponds to a block with a trailing expression, return that expression
872 pub(crate) fn maybe_get_block_expr(
874 expr: &hir::Expr<'tcx>,
875 ) -> Option<&'tcx hir::Expr<'tcx>> {
877 hir::Expr { kind: hir::ExprKind::Block(block, ..), .. } => block.expr,
882 /// Returns whether the given expression is an `else if`.
883 pub(crate) fn is_else_if_block(&self, expr: &hir::Expr<'_>) -> bool {
884 if let hir::ExprKind::If(..) = expr.kind {
885 let parent_id = self.tcx.hir().parent_id(expr.hir_id);
886 if let Some(Node::Expr(hir::Expr {
887 kind: hir::ExprKind::If(_, _, Some(else_expr)),
889 })) = self.tcx.hir().find(parent_id)
891 return else_expr.hir_id == expr.hir_id;
897 /// This function is used to determine potential "simple" improvements or users' errors and
898 /// provide them useful help. For example:
900 /// ```compile_fail,E0308
901 /// fn some_fn(s: &str) {}
903 /// let x = "hey!".to_owned();
904 /// some_fn(x); // error
907 /// No need to find every potential function which could make a coercion to transform a
908 /// `String` into a `&str` since a `&` would do the trick!
910 /// In addition of this check, it also checks between references mutability state. If the
911 /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
915 expr: &hir::Expr<'tcx>,
916 checked_ty: Ty<'tcx>,
924 bool, /* suggest `&` or `&mut` type annotation */
926 let sess = self.sess();
929 // If the span is from an external macro, there's no suggestion we can make.
930 if in_external_macro(sess, sp) {
934 let sm = sess.source_map();
936 let replace_prefix = |s: &str, old: &str, new: &str| {
937 s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
940 // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
941 let expr = expr.peel_drop_temps();
943 match (&expr.kind, expected.kind(), checked_ty.kind()) {
944 (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (exp.kind(), check.kind()) {
945 (&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
946 if let hir::ExprKind::Lit(_) = expr.kind
947 && let Ok(src) = sm.span_to_snippet(sp)
948 && replace_prefix(&src, "b\"", "\"").is_some()
950 let pos = sp.lo() + BytePos(1);
953 "consider removing the leading `b`".to_string(),
955 Applicability::MachineApplicable,
961 (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
962 if let hir::ExprKind::Lit(_) = expr.kind
963 && let Ok(src) = sm.span_to_snippet(sp)
964 && replace_prefix(&src, "\"", "b\"").is_some()
968 "consider adding a leading `b`".to_string(),
970 Applicability::MachineApplicable,
978 (_, &ty::Ref(_, _, mutability), _) => {
979 // Check if it can work when put into a ref. For example:
982 // fn bar(x: &mut i32) {}
985 // bar(&x); // error, expected &mut
987 let ref_ty = match mutability {
988 hir::Mutability::Mut => {
989 self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
991 hir::Mutability::Not => {
992 self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
995 if self.can_coerce(ref_ty, expected) {
996 let mut sugg_sp = sp;
997 if let hir::ExprKind::MethodCall(ref segment, receiver, args, _) = expr.kind {
999 self.tcx.require_lang_item(LangItem::Clone, Some(segment.ident.span));
1001 && self.typeck_results.borrow().type_dependent_def_id(expr.hir_id).map(
1003 let ai = self.tcx.associated_item(did);
1004 ai.trait_container(self.tcx) == Some(clone_trait)
1007 && segment.ident.name == sym::clone
1009 // If this expression had a clone call when suggesting borrowing
1010 // we want to suggest removing it because it'd now be unnecessary.
1011 sugg_sp = receiver.span;
1014 if let Ok(src) = sm.span_to_snippet(sugg_sp) {
1015 let needs_parens = match expr.kind {
1016 // parenthesize if needed (Issue #46756)
1017 hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true,
1018 // parenthesize borrows of range literals (Issue #54505)
1019 _ if is_range_literal(expr) => true,
1023 if let Some(sugg) = self.can_use_as_ref(expr) {
1028 Applicability::MachineApplicable,
1034 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
1035 Some(ident) => format!("{ident}: "),
1036 None => String::new(),
1039 if let Some(hir::Node::Expr(hir::Expr {
1040 kind: hir::ExprKind::Assign(..),
1042 })) = self.tcx.hir().find_parent(expr.hir_id)
1044 if mutability.is_mut() {
1045 // Suppressing this diagnostic, we'll properly print it in `check_expr_assign`
1050 let sugg_expr = if needs_parens { format!("({src})") } else { src };
1053 format!("consider {}borrowing here", mutability.mutably_str()),
1054 format!("{prefix}{}{sugg_expr}", mutability.ref_prefix_str()),
1055 Applicability::MachineApplicable,
1063 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
1065 &ty::Ref(_, checked, _),
1066 ) if self.can_sub(self.param_env, checked, expected).is_ok() => {
1067 // We have `&T`, check if what was expected was `T`. If so,
1068 // we may want to suggest removing a `&`.
1069 if sm.is_imported(expr.span) {
1070 // Go through the spans from which this span was expanded,
1071 // and find the one that's pointing inside `sp`.
1073 // E.g. for `&format!("")`, where we want the span to the
1074 // `format!()` invocation instead of its expansion.
1075 if let Some(call_span) =
1076 iter::successors(Some(expr.span), |s| s.parent_callsite())
1077 .find(|&s| sp.contains(s))
1078 && sm.is_span_accessible(call_span)
1081 sp.with_hi(call_span.lo()),
1082 "consider removing the borrow".to_string(),
1084 Applicability::MachineApplicable,
1091 if sp.contains(expr.span)
1092 && sm.is_span_accessible(expr.span)
1095 sp.with_hi(expr.span.lo()),
1096 "consider removing the borrow".to_string(),
1098 Applicability::MachineApplicable,
1106 &ty::RawPtr(TypeAndMut { ty: ty_b, mutbl: mutbl_b }),
1107 &ty::Ref(_, ty_a, mutbl_a),
1109 if let Some(steps) = self.deref_steps(ty_a, ty_b)
1110 // Only suggest valid if dereferencing needed.
1112 // The pointer type implements `Copy` trait so the suggestion is always valid.
1113 && let Ok(src) = sm.span_to_snippet(sp)
1115 let derefs = "*".repeat(steps);
1116 let old_prefix = mutbl_a.ref_prefix_str();
1117 let new_prefix = mutbl_b.ref_prefix_str().to_owned() + &derefs;
1119 let suggestion = replace_prefix(&src, old_prefix, &new_prefix).map(|_| {
1120 // skip `&` or `&mut ` if both mutabilities are mutable
1121 let lo = sp.lo() + BytePos(min(old_prefix.len(), mutbl_b.ref_prefix_str().len()) as _);
1122 // skip `&` or `&mut `
1123 let hi = sp.lo() + BytePos(old_prefix.len() as _);
1124 let sp = sp.with_lo(lo).with_hi(hi);
1128 format!("{}{derefs}", if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" }),
1129 if mutbl_b <= mutbl_a { Applicability::MachineApplicable } else { Applicability::MaybeIncorrect }
1133 if let Some((span, src, applicability)) = suggestion {
1136 "consider dereferencing".to_string(),
1145 _ if sp == expr.span => {
1146 if let Some(mut steps) = self.deref_steps(checked_ty, expected) {
1147 let mut expr = expr.peel_blocks();
1148 let mut prefix_span = expr.span.shrink_to_lo();
1149 let mut remove = String::new();
1151 // Try peeling off any existing `&` and `&mut` to reach our target type
1153 if let hir::ExprKind::AddrOf(_, mutbl, inner) = expr.kind {
1154 // If the expression has `&`, removing it would fix the error
1155 prefix_span = prefix_span.with_hi(inner.span.lo());
1157 remove.push_str(mutbl.ref_prefix_str());
1163 // If we've reached our target type with just removing `&`, then just print now.
1167 format!("consider removing the `{}`", remove.trim()),
1169 // Do not remove `&&` to get to bool, because it might be something like
1170 // { a } && b, which we have a separate fixup suggestion that is more
1171 // likely correct...
1172 if remove.trim() == "&&" && expected == self.tcx.types.bool {
1173 Applicability::MaybeIncorrect
1175 Applicability::MachineApplicable
1182 // For this suggestion to make sense, the type would need to be `Copy`,
1183 // or we have to be moving out of a `Box<T>`
1184 if self.type_is_copy_modulo_regions(self.param_env, expected, sp)
1185 // FIXME(compiler-errors): We can actually do this if the checked_ty is
1186 // `steps` layers of boxes, not just one, but this is easier and most likely.
1187 || (checked_ty.is_box() && steps == 1)
1189 let deref_kind = if checked_ty.is_box() {
1190 "unboxing the value"
1191 } else if checked_ty.is_region_ptr() {
1192 "dereferencing the borrow"
1194 "dereferencing the type"
1197 // Suggest removing `&` if we have removed any, otherwise suggest just
1198 // dereferencing the remaining number of steps.
1199 let message = if remove.is_empty() {
1200 format!("consider {deref_kind}")
1203 "consider removing the `{}` and {} instead",
1209 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
1210 Some(ident) => format!("{ident}: "),
1211 None => String::new(),
1214 let (span, suggestion) = if self.is_else_if_block(expr) {
1215 // Don't suggest nonsense like `else *if`
1217 } else if let Some(expr) = self.maybe_get_block_expr(expr) {
1218 // prefix should be empty here..
1219 (expr.span.shrink_to_lo(), "*".to_string())
1221 (prefix_span, format!("{}{}", prefix, "*".repeat(steps)))
1228 Applicability::MachineApplicable,
1240 pub fn check_for_cast(
1242 err: &mut Diagnostic,
1243 expr: &hir::Expr<'_>,
1244 checked_ty: Ty<'tcx>,
1245 expected_ty: Ty<'tcx>,
1246 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
1248 if self.tcx.sess.source_map().is_imported(expr.span) {
1249 // Ignore if span is from within a macro.
1253 let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) else {
1257 // If casting this expression to a given numeric type would be appropriate in case of a type
1260 // We want to minimize the amount of casting operations that are suggested, as it can be a
1261 // lossy operation with potentially bad side effects, so we only suggest when encountering
1262 // an expression that indicates that the original type couldn't be directly changed.
1264 // For now, don't suggest casting with `as`.
1265 let can_cast = false;
1267 let mut sugg = vec![];
1269 if let Some(hir::Node::ExprField(field)) = self.tcx.hir().find_parent(expr.hir_id) {
1270 // `expr` is a literal field for a struct, only suggest if appropriate
1271 if field.is_shorthand {
1272 // This is a field literal
1273 sugg.push((field.ident.span.shrink_to_lo(), format!("{}: ", field.ident)));
1275 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
1280 if let hir::ExprKind::Call(path, args) = &expr.kind
1281 && let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
1282 (&path.kind, args.len())
1283 // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
1284 && let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
1285 (&base_ty.kind, path_segment.ident.name)
1287 if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
1301 if base_ty_path.segments.len() == 1 =>
1311 "you can convert {} `{}` to {} `{}`",
1312 checked_ty.kind().article(),
1314 expected_ty.kind().article(),
1317 let cast_msg = format!(
1318 "you can cast {} `{}` to {} `{}`",
1319 checked_ty.kind().article(),
1321 expected_ty.kind().article(),
1324 let lit_msg = format!(
1325 "change the type of the numeric literal from `{checked_ty}` to `{expected_ty}`",
1328 let close_paren = if expr.precedence().order() < PREC_POSTFIX {
1329 sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1335 let mut cast_suggestion = sugg.clone();
1336 cast_suggestion.push((expr.span.shrink_to_hi(), format!("{close_paren} as {expected_ty}")));
1337 let mut into_suggestion = sugg.clone();
1338 into_suggestion.push((expr.span.shrink_to_hi(), format!("{close_paren}.into()")));
1339 let mut suffix_suggestion = sugg.clone();
1340 suffix_suggestion.push((
1342 (&expected_ty.kind(), &checked_ty.kind()),
1343 (ty::Int(_) | ty::Uint(_), ty::Float(_))
1345 // Remove fractional part from literal, for example `42.0f32` into `42`
1346 let src = src.trim_end_matches(&checked_ty.to_string());
1347 let len = src.split('.').next().unwrap().len();
1348 expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
1350 let len = src.trim_end_matches(&checked_ty.to_string()).len();
1351 expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
1353 if expr.precedence().order() < PREC_POSTFIX {
1355 format!("{expected_ty})")
1357 expected_ty.to_string()
1360 let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
1361 if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
1363 let is_negative_int =
1364 |expr: &hir::Expr<'_>| matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::Neg, ..));
1365 let is_uint = |ty: Ty<'_>| matches!(ty.kind(), ty::Uint(..));
1367 let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id);
1369 let suggest_fallible_into_or_lhs_from =
1370 |err: &mut Diagnostic, exp_to_found_is_fallible: bool| {
1371 // If we know the expression the expected type is derived from, we might be able
1372 // to suggest a widening conversion rather than a narrowing one (which may
1373 // panic). For example, given x: u8 and y: u32, if we know the span of "x",
1375 // can be given the suggestion "u32::from(x) > y" rather than
1376 // "x > y.try_into().unwrap()".
1377 let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
1381 .span_to_snippet(expr.span)
1383 .map(|src| (expr, src))
1385 let (msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
1386 (lhs_expr_and_src, exp_to_found_is_fallible)
1389 "you can convert `{lhs_src}` from `{expected_ty}` to `{checked_ty}`, matching the type of `{src}`",
1391 let suggestion = vec![
1392 (lhs_expr.span.shrink_to_lo(), format!("{checked_ty}::from(")),
1393 (lhs_expr.span.shrink_to_hi(), ")".to_string()),
1397 let msg = format!("{msg} and panic if the converted value doesn't fit");
1398 let mut suggestion = sugg.clone();
1400 expr.span.shrink_to_hi(),
1401 format!("{close_paren}.try_into().unwrap()"),
1405 err.multipart_suggestion_verbose(
1408 Applicability::MachineApplicable,
1412 let suggest_to_change_suffix_or_into =
1413 |err: &mut Diagnostic,
1414 found_to_exp_is_fallible: bool,
1415 exp_to_found_is_fallible: bool| {
1417 expected_ty_expr.map(|e| self.tcx.hir().is_lhs(e.hir_id)).unwrap_or(false);
1423 let always_fallible = found_to_exp_is_fallible
1424 && (exp_to_found_is_fallible || expected_ty_expr.is_none());
1425 let msg = if literal_is_ty_suffixed(expr) {
1427 } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
1428 // We now know that converting either the lhs or rhs is fallible. Before we
1429 // suggest a fallible conversion, check if the value can never fit in the
1431 let msg = format!("`{src}` cannot fit into type `{expected_ty}`");
1434 } else if in_const_context {
1435 // Do not recommend `into` or `try_into` in const contexts.
1437 } else if found_to_exp_is_fallible {
1438 return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
1442 let suggestion = if literal_is_ty_suffixed(expr) {
1443 suffix_suggestion.clone()
1445 into_suggestion.clone()
1447 err.multipart_suggestion_verbose(msg, suggestion, Applicability::MachineApplicable);
1450 match (&expected_ty.kind(), &checked_ty.kind()) {
1451 (ty::Int(exp), ty::Int(found)) => {
1452 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1454 (Some(exp), Some(found)) if exp < found => (true, false),
1455 (Some(exp), Some(found)) if exp > found => (false, true),
1456 (None, Some(8 | 16)) => (false, true),
1457 (Some(8 | 16), None) => (true, false),
1458 (None, _) | (_, None) => (true, true),
1459 _ => (false, false),
1461 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1464 (ty::Uint(exp), ty::Uint(found)) => {
1465 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1467 (Some(exp), Some(found)) if exp < found => (true, false),
1468 (Some(exp), Some(found)) if exp > found => (false, true),
1469 (None, Some(8 | 16)) => (false, true),
1470 (Some(8 | 16), None) => (true, false),
1471 (None, _) | (_, None) => (true, true),
1472 _ => (false, false),
1474 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1477 (&ty::Int(exp), &ty::Uint(found)) => {
1478 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1480 (Some(exp), Some(found)) if found < exp => (false, true),
1481 (None, Some(8)) => (false, true),
1484 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1487 (&ty::Uint(exp), &ty::Int(found)) => {
1488 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1490 (Some(exp), Some(found)) if found > exp => (true, false),
1491 (Some(8), None) => (true, false),
1494 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1497 (ty::Float(exp), ty::Float(found)) => {
1498 if found.bit_width() < exp.bit_width() {
1499 suggest_to_change_suffix_or_into(err, false, true);
1500 } else if literal_is_ty_suffixed(expr) {
1501 err.multipart_suggestion_verbose(
1504 Applicability::MachineApplicable,
1506 } else if can_cast {
1507 // Missing try_into implementation for `f64` to `f32`
1508 err.multipart_suggestion_verbose(
1509 &format!("{cast_msg}, producing the closest possible value"),
1511 Applicability::MaybeIncorrect, // lossy conversion
1516 (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
1517 if literal_is_ty_suffixed(expr) {
1518 err.multipart_suggestion_verbose(
1521 Applicability::MachineApplicable,
1523 } else if can_cast {
1524 // Missing try_into implementation for `{float}` to `{integer}`
1525 err.multipart_suggestion_verbose(
1526 &format!("{msg}, rounding the float towards zero"),
1528 Applicability::MaybeIncorrect, // lossy conversion
1533 (ty::Float(exp), ty::Uint(found)) => {
1534 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
1535 if exp.bit_width() > found.bit_width().unwrap_or(256) {
1536 err.multipart_suggestion_verbose(
1538 "{msg}, producing the floating point representation of the integer",
1541 Applicability::MachineApplicable,
1543 } else if literal_is_ty_suffixed(expr) {
1544 err.multipart_suggestion_verbose(
1547 Applicability::MachineApplicable,
1550 // Missing try_into implementation for `{integer}` to `{float}`
1551 err.multipart_suggestion_verbose(
1553 "{cast_msg}, producing the floating point representation of the integer, \
1554 rounded if necessary",
1557 Applicability::MaybeIncorrect, // lossy conversion
1562 (ty::Float(exp), ty::Int(found)) => {
1563 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
1564 if exp.bit_width() > found.bit_width().unwrap_or(256) {
1565 err.multipart_suggestion_verbose(
1567 "{}, producing the floating point representation of the integer",
1571 Applicability::MachineApplicable,
1573 } else if literal_is_ty_suffixed(expr) {
1574 err.multipart_suggestion_verbose(
1577 Applicability::MachineApplicable,
1580 // Missing try_into implementation for `{integer}` to `{float}`
1581 err.multipart_suggestion_verbose(
1583 "{}, producing the floating point representation of the integer, \
1584 rounded if necessary",
1588 Applicability::MaybeIncorrect, // lossy conversion
1594 &ty::Uint(ty::UintTy::U32 | ty::UintTy::U64 | ty::UintTy::U128)
1595 | &ty::Int(ty::IntTy::I32 | ty::IntTy::I64 | ty::IntTy::I128),
1598 err.multipart_suggestion_verbose(
1599 &format!("{cast_msg}, since a `char` always occupies 4 bytes"),
1601 Applicability::MachineApplicable,
1609 /// Identify when the user has written `foo..bar()` instead of `foo.bar()`.
1610 pub fn check_for_range_as_method_call(
1612 err: &mut Diagnostic,
1613 expr: &hir::Expr<'_>,
1614 checked_ty: Ty<'tcx>,
1615 expected_ty: Ty<'tcx>,
1617 if !hir::is_range_literal(expr) {
1620 let hir::ExprKind::Struct(
1621 hir::QPath::LangItem(LangItem::Range, ..),
1624 ) = expr.kind else { return; };
1625 let parent = self.tcx.hir().parent_id(expr.hir_id);
1626 if let Some(hir::Node::ExprField(_)) = self.tcx.hir().find(parent) {
1627 // Ignore `Foo { field: a..Default::default() }`
1630 let mut expr = end.expr;
1631 while let hir::ExprKind::MethodCall(_, rcvr, ..) = expr.kind {
1632 // Getting to the root receiver and asserting it is a fn call let's us ignore cases in
1633 // `src/test/ui/methods/issues/issue-90315.stderr`.
1636 let hir::ExprKind::Call(method_name, _) = expr.kind else { return; };
1637 let ty::Adt(adt, _) = checked_ty.kind() else { return; };
1638 if self.tcx.lang_items().range_struct() != Some(adt.did()) {
1641 if let ty::Adt(adt, _) = expected_ty.kind()
1642 && self.tcx.lang_items().range_struct() == Some(adt.did())
1646 // Check if start has method named end.
1647 let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = method_name.kind else { return; };
1648 let [hir::PathSegment { ident, .. }] = p.segments else { return; };
1649 let self_ty = self.typeck_results.borrow().expr_ty(start.expr);
1650 let Ok(_pick) = self.probe_for_name(
1651 probe::Mode::MethodCall,
1653 probe::IsSuggestion(true),
1656 probe::ProbeScope::AllTraits,
1659 let mut span = start.expr.span.between(end.expr.span);
1660 if span.lo() + BytePos(2) == span.hi() {
1661 // There's no space between the start, the range op and the end, suggest removal which
1662 // will be more noticeable than the replacement of `..` with `.`.
1663 span = span.with_lo(span.lo() + BytePos(1));
1666 err.span_suggestion_verbose(
1668 "you likely meant to write a method call instead of a range",
1670 Applicability::MachineApplicable,