1 use crate::check::FnCtxt;
2 use rustc_infer::infer::InferOk;
3 use rustc_middle::middle::stability::EvalResult;
4 use rustc_trait_selection::infer::InferCtxtExt as _;
5 use rustc_trait_selection::traits::ObligationCause;
7 use rustc_ast::util::parser::PREC_POSTFIX;
8 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
10 use rustc_hir::lang_items::LangItem;
11 use rustc_hir::{is_range_literal, Node};
12 use rustc_middle::lint::in_external_macro;
13 use rustc_middle::ty::adjustment::AllowTwoPhase;
14 use rustc_middle::ty::error::{ExpectedFound, TypeError};
15 use rustc_middle::ty::print::with_no_trimmed_paths;
16 use rustc_middle::ty::{self, Article, AssocItem, Ty, TypeAndMut};
17 use rustc_span::symbol::{sym, Symbol};
18 use rustc_span::{BytePos, Span};
20 use super::method::probe;
24 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25 pub fn emit_coerce_suggestions(
28 expr: &hir::Expr<'tcx>,
31 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
32 error: Option<TypeError<'tcx>>,
34 self.annotate_expected_due_to_let_ty(err, expr, error);
35 self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr);
36 self.suggest_compatible_variants(err, expr, expected, expr_ty);
37 self.suggest_non_zero_new_unwrap(err, expr, expected, expr_ty);
38 if self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty) {
41 self.suggest_no_capture_closure(err, expected, expr_ty);
42 self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty);
43 self.suggest_missing_parentheses(err, expr);
44 self.suggest_block_to_brackets_peeling_refs(err, expr, expr_ty, expected);
45 self.note_type_is_not_clone(err, expected, expr_ty, expr);
46 self.note_need_for_fn_pointer(err, expected, expr_ty);
47 self.note_internal_mutation_in_method(err, expr, expected, expr_ty);
50 // Requires that the two types unify, and prints an error message if
52 pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
53 if let Some(mut e) = self.demand_suptype_diag(sp, expected, actual) {
58 pub fn demand_suptype_diag(
63 ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
64 self.demand_suptype_with_origin(&self.misc(sp), expected, actual)
67 #[instrument(skip(self), level = "debug")]
68 pub fn demand_suptype_with_origin(
70 cause: &ObligationCause<'tcx>,
73 ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
74 match self.at(cause, self.param_env).sup(expected, actual) {
75 Ok(InferOk { obligations, value: () }) => {
76 self.register_predicates(obligations);
79 Err(e) => Some(self.report_mismatched_types(&cause, expected, actual, e)),
83 pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
84 if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
89 pub fn demand_eqtype_diag(
94 ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
95 self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
98 pub fn demand_eqtype_with_origin(
100 cause: &ObligationCause<'tcx>,
103 ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
104 match self.at(cause, self.param_env).eq(expected, actual) {
105 Ok(InferOk { obligations, value: () }) => {
106 self.register_predicates(obligations);
109 Err(e) => Some(self.report_mismatched_types(cause, expected, actual, e)),
113 pub fn demand_coerce(
115 expr: &hir::Expr<'tcx>,
116 checked_ty: Ty<'tcx>,
118 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
119 allow_two_phase: AllowTwoPhase,
122 self.demand_coerce_diag(expr, checked_ty, expected, expected_ty_expr, allow_two_phase);
123 if let Some(mut err) = err {
129 /// Checks that the type of `expr` can be coerced to `expected`.
131 /// N.B., this code relies on `self.diverges` to be accurate. In particular, assignments to `!`
132 /// will be permitted if the diverges flag is currently "always".
133 #[tracing::instrument(level = "debug", skip(self, expr, expected_ty_expr, allow_two_phase))]
134 pub fn demand_coerce_diag(
136 expr: &hir::Expr<'tcx>,
137 checked_ty: Ty<'tcx>,
139 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
140 allow_two_phase: AllowTwoPhase,
141 ) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>>) {
142 let expected = self.resolve_vars_with_obligations(expected);
144 let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase, None) {
145 Ok(ty) => return (ty, None),
149 self.set_tainted_by_errors();
150 let expr = expr.peel_drop_temps();
151 let cause = self.misc(expr.span);
152 let expr_ty = self.resolve_vars_with_obligations(checked_ty);
153 let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e.clone());
155 let is_insufficiently_polymorphic =
156 matches!(e, TypeError::RegionsInsufficientlyPolymorphic(..));
158 // FIXME(#73154): For now, we do leak check when coercing function
159 // pointers in typeck, instead of only during borrowck. This can lead
160 // to these `RegionsInsufficientlyPolymorphic` errors that aren't helpful.
161 if !is_insufficiently_polymorphic {
162 self.emit_coerce_suggestions(
172 (expected, Some(err))
175 fn annotate_expected_due_to_let_ty(
177 err: &mut Diagnostic,
178 expr: &hir::Expr<'_>,
179 error: Option<TypeError<'_>>,
181 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
182 match (self.tcx.hir().find(parent), error) {
183 (Some(hir::Node::Local(hir::Local { ty: Some(ty), init: Some(init), .. })), _)
184 if init.hir_id == expr.hir_id =>
186 // Point at `let` assignment type.
187 err.span_label(ty.span, "expected due to this");
190 Some(hir::Node::Expr(hir::Expr {
191 kind: hir::ExprKind::Assign(lhs, rhs, _), ..
193 Some(TypeError::Sorts(ExpectedFound { expected, .. })),
194 ) if rhs.hir_id == expr.hir_id && !expected.is_closure() => {
195 // We ignore closures explicitly because we already point at them elsewhere.
196 // Point at the assigned-to binding.
197 let mut primary_span = lhs.span;
198 let mut secondary_span = lhs.span;
199 let mut post_message = "";
201 hir::ExprKind::Path(hir::QPath::Resolved(
206 hir::def::DefKind::Static(_) | hir::def::DefKind::Const,
212 if let Some(hir::Node::Item(hir::Item {
214 kind: hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..),
216 })) = self.tcx.hir().get_if_local(*def_id)
218 primary_span = ty.span;
219 secondary_span = ident.span;
220 post_message = " type";
223 hir::ExprKind::Path(hir::QPath::Resolved(
225 hir::Path { res: hir::def::Res::Local(hir_id), .. },
227 if let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(*hir_id) {
228 let parent = self.tcx.hir().get_parent_node(pat.hir_id);
229 primary_span = pat.span;
230 secondary_span = pat.span;
231 match self.tcx.hir().find(parent) {
232 Some(hir::Node::Local(hir::Local { ty: Some(ty), .. })) => {
233 primary_span = ty.span;
234 post_message = " type";
236 Some(hir::Node::Local(hir::Local { init: Some(init), .. })) => {
237 primary_span = init.span;
238 post_message = " value";
240 Some(hir::Node::Param(hir::Param { ty_span, .. })) => {
241 primary_span = *ty_span;
242 post_message = " parameter type";
251 if primary_span != secondary_span
256 .is_multiline(secondary_span.shrink_to_hi().until(primary_span))
258 // We are pointing at the binding's type or initializer value, but it's pattern
259 // is in a different line, so we point at both.
260 err.span_label(secondary_span, "expected due to the type of this binding");
261 err.span_label(primary_span, &format!("expected due to this{post_message}"));
262 } else if post_message == "" {
263 // We are pointing at either the assignment lhs or the binding def pattern.
264 err.span_label(primary_span, "expected due to the type of this binding");
266 // We are pointing at the binding's type or initializer value.
267 err.span_label(primary_span, &format!("expected due to this{post_message}"));
270 if !lhs.is_syntactic_place_expr() {
271 // We already emitted E0070 "invalid left-hand side of assignment", so we
273 err.downgrade_to_delayed_bug();
280 /// If the expected type is an enum (Issue #55250) with any variants whose
281 /// sole field is of the found type, suggest such variants. (Issue #42764)
282 fn suggest_compatible_variants(
284 err: &mut Diagnostic,
285 expr: &hir::Expr<'_>,
289 if let ty::Adt(expected_adt, substs) = expected.kind() {
290 if let hir::ExprKind::Field(base, ident) = expr.kind {
291 let base_ty = self.typeck_results.borrow().expr_ty(base);
292 if self.can_eq(self.param_env, base_ty, expected).is_ok()
293 && let Some(base_span) = base.span.find_ancestor_inside(expr.span)
295 err.span_suggestion_verbose(
296 expr.span.with_lo(base_span.hi()),
297 format!("consider removing the tuple struct field `{ident}`"),
299 Applicability::MaybeIncorrect,
305 // If the expression is of type () and it's the return expression of a block,
306 // we suggest adding a separate return expression instead.
307 // (To avoid things like suggesting `Ok(while .. { .. })`.)
308 if expr_ty.is_unit() {
309 let mut id = expr.hir_id;
312 // Unroll desugaring, to make sure this works for `for` loops etc.
314 parent = self.tcx.hir().get_parent_node(id);
315 if let Some(parent_span) = self.tcx.hir().opt_span(parent) {
316 if parent_span.find_ancestor_inside(expr.span).is_some() {
317 // The parent node is part of the same span, so is the result of the
318 // same expansion/desugaring and not the 'real' parent node.
326 if let Some(hir::Node::Block(&hir::Block {
327 span: block_span, expr: Some(e), ..
328 })) = self.tcx.hir().find(parent)
331 if let Some(span) = expr.span.find_ancestor_inside(block_span) {
332 let return_suggestions = if self
334 .is_diagnostic_item(sym::Result, expected_adt.did())
337 } else if self.tcx.is_diagnostic_item(sym::Option, expected_adt.did()) {
338 vec!["None", "Some(())"]
342 if let Some(indent) =
343 self.tcx.sess.source_map().indentation_before(span.shrink_to_lo())
345 // Add a semicolon, except after `}`.
347 match self.tcx.sess.source_map().span_to_snippet(span) {
348 Ok(s) if s.ends_with('}') => "",
351 err.span_suggestions(
353 "try adding an expression at the end of the block",
356 .map(|r| format!("{semicolon}\n{indent}{r}")),
357 Applicability::MaybeIncorrect,
366 let compatible_variants: Vec<(String, _, _, Option<String>)> = expected_adt
370 variant.fields.len() == 1
372 .filter_map(|variant| {
373 let sole_field = &variant.fields[0];
375 let field_is_local = sole_field.did.is_local();
376 let field_is_accessible =
377 sole_field.vis.is_accessible_from(expr.hir_id.owner.to_def_id(), self.tcx)
378 // Skip suggestions for unstable public fields (for example `Pin::pointer`)
379 && matches!(self.tcx.eval_stability(sole_field.did, None, expr.span, None), EvalResult::Allow | EvalResult::Unmarked);
381 if !field_is_local && !field_is_accessible {
385 let note_about_variant_field_privacy = (field_is_local && !field_is_accessible)
386 .then(|| format!(" (its field is private, but it's local to this crate and its privacy can be changed)"));
388 let sole_field_ty = sole_field.ty(self.tcx, substs);
389 if self.can_coerce(expr_ty, sole_field_ty) {
391 with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
392 // FIXME #56861: DRYer prelude filtering
393 if let Some(path) = variant_path.strip_prefix("std::prelude::")
394 && let Some((_, path)) = path.split_once("::")
396 return Some((path.to_string(), variant.ctor_kind, sole_field.name, note_about_variant_field_privacy));
398 Some((variant_path, variant.ctor_kind, sole_field.name, note_about_variant_field_privacy))
405 let suggestions_for = |variant: &_, ctor, field_name| {
406 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
407 Some(ident) => format!("{ident}: "),
408 None => String::new(),
411 let (open, close) = match ctor {
412 hir::def::CtorKind::Fn => ("(".to_owned(), ")"),
413 hir::def::CtorKind::Fictive => (format!(" {{ {field_name}: "), " }"),
415 // unit variants don't have fields
416 hir::def::CtorKind::Const => unreachable!(),
420 (expr.span.shrink_to_lo(), format!("{prefix}{variant}{open}")),
421 (expr.span.shrink_to_hi(), close.to_owned()),
425 match &compatible_variants[..] {
426 [] => { /* No variants to format */ }
427 [(variant, ctor_kind, field_name, note)] => {
428 // Just a single matching variant.
429 err.multipart_suggestion_verbose(
431 "try wrapping the expression in `{variant}`{note}",
432 note = note.as_deref().unwrap_or("")
434 suggestions_for(&**variant, *ctor_kind, *field_name),
435 Applicability::MaybeIncorrect,
439 // More than one matching variant.
440 err.multipart_suggestions(
442 "try wrapping the expression in a variant of `{}`",
443 self.tcx.def_path_str(expected_adt.did())
445 compatible_variants.into_iter().map(
446 |(variant, ctor_kind, field_name, _)| {
447 suggestions_for(&variant, ctor_kind, field_name)
450 Applicability::MaybeIncorrect,
457 fn suggest_non_zero_new_unwrap(
459 err: &mut Diagnostic,
460 expr: &hir::Expr<'_>,
465 let (adt, unwrap) = match expected.kind() {
466 // In case Option<NonZero*> is wanted, but * is provided, suggest calling new
467 ty::Adt(adt, substs) if tcx.is_diagnostic_item(sym::Option, adt.did()) => {
469 let ty::Adt(adt, _) = substs.type_at(0).kind() else { return };
473 // In case NonZero* is wanted, but * is provided also add `.unwrap()` to satisfy types
474 ty::Adt(adt, _) => (adt, ".unwrap()"),
479 (sym::NonZeroU8, tcx.types.u8),
480 (sym::NonZeroU16, tcx.types.u16),
481 (sym::NonZeroU32, tcx.types.u32),
482 (sym::NonZeroU64, tcx.types.u64),
483 (sym::NonZeroU128, tcx.types.u128),
484 (sym::NonZeroI8, tcx.types.i8),
485 (sym::NonZeroI16, tcx.types.i16),
486 (sym::NonZeroI32, tcx.types.i32),
487 (sym::NonZeroI64, tcx.types.i64),
488 (sym::NonZeroI128, tcx.types.i128),
491 let Some((s, _)) = map
493 .find(|&&(s, t)| self.tcx.is_diagnostic_item(s, adt.did()) && self.can_coerce(expr_ty, t))
496 let path = self.tcx.def_path_str(adt.non_enum_variant().def_id);
498 err.multipart_suggestion(
499 format!("consider calling `{s}::new`"),
501 (expr.span.shrink_to_lo(), format!("{path}::new(")),
502 (expr.span.shrink_to_hi(), format!("){unwrap}")),
504 Applicability::MaybeIncorrect,
508 pub fn get_conversion_methods(
512 checked_ty: Ty<'tcx>,
514 ) -> Vec<AssocItem> {
516 self.probe_for_return_type(span, probe::Mode::MethodCall, expected, checked_ty, hir_id);
518 self.has_only_self_parameter(m)
521 // This special internal attribute is used to permit
522 // "identity-like" conversion methods to be suggested here.
524 // FIXME (#46459 and #46460): ideally
525 // `std::convert::Into::into` and `std::borrow:ToOwned` would
526 // also be `#[rustc_conversion_suggestion]`, if not for
527 // method-probing false-positives and -negatives (respectively).
529 // FIXME? Other potential candidate methods: `as_ref` and
531 .has_attr(m.def_id, sym::rustc_conversion_suggestion)
537 /// This function checks whether the method is not static and does not accept other parameters than `self`.
538 fn has_only_self_parameter(&self, method: &AssocItem) -> bool {
540 ty::AssocKind::Fn => {
541 method.fn_has_self_parameter
542 && self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1
548 /// Identify some cases where `as_ref()` would be appropriate and suggest it.
550 /// Given the following code:
551 /// ```compile_fail,E0308
553 /// fn takes_ref(_: &Foo) {}
554 /// let ref opt = Some(Foo);
556 /// opt.map(|param| takes_ref(param));
558 /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
560 /// It only checks for `Option` and `Result` and won't work with
561 /// ```ignore (illustrative)
562 /// opt.map(|param| { takes_ref(param) });
564 fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Span, &'static str, String)> {
565 let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.kind else {
569 let hir::def::Res::Local(local_id) = path.res else {
573 let local_parent = self.tcx.hir().get_parent_node(local_id);
574 let Some(Node::Param(hir::Param { hir_id: param_hir_id, .. })) = self.tcx.hir().find(local_parent) else {
578 let param_parent = self.tcx.hir().get_parent_node(*param_hir_id);
579 let Some(Node::Expr(hir::Expr {
581 kind: hir::ExprKind::Closure(hir::Closure { fn_decl: closure_fn_decl, .. }),
583 })) = self.tcx.hir().find(param_parent) else {
587 let expr_parent = self.tcx.hir().get_parent_node(*expr_hir_id);
588 let hir = self.tcx.hir().find(expr_parent);
589 let closure_params_len = closure_fn_decl.inputs.len();
591 Some(Node::Expr(hir::Expr {
592 kind: hir::ExprKind::MethodCall(method_path, method_expr, _),
596 ) = (hir, closure_params_len) else {
600 let self_ty = self.typeck_results.borrow().expr_ty(&method_expr[0]);
601 let self_ty = format!("{:?}", self_ty);
602 let name = method_path.ident.name;
603 let is_as_ref_able = (self_ty.starts_with("&std::option::Option")
604 || self_ty.starts_with("&std::result::Result")
605 || self_ty.starts_with("std::option::Option")
606 || self_ty.starts_with("std::result::Result"))
607 && (name == sym::map || name == sym::and_then);
608 match (is_as_ref_able, self.sess().source_map().span_to_snippet(method_path.ident.span)) {
610 let suggestion = format!("as_ref().{}", src);
611 Some((method_path.ident.span, "consider using `as_ref` instead", suggestion))
617 pub(crate) fn maybe_get_struct_pattern_shorthand_field(
619 expr: &hir::Expr<'_>,
620 ) -> Option<Symbol> {
621 let hir = self.tcx.hir();
622 let local = match expr {
625 hir::ExprKind::Path(hir::QPath::Resolved(
628 res: hir::def::Res::Local(_),
629 segments: [hir::PathSegment { ident, .. }],
638 match hir.find(hir.get_parent_node(expr.hir_id))? {
639 Node::Expr(hir::Expr { kind: hir::ExprKind::Struct(_, fields, ..), .. }) => {
640 for field in *fields {
641 if field.ident.name == local.name && field.is_shorthand {
642 return Some(local.name);
652 /// If the given `HirId` corresponds to a block with a trailing expression, return that expression
653 pub(crate) fn maybe_get_block_expr(
655 expr: &hir::Expr<'tcx>,
656 ) -> Option<&'tcx hir::Expr<'tcx>> {
658 hir::Expr { kind: hir::ExprKind::Block(block, ..), .. } => block.expr,
663 /// Returns whether the given expression is an `else if`.
664 pub(crate) fn is_else_if_block(&self, expr: &hir::Expr<'_>) -> bool {
665 if let hir::ExprKind::If(..) = expr.kind {
666 let parent_id = self.tcx.hir().get_parent_node(expr.hir_id);
667 if let Some(Node::Expr(hir::Expr {
668 kind: hir::ExprKind::If(_, _, Some(else_expr)),
670 })) = self.tcx.hir().find(parent_id)
672 return else_expr.hir_id == expr.hir_id;
678 /// This function is used to determine potential "simple" improvements or users' errors and
679 /// provide them useful help. For example:
681 /// ```compile_fail,E0308
682 /// fn some_fn(s: &str) {}
684 /// let x = "hey!".to_owned();
685 /// some_fn(x); // error
688 /// No need to find every potential function which could make a coercion to transform a
689 /// `String` into a `&str` since a `&` would do the trick!
691 /// In addition of this check, it also checks between references mutability state. If the
692 /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
696 expr: &hir::Expr<'tcx>,
697 checked_ty: Ty<'tcx>,
699 ) -> Option<(Span, String, String, Applicability, bool /* verbose */)> {
700 let sess = self.sess();
703 // If the span is from an external macro, there's no suggestion we can make.
704 if in_external_macro(sess, sp) {
708 let sm = sess.source_map();
710 let replace_prefix = |s: &str, old: &str, new: &str| {
711 s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
714 // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
715 let expr = expr.peel_drop_temps();
717 match (&expr.kind, expected.kind(), checked_ty.kind()) {
718 (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (exp.kind(), check.kind()) {
719 (&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
720 if let hir::ExprKind::Lit(_) = expr.kind
721 && let Ok(src) = sm.span_to_snippet(sp)
722 && replace_prefix(&src, "b\"", "\"").is_some()
724 let pos = sp.lo() + BytePos(1);
727 "consider removing the leading `b`".to_string(),
729 Applicability::MachineApplicable,
734 (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
735 if let hir::ExprKind::Lit(_) = expr.kind
736 && let Ok(src) = sm.span_to_snippet(sp)
737 && replace_prefix(&src, "\"", "b\"").is_some()
741 "consider adding a leading `b`".to_string(),
743 Applicability::MachineApplicable,
750 (_, &ty::Ref(_, _, mutability), _) => {
751 // Check if it can work when put into a ref. For example:
754 // fn bar(x: &mut i32) {}
757 // bar(&x); // error, expected &mut
759 let ref_ty = match mutability {
760 hir::Mutability::Mut => {
761 self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
763 hir::Mutability::Not => {
764 self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
767 if self.can_coerce(ref_ty, expected) {
768 let mut sugg_sp = sp;
769 if let hir::ExprKind::MethodCall(ref segment, ref args, _) = expr.kind {
771 self.tcx.require_lang_item(LangItem::Clone, Some(segment.ident.span));
772 if let ([arg], Some(true), sym::clone) = (
774 self.typeck_results.borrow().type_dependent_def_id(expr.hir_id).map(
776 let ai = self.tcx.associated_item(did);
777 ai.trait_container(self.tcx) == Some(clone_trait)
782 // If this expression had a clone call when suggesting borrowing
783 // we want to suggest removing it because it'd now be unnecessary.
787 if let Ok(src) = sm.span_to_snippet(sugg_sp) {
788 let needs_parens = match expr.kind {
789 // parenthesize if needed (Issue #46756)
790 hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true,
791 // parenthesize borrows of range literals (Issue #54505)
792 _ if is_range_literal(expr) => true,
795 let sugg_expr = if needs_parens { format!("({src})") } else { src };
797 if let Some(sugg) = self.can_use_as_ref(expr) {
802 Applicability::MachineApplicable,
807 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
808 Some(ident) => format!("{ident}: "),
809 None => String::new(),
812 if let Some(hir::Node::Expr(hir::Expr {
813 kind: hir::ExprKind::Assign(..),
815 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
817 if mutability == hir::Mutability::Mut {
818 // Suppressing this diagnostic, we'll properly print it in `check_expr_assign`
823 return Some(match mutability {
824 hir::Mutability::Mut => (
826 "consider mutably borrowing here".to_string(),
827 format!("{prefix}&mut {sugg_expr}"),
828 Applicability::MachineApplicable,
831 hir::Mutability::Not => (
833 "consider borrowing here".to_string(),
834 format!("{prefix}&{sugg_expr}"),
835 Applicability::MachineApplicable,
843 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
845 &ty::Ref(_, checked, _),
846 ) if self.can_sub(self.param_env, checked, expected).is_ok() => {
847 // We have `&T`, check if what was expected was `T`. If so,
848 // we may want to suggest removing a `&`.
849 if sm.is_imported(expr.span) {
850 // Go through the spans from which this span was expanded,
851 // and find the one that's pointing inside `sp`.
853 // E.g. for `&format!("")`, where we want the span to the
854 // `format!()` invocation instead of its expansion.
855 if let Some(call_span) =
856 iter::successors(Some(expr.span), |s| s.parent_callsite())
857 .find(|&s| sp.contains(s))
858 && sm.is_span_accessible(call_span)
861 sp.with_hi(call_span.lo()),
862 "consider removing the borrow".to_string(),
864 Applicability::MachineApplicable,
870 if sp.contains(expr.span)
871 && sm.is_span_accessible(expr.span)
874 sp.with_hi(expr.span.lo()),
875 "consider removing the borrow".to_string(),
877 Applicability::MachineApplicable,
884 &ty::RawPtr(TypeAndMut { ty: ty_b, mutbl: mutbl_b }),
885 &ty::Ref(_, ty_a, mutbl_a),
887 if let Some(steps) = self.deref_steps(ty_a, ty_b)
888 // Only suggest valid if dereferencing needed.
890 // The pointer type implements `Copy` trait so the suggestion is always valid.
891 && let Ok(src) = sm.span_to_snippet(sp)
893 let derefs = "*".repeat(steps);
894 if let Some((span, src, applicability)) = match mutbl_b {
895 hir::Mutability::Mut => {
896 let new_prefix = "&mut ".to_owned() + &derefs;
898 hir::Mutability::Mut => {
899 replace_prefix(&src, "&mut ", &new_prefix).map(|_| {
900 let pos = sp.lo() + BytePos(5);
901 let sp = sp.with_lo(pos).with_hi(pos);
902 (sp, derefs, Applicability::MachineApplicable)
905 hir::Mutability::Not => {
906 replace_prefix(&src, "&", &new_prefix).map(|_| {
907 let pos = sp.lo() + BytePos(1);
908 let sp = sp.with_lo(pos).with_hi(pos);
911 format!("mut {derefs}"),
912 Applicability::Unspecified,
918 hir::Mutability::Not => {
919 let new_prefix = "&".to_owned() + &derefs;
921 hir::Mutability::Mut => {
922 replace_prefix(&src, "&mut ", &new_prefix).map(|_| {
923 let lo = sp.lo() + BytePos(1);
924 let hi = sp.lo() + BytePos(5);
925 let sp = sp.with_lo(lo).with_hi(hi);
926 (sp, derefs, Applicability::MachineApplicable)
929 hir::Mutability::Not => {
930 replace_prefix(&src, "&", &new_prefix).map(|_| {
931 let pos = sp.lo() + BytePos(1);
932 let sp = sp.with_lo(pos).with_hi(pos);
933 (sp, derefs, Applicability::MachineApplicable)
941 "consider dereferencing".to_string(),
949 _ if sp == expr.span => {
950 if let Some(mut steps) = self.deref_steps(checked_ty, expected) {
951 let mut expr = expr.peel_blocks();
952 let mut prefix_span = expr.span.shrink_to_lo();
953 let mut remove = String::new();
955 // Try peeling off any existing `&` and `&mut` to reach our target type
957 if let hir::ExprKind::AddrOf(_, mutbl, inner) = expr.kind {
958 // If the expression has `&`, removing it would fix the error
959 prefix_span = prefix_span.with_hi(inner.span.lo());
961 remove += match mutbl {
962 hir::Mutability::Not => "&",
963 hir::Mutability::Mut => "&mut ",
970 // If we've reached our target type with just removing `&`, then just print now.
974 format!("consider removing the `{}`", remove.trim()),
976 // Do not remove `&&` to get to bool, because it might be something like
977 // { a } && b, which we have a separate fixup suggestion that is more
979 if remove.trim() == "&&" && expected == self.tcx.types.bool {
980 Applicability::MaybeIncorrect
982 Applicability::MachineApplicable
988 // For this suggestion to make sense, the type would need to be `Copy`,
989 // or we have to be moving out of a `Box<T>`
990 if self.type_is_copy_modulo_regions(self.param_env, expected, sp)
991 // FIXME(compiler-errors): We can actually do this if the checked_ty is
992 // `steps` layers of boxes, not just one, but this is easier and most likely.
993 || (checked_ty.is_box() && steps == 1)
995 let deref_kind = if checked_ty.is_box() {
997 } else if checked_ty.is_region_ptr() {
998 "dereferencing the borrow"
1000 "dereferencing the type"
1003 // Suggest removing `&` if we have removed any, otherwise suggest just
1004 // dereferencing the remaining number of steps.
1005 let message = if remove.is_empty() {
1006 format!("consider {deref_kind}")
1009 "consider removing the `{}` and {} instead",
1015 let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
1016 Some(ident) => format!("{ident}: "),
1017 None => String::new(),
1020 let (span, suggestion) = if self.is_else_if_block(expr) {
1021 // Don't suggest nonsense like `else *if`
1023 } else if let Some(expr) = self.maybe_get_block_expr(expr) {
1024 // prefix should be empty here..
1025 (expr.span.shrink_to_lo(), "*".to_string())
1027 (prefix_span, format!("{}{}", prefix, "*".repeat(steps)))
1034 Applicability::MachineApplicable,
1045 pub fn check_for_cast(
1047 err: &mut Diagnostic,
1048 expr: &hir::Expr<'_>,
1049 checked_ty: Ty<'tcx>,
1050 expected_ty: Ty<'tcx>,
1051 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
1053 if self.tcx.sess.source_map().is_imported(expr.span) {
1054 // Ignore if span is from within a macro.
1058 let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) else {
1062 // If casting this expression to a given numeric type would be appropriate in case of a type
1065 // We want to minimize the amount of casting operations that are suggested, as it can be a
1066 // lossy operation with potentially bad side effects, so we only suggest when encountering
1067 // an expression that indicates that the original type couldn't be directly changed.
1069 // For now, don't suggest casting with `as`.
1070 let can_cast = false;
1072 let mut sugg = vec![];
1074 if let Some(hir::Node::Expr(hir::Expr {
1075 kind: hir::ExprKind::Struct(_, fields, _), ..
1076 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
1078 // `expr` is a literal field for a struct, only suggest if appropriate
1081 .find(|field| field.expr.hir_id == expr.hir_id && field.is_shorthand)
1083 // This is a field literal
1085 sugg.push((field.ident.span.shrink_to_lo(), format!("{}: ", field.ident)));
1087 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
1088 None => return false,
1092 if let hir::ExprKind::Call(path, args) = &expr.kind
1093 && let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
1094 (&path.kind, args.len())
1095 // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
1096 && let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
1097 (&base_ty.kind, path_segment.ident.name)
1099 if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
1113 if base_ty_path.segments.len() == 1 =>
1123 "you can convert {} `{}` to {} `{}`",
1124 checked_ty.kind().article(),
1126 expected_ty.kind().article(),
1129 let cast_msg = format!(
1130 "you can cast {} `{}` to {} `{}`",
1131 checked_ty.kind().article(),
1133 expected_ty.kind().article(),
1136 let lit_msg = format!(
1137 "change the type of the numeric literal from `{checked_ty}` to `{expected_ty}`",
1140 let close_paren = if expr.precedence().order() < PREC_POSTFIX {
1141 sugg.push((expr.span.shrink_to_lo(), "(".to_string()));
1147 let mut cast_suggestion = sugg.clone();
1148 cast_suggestion.push((expr.span.shrink_to_hi(), format!("{close_paren} as {expected_ty}")));
1149 let mut into_suggestion = sugg.clone();
1150 into_suggestion.push((expr.span.shrink_to_hi(), format!("{close_paren}.into()")));
1151 let mut suffix_suggestion = sugg.clone();
1152 suffix_suggestion.push((
1154 (&expected_ty.kind(), &checked_ty.kind()),
1155 (ty::Int(_) | ty::Uint(_), ty::Float(_))
1157 // Remove fractional part from literal, for example `42.0f32` into `42`
1158 let src = src.trim_end_matches(&checked_ty.to_string());
1159 let len = src.split('.').next().unwrap().len();
1160 expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
1162 let len = src.trim_end_matches(&checked_ty.to_string()).len();
1163 expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
1165 if expr.precedence().order() < PREC_POSTFIX {
1167 format!("{expected_ty})")
1169 expected_ty.to_string()
1172 let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
1173 if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
1175 let is_negative_int =
1176 |expr: &hir::Expr<'_>| matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::Neg, ..));
1177 let is_uint = |ty: Ty<'_>| matches!(ty.kind(), ty::Uint(..));
1179 let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id);
1181 let suggest_fallible_into_or_lhs_from =
1182 |err: &mut Diagnostic, exp_to_found_is_fallible: bool| {
1183 // If we know the expression the expected type is derived from, we might be able
1184 // to suggest a widening conversion rather than a narrowing one (which may
1185 // panic). For example, given x: u8 and y: u32, if we know the span of "x",
1187 // can be given the suggestion "u32::from(x) > y" rather than
1188 // "x > y.try_into().unwrap()".
1189 let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
1193 .span_to_snippet(expr.span)
1195 .map(|src| (expr, src))
1197 let (msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
1198 (lhs_expr_and_src, exp_to_found_is_fallible)
1201 "you can convert `{lhs_src}` from `{expected_ty}` to `{checked_ty}`, matching the type of `{src}`",
1203 let suggestion = vec![
1204 (lhs_expr.span.shrink_to_lo(), format!("{checked_ty}::from(")),
1205 (lhs_expr.span.shrink_to_hi(), ")".to_string()),
1209 let msg = format!("{msg} and panic if the converted value doesn't fit");
1210 let mut suggestion = sugg.clone();
1212 expr.span.shrink_to_hi(),
1213 format!("{close_paren}.try_into().unwrap()"),
1217 err.multipart_suggestion_verbose(
1220 Applicability::MachineApplicable,
1224 let suggest_to_change_suffix_or_into =
1225 |err: &mut Diagnostic,
1226 found_to_exp_is_fallible: bool,
1227 exp_to_found_is_fallible: bool| {
1229 expected_ty_expr.map(|e| self.tcx.hir().is_lhs(e.hir_id)).unwrap_or(false);
1235 let always_fallible = found_to_exp_is_fallible
1236 && (exp_to_found_is_fallible || expected_ty_expr.is_none());
1237 let msg = if literal_is_ty_suffixed(expr) {
1239 } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
1240 // We now know that converting either the lhs or rhs is fallible. Before we
1241 // suggest a fallible conversion, check if the value can never fit in the
1243 let msg = format!("`{src}` cannot fit into type `{expected_ty}`");
1246 } else if in_const_context {
1247 // Do not recommend `into` or `try_into` in const contexts.
1249 } else if found_to_exp_is_fallible {
1250 return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
1254 let suggestion = if literal_is_ty_suffixed(expr) {
1255 suffix_suggestion.clone()
1257 into_suggestion.clone()
1259 err.multipart_suggestion_verbose(msg, suggestion, Applicability::MachineApplicable);
1262 match (&expected_ty.kind(), &checked_ty.kind()) {
1263 (&ty::Int(ref exp), &ty::Int(ref found)) => {
1264 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1266 (Some(exp), Some(found)) if exp < found => (true, false),
1267 (Some(exp), Some(found)) if exp > found => (false, true),
1268 (None, Some(8 | 16)) => (false, true),
1269 (Some(8 | 16), None) => (true, false),
1270 (None, _) | (_, None) => (true, true),
1271 _ => (false, false),
1273 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1276 (&ty::Uint(ref exp), &ty::Uint(ref found)) => {
1277 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1279 (Some(exp), Some(found)) if exp < found => (true, false),
1280 (Some(exp), Some(found)) if exp > found => (false, true),
1281 (None, Some(8 | 16)) => (false, true),
1282 (Some(8 | 16), None) => (true, false),
1283 (None, _) | (_, None) => (true, true),
1284 _ => (false, false),
1286 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1289 (&ty::Int(exp), &ty::Uint(found)) => {
1290 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1292 (Some(exp), Some(found)) if found < exp => (false, true),
1293 (None, Some(8)) => (false, true),
1296 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1299 (&ty::Uint(exp), &ty::Int(found)) => {
1300 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
1302 (Some(exp), Some(found)) if found > exp => (true, false),
1303 (Some(8), None) => (true, false),
1306 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
1309 (&ty::Float(ref exp), &ty::Float(ref found)) => {
1310 if found.bit_width() < exp.bit_width() {
1311 suggest_to_change_suffix_or_into(err, false, true);
1312 } else if literal_is_ty_suffixed(expr) {
1313 err.multipart_suggestion_verbose(
1316 Applicability::MachineApplicable,
1318 } else if can_cast {
1319 // Missing try_into implementation for `f64` to `f32`
1320 err.multipart_suggestion_verbose(
1321 &format!("{cast_msg}, producing the closest possible value"),
1323 Applicability::MaybeIncorrect, // lossy conversion
1328 (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
1329 if literal_is_ty_suffixed(expr) {
1330 err.multipart_suggestion_verbose(
1333 Applicability::MachineApplicable,
1335 } else if can_cast {
1336 // Missing try_into implementation for `{float}` to `{integer}`
1337 err.multipart_suggestion_verbose(
1338 &format!("{msg}, rounding the float towards zero"),
1340 Applicability::MaybeIncorrect, // lossy conversion
1345 (&ty::Float(ref exp), &ty::Uint(ref found)) => {
1346 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
1347 if exp.bit_width() > found.bit_width().unwrap_or(256) {
1348 err.multipart_suggestion_verbose(
1350 "{msg}, producing the floating point representation of the integer",
1353 Applicability::MachineApplicable,
1355 } else if literal_is_ty_suffixed(expr) {
1356 err.multipart_suggestion_verbose(
1359 Applicability::MachineApplicable,
1362 // Missing try_into implementation for `{integer}` to `{float}`
1363 err.multipart_suggestion_verbose(
1365 "{cast_msg}, producing the floating point representation of the integer, \
1366 rounded if necessary",
1369 Applicability::MaybeIncorrect, // lossy conversion
1374 (&ty::Float(ref exp), &ty::Int(ref found)) => {
1375 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
1376 if exp.bit_width() > found.bit_width().unwrap_or(256) {
1377 err.multipart_suggestion_verbose(
1379 "{}, producing the floating point representation of the integer",
1383 Applicability::MachineApplicable,
1385 } else if literal_is_ty_suffixed(expr) {
1386 err.multipart_suggestion_verbose(
1389 Applicability::MachineApplicable,
1392 // Missing try_into implementation for `{integer}` to `{float}`
1393 err.multipart_suggestion_verbose(
1395 "{}, producing the floating point representation of the integer, \
1396 rounded if necessary",
1400 Applicability::MaybeIncorrect, // lossy conversion
1406 &ty::Uint(ty::UintTy::U32 | ty::UintTy::U64 | ty::UintTy::U128)
1407 | &ty::Int(ty::IntTy::I32 | ty::IntTy::I64 | ty::IntTy::I128),
1410 err.multipart_suggestion_verbose(
1411 &format!("{cast_msg}, since a `char` always occupies 4 bytes"),
1413 Applicability::MachineApplicable,