1 use crate::check::FnCtxt;
2 use rustc_infer::infer::InferOk;
3 use rustc_trait_selection::infer::InferCtxtExt as _;
4 use rustc_trait_selection::traits::ObligationCause;
6 use rustc_ast::util::parser::PREC_POSTFIX;
7 use rustc_errors::{Applicability, DiagnosticBuilder};
9 use rustc_hir::lang_items::LangItem;
10 use rustc_hir::{is_range_literal, Node};
11 use rustc_middle::ty::adjustment::AllowTwoPhase;
12 use rustc_middle::ty::{self, AssocItem, Ty, TypeAndMut};
13 use rustc_span::symbol::sym;
16 use super::method::probe;
20 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
21 pub fn emit_coerce_suggestions(
23 err: &mut DiagnosticBuilder<'_>,
27 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
29 self.annotate_expected_due_to_let_ty(err, expr);
30 self.suggest_compatible_variants(err, expr, expected, expr_ty);
31 self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr);
32 if self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty) {
35 self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty);
36 self.suggest_missing_await(err, expr, expected, expr_ty);
37 self.suggest_missing_parentheses(err, expr);
38 self.note_need_for_fn_pointer(err, expected, expr_ty);
39 self.note_internal_mutation_in_method(err, expr, expected, expr_ty);
42 // Requires that the two types unify, and prints an error message if
44 pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
45 if let Some(mut e) = self.demand_suptype_diag(sp, expected, actual) {
50 pub fn demand_suptype_diag(
55 ) -> Option<DiagnosticBuilder<'tcx>> {
56 self.demand_suptype_with_origin(&self.misc(sp), expected, actual)
59 pub fn demand_suptype_with_origin(
61 cause: &ObligationCause<'tcx>,
64 ) -> Option<DiagnosticBuilder<'tcx>> {
65 match self.at(cause, self.param_env).sup(expected, actual) {
66 Ok(InferOk { obligations, value: () }) => {
67 self.register_predicates(obligations);
70 Err(e) => Some(self.report_mismatched_types(&cause, expected, actual, e)),
74 pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
75 if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
80 pub fn demand_eqtype_diag(
85 ) -> Option<DiagnosticBuilder<'tcx>> {
86 self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
89 pub fn demand_eqtype_with_origin(
91 cause: &ObligationCause<'tcx>,
94 ) -> Option<DiagnosticBuilder<'tcx>> {
95 match self.at(cause, self.param_env).eq(expected, actual) {
96 Ok(InferOk { obligations, value: () }) => {
97 self.register_predicates(obligations);
100 Err(e) => Some(self.report_mismatched_types(cause, expected, actual, e)),
104 pub fn demand_coerce(
106 expr: &hir::Expr<'_>,
107 checked_ty: Ty<'tcx>,
109 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
110 allow_two_phase: AllowTwoPhase,
113 self.demand_coerce_diag(expr, checked_ty, expected, expected_ty_expr, allow_two_phase);
114 if let Some(mut err) = err {
120 // Checks that the type of `expr` can be coerced to `expected`.
122 // N.B., this code relies on `self.diverges` to be accurate. In
123 // particular, assignments to `!` will be permitted if the
124 // diverges flag is currently "always".
125 pub fn demand_coerce_diag(
127 expr: &hir::Expr<'_>,
128 checked_ty: Ty<'tcx>,
130 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
131 allow_two_phase: AllowTwoPhase,
132 ) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx>>) {
133 let expected = self.resolve_vars_with_obligations(expected);
135 let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase) {
136 Ok(ty) => return (ty, None),
140 let expr = expr.peel_drop_temps();
141 let cause = self.misc(expr.span);
142 let expr_ty = self.resolve_vars_with_obligations(checked_ty);
143 let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e);
145 if self.is_assign_to_bool(expr, expected) {
146 // Error reported in `check_assign` so avoid emitting error again.
148 return (expected, None);
151 self.emit_coerce_suggestions(&mut err, expr, expr_ty, expected, expected_ty_expr);
153 (expected, Some(err))
156 fn annotate_expected_due_to_let_ty(
158 err: &mut DiagnosticBuilder<'_>,
159 expr: &hir::Expr<'_>,
161 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
162 if let Some(hir::Node::Local(hir::Local { ty: Some(ty), init: Some(init), .. })) =
163 self.tcx.hir().find(parent)
165 if init.hir_id == expr.hir_id {
166 // Point at `let` assignment type.
167 err.span_label(ty.span, "expected due to this");
172 /// Returns whether the expected type is `bool` and the expression is `x = y`.
173 pub fn is_assign_to_bool(&self, expr: &hir::Expr<'_>, expected: Ty<'tcx>) -> bool {
174 if let hir::ExprKind::Assign(..) = expr.kind {
175 return expected == self.tcx.types.bool;
180 /// If the expected type is an enum (Issue #55250) with any variants whose
181 /// sole field is of the found type, suggest such variants. (Issue #42764)
182 fn suggest_compatible_variants(
184 err: &mut DiagnosticBuilder<'_>,
185 expr: &hir::Expr<'_>,
189 if let ty::Adt(expected_adt, substs) = expected.kind {
190 if !expected_adt.is_enum() {
194 let mut compatible_variants = expected_adt
197 .filter(|variant| variant.fields.len() == 1)
198 .filter_map(|variant| {
199 let sole_field = &variant.fields[0];
200 let sole_field_ty = sole_field.ty(self.tcx, substs);
201 if self.can_coerce(expr_ty, sole_field_ty) {
202 let variant_path = self.tcx.def_path_str(variant.def_id);
203 // FIXME #56861: DRYer prelude filtering
204 Some(variant_path.trim_start_matches("std::prelude::v1::").to_string())
211 if compatible_variants.peek().is_some() {
212 if let Ok(expr_text) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
213 let suggestions = compatible_variants.map(|v| format!("{}({})", v, expr_text));
214 let msg = "try using a variant of the expected enum";
215 err.span_suggestions(
219 Applicability::MaybeIncorrect,
226 pub fn get_conversion_methods(
230 checked_ty: Ty<'tcx>,
232 ) -> Vec<AssocItem> {
234 self.probe_for_return_type(span, probe::Mode::MethodCall, expected, checked_ty, hir_id);
236 self.has_only_self_parameter(m)
241 // This special internal attribute is used to permit
242 // "identity-like" conversion methods to be suggested here.
244 // FIXME (#46459 and #46460): ideally
245 // `std::convert::Into::into` and `std::borrow:ToOwned` would
246 // also be `#[rustc_conversion_suggestion]`, if not for
247 // method-probing false-positives and -negatives (respectively).
249 // FIXME? Other potential candidate methods: `as_ref` and
251 .any(|a| self.sess().check_name(a, sym::rustc_conversion_suggestion))
257 /// This function checks whether the method is not static and does not accept other parameters than `self`.
258 fn has_only_self_parameter(&self, method: &AssocItem) -> bool {
260 ty::AssocKind::Fn => {
261 method.fn_has_self_parameter
262 && self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1
268 /// Identify some cases where `as_ref()` would be appropriate and suggest it.
270 /// Given the following code:
273 /// fn takes_ref(_: &Foo) {}
274 /// let ref opt = Some(Foo);
276 /// opt.map(|param| takes_ref(param));
278 /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
280 /// It only checks for `Option` and `Result` and won't work with
282 /// opt.map(|param| { takes_ref(param) });
284 fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Span, &'static str, String)> {
285 let path = match expr.kind {
286 hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => path,
290 let local_id = match path.res {
291 hir::def::Res::Local(id) => id,
295 let local_parent = self.tcx.hir().get_parent_node(local_id);
296 let param_hir_id = match self.tcx.hir().find(local_parent) {
297 Some(Node::Param(hir::Param { hir_id, .. })) => hir_id,
301 let param_parent = self.tcx.hir().get_parent_node(*param_hir_id);
302 let (expr_hir_id, closure_fn_decl) = match self.tcx.hir().find(param_parent) {
303 Some(Node::Expr(hir::Expr {
305 kind: hir::ExprKind::Closure(_, decl, ..),
307 })) => (hir_id, decl),
311 let expr_parent = self.tcx.hir().get_parent_node(*expr_hir_id);
312 let hir = self.tcx.hir().find(expr_parent);
313 let closure_params_len = closure_fn_decl.inputs.len();
314 let (method_path, method_span, method_expr) = match (hir, closure_params_len) {
316 Some(Node::Expr(hir::Expr {
317 kind: hir::ExprKind::MethodCall(path, span, expr, _),
321 ) => (path, span, expr),
325 let self_ty = self.typeck_results.borrow().node_type(method_expr[0].hir_id);
326 let self_ty = format!("{:?}", self_ty);
327 let name = method_path.ident.name;
328 let is_as_ref_able = (self_ty.starts_with("&std::option::Option")
329 || self_ty.starts_with("&std::result::Result")
330 || self_ty.starts_with("std::option::Option")
331 || self_ty.starts_with("std::result::Result"))
332 && (name == sym::map || name == sym::and_then);
333 match (is_as_ref_able, self.sess().source_map().span_to_snippet(*method_span)) {
335 let suggestion = format!("as_ref().{}", src);
336 Some((*method_span, "consider using `as_ref` instead", suggestion))
342 crate fn is_hir_id_from_struct_pattern_shorthand_field(
347 let sm = self.sess().source_map();
348 let parent_id = self.tcx.hir().get_parent_node(hir_id);
349 if let Some(parent) = self.tcx.hir().find(parent_id) {
350 // Account for fields
351 if let Node::Expr(hir::Expr { kind: hir::ExprKind::Struct(_, fields, ..), .. }) = parent
353 if let Ok(src) = sm.span_to_snippet(sp) {
354 for field in *fields {
355 if field.ident.as_str() == src && field.is_shorthand {
365 fn replace_prefix<A, B, C>(&self, s: A, old: B, new: C) -> Option<String>
372 let old = old.as_ref();
373 if s.starts_with(old) { Some(new.as_ref().to_owned() + &s[old.len()..]) } else { None }
376 /// This function is used to determine potential "simple" improvements or users' errors and
377 /// provide them useful help. For example:
380 /// fn some_fn(s: &str) {}
382 /// let x = "hey!".to_owned();
383 /// some_fn(x); // error
386 /// No need to find every potential function which could make a coercion to transform a
387 /// `String` into a `&str` since a `&` would do the trick!
389 /// In addition of this check, it also checks between references mutability state. If the
390 /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
394 expr: &hir::Expr<'_>,
395 checked_ty: Ty<'tcx>,
397 ) -> Option<(Span, &'static str, String, Applicability)> {
398 let sm = self.sess().source_map();
400 if sm.is_imported(sp) {
401 // Ignore if span is from within a macro #41858, #58298. We previously used the macro
402 // call span, but that breaks down when the type error comes from multiple calls down.
406 let is_struct_pat_shorthand_field =
407 self.is_hir_id_from_struct_pattern_shorthand_field(expr.hir_id, sp);
409 // If the span is from a macro, then it's hard to extract the text
410 // and make a good suggestion, so don't bother.
411 let is_macro = sp.from_expansion() && sp.desugaring_kind().is_none();
413 // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
414 let expr = expr.peel_drop_temps();
416 match (&expr.kind, &expected.kind, &checked_ty.kind) {
417 (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (&exp.kind, &check.kind) {
418 (&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
419 if let hir::ExprKind::Lit(_) = expr.kind {
420 if let Ok(src) = sm.span_to_snippet(sp) {
421 if let Some(src) = self.replace_prefix(src, "b\"", "\"") {
424 "consider removing the leading `b`",
426 Applicability::MachineApplicable,
432 (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
433 if let hir::ExprKind::Lit(_) = expr.kind {
434 if let Ok(src) = sm.span_to_snippet(sp) {
435 if let Some(src) = self.replace_prefix(src, "\"", "b\"") {
438 "consider adding a leading `b`",
440 Applicability::MachineApplicable,
448 (_, &ty::Ref(_, _, mutability), _) => {
449 // Check if it can work when put into a ref. For example:
452 // fn bar(x: &mut i32) {}
455 // bar(&x); // error, expected &mut
457 let ref_ty = match mutability {
458 hir::Mutability::Mut => {
459 self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
461 hir::Mutability::Not => {
462 self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
465 if self.can_coerce(ref_ty, expected) {
466 let mut sugg_sp = sp;
467 if let hir::ExprKind::MethodCall(ref segment, sp, ref args, _) = expr.kind {
468 let clone_trait = self.tcx.require_lang_item(LangItem::Clone, Some(sp));
469 if let ([arg], Some(true), sym::clone) = (
471 self.typeck_results.borrow().type_dependent_def_id(expr.hir_id).map(
473 let ai = self.tcx.associated_item(did);
474 ai.container == ty::TraitContainer(clone_trait)
479 // If this expression had a clone call when suggesting borrowing
480 // we want to suggest removing it because it'd now be unnecessary.
484 if let Ok(src) = sm.span_to_snippet(sugg_sp) {
485 let needs_parens = match expr.kind {
486 // parenthesize if needed (Issue #46756)
487 hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true,
488 // parenthesize borrows of range literals (Issue #54505)
489 _ if is_range_literal(expr) => true,
492 let sugg_expr = if needs_parens { format!("({})", src) } else { src };
494 if let Some(sugg) = self.can_use_as_ref(expr) {
499 Applicability::MachineApplicable,
502 let field_name = if is_struct_pat_shorthand_field {
503 format!("{}: ", sugg_expr)
507 if let Some(hir::Node::Expr(hir::Expr {
508 kind: hir::ExprKind::Assign(left_expr, ..),
510 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
512 if mutability == hir::Mutability::Mut {
513 // Found the following case:
514 // fn foo(opt: &mut Option<String>){ opt = None }
517 // consider dereferencing here: `*opt` |
518 // expected mutable reference, found enum `Option`
519 if let Ok(src) = sm.span_to_snippet(left_expr.span) {
522 "consider dereferencing here to assign to the mutable \
523 borrowed piece of memory",
525 Applicability::MachineApplicable,
531 return Some(match mutability {
532 hir::Mutability::Mut => (
534 "consider mutably borrowing here",
535 format!("{}&mut {}", field_name, sugg_expr),
536 Applicability::MachineApplicable,
538 hir::Mutability::Not => (
540 "consider borrowing here",
541 format!("{}&{}", field_name, sugg_expr),
542 Applicability::MachineApplicable,
549 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
551 &ty::Ref(_, checked, _),
553 self.infcx.can_sub(self.param_env, checked, &expected).is_ok() && !is_macro
556 // We have `&T`, check if what was expected was `T`. If so,
557 // we may want to suggest removing a `&`.
558 if sm.is_imported(expr.span) {
559 if let Ok(src) = sm.span_to_snippet(sp) {
560 if let Some(src) = self.replace_prefix(src, "&", "") {
563 "consider removing the borrow",
565 Applicability::MachineApplicable,
571 if let Ok(code) = sm.span_to_snippet(expr.span) {
574 "consider removing the borrow",
576 Applicability::MachineApplicable,
582 &ty::RawPtr(TypeAndMut { ty: ty_b, mutbl: mutbl_b }),
583 &ty::Ref(_, ty_a, mutbl_a),
585 if let Some(steps) = self.deref_steps(ty_a, ty_b) {
586 // Only suggest valid if dereferencing needed.
588 // The pointer type implements `Copy` trait so the suggestion is always valid.
589 if let Ok(src) = sm.span_to_snippet(sp) {
590 let derefs = &"*".repeat(steps);
591 if let Some((src, applicability)) = match mutbl_b {
592 hir::Mutability::Mut => {
593 let new_prefix = "&mut ".to_owned() + derefs;
595 hir::Mutability::Mut => {
597 self.replace_prefix(src, "&mut ", new_prefix)
599 Some((s, Applicability::MachineApplicable))
604 hir::Mutability::Not => {
606 self.replace_prefix(src, "&", new_prefix)
608 Some((s, Applicability::Unspecified))
615 hir::Mutability::Not => {
616 let new_prefix = "&".to_owned() + derefs;
618 hir::Mutability::Mut => {
620 self.replace_prefix(src, "&mut ", new_prefix)
622 Some((s, Applicability::MachineApplicable))
627 hir::Mutability::Not => {
629 self.replace_prefix(src, "&", new_prefix)
631 Some((s, Applicability::MachineApplicable))
639 return Some((sp, "consider dereferencing", src, applicability));
645 _ if sp == expr.span && !is_macro => {
646 if let Some(steps) = self.deref_steps(checked_ty, expected) {
648 // For a suggestion to make sense, the type would need to be `Copy`.
649 if self.infcx.type_is_copy_modulo_regions(self.param_env, expected, sp) {
650 if let Ok(code) = sm.span_to_snippet(sp) {
651 let message = if checked_ty.is_region_ptr() {
652 "consider dereferencing the borrow"
654 "consider dereferencing the type"
656 let suggestion = if is_struct_pat_shorthand_field {
657 format!("{}: *{}", code, code)
665 Applicability::MachineApplicable,
677 pub fn check_for_cast(
679 err: &mut DiagnosticBuilder<'_>,
680 expr: &hir::Expr<'_>,
681 checked_ty: Ty<'tcx>,
682 expected_ty: Ty<'tcx>,
683 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
685 if self.tcx.sess.source_map().is_imported(expr.span) {
686 // Ignore if span is from within a macro.
690 let src = if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
696 // If casting this expression to a given numeric type would be appropriate in case of a type
699 // We want to minimize the amount of casting operations that are suggested, as it can be a
700 // lossy operation with potentially bad side effects, so we only suggest when encountering
701 // an expression that indicates that the original type couldn't be directly changed.
703 // For now, don't suggest casting with `as`.
704 let can_cast = false;
706 let prefix = if let Some(hir::Node::Expr(hir::Expr {
707 kind: hir::ExprKind::Struct(_, fields, _),
709 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
711 // `expr` is a literal field for a struct, only suggest if appropriate
714 .find(|field| field.expr.hir_id == expr.hir_id && field.is_shorthand)
716 // This is a field literal
717 Some(field) => format!("{}: ", field.ident),
718 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
719 None => return false,
725 if let hir::ExprKind::Call(path, args) = &expr.kind {
726 if let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
727 (&path.kind, args.len())
729 // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
730 if let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
731 (&base_ty.kind, path_segment.ident.name)
733 if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
747 if base_ty_path.segments.len() == 1 =>
758 let msg = format!("you can convert an `{}` to `{}`", checked_ty, expected_ty);
759 let cast_msg = format!("you can cast an `{} to `{}`", checked_ty, expected_ty);
760 let lit_msg = format!(
761 "change the type of the numeric literal from `{}` to `{}`",
762 checked_ty, expected_ty,
765 let with_opt_paren: fn(&dyn fmt::Display) -> String =
766 if expr.precedence().order() < PREC_POSTFIX {
767 |s| format!("({})", s)
772 let cast_suggestion = format!("{}{} as {}", prefix, with_opt_paren(&src), expected_ty);
773 let into_suggestion = format!("{}{}.into()", prefix, with_opt_paren(&src));
774 let suffix_suggestion = with_opt_paren(&format_args!(
777 (&expected_ty.kind, &checked_ty.kind),
778 (ty::Int(_) | ty::Uint(_), ty::Float(_))
780 // Remove fractional part from literal, for example `42.0f32` into `42`
781 let src = src.trim_end_matches(&checked_ty.to_string());
782 src.split('.').next().unwrap()
784 src.trim_end_matches(&checked_ty.to_string())
788 let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
789 if let hir::ExprKind::Lit(lit) = &expr.kind { lit.node.is_suffixed() } else { false }
791 let is_negative_int =
792 |expr: &hir::Expr<'_>| matches!(expr.kind, hir::ExprKind::Unary(hir::UnOp::UnNeg, ..));
793 let is_uint = |ty: Ty<'_>| matches!(ty.kind, ty::Uint(..));
795 let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id);
797 let suggest_fallible_into_or_lhs_from =
798 |err: &mut DiagnosticBuilder<'_>, exp_to_found_is_fallible: bool| {
799 // If we know the expression the expected type is derived from, we might be able
800 // to suggest a widening conversion rather than a narrowing one (which may
801 // panic). For example, given x: u8 and y: u32, if we know the span of "x",
803 // can be given the suggestion "u32::from(x) > y" rather than
804 // "x > y.try_into().unwrap()".
805 let lhs_expr_and_src = expected_ty_expr.and_then(|expr| {
806 match self.tcx.sess.source_map().span_to_snippet(expr.span).ok() {
807 Some(src) => Some((expr, src)),
811 let (span, msg, suggestion) = if let (Some((lhs_expr, lhs_src)), false) =
812 (lhs_expr_and_src, exp_to_found_is_fallible)
815 "you can convert `{}` from `{}` to `{}`, matching the type of `{}`",
816 lhs_src, expected_ty, checked_ty, src
818 let suggestion = format!("{}::from({})", checked_ty, lhs_src);
819 (lhs_expr.span, msg, suggestion)
821 let msg = format!("{} and panic if the converted value wouldn't fit", msg);
823 format!("{}{}.try_into().unwrap()", prefix, with_opt_paren(&src));
824 (expr.span, msg, suggestion)
826 err.span_suggestion(span, &msg, suggestion, Applicability::MachineApplicable);
829 let suggest_to_change_suffix_or_into =
830 |err: &mut DiagnosticBuilder<'_>,
831 found_to_exp_is_fallible: bool,
832 exp_to_found_is_fallible: bool| {
833 let always_fallible = found_to_exp_is_fallible
834 && (exp_to_found_is_fallible || expected_ty_expr.is_none());
835 let msg = if literal_is_ty_suffixed(expr) {
837 } else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
838 // We now know that converting either the lhs or rhs is fallible. Before we
839 // suggest a fallible conversion, check if the value can never fit in the
841 let msg = format!("`{}` cannot fit into type `{}`", src, expected_ty);
844 } else if in_const_context {
845 // Do not recommend `into` or `try_into` in const contexts.
847 } else if found_to_exp_is_fallible {
848 return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
852 let suggestion = if literal_is_ty_suffixed(expr) {
853 suffix_suggestion.clone()
855 into_suggestion.clone()
857 err.span_suggestion(expr.span, msg, suggestion, Applicability::MachineApplicable);
860 match (&expected_ty.kind, &checked_ty.kind) {
861 (&ty::Int(ref exp), &ty::Int(ref found)) => {
862 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
864 (Some(exp), Some(found)) if exp < found => (true, false),
865 (Some(exp), Some(found)) if exp > found => (false, true),
866 (None, Some(8 | 16)) => (false, true),
867 (Some(8 | 16), None) => (true, false),
868 (None, _) | (_, None) => (true, true),
871 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
874 (&ty::Uint(ref exp), &ty::Uint(ref found)) => {
875 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
877 (Some(exp), Some(found)) if exp < found => (true, false),
878 (Some(exp), Some(found)) if exp > found => (false, true),
879 (None, Some(8 | 16)) => (false, true),
880 (Some(8 | 16), None) => (true, false),
881 (None, _) | (_, None) => (true, true),
884 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
887 (&ty::Int(exp), &ty::Uint(found)) => {
888 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
890 (Some(exp), Some(found)) if found < exp => (false, true),
891 (None, Some(8)) => (false, true),
894 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
897 (&ty::Uint(exp), &ty::Int(found)) => {
898 let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width())
900 (Some(exp), Some(found)) if found > exp => (true, false),
901 (Some(8), None) => (true, false),
904 suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible);
907 (&ty::Float(ref exp), &ty::Float(ref found)) => {
908 if found.bit_width() < exp.bit_width() {
909 suggest_to_change_suffix_or_into(err, false, true);
910 } else if literal_is_ty_suffixed(expr) {
915 Applicability::MachineApplicable,
918 // Missing try_into implementation for `f64` to `f32`
921 &format!("{}, producing the closest possible value", cast_msg),
923 Applicability::MaybeIncorrect, // lossy conversion
928 (&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
929 if literal_is_ty_suffixed(expr) {
934 Applicability::MachineApplicable,
937 // Missing try_into implementation for `{float}` to `{integer}`
940 &format!("{}, rounding the float towards zero", msg),
942 Applicability::MaybeIncorrect, // lossy conversion
947 (&ty::Float(ref exp), &ty::Uint(ref found)) => {
948 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
949 if exp.bit_width() > found.bit_width().unwrap_or(256) {
953 "{}, producing the floating point representation of the integer",
957 Applicability::MachineApplicable,
959 } else if literal_is_ty_suffixed(expr) {
964 Applicability::MachineApplicable,
967 // Missing try_into implementation for `{integer}` to `{float}`
971 "{}, producing the floating point representation of the integer,
972 rounded if necessary",
976 Applicability::MaybeIncorrect, // lossy conversion
981 (&ty::Float(ref exp), &ty::Int(ref found)) => {
982 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
983 if exp.bit_width() > found.bit_width().unwrap_or(256) {
987 "{}, producing the floating point representation of the integer",
991 Applicability::MachineApplicable,
993 } else if literal_is_ty_suffixed(expr) {
998 Applicability::MachineApplicable,
1001 // Missing try_into implementation for `{integer}` to `{float}`
1002 err.span_suggestion(
1005 "{}, producing the floating point representation of the integer, \
1006 rounded if necessary",
1010 Applicability::MaybeIncorrect, // lossy conversion