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().get_parent_node(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 let parent = self.tcx.hir().get_parent_node(pat.hir_id);
262 primary_span = pat.span;
263 secondary_span = pat.span;
264 match self.tcx.hir().find(parent) {
265 Some(hir::Node::Local(hir::Local { ty: Some(ty), .. })) => {
266 primary_span = ty.span;
267 post_message = " type";
269 Some(hir::Node::Local(hir::Local { init: Some(init), .. })) => {
270 primary_span = init.span;
271 post_message = " value";
273 Some(hir::Node::Param(hir::Param { ty_span, .. })) => {
274 primary_span = *ty_span;
275 post_message = " parameter type";
284 if primary_span != secondary_span
289 .is_multiline(secondary_span.shrink_to_hi().until(primary_span))
291 // We are pointing at the binding's type or initializer value, but it's pattern
292 // is in a different line, so we point at both.
293 err.span_label(secondary_span, "expected due to the type of this binding");
294 err.span_label(primary_span, &format!("expected due to this{post_message}"));
295 } else if post_message == "" {
296 // We are pointing at either the assignment lhs or the binding def pattern.
297 err.span_label(primary_span, "expected due to the type of this binding");
299 // We are pointing at the binding's type or initializer value.
300 err.span_label(primary_span, &format!("expected due to this{post_message}"));
303 if !lhs.is_syntactic_place_expr() {
304 // We already emitted E0070 "invalid left-hand side of assignment", so we
306 err.downgrade_to_delayed_bug();
310 Some(hir::Node::Expr(hir::Expr {
311 kind: hir::ExprKind::Binary(_, lhs, rhs), ..
313 Some(TypeError::Sorts(ExpectedFound { expected, .. })),
314 ) if rhs.hir_id == expr.hir_id
315 && self.typeck_results.borrow().expr_ty_adjusted_opt(lhs) == Some(expected) =>
317 err.span_label(lhs.span, &format!("expected because this is `{expected}`"));
323 fn annotate_alternative_method_deref(
325 err: &mut Diagnostic,
326 expr: &hir::Expr<'_>,
327 error: Option<TypeError<'tcx>>,
329 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
330 let Some(TypeError::Sorts(ExpectedFound { expected, .. })) = error else {return;};
331 let Some(hir::Node::Expr(hir::Expr {
332 kind: hir::ExprKind::Assign(lhs, rhs, _), ..
333 })) = self.tcx.hir().find(parent) else {return; };
334 if rhs.hir_id != expr.hir_id || expected.is_closure() {
337 let hir::ExprKind::Unary(hir::UnOp::Deref, deref) = lhs.kind else { return; };
338 let hir::ExprKind::MethodCall(path, base, args, _) = deref.kind else { return; };
339 let Some(self_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(base) else { return; };
343 probe::Mode::MethodCall,
345 probe::IsSuggestion(true),
348 probe::ProbeScope::TraitsInScope,
352 let in_scope_methods = self.probe_for_name_many(
353 probe::Mode::MethodCall,
355 probe::IsSuggestion(true),
358 probe::ProbeScope::TraitsInScope,
360 let other_methods_in_scope: Vec<_> =
361 in_scope_methods.iter().filter(|c| c.item.def_id != pick.item.def_id).collect();
363 let all_methods = self.probe_for_name_many(
364 probe::Mode::MethodCall,
366 probe::IsSuggestion(true),
369 probe::ProbeScope::AllTraits,
371 let suggestions: Vec<_> = all_methods
373 .filter(|c| c.item.def_id != pick.item.def_id)
376 let substs = ty::InternalSubsts::for_item(self.tcx, m.def_id, |param, _| {
377 self.var_for_def(deref.span, param)
381 deref.span.until(base.span),
384 with_no_trimmed_paths!(
385 self.tcx.def_path_str_with_substs(m.def_id, substs,)
387 match self.tcx.fn_sig(m.def_id).input(0).skip_binder().kind() {
388 ty::Ref(_, _, hir::Mutability::Mut) => "&mut ",
389 ty::Ref(_, _, _) => "&",
395 [] => (base.span.shrink_to_hi().with_hi(deref.span.hi()), ")".to_string()),
396 [first, ..] => (base.span.between(first.span), ", ".to_string()),
401 if suggestions.is_empty() {
404 let mut path_span: MultiSpan = path.ident.span.into();
405 path_span.push_span_label(
407 with_no_trimmed_paths!(format!(
409 self.tcx.def_path_str(pick.item.def_id),
412 let container_id = pick.item.container_id(self.tcx);
413 let container = with_no_trimmed_paths!(self.tcx.def_path_str(container_id));
414 for def_id in pick.import_ids {
415 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
416 path_span.push_span_label(
417 self.tcx.hir().span(hir_id),
418 format!("`{container}` imported here"),
421 let tail = with_no_trimmed_paths!(match &other_methods_in_scope[..] {
423 [candidate] => format!(
424 "the method of the same name on {} `{}`",
425 match candidate.kind {
426 probe::CandidateKind::InherentImplCandidate(..) => "the inherent impl for",
429 self.tcx.def_path_str(candidate.item.container_id(self.tcx))
431 [.., last] if other_methods_in_scope.len() < 5 => {
433 "the methods of the same name on {} and `{}`",
434 other_methods_in_scope[..other_methods_in_scope.len() - 1]
438 self.tcx.def_path_str(c.item.container_id(self.tcx))
440 .collect::<Vec<String>>()
442 self.tcx.def_path_str(last.item.container_id(self.tcx))
446 "the methods of the same name on {} other traits",
447 other_methods_in_scope.len()
453 "the `{}` call is resolved to the method in `{container}`, shadowing {tail}",
457 if suggestions.len() > other_methods_in_scope.len() {
459 "additionally, there are {} other available methods that aren't in scope",
460 suggestions.len() - other_methods_in_scope.len()
463 err.multipart_suggestions(
465 "you might have meant to call {}; you can use the fully-qualified path to call {} \
467 if suggestions.len() == 1 {
470 "one of the other methods"
472 if suggestions.len() == 1 { "it" } else { "one of them" },
475 Applicability::MaybeIncorrect,
479 /// If the expected type is an enum (Issue #55250) with any variants whose
480 /// sole field is of the found type, suggest such variants. (Issue #42764)
481 fn suggest_compatible_variants(
483 err: &mut Diagnostic,
484 expr: &hir::Expr<'_>,
488 if let ty::Adt(expected_adt, substs) = expected.kind() {
489 if let hir::ExprKind::Field(base, ident) = expr.kind {
490 let base_ty = self.typeck_results.borrow().expr_ty(base);
491 if self.can_eq(self.param_env, base_ty, expected).is_ok()
492 && let Some(base_span) = base.span.find_ancestor_inside(expr.span)
494 err.span_suggestion_verbose(
495 expr.span.with_lo(base_span.hi()),
496 format!("consider removing the tuple struct field `{ident}`"),
498 Applicability::MaybeIncorrect,
504 // If the expression is of type () and it's the return expression of a block,
505 // we suggest adding a separate return expression instead.
506 // (To avoid things like suggesting `Ok(while .. { .. })`.)
507 if expr_ty.is_unit() {
508 let mut id = expr.hir_id;
511 // Unroll desugaring, to make sure this works for `for` loops etc.
513 parent = self.tcx.hir().get_parent_node(id);
514 if let Some(parent_span) = self.tcx.hir().opt_span(parent) {
515 if parent_span.find_ancestor_inside(expr.span).is_some() {
516 // The parent node is part of the same span, so is the result of the
517 // same expansion/desugaring and not the 'real' parent node.
525 if let Some(hir::Node::Block(&hir::Block {
526 span: block_span, expr: Some(e), ..
527 })) = self.tcx.hir().find(parent)
530 if let Some(span) = expr.span.find_ancestor_inside(block_span) {
531 let return_suggestions = if self
533 .is_diagnostic_item(sym::Result, expected_adt.did())
536 } else if self.tcx.is_diagnostic_item(sym::Option, expected_adt.did()) {
537 vec!["None", "Some(())"]
541 if let Some(indent) =
542 self.tcx.sess.source_map().indentation_before(span.shrink_to_lo())
544 // Add a semicolon, except after `}`.
546 match self.tcx.sess.source_map().span_to_snippet(span) {
547 Ok(s) if s.ends_with('}') => "",
550 err.span_suggestions(
552 "try adding an expression at the end of the block",
555 .map(|r| format!("{semicolon}\n{indent}{r}")),
556 Applicability::MaybeIncorrect,
565 let compatible_variants: Vec<(String, _, _, Option<String>)> = expected_adt
569 variant.fields.len() == 1
571 .filter_map(|variant| {
572 let sole_field = &variant.fields[0];
574 let field_is_local = sole_field.did.is_local();
575 let field_is_accessible =
576 sole_field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
577 // Skip suggestions for unstable public fields (for example `Pin::pointer`)
578 && matches!(self.tcx.eval_stability(sole_field.did, None, expr.span, None), EvalResult::Allow | EvalResult::Unmarked);
580 if !field_is_local && !field_is_accessible {
584 let note_about_variant_field_privacy = (field_is_local && !field_is_accessible)
585 .then(|| " (its field is private, but it's local to this crate and its privacy can be changed)".to_string());
587 let sole_field_ty = sole_field.ty(self.tcx, substs);
588 if self.can_coerce(expr_ty, sole_field_ty) {
590 with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
591 // FIXME #56861: DRYer prelude filtering
592 if let Some(path) = variant_path.strip_prefix("std::prelude::")
593 && let Some((_, path)) = path.split_once("::")
595 return Some((path.to_string(), variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy));
597 Some((variant_path, variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy))
604 let suggestions_for = |variant: &_, ctor_kind, field_name| {
605 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
606 Some(ident) => format!("{ident}: "),
607 None => String::new(),
610 let (open, close) = match ctor_kind {
611 Some(CtorKind::Fn) => ("(".to_owned(), ")"),
612 None => (format!(" {{ {field_name}: "), " }"),
614 // unit variants don't have fields
615 Some(CtorKind::Const) => unreachable!(),
618 // Suggest constructor as deep into the block tree as possible.
619 // This fixes https://github.com/rust-lang/rust/issues/101065,
620 // and also just helps make the most minimal suggestions.
622 while let hir::ExprKind::Block(block, _) = &expr.kind
623 && let Some(expr_) = &block.expr
629 (expr.span.shrink_to_lo(), format!("{prefix}{variant}{open}")),
630 (expr.span.shrink_to_hi(), close.to_owned()),
634 match &compatible_variants[..] {
635 [] => { /* No variants to format */ }
636 [(variant, ctor_kind, field_name, note)] => {
637 // Just a single matching variant.
638 err.multipart_suggestion_verbose(
640 "try wrapping the expression in `{variant}`{note}",
641 note = note.as_deref().unwrap_or("")
643 suggestions_for(&**variant, *ctor_kind, *field_name),
644 Applicability::MaybeIncorrect,
649 // More than one matching variant.
650 err.multipart_suggestions(
652 "try wrapping the expression in a variant of `{}`",
653 self.tcx.def_path_str(expected_adt.did())
655 compatible_variants.into_iter().map(
656 |(variant, ctor_kind, field_name, _)| {
657 suggestions_for(&variant, ctor_kind, field_name)
660 Applicability::MaybeIncorrect,
670 fn suggest_non_zero_new_unwrap(
672 err: &mut Diagnostic,
673 expr: &hir::Expr<'_>,
678 let (adt, unwrap) = match expected.kind() {
679 // In case Option<NonZero*> is wanted, but * is provided, suggest calling new
680 ty::Adt(adt, substs) if tcx.is_diagnostic_item(sym::Option, adt.did()) => {
682 let ty::Adt(adt, _) = substs.type_at(0).kind() else { return false; };
686 // In case NonZero* is wanted, but * is provided also add `.unwrap()` to satisfy types
687 ty::Adt(adt, _) => (adt, ".unwrap()"),
692 (sym::NonZeroU8, tcx.types.u8),
693 (sym::NonZeroU16, tcx.types.u16),
694 (sym::NonZeroU32, tcx.types.u32),
695 (sym::NonZeroU64, tcx.types.u64),
696 (sym::NonZeroU128, tcx.types.u128),
697 (sym::NonZeroI8, tcx.types.i8),
698 (sym::NonZeroI16, tcx.types.i16),
699 (sym::NonZeroI32, tcx.types.i32),
700 (sym::NonZeroI64, tcx.types.i64),
701 (sym::NonZeroI128, tcx.types.i128),
704 let Some((s, _)) = map
706 .find(|&&(s, t)| self.tcx.is_diagnostic_item(s, adt.did()) && self.can_coerce(expr_ty, t))
707 else { return false; };
709 let path = self.tcx.def_path_str(adt.non_enum_variant().def_id);
711 err.multipart_suggestion(
712 format!("consider calling `{s}::new`"),
714 (expr.span.shrink_to_lo(), format!("{path}::new(")),
715 (expr.span.shrink_to_hi(), format!("){unwrap}")),
717 Applicability::MaybeIncorrect,
723 pub fn get_conversion_methods(
727 checked_ty: Ty<'tcx>,
729 ) -> Vec<AssocItem> {
730 let methods = self.probe_for_return_type(
732 probe::Mode::MethodCall,
737 self.has_only_self_parameter(m)
740 // This special internal attribute is used to permit
741 // "identity-like" conversion methods to be suggested here.
743 // FIXME (#46459 and #46460): ideally
744 // `std::convert::Into::into` and `std::borrow:ToOwned` would
745 // also be `#[rustc_conversion_suggestion]`, if not for
746 // method-probing false-positives and -negatives (respectively).
748 // FIXME? Other potential candidate methods: `as_ref` and
750 .has_attr(m.def_id, sym::rustc_conversion_suggestion)
757 /// This function checks whether the method is not static and does not accept other parameters than `self`.
758 fn has_only_self_parameter(&self, method: &AssocItem) -> bool {
760 ty::AssocKind::Fn => {
761 method.fn_has_self_parameter
762 && self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1
768 /// Identify some cases where `as_ref()` would be appropriate and suggest it.
770 /// Given the following code:
771 /// ```compile_fail,E0308
773 /// fn takes_ref(_: &Foo) {}
774 /// let ref opt = Some(Foo);
776 /// opt.map(|param| takes_ref(param));
778 /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
780 /// It only checks for `Option` and `Result` and won't work with
781 /// ```ignore (illustrative)
782 /// opt.map(|param| { takes_ref(param) });
784 fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Span, &'static str, String)> {
785 let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.kind else {
789 let hir::def::Res::Local(local_id) = path.res else {
793 let local_parent = self.tcx.hir().get_parent_node(local_id);
794 let Some(Node::Param(hir::Param { hir_id: param_hir_id, .. })) = self.tcx.hir().find(local_parent) else {
798 let param_parent = self.tcx.hir().get_parent_node(*param_hir_id);
799 let Some(Node::Expr(hir::Expr {
801 kind: hir::ExprKind::Closure(hir::Closure { fn_decl: closure_fn_decl, .. }),
803 })) = self.tcx.hir().find(param_parent) else {
807 let expr_parent = self.tcx.hir().get_parent_node(*expr_hir_id);
808 let hir = self.tcx.hir().find(expr_parent);
809 let closure_params_len = closure_fn_decl.inputs.len();
811 Some(Node::Expr(hir::Expr {
812 kind: hir::ExprKind::MethodCall(method_path, receiver, ..),
816 ) = (hir, closure_params_len) else {
820 let self_ty = self.typeck_results.borrow().expr_ty(receiver);
821 let name = method_path.ident.name;
822 let is_as_ref_able = match self_ty.peel_refs().kind() {
824 (self.tcx.is_diagnostic_item(sym::Option, def.did())
825 || self.tcx.is_diagnostic_item(sym::Result, def.did()))
826 && (name == sym::map || name == sym::and_then)
830 match (is_as_ref_able, self.sess().source_map().span_to_snippet(method_path.ident.span)) {
832 let suggestion = format!("as_ref().{}", src);
833 Some((method_path.ident.span, "consider using `as_ref` instead", suggestion))
839 pub(crate) fn maybe_get_struct_pattern_shorthand_field(
841 expr: &hir::Expr<'_>,
842 ) -> Option<Symbol> {
843 let hir = self.tcx.hir();
844 let local = match expr {
847 hir::ExprKind::Path(hir::QPath::Resolved(
850 res: hir::def::Res::Local(_),
851 segments: [hir::PathSegment { ident, .. }],
860 match hir.find(hir.get_parent_node(expr.hir_id))? {
861 Node::ExprField(field) => {
862 if field.ident.name == local.name && field.is_shorthand {
863 return Some(local.name);
872 /// If the given `HirId` corresponds to a block with a trailing expression, return that expression
873 pub(crate) fn maybe_get_block_expr(
875 expr: &hir::Expr<'tcx>,
876 ) -> Option<&'tcx hir::Expr<'tcx>> {
878 hir::Expr { kind: hir::ExprKind::Block(block, ..), .. } => block.expr,
883 /// Returns whether the given expression is an `else if`.
884 pub(crate) fn is_else_if_block(&self, expr: &hir::Expr<'_>) -> bool {
885 if let hir::ExprKind::If(..) = expr.kind {
886 let parent_id = self.tcx.hir().get_parent_node(expr.hir_id);
887 if let Some(Node::Expr(hir::Expr {
888 kind: hir::ExprKind::If(_, _, Some(else_expr)),
890 })) = self.tcx.hir().find(parent_id)
892 return else_expr.hir_id == expr.hir_id;
898 /// This function is used to determine potential "simple" improvements or users' errors and
899 /// provide them useful help. For example:
901 /// ```compile_fail,E0308
902 /// fn some_fn(s: &str) {}
904 /// let x = "hey!".to_owned();
905 /// some_fn(x); // error
908 /// No need to find every potential function which could make a coercion to transform a
909 /// `String` into a `&str` since a `&` would do the trick!
911 /// In addition of this check, it also checks between references mutability state. If the
912 /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
916 expr: &hir::Expr<'tcx>,
917 checked_ty: Ty<'tcx>,
925 bool, /* suggest `&` or `&mut` type annotation */
927 let sess = self.sess();
930 // If the span is from an external macro, there's no suggestion we can make.
931 if in_external_macro(sess, sp) {
935 let sm = sess.source_map();
937 let replace_prefix = |s: &str, old: &str, new: &str| {
938 s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
941 // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
942 let expr = expr.peel_drop_temps();
944 match (&expr.kind, expected.kind(), checked_ty.kind()) {
945 (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (exp.kind(), check.kind()) {
946 (&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
947 if let hir::ExprKind::Lit(_) = expr.kind
948 && let Ok(src) = sm.span_to_snippet(sp)
949 && replace_prefix(&src, "b\"", "\"").is_some()
951 let pos = sp.lo() + BytePos(1);
954 "consider removing the leading `b`".to_string(),
956 Applicability::MachineApplicable,
962 (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
963 if let hir::ExprKind::Lit(_) = expr.kind
964 && let Ok(src) = sm.span_to_snippet(sp)
965 && replace_prefix(&src, "\"", "b\"").is_some()
969 "consider adding a leading `b`".to_string(),
971 Applicability::MachineApplicable,
979 (_, &ty::Ref(_, _, mutability), _) => {
980 // Check if it can work when put into a ref. For example:
983 // fn bar(x: &mut i32) {}
986 // bar(&x); // error, expected &mut
988 let ref_ty = match mutability {
989 hir::Mutability::Mut => {
990 self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
992 hir::Mutability::Not => {
993 self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
996 if self.can_coerce(ref_ty, expected) {
997 let mut sugg_sp = sp;
998 if let hir::ExprKind::MethodCall(ref segment, receiver, args, _) = expr.kind {
1000 self.tcx.require_lang_item(LangItem::Clone, Some(segment.ident.span));
1002 && self.typeck_results.borrow().type_dependent_def_id(expr.hir_id).map(
1004 let ai = self.tcx.associated_item(did);
1005 ai.trait_container(self.tcx) == Some(clone_trait)
1008 && segment.ident.name == sym::clone
1010 // If this expression had a clone call when suggesting borrowing
1011 // we want to suggest removing it because it'd now be unnecessary.
1012 sugg_sp = receiver.span;
1015 if let Ok(src) = sm.span_to_snippet(sugg_sp) {
1016 let needs_parens = match expr.kind {
1017 // parenthesize if needed (Issue #46756)
1018 hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true,
1019 // parenthesize borrows of range literals (Issue #54505)
1020 _ if is_range_literal(expr) => true,
1024 if let Some(sugg) = self.can_use_as_ref(expr) {
1029 Applicability::MachineApplicable,
1035 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
1036 Some(ident) => format!("{ident}: "),
1037 None => String::new(),
1040 if let Some(hir::Node::Expr(hir::Expr {
1041 kind: hir::ExprKind::Assign(..),
1043 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
1045 if mutability.is_mut() {
1046 // Suppressing this diagnostic, we'll properly print it in `check_expr_assign`
1051 let sugg_expr = if needs_parens { format!("({src})") } else { src };
1054 format!("consider {}borrowing here", mutability.mutably_str()),
1055 format!("{prefix}{}{sugg_expr}", mutability.ref_prefix_str()),
1056 Applicability::MachineApplicable,
1064 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
1066 &ty::Ref(_, checked, _),
1067 ) if self.can_sub(self.param_env, checked, expected).is_ok() => {
1068 // We have `&T`, check if what was expected was `T`. If so,
1069 // we may want to suggest removing a `&`.
1070 if sm.is_imported(expr.span) {
1071 // Go through the spans from which this span was expanded,
1072 // and find the one that's pointing inside `sp`.
1074 // E.g. for `&format!("")`, where we want the span to the
1075 // `format!()` invocation instead of its expansion.
1076 if let Some(call_span) =
1077 iter::successors(Some(expr.span), |s| s.parent_callsite())
1078 .find(|&s| sp.contains(s))
1079 && sm.is_span_accessible(call_span)
1082 sp.with_hi(call_span.lo()),
1083 "consider removing the borrow".to_string(),
1085 Applicability::MachineApplicable,
1092 if sp.contains(expr.span)
1093 && sm.is_span_accessible(expr.span)
1096 sp.with_hi(expr.span.lo()),
1097 "consider removing the borrow".to_string(),
1099 Applicability::MachineApplicable,
1107 &ty::RawPtr(TypeAndMut { ty: ty_b, mutbl: mutbl_b }),
1108 &ty::Ref(_, ty_a, mutbl_a),
1110 if let Some(steps) = self.deref_steps(ty_a, ty_b)
1111 // Only suggest valid if dereferencing needed.
1113 // The pointer type implements `Copy` trait so the suggestion is always valid.
1114 && let Ok(src) = sm.span_to_snippet(sp)
1116 let derefs = "*".repeat(steps);
1117 let old_prefix = mutbl_a.ref_prefix_str();
1118 let new_prefix = mutbl_b.ref_prefix_str().to_owned() + &derefs;
1120 let suggestion = replace_prefix(&src, old_prefix, &new_prefix).map(|_| {
1121 // skip `&` or `&mut ` if both mutabilities are mutable
1122 let lo = sp.lo() + BytePos(min(old_prefix.len(), mutbl_b.ref_prefix_str().len()) as _);
1123 // skip `&` or `&mut `
1124 let hi = sp.lo() + BytePos(old_prefix.len() as _);
1125 let sp = sp.with_lo(lo).with_hi(hi);
1129 format!("{}{derefs}", if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" }),
1130 if mutbl_b <= mutbl_a { Applicability::MachineApplicable } else { Applicability::MaybeIncorrect }
1134 if let Some((span, src, applicability)) = suggestion {
1137 "consider dereferencing".to_string(),
1146 _ if sp == expr.span => {
1147 if let Some(mut steps) = self.deref_steps(checked_ty, expected) {
1148 let mut expr = expr.peel_blocks();
1149 let mut prefix_span = expr.span.shrink_to_lo();
1150 let mut remove = String::new();
1152 // Try peeling off any existing `&` and `&mut` to reach our target type
1154 if let hir::ExprKind::AddrOf(_, mutbl, inner) = expr.kind {
1155 // If the expression has `&`, removing it would fix the error
1156 prefix_span = prefix_span.with_hi(inner.span.lo());
1158 remove.push_str(mutbl.ref_prefix_str());
1164 // If we've reached our target type with just removing `&`, then just print now.
1168 format!("consider removing the `{}`", remove.trim()),
1170 // Do not remove `&&` to get to bool, because it might be something like
1171 // { a } && b, which we have a separate fixup suggestion that is more
1172 // likely correct...
1173 if remove.trim() == "&&" && expected == self.tcx.types.bool {
1174 Applicability::MaybeIncorrect
1176 Applicability::MachineApplicable
1183 // For this suggestion to make sense, the type would need to be `Copy`,
1184 // or we have to be moving out of a `Box<T>`
1185 if self.type_is_copy_modulo_regions(self.param_env, expected, sp)
1186 // FIXME(compiler-errors): We can actually do this if the checked_ty is
1187 // `steps` layers of boxes, not just one, but this is easier and most likely.
1188 || (checked_ty.is_box() && steps == 1)
1190 let deref_kind = if checked_ty.is_box() {
1191 "unboxing the value"
1192 } else if checked_ty.is_region_ptr() {
1193 "dereferencing the borrow"
1195 "dereferencing the type"
1198 // Suggest removing `&` if we have removed any, otherwise suggest just
1199 // dereferencing the remaining number of steps.
1200 let message = if remove.is_empty() {
1201 format!("consider {deref_kind}")
1204 "consider removing the `{}` and {} instead",
1210 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
1211 Some(ident) => format!("{ident}: "),
1212 None => String::new(),
1215 let (span, suggestion) = if self.is_else_if_block(expr) {
1216 // Don't suggest nonsense like `else *if`
1218 } else if let Some(expr) = self.maybe_get_block_expr(expr) {
1219 // prefix should be empty here..
1220 (expr.span.shrink_to_lo(), "*".to_string())
1222 (prefix_span, format!("{}{}", prefix, "*".repeat(steps)))
1229 Applicability::MachineApplicable,
1241 pub fn check_for_cast(
1243 err: &mut Diagnostic,
1244 expr: &hir::Expr<'_>,
1245 checked_ty: Ty<'tcx>,
1246 expected_ty: Ty<'tcx>,
1247 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
1249 if self.tcx.sess.source_map().is_imported(expr.span) {
1250 // Ignore if span is from within a macro.
1254 let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) else {
1258 // If casting this expression to a given numeric type would be appropriate in case of a type
1261 // We want to minimize the amount of casting operations that are suggested, as it can be a
1262 // lossy operation with potentially bad side effects, so we only suggest when encountering
1263 // an expression that indicates that the original type couldn't be directly changed.
1265 // For now, don't suggest casting with `as`.
1266 let can_cast = false;
1268 let mut sugg = vec![];
1270 if let Some(hir::Node::ExprField(field)) =
1271 self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
1273 // `expr` is a literal field for a struct, only suggest if appropriate
1274 if field.is_shorthand {
1275 // This is a field literal
1276 sugg.push((field.ident.span.shrink_to_lo(), format!("{}: ", field.ident)));
1278 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
1283 if let hir::ExprKind::Call(path, args) = &expr.kind
1284 && let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
1285 (&path.kind, args.len())
1286 // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
1287 && let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
1288 (&base_ty.kind, path_segment.ident.name)
1290 if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
1304 if base_ty_path.segments.len() == 1 =>
1314 "you can convert {} `{}` to {} `{}`",
1315 checked_ty.kind().article(),
1317 expected_ty.kind().article(),
1320 let cast_msg = format!(
1321 "you can cast {} `{}` to {} `{}`",
1322 checked_ty.kind().article(),
1324 expected_ty.kind().article(),
1327 let lit_msg = format!(
1328 "change the type of the numeric literal from `{checked_ty}` to `{expected_ty}`",
1331 let close_paren = if expr.precedence().order() < PREC_POSTFIX {
1332 sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1338 let mut cast_suggestion = sugg.clone();
1339 cast_suggestion.push((expr.span.shrink_to_hi(), format!("{close_paren} as {expected_ty}")));
1340 let mut into_suggestion = sugg.clone();
1341 into_suggestion.push((expr.span.shrink_to_hi(), format!("{close_paren}.into()")));
1342 let mut suffix_suggestion = sugg.clone();
1343 suffix_suggestion.push((
1345 (&expected_ty.kind(), &checked_ty.kind()),
1346 (ty::Int(_) | ty::Uint(_), ty::Float(_))
1348 // Remove fractional part from literal, for example `42.0f32` into `42`
1349 let src = src.trim_end_matches(&checked_ty.to_string());
1350 let len = src.split('.').next().unwrap().len();
1351 expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
1353 let len = src.trim_end_matches(&checked_ty.to_string()).len();
1354 expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
1356 if expr.precedence().order() < PREC_POSTFIX {
1358 format!("{expected_ty})")
1360 expected_ty.to_string()
1363 let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
1364 if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
1366 let is_negative_int =
1367 |expr: &hir::Expr<'_>| matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::Neg, ..));
1368 let is_uint = |ty: Ty<'_>| matches!(ty.kind(), ty::Uint(..));
1370 let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id);
1372 let suggest_fallible_into_or_lhs_from =
1373 |err: &mut Diagnostic, exp_to_found_is_fallible: bool| {
1374 // If we know the expression the expected type is derived from, we might be able
1375 // to suggest a widening conversion rather than a narrowing one (which may
1376 // panic). For example, given x: u8 and y: u32, if we know the span of "x",
1378 // can be given the suggestion "u32::from(x) > y" rather than
1379 // "x > y.try_into().unwrap()".
1380 let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
1384 .span_to_snippet(expr.span)
1386 .map(|src| (expr, src))
1388 let (msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
1389 (lhs_expr_and_src, exp_to_found_is_fallible)
1392 "you can convert `{lhs_src}` from `{expected_ty}` to `{checked_ty}`, matching the type of `{src}`",
1394 let suggestion = vec![
1395 (lhs_expr.span.shrink_to_lo(), format!("{checked_ty}::from(")),
1396 (lhs_expr.span.shrink_to_hi(), ")".to_string()),
1400 let msg = format!("{msg} and panic if the converted value doesn't fit");
1401 let mut suggestion = sugg.clone();
1403 expr.span.shrink_to_hi(),
1404 format!("{close_paren}.try_into().unwrap()"),
1408 err.multipart_suggestion_verbose(
1411 Applicability::MachineApplicable,
1415 let suggest_to_change_suffix_or_into =
1416 |err: &mut Diagnostic,
1417 found_to_exp_is_fallible: bool,
1418 exp_to_found_is_fallible: bool| {
1420 expected_ty_expr.map(|e| self.tcx.hir().is_lhs(e.hir_id)).unwrap_or(false);
1426 let always_fallible = found_to_exp_is_fallible
1427 && (exp_to_found_is_fallible || expected_ty_expr.is_none());
1428 let msg = if literal_is_ty_suffixed(expr) {
1430 } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
1431 // We now know that converting either the lhs or rhs is fallible. Before we
1432 // suggest a fallible conversion, check if the value can never fit in the
1434 let msg = format!("`{src}` cannot fit into type `{expected_ty}`");
1437 } else if in_const_context {
1438 // Do not recommend `into` or `try_into` in const contexts.
1440 } else if found_to_exp_is_fallible {
1441 return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
1445 let suggestion = if literal_is_ty_suffixed(expr) {
1446 suffix_suggestion.clone()
1448 into_suggestion.clone()
1450 err.multipart_suggestion_verbose(msg, suggestion, Applicability::MachineApplicable);
1453 match (&expected_ty.kind(), &checked_ty.kind()) {
1454 (ty::Int(exp), ty::Int(found)) => {
1455 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1457 (Some(exp), Some(found)) if exp < found => (true, false),
1458 (Some(exp), Some(found)) if exp > found => (false, true),
1459 (None, Some(8 | 16)) => (false, true),
1460 (Some(8 | 16), None) => (true, false),
1461 (None, _) | (_, None) => (true, true),
1462 _ => (false, false),
1464 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1467 (ty::Uint(exp), ty::Uint(found)) => {
1468 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1470 (Some(exp), Some(found)) if exp < found => (true, false),
1471 (Some(exp), Some(found)) if exp > found => (false, true),
1472 (None, Some(8 | 16)) => (false, true),
1473 (Some(8 | 16), None) => (true, false),
1474 (None, _) | (_, None) => (true, true),
1475 _ => (false, false),
1477 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1480 (&ty::Int(exp), &ty::Uint(found)) => {
1481 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1483 (Some(exp), Some(found)) if found < exp => (false, true),
1484 (None, Some(8)) => (false, true),
1487 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1490 (&ty::Uint(exp), &ty::Int(found)) => {
1491 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1493 (Some(exp), Some(found)) if found > exp => (true, false),
1494 (Some(8), None) => (true, false),
1497 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1500 (ty::Float(exp), ty::Float(found)) => {
1501 if found.bit_width() < exp.bit_width() {
1502 suggest_to_change_suffix_or_into(err, false, true);
1503 } else if literal_is_ty_suffixed(expr) {
1504 err.multipart_suggestion_verbose(
1507 Applicability::MachineApplicable,
1509 } else if can_cast {
1510 // Missing try_into implementation for `f64` to `f32`
1511 err.multipart_suggestion_verbose(
1512 &format!("{cast_msg}, producing the closest possible value"),
1514 Applicability::MaybeIncorrect, // lossy conversion
1519 (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
1520 if literal_is_ty_suffixed(expr) {
1521 err.multipart_suggestion_verbose(
1524 Applicability::MachineApplicable,
1526 } else if can_cast {
1527 // Missing try_into implementation for `{float}` to `{integer}`
1528 err.multipart_suggestion_verbose(
1529 &format!("{msg}, rounding the float towards zero"),
1531 Applicability::MaybeIncorrect, // lossy conversion
1536 (ty::Float(exp), ty::Uint(found)) => {
1537 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
1538 if exp.bit_width() > found.bit_width().unwrap_or(256) {
1539 err.multipart_suggestion_verbose(
1541 "{msg}, producing the floating point representation of the integer",
1544 Applicability::MachineApplicable,
1546 } else if literal_is_ty_suffixed(expr) {
1547 err.multipart_suggestion_verbose(
1550 Applicability::MachineApplicable,
1553 // Missing try_into implementation for `{integer}` to `{float}`
1554 err.multipart_suggestion_verbose(
1556 "{cast_msg}, producing the floating point representation of the integer, \
1557 rounded if necessary",
1560 Applicability::MaybeIncorrect, // lossy conversion
1565 (ty::Float(exp), ty::Int(found)) => {
1566 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
1567 if exp.bit_width() > found.bit_width().unwrap_or(256) {
1568 err.multipart_suggestion_verbose(
1570 "{}, producing the floating point representation of the integer",
1574 Applicability::MachineApplicable,
1576 } else if literal_is_ty_suffixed(expr) {
1577 err.multipart_suggestion_verbose(
1580 Applicability::MachineApplicable,
1583 // Missing try_into implementation for `{integer}` to `{float}`
1584 err.multipart_suggestion_verbose(
1586 "{}, producing the floating point representation of the integer, \
1587 rounded if necessary",
1591 Applicability::MaybeIncorrect, // lossy conversion
1597 &ty::Uint(ty::UintTy::U32 | ty::UintTy::U64 | ty::UintTy::U128)
1598 | &ty::Int(ty::IntTy::I32 | ty::IntTy::I64 | ty::IntTy::I128),
1601 err.multipart_suggestion_verbose(
1602 &format!("{cast_msg}, since a `char` always occupies 4 bytes"),
1604 Applicability::MachineApplicable,
1612 /// Identify when the user has written `foo..bar()` instead of `foo.bar()`.
1613 pub fn check_for_range_as_method_call(
1615 err: &mut Diagnostic,
1616 expr: &hir::Expr<'_>,
1617 checked_ty: Ty<'tcx>,
1618 expected_ty: Ty<'tcx>,
1620 if !hir::is_range_literal(expr) {
1623 let hir::ExprKind::Struct(
1624 hir::QPath::LangItem(LangItem::Range, ..),
1627 ) = expr.kind else { return; };
1628 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
1629 if let Some(hir::Node::ExprField(_)) = self.tcx.hir().find(parent) {
1630 // Ignore `Foo { field: a..Default::default() }`
1633 let mut expr = end.expr;
1634 while let hir::ExprKind::MethodCall(_, rcvr, ..) = expr.kind {
1635 // Getting to the root receiver and asserting it is a fn call let's us ignore cases in
1636 // `src/test/ui/methods/issues/issue-90315.stderr`.
1639 let hir::ExprKind::Call(method_name, _) = expr.kind else { return; };
1640 let ty::Adt(adt, _) = checked_ty.kind() else { return; };
1641 if self.tcx.lang_items().range_struct() != Some(adt.did()) {
1644 if let ty::Adt(adt, _) = expected_ty.kind()
1645 && self.tcx.lang_items().range_struct() == Some(adt.did())
1649 // Check if start has method named end.
1650 let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = method_name.kind else { return; };
1651 let [hir::PathSegment { ident, .. }] = p.segments else { return; };
1652 let self_ty = self.typeck_results.borrow().expr_ty(start.expr);
1653 let Ok(_pick) = self.probe_for_name(
1654 probe::Mode::MethodCall,
1656 probe::IsSuggestion(true),
1659 probe::ProbeScope::AllTraits,
1662 let mut span = start.expr.span.between(end.expr.span);
1663 if span.lo() + BytePos(2) == span.hi() {
1664 // There's no space between the start, the range op and the end, suggest removal which
1665 // will be more noticeable than the replacement of `..` with `.`.
1666 span = span.with_lo(span.lo() + BytePos(1));
1669 err.span_suggestion_verbose(
1671 "you likely meant to write a method call instead of a range",
1673 Applicability::MachineApplicable,