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};
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,
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;
28 use super::method::probe;
33 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
34 pub fn emit_type_mismatch_suggestions(
37 expr: &hir::Expr<'tcx>,
40 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
41 error: Option<TypeError<'tcx>>,
43 if expr_ty == expected {
47 self.annotate_alternative_method_deref(err, expr, error);
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);
65 self.point_at_expr_source_of_inferred_type(err, expr, expr_ty, expected);
69 pub fn emit_coerce_suggestions(
72 expr: &hir::Expr<'tcx>,
75 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
76 error: Option<TypeError<'tcx>>,
78 if expr_ty == expected {
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);
90 /// Requires that the two types unify, and prints an error message if
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) {
98 pub fn demand_suptype_diag(
103 ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
104 self.demand_suptype_with_origin(&self.misc(sp), expected, actual)
107 #[instrument(skip(self), level = "debug")]
108 pub fn demand_suptype_with_origin(
110 cause: &ObligationCause<'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);
119 Err(e) => Some(self.err_ctxt().report_mismatched_types(&cause, expected, actual, e)),
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) {
129 pub fn demand_eqtype_diag(
134 ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
135 self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
138 pub fn demand_eqtype_with_origin(
140 cause: &ObligationCause<'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);
149 Err(e) => Some(self.err_ctxt().report_mismatched_types(cause, expected, actual, e)),
153 pub fn demand_coerce(
155 expr: &hir::Expr<'tcx>,
156 checked_ty: Ty<'tcx>,
158 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
159 allow_two_phase: AllowTwoPhase,
162 self.demand_coerce_diag(expr, checked_ty, expected, expected_ty_expr, allow_two_phase);
163 if let Some(mut err) = err {
169 /// Checks that the type of `expr` can be coerced to `expected`.
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(
176 expr: &hir::Expr<'tcx>,
177 checked_ty: 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);
184 let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase, None) {
185 Ok(ty) => return (ty, None),
189 self.set_tainted_by_errors(self.tcx.sess.delay_span_bug(
191 "`TypeError` when attempting coercion but no error emitted",
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);
198 let is_insufficiently_polymorphic =
199 matches!(e, TypeError::RegionsInsufficientlyPolymorphic(..));
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(
215 (expected, Some(err))
218 fn point_at_expr_source_of_inferred_type(
220 err: &mut Diagnostic,
221 expr: &hir::Expr<'_>,
226 let map = self.tcx.hir();
228 // Hack to make equality checks on types with inference variables and regions useful.
229 struct TypeEraser<'tcx> {
232 impl<'tcx> TypeFolder<'tcx> for TypeEraser<'tcx> {
233 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
236 fn fold_region(&mut self, _r: ty::Region<'tcx>) -> ty::Region<'tcx> {
237 self.tcx().lifetimes.re_erased
239 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
240 if !t.needs_infer() && !t.has_erasable_regions() {
244 ty::Infer(ty::TyVar(_) | ty::FreshTy(_)) => {
245 self.tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0)))
247 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => {
248 self.tcx.mk_ty_infer(ty::IntVar(ty::IntVid { index: 0 }))
250 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => {
251 self.tcx.mk_ty_infer(ty::FloatVar(ty::FloatVid { index: 0 }))
253 _ => t.super_fold_with(self),
256 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
257 ct.super_fold_with(self)
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 {
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() {
276 // Locate all the usages of the relevant binding.
277 struct FindExprs<'hir> {
279 uses: Vec<&'hir hir::Expr<'hir>>,
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
289 hir::intravisit::walk_expr(self, ex);
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();
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;
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),
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)
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,
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),
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.
348 let arg_ty = self.node_ty(arg.hir_id);
352 "this is of type `{arg_ty}`, which makes `{ident}` to be \
356 param_args.insert(param_ty, (arg, arg_ty));
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 {
366 param_env: self.param_env,
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);
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);
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);
389 let ty = eraser.fold_ty(ty);
390 if ty.references_error() {
394 && param_args.is_empty()
395 && self.can_eq(self.param_env, ty, found).is_ok()
397 // We only point at the first place where the found type was inferred.
400 with_forced_trimmed_paths!(format!(
401 "here the type of `{ident}` is inferred to be `{ty}`",
408 let ty = eraser.fold_ty(self.node_ty(binding.hir_id));
409 if ty.references_error() {
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.
419 with_forced_trimmed_paths!(format!(
420 "here the type of `{ident}` is inferred to be `{ty}`",
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.
432 prev_span = Some(binding.span);
438 fn annotate_expected_due_to_let_ty(
440 err: &mut Diagnostic,
441 expr: &hir::Expr<'_>,
442 error: Option<TypeError<'tcx>>,
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 =>
449 // Point at `let` assignment type.
450 err.span_label(ty.span, "expected due to this");
453 Some(hir::Node::Expr(hir::Expr {
454 kind: hir::ExprKind::Assign(lhs, rhs, _), ..
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 = "";
464 hir::ExprKind::Path(hir::QPath::Resolved(
469 hir::def::DefKind::Static(_) | hir::def::DefKind::Const,
475 if let Some(hir::Node::Item(hir::Item {
477 kind: hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..),
479 })) = self.tcx.hir().get_if_local(*def_id)
481 primary_span = ty.span;
482 secondary_span = ident.span;
483 post_message = " type";
486 hir::ExprKind::Path(hir::QPath::Resolved(
488 hir::Path { res: hir::def::Res::Local(hir_id), .. },
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";
498 Some(hir::Node::Local(hir::Local { init: Some(init), .. })) => {
499 primary_span = init.span;
500 post_message = " value";
502 Some(hir::Node::Param(hir::Param { ty_span, .. })) => {
503 primary_span = *ty_span;
504 post_message = " parameter type";
513 if primary_span != secondary_span
518 .is_multiline(secondary_span.shrink_to_hi().until(primary_span))
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");
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}"));
532 if !lhs.is_syntactic_place_expr() {
533 // We already emitted E0070 "invalid left-hand side of assignment", so we
535 err.downgrade_to_delayed_bug();
539 Some(hir::Node::Expr(hir::Expr {
540 kind: hir::ExprKind::Binary(_, lhs, rhs), ..
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) =>
546 err.span_label(lhs.span, &format!("expected because this is `{expected}`"));
552 fn annotate_alternative_method_deref(
554 err: &mut Diagnostic,
555 expr: &hir::Expr<'_>,
556 error: Option<TypeError<'tcx>>,
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() {
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; };
572 probe::Mode::MethodCall,
574 probe::IsSuggestion(true),
577 probe::ProbeScope::TraitsInScope,
581 let in_scope_methods = self.probe_for_name_many(
582 probe::Mode::MethodCall,
584 probe::IsSuggestion(true),
587 probe::ProbeScope::TraitsInScope,
589 let other_methods_in_scope: Vec<_> =
590 in_scope_methods.iter().filter(|c| c.item.def_id != pick.item.def_id).collect();
592 let all_methods = self.probe_for_name_many(
593 probe::Mode::MethodCall,
595 probe::IsSuggestion(true),
598 probe::ProbeScope::AllTraits,
600 let suggestions: Vec<_> = all_methods
602 .filter(|c| c.item.def_id != pick.item.def_id)
605 let substs = ty::InternalSubsts::for_item(self.tcx, m.def_id, |param, _| {
606 self.var_for_def(deref.span, param)
610 deref.span.until(base.span),
613 with_no_trimmed_paths!(
614 self.tcx.def_path_str_with_substs(m.def_id, substs,)
616 match self.tcx.fn_sig(m.def_id).input(0).skip_binder().kind() {
617 ty::Ref(_, _, hir::Mutability::Mut) => "&mut ",
618 ty::Ref(_, _, _) => "&",
624 [] => (base.span.shrink_to_hi().with_hi(deref.span.hi()), ")".to_string()),
625 [first, ..] => (base.span.between(first.span), ", ".to_string()),
630 if suggestions.is_empty() {
633 let mut path_span: MultiSpan = path.ident.span.into();
634 path_span.push_span_label(
636 with_no_trimmed_paths!(format!(
638 self.tcx.def_path_str(pick.item.def_id),
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"),
650 let tail = with_no_trimmed_paths!(match &other_methods_in_scope[..] {
652 [candidate] => format!(
653 "the method of the same name on {} `{}`",
654 match candidate.kind {
655 probe::CandidateKind::InherentImplCandidate(..) => "the inherent impl for",
658 self.tcx.def_path_str(candidate.item.container_id(self.tcx))
660 [.., last] if other_methods_in_scope.len() < 5 => {
662 "the methods of the same name on {} and `{}`",
663 other_methods_in_scope[..other_methods_in_scope.len() - 1]
667 self.tcx.def_path_str(c.item.container_id(self.tcx))
669 .collect::<Vec<String>>()
671 self.tcx.def_path_str(last.item.container_id(self.tcx))
675 "the methods of the same name on {} other traits",
676 other_methods_in_scope.len()
682 "the `{}` call is resolved to the method in `{container}`, shadowing {tail}",
686 if suggestions.len() > other_methods_in_scope.len() {
688 "additionally, there are {} other available methods that aren't in scope",
689 suggestions.len() - other_methods_in_scope.len()
692 err.multipart_suggestions(
694 "you might have meant to call {}; you can use the fully-qualified path to call {} \
696 if suggestions.len() == 1 {
699 "one of the other methods"
701 if suggestions.len() == 1 { "it" } else { "one of them" },
704 Applicability::MaybeIncorrect,
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(
712 err: &mut Diagnostic,
713 expr: &hir::Expr<'_>,
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)
723 err.span_suggestion_verbose(
724 expr.span.with_lo(base_span.hi()),
725 format!("consider removing the tuple struct field `{ident}`"),
727 Applicability::MaybeIncorrect,
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;
740 // Unroll desugaring, to make sure this works for `for` loops etc.
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.
754 if let Some(hir::Node::Block(&hir::Block {
755 span: block_span, expr: Some(e), ..
756 })) = self.tcx.hir().find(parent)
759 if let Some(span) = expr.span.find_ancestor_inside(block_span) {
760 let return_suggestions = if self
762 .is_diagnostic_item(sym::Result, expected_adt.did())
765 } else if self.tcx.is_diagnostic_item(sym::Option, expected_adt.did()) {
766 vec!["None", "Some(())"]
770 if let Some(indent) =
771 self.tcx.sess.source_map().indentation_before(span.shrink_to_lo())
773 // Add a semicolon, except after `}`.
775 match self.tcx.sess.source_map().span_to_snippet(span) {
776 Ok(s) if s.ends_with('}') => "",
779 err.span_suggestions(
781 "try adding an expression at the end of the block",
784 .map(|r| format!("{semicolon}\n{indent}{r}")),
785 Applicability::MaybeIncorrect,
794 let compatible_variants: Vec<(String, _, _, Option<String>)> = expected_adt
798 variant.fields.len() == 1
800 .filter_map(|variant| {
801 let sole_field = &variant.fields[0];
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);
809 if !field_is_local && !field_is_accessible {
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());
816 let sole_field_ty = sole_field.ty(self.tcx, substs);
817 if self.can_coerce(expr_ty, sole_field_ty) {
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("::")
824 return Some((path.to_string(), variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy));
826 Some((variant_path, variant.ctor_kind(), sole_field.name, note_about_variant_field_privacy))
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(),
839 let (open, close) = match ctor_kind {
840 Some(CtorKind::Fn) => ("(".to_owned(), ")"),
841 None => (format!(" {{ {field_name}: "), " }"),
843 // unit variants don't have fields
844 Some(CtorKind::Const) => unreachable!(),
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.
851 while let hir::ExprKind::Block(block, _) = &expr.kind
852 && let Some(expr_) = &block.expr
858 (expr.span.shrink_to_lo(), format!("{prefix}{variant}{open}")),
859 (expr.span.shrink_to_hi(), close.to_owned()),
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(
869 "try wrapping the expression in `{variant}`{note}",
870 note = note.as_deref().unwrap_or("")
872 suggestions_for(&**variant, *ctor_kind, *field_name),
873 Applicability::MaybeIncorrect,
878 // More than one matching variant.
879 err.multipart_suggestions(
881 "try wrapping the expression in a variant of `{}`",
882 self.tcx.def_path_str(expected_adt.did())
884 compatible_variants.into_iter().map(
885 |(variant, ctor_kind, field_name, _)| {
886 suggestions_for(&variant, ctor_kind, field_name)
889 Applicability::MaybeIncorrect,
899 fn suggest_non_zero_new_unwrap(
901 err: &mut Diagnostic,
902 expr: &hir::Expr<'_>,
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()) => {
911 let ty::Adt(adt, _) = substs.type_at(0).kind() else { return false; };
915 // In case NonZero* is wanted, but * is provided also add `.unwrap()` to satisfy types
916 ty::Adt(adt, _) => (adt, ".unwrap()"),
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),
933 let Some((s, _)) = map
935 .find(|&&(s, t)| self.tcx.is_diagnostic_item(s, adt.did()) && self.can_coerce(expr_ty, t))
936 else { return false; };
938 let path = self.tcx.def_path_str(adt.non_enum_variant().def_id);
940 err.multipart_suggestion(
941 format!("consider calling `{s}::new`"),
943 (expr.span.shrink_to_lo(), format!("{path}::new(")),
944 (expr.span.shrink_to_hi(), format!("){unwrap}")),
946 Applicability::MaybeIncorrect,
952 pub fn get_conversion_methods(
956 checked_ty: Ty<'tcx>,
958 ) -> Vec<AssocItem> {
959 let methods = self.probe_for_return_type(
961 probe::Mode::MethodCall,
966 self.has_only_self_parameter(m)
969 // This special internal attribute is used to permit
970 // "identity-like" conversion methods to be suggested here.
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).
977 // FIXME? Other potential candidate methods: `as_ref` and
979 .has_attr(m.def_id, sym::rustc_conversion_suggestion)
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 {
989 ty::AssocKind::Fn => {
990 method.fn_has_self_parameter
991 && self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1
997 /// Identify some cases where `as_ref()` would be appropriate and suggest it.
999 /// Given the following code:
1000 /// ```compile_fail,E0308
1002 /// fn takes_ref(_: &Foo) {}
1003 /// let ref opt = Some(Foo);
1005 /// opt.map(|param| takes_ref(param));
1007 /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
1009 /// It only checks for `Option` and `Result` and won't work with
1010 /// ```ignore (illustrative)
1011 /// opt.map(|param| { takes_ref(param) });
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 {
1018 let hir::def::Res::Local(local_id) = path.res else {
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 {
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, .. }),
1032 })) = self.tcx.hir().find(param_parent) else {
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();
1040 Some(Node::Expr(hir::Expr {
1041 kind: hir::ExprKind::MethodCall(method_path, receiver, ..),
1045 ) = (hir, closure_params_len) else {
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)
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))
1068 pub(crate) fn maybe_get_struct_pattern_shorthand_field(
1070 expr: &hir::Expr<'_>,
1071 ) -> Option<Symbol> {
1072 let hir = self.tcx.hir();
1073 let local = match expr {
1076 hir::ExprKind::Path(hir::QPath::Resolved(
1079 res: hir::def::Res::Local(_),
1080 segments: [hir::PathSegment { ident, .. }],
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);
1101 /// If the given `HirId` corresponds to a block with a trailing expression, return that expression
1102 pub(crate) fn maybe_get_block_expr(
1104 expr: &hir::Expr<'tcx>,
1105 ) -> Option<&'tcx hir::Expr<'tcx>> {
1107 hir::Expr { kind: hir::ExprKind::Block(block, ..), .. } => block.expr,
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)),
1119 })) = self.tcx.hir().find(parent_id)
1121 return else_expr.hir_id == expr.hir_id;
1127 /// This function is used to determine potential "simple" improvements or users' errors and
1128 /// provide them useful help. For example:
1130 /// ```compile_fail,E0308
1131 /// fn some_fn(s: &str) {}
1133 /// let x = "hey!".to_owned();
1134 /// some_fn(x); // error
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!
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
1145 expr: &hir::Expr<'tcx>,
1146 checked_ty: Ty<'tcx>,
1154 bool, /* suggest `&` or `&mut` type annotation */
1156 let sess = self.sess();
1159 // If the span is from an external macro, there's no suggestion we can make.
1160 if in_external_macro(sess, sp) {
1164 let sm = sess.source_map();
1166 let replace_prefix = |s: &str, old: &str, new: &str| {
1167 s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
1170 // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
1171 let expr = expr.peel_drop_temps();
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()
1180 let pos = sp.lo() + BytePos(1);
1183 "consider removing the leading `b`".to_string(),
1185 Applicability::MachineApplicable,
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()
1198 "consider adding a leading `b`".to_string(),
1200 Applicability::MachineApplicable,
1208 (_, &ty::Ref(_, _, mutability), _) => {
1209 // Check if it can work when put into a ref. For example:
1212 // fn bar(x: &mut i32) {}
1215 // bar(&x); // error, expected &mut
1217 let ref_ty = match mutability {
1218 hir::Mutability::Mut => {
1219 self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
1221 hir::Mutability::Not => {
1222 self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
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 {
1229 self.tcx.require_lang_item(LangItem::Clone, Some(segment.ident.span));
1231 && self.typeck_results.borrow().type_dependent_def_id(expr.hir_id).map(
1233 let ai = self.tcx.associated_item(did);
1234 ai.trait_container(self.tcx) == Some(clone_trait)
1237 && segment.ident.name == sym::clone
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;
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,
1253 if let Some(sugg) = self.can_use_as_ref(expr) {
1258 Applicability::MachineApplicable,
1264 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
1265 Some(ident) => format!("{ident}: "),
1266 None => String::new(),
1269 if let Some(hir::Node::Expr(hir::Expr {
1270 kind: hir::ExprKind::Assign(..),
1272 })) = self.tcx.hir().find_parent(expr.hir_id)
1274 if mutability.is_mut() {
1275 // Suppressing this diagnostic, we'll properly print it in `check_expr_assign`
1280 let sugg_expr = if needs_parens { format!("({src})") } else { src };
1283 format!("consider {}borrowing here", mutability.mutably_str()),
1284 format!("{prefix}{}{sugg_expr}", mutability.ref_prefix_str()),
1285 Applicability::MachineApplicable,
1293 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
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`.
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)
1311 sp.with_hi(call_span.lo()),
1312 "consider removing the borrow".to_string(),
1314 Applicability::MachineApplicable,
1321 if sp.contains(expr.span)
1322 && sm.is_span_accessible(expr.span)
1325 sp.with_hi(expr.span.lo()),
1326 "consider removing the borrow".to_string(),
1328 Applicability::MachineApplicable,
1336 &ty::RawPtr(TypeAndMut { ty: ty_b, mutbl: mutbl_b }),
1337 &ty::Ref(_, ty_a, mutbl_a),
1339 if let Some(steps) = self.deref_steps(ty_a, ty_b)
1340 // Only suggest valid if dereferencing needed.
1342 // The pointer type implements `Copy` trait so the suggestion is always valid.
1343 && let Ok(src) = sm.span_to_snippet(sp)
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;
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);
1358 format!("{}{derefs}", if mutbl_a != mutbl_b { mutbl_b.prefix_str() } else { "" }),
1359 if mutbl_b <= mutbl_a { Applicability::MachineApplicable } else { Applicability::MaybeIncorrect }
1363 if let Some((span, src, applicability)) = suggestion {
1366 "consider dereferencing".to_string(),
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();
1381 // Try peeling off any existing `&` and `&mut` to reach our target type
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());
1387 remove.push_str(mutbl.ref_prefix_str());
1393 // If we've reached our target type with just removing `&`, then just print now.
1397 format!("consider removing the `{}`", remove.trim()),
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
1405 Applicability::MachineApplicable
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)
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"
1424 "dereferencing the type"
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}")
1433 "consider removing the `{}` and {} instead",
1439 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
1440 Some(ident) => format!("{ident}: "),
1441 None => String::new(),
1444 let (span, suggestion) = if self.is_else_if_block(expr) {
1445 // Don't suggest nonsense like `else *if`
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())
1451 (prefix_span, format!("{}{}", prefix, "*".repeat(steps)))
1458 Applicability::MachineApplicable,
1470 pub fn check_for_cast(
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>>,
1478 if self.tcx.sess.source_map().is_imported(expr.span) {
1479 // Ignore if span is from within a macro.
1483 let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) else {
1487 // If casting this expression to a given numeric type would be appropriate in case of a type
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.
1494 // For now, don't suggest casting with `as`.
1495 let can_cast = false;
1497 let mut sugg = vec![];
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)));
1505 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
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)
1517 if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
1531 if base_ty_path.segments.len() == 1 =>
1541 "you can convert {} `{}` to {} `{}`",
1542 checked_ty.kind().article(),
1544 expected_ty.kind().article(),
1547 let cast_msg = format!(
1548 "you can cast {} `{}` to {} `{}`",
1549 checked_ty.kind().article(),
1551 expected_ty.kind().article(),
1554 let lit_msg = format!(
1555 "change the type of the numeric literal from `{checked_ty}` to `{expected_ty}`",
1558 let close_paren = if expr.precedence().order() < PREC_POSTFIX {
1559 sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
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((
1572 (&expected_ty.kind(), &checked_ty.kind()),
1573 (ty::Int(_) | ty::Uint(_), ty::Float(_))
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))
1580 let len = src.trim_end_matches(&checked_ty.to_string()).len();
1581 expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
1583 if expr.precedence().order() < PREC_POSTFIX {
1585 format!("{expected_ty})")
1587 expected_ty.to_string()
1590 let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
1591 if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
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(..));
1597 let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id);
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",
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| {
1611 .span_to_snippet(expr.span)
1613 .map(|src| (expr, src))
1615 let (msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
1616 (lhs_expr_and_src, exp_to_found_is_fallible)
1619 "you can convert `{lhs_src}` from `{expected_ty}` to `{checked_ty}`, matching the type of `{src}`",
1621 let suggestion = vec![
1622 (lhs_expr.span.shrink_to_lo(), format!("{checked_ty}::from(")),
1623 (lhs_expr.span.shrink_to_hi(), ")".to_string()),
1627 let msg = format!("{msg} and panic if the converted value doesn't fit");
1628 let mut suggestion = sugg.clone();
1630 expr.span.shrink_to_hi(),
1631 format!("{close_paren}.try_into().unwrap()"),
1635 err.multipart_suggestion_verbose(
1638 Applicability::MachineApplicable,
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| {
1647 expected_ty_expr.map(|e| self.tcx.hir().is_lhs(e.hir_id)).unwrap_or(false);
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) {
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
1661 let msg = format!("`{src}` cannot fit into type `{expected_ty}`");
1664 } else if in_const_context {
1665 // Do not recommend `into` or `try_into` in const contexts.
1667 } else if found_to_exp_is_fallible {
1668 return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
1672 let suggestion = if literal_is_ty_suffixed(expr) {
1673 suffix_suggestion.clone()
1675 into_suggestion.clone()
1677 err.multipart_suggestion_verbose(msg, suggestion, Applicability::MachineApplicable);
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())
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),
1691 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1694 (ty::Uint(exp), ty::Uint(found)) => {
1695 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
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),
1704 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1707 (&ty::Int(exp), &ty::Uint(found)) => {
1708 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1710 (Some(exp), Some(found)) if found < exp => (false, true),
1711 (None, Some(8)) => (false, true),
1714 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1717 (&ty::Uint(exp), &ty::Int(found)) => {
1718 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1720 (Some(exp), Some(found)) if found > exp => (true, false),
1721 (Some(8), None) => (true, false),
1724 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
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(
1734 Applicability::MachineApplicable,
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"),
1741 Applicability::MaybeIncorrect, // lossy conversion
1746 (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
1747 if literal_is_ty_suffixed(expr) {
1748 err.multipart_suggestion_verbose(
1751 Applicability::MachineApplicable,
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"),
1758 Applicability::MaybeIncorrect, // lossy conversion
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(
1768 "{msg}, producing the floating point representation of the integer",
1771 Applicability::MachineApplicable,
1773 } else if literal_is_ty_suffixed(expr) {
1774 err.multipart_suggestion_verbose(
1777 Applicability::MachineApplicable,
1780 // Missing try_into implementation for `{integer}` to `{float}`
1781 err.multipart_suggestion_verbose(
1783 "{cast_msg}, producing the floating point representation of the integer, \
1784 rounded if necessary",
1787 Applicability::MaybeIncorrect, // lossy conversion
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(
1797 "{}, producing the floating point representation of the integer",
1801 Applicability::MachineApplicable,
1803 } else if literal_is_ty_suffixed(expr) {
1804 err.multipart_suggestion_verbose(
1807 Applicability::MachineApplicable,
1810 // Missing try_into implementation for `{integer}` to `{float}`
1811 err.multipart_suggestion_verbose(
1813 "{}, producing the floating point representation of the integer, \
1814 rounded if necessary",
1818 Applicability::MaybeIncorrect, // lossy conversion
1824 &ty::Uint(ty::UintTy::U32 | ty::UintTy::U64 | ty::UintTy::U128)
1825 | &ty::Int(ty::IntTy::I32 | ty::IntTy::I64 | ty::IntTy::I128),
1828 err.multipart_suggestion_verbose(
1829 &format!("{cast_msg}, since a `char` always occupies 4 bytes"),
1831 Applicability::MachineApplicable,
1839 /// Identify when the user has written `foo..bar()` instead of `foo.bar()`.
1840 pub fn check_for_range_as_method_call(
1842 err: &mut Diagnostic,
1843 expr: &hir::Expr<'_>,
1844 checked_ty: Ty<'tcx>,
1845 expected_ty: Ty<'tcx>,
1847 if !hir::is_range_literal(expr) {
1850 let hir::ExprKind::Struct(
1851 hir::QPath::LangItem(LangItem::Range, ..),
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() }`
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`.
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()) {
1871 if let ty::Adt(adt, _) = expected_ty.kind()
1872 && self.tcx.lang_items().range_struct() == Some(adt.did())
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,
1883 probe::IsSuggestion(true),
1886 probe::ProbeScope::AllTraits,
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));
1896 err.span_suggestion_verbose(
1898 "you likely meant to write a method call instead of a range",
1900 Applicability::MachineApplicable,