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::query::evaluate_obligation::InferCtxtExt as _;
5 use rustc_trait_selection::traits::{self, ObligationCause};
7 use rustc_ast::util::parser::PREC_POSTFIX;
8 use rustc_errors::{Applicability, DiagnosticBuilder};
10 use rustc_hir::{is_range_literal, Node};
11 use rustc_middle::ty::adjustment::AllowTwoPhase;
12 use rustc_middle::ty::{self, AssocItem, Ty};
13 use rustc_span::symbol::sym;
16 use super::method::probe;
18 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
19 pub fn emit_coerce_suggestions(
21 err: &mut DiagnosticBuilder<'_>,
26 self.annotate_expected_due_to_let_ty(err, expr);
27 self.suggest_compatible_variants(err, expr, expected, expr_ty);
28 self.suggest_ref_or_into(err, expr, expected, expr_ty);
29 if self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty) {
32 self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty);
33 self.suggest_missing_await(err, expr, expected, expr_ty);
36 // Requires that the two types unify, and prints an error message if
38 pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
39 self.demand_suptype_diag(sp, expected, actual).map(|mut e| e.emit());
42 pub fn demand_suptype_diag(
47 ) -> Option<DiagnosticBuilder<'tcx>> {
48 self.demand_suptype_with_origin(&self.misc(sp), expected, actual)
51 pub fn demand_suptype_with_origin(
53 cause: &ObligationCause<'tcx>,
56 ) -> Option<DiagnosticBuilder<'tcx>> {
57 match self.at(cause, self.param_env).sup(expected, actual) {
58 Ok(InferOk { obligations, value: () }) => {
59 self.register_predicates(obligations);
62 Err(e) => Some(self.report_mismatched_types(&cause, expected, actual, e)),
66 pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
67 if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
72 pub fn demand_eqtype_diag(
77 ) -> Option<DiagnosticBuilder<'tcx>> {
78 self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
81 pub fn demand_eqtype_with_origin(
83 cause: &ObligationCause<'tcx>,
86 ) -> Option<DiagnosticBuilder<'tcx>> {
87 match self.at(cause, self.param_env).eq(expected, actual) {
88 Ok(InferOk { obligations, value: () }) => {
89 self.register_predicates(obligations);
92 Err(e) => Some(self.report_mismatched_types(cause, expected, actual, e)),
101 allow_two_phase: AllowTwoPhase,
103 let (ty, err) = self.demand_coerce_diag(expr, checked_ty, expected, allow_two_phase);
104 if let Some(mut err) = err {
110 // Checks that the type of `expr` can be coerced to `expected`.
112 // N.B., this code relies on `self.diverges` to be accurate. In
113 // particular, assignments to `!` will be permitted if the
114 // diverges flag is currently "always".
115 pub fn demand_coerce_diag(
117 expr: &hir::Expr<'_>,
118 checked_ty: Ty<'tcx>,
120 allow_two_phase: AllowTwoPhase,
121 ) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx>>) {
122 let expected = self.resolve_vars_with_obligations(expected);
124 let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase) {
125 Ok(ty) => return (ty, None),
129 let expr = expr.peel_drop_temps();
130 let cause = self.misc(expr.span);
131 let expr_ty = self.resolve_vars_with_obligations(checked_ty);
132 let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e);
134 if self.is_assign_to_bool(expr, expected) {
135 // Error reported in `check_assign` so avoid emitting error again.
137 return (expected, None);
140 self.emit_coerce_suggestions(&mut err, expr, expr_ty, expected);
142 (expected, Some(err))
145 fn annotate_expected_due_to_let_ty(
147 err: &mut DiagnosticBuilder<'_>,
148 expr: &hir::Expr<'_>,
150 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
151 if let Some(hir::Node::Local(hir::Local { ty: Some(ty), init: Some(init), .. })) =
152 self.tcx.hir().find(parent)
154 if init.hir_id == expr.hir_id {
155 // Point at `let` assignment type.
156 err.span_label(ty.span, "expected due to this");
161 /// Returns whether the expected type is `bool` and the expression is `x = y`.
162 pub fn is_assign_to_bool(&self, expr: &hir::Expr<'_>, expected: Ty<'tcx>) -> bool {
163 if let hir::ExprKind::Assign(..) = expr.kind {
164 return expected == self.tcx.types.bool;
169 /// If the expected type is an enum (Issue #55250) with any variants whose
170 /// sole field is of the found type, suggest such variants. (Issue #42764)
171 fn suggest_compatible_variants(
173 err: &mut DiagnosticBuilder<'_>,
174 expr: &hir::Expr<'_>,
178 if let ty::Adt(expected_adt, substs) = expected.kind {
179 if !expected_adt.is_enum() {
183 let mut compatible_variants = expected_adt
186 .filter(|variant| variant.fields.len() == 1)
187 .filter_map(|variant| {
188 let sole_field = &variant.fields[0];
189 let sole_field_ty = sole_field.ty(self.tcx, substs);
190 if self.can_coerce(expr_ty, sole_field_ty) {
191 let variant_path = self.tcx.def_path_str(variant.def_id);
192 // FIXME #56861: DRYer prelude filtering
193 Some(variant_path.trim_start_matches("std::prelude::v1::").to_string())
200 if compatible_variants.peek().is_some() {
201 if let Ok(expr_text) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
202 let suggestions = compatible_variants.map(|v| format!("{}({})", v, expr_text));
203 let msg = "try using a variant of the expected enum";
204 err.span_suggestions(
208 Applicability::MaybeIncorrect,
215 pub fn get_conversion_methods(
219 checked_ty: Ty<'tcx>,
221 ) -> Vec<AssocItem> {
223 self.probe_for_return_type(span, probe::Mode::MethodCall, expected, checked_ty, hir_id);
225 self.has_no_input_arg(m)
230 // This special internal attribute is used to whitelist
231 // "identity-like" conversion methods to be suggested here.
233 // FIXME (#46459 and #46460): ideally
234 // `std::convert::Into::into` and `std::borrow:ToOwned` would
235 // also be `#[rustc_conversion_suggestion]`, if not for
236 // method-probing false-positives and -negatives (respectively).
238 // FIXME? Other potential candidate methods: `as_ref` and
240 .any(|a| a.check_name(sym::rustc_conversion_suggestion))
246 // This function checks if the method isn't static and takes other arguments than `self`.
247 fn has_no_input_arg(&self, method: &AssocItem) -> bool {
249 ty::AssocKind::Fn => self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1,
254 /// Identify some cases where `as_ref()` would be appropriate and suggest it.
256 /// Given the following code:
259 /// fn takes_ref(_: &Foo) {}
260 /// let ref opt = Some(Foo);
262 /// opt.map(|param| takes_ref(param));
264 /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
266 /// It only checks for `Option` and `Result` and won't work with
268 /// opt.map(|param| { takes_ref(param) });
270 fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Span, &'static str, String)> {
271 let path = match expr.kind {
272 hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => path,
276 let local_id = match path.res {
277 hir::def::Res::Local(id) => id,
281 let local_parent = self.tcx.hir().get_parent_node(local_id);
282 let param_hir_id = match self.tcx.hir().find(local_parent) {
283 Some(Node::Param(hir::Param { hir_id, .. })) => hir_id,
287 let param_parent = self.tcx.hir().get_parent_node(*param_hir_id);
288 let (expr_hir_id, closure_fn_decl) = match self.tcx.hir().find(param_parent) {
289 Some(Node::Expr(hir::Expr {
291 kind: hir::ExprKind::Closure(_, decl, ..),
293 })) => (hir_id, decl),
297 let expr_parent = self.tcx.hir().get_parent_node(*expr_hir_id);
298 let hir = self.tcx.hir().find(expr_parent);
299 let closure_params_len = closure_fn_decl.inputs.len();
300 let (method_path, method_span, method_expr) = match (hir, closure_params_len) {
302 Some(Node::Expr(hir::Expr {
303 kind: hir::ExprKind::MethodCall(path, span, expr),
307 ) => (path, span, expr),
311 let self_ty = self.tables.borrow().node_type(method_expr[0].hir_id);
312 let self_ty = format!("{:?}", self_ty);
313 let name = method_path.ident.as_str();
314 let is_as_ref_able = (self_ty.starts_with("&std::option::Option")
315 || self_ty.starts_with("&std::result::Result")
316 || self_ty.starts_with("std::option::Option")
317 || self_ty.starts_with("std::result::Result"))
318 && (name == "map" || name == "and_then");
319 match (is_as_ref_able, self.sess().source_map().span_to_snippet(*method_span)) {
321 let suggestion = format!("as_ref().{}", src);
322 Some((*method_span, "consider using `as_ref` instead", suggestion))
328 crate fn is_hir_id_from_struct_pattern_shorthand_field(
333 let sm = self.sess().source_map();
334 let parent_id = self.tcx.hir().get_parent_node(hir_id);
335 if let Some(parent) = self.tcx.hir().find(parent_id) {
336 // Account for fields
337 if let Node::Expr(hir::Expr { kind: hir::ExprKind::Struct(_, fields, ..), .. }) = parent
339 if let Ok(src) = sm.span_to_snippet(sp) {
340 for field in *fields {
341 if field.ident.as_str() == src && field.is_shorthand {
351 /// This function is used to determine potential "simple" improvements or users' errors and
352 /// provide them useful help. For example:
355 /// fn some_fn(s: &str) {}
357 /// let x = "hey!".to_owned();
358 /// some_fn(x); // error
361 /// No need to find every potential function which could make a coercion to transform a
362 /// `String` into a `&str` since a `&` would do the trick!
364 /// In addition of this check, it also checks between references mutability state. If the
365 /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
369 expr: &hir::Expr<'_>,
370 checked_ty: Ty<'tcx>,
372 ) -> Option<(Span, &'static str, String)> {
373 let sm = self.sess().source_map();
375 if sm.is_imported(sp) {
376 // Ignore if span is from within a macro #41858, #58298. We previously used the macro
377 // call span, but that breaks down when the type error comes from multiple calls down.
381 let is_struct_pat_shorthand_field =
382 self.is_hir_id_from_struct_pattern_shorthand_field(expr.hir_id, sp);
384 // If the span is from a macro, then it's hard to extract the text
385 // and make a good suggestion, so don't bother.
386 let is_macro = sp.from_expansion() && sp.desugaring_kind().is_none();
388 // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
389 let expr = expr.peel_drop_temps();
391 match (&expr.kind, &expected.kind, &checked_ty.kind) {
392 (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (&exp.kind, &check.kind) {
393 (&ty::Str, &ty::Array(arr, _)) | (&ty::Str, &ty::Slice(arr))
394 if arr == self.tcx.types.u8 =>
396 if let hir::ExprKind::Lit(_) = expr.kind {
397 if let Ok(src) = sm.span_to_snippet(sp) {
398 if src.starts_with("b\"") {
401 "consider removing the leading `b`",
402 src[1..].to_string(),
408 (&ty::Array(arr, _), &ty::Str) | (&ty::Slice(arr), &ty::Str)
409 if arr == self.tcx.types.u8 =>
411 if let hir::ExprKind::Lit(_) = expr.kind {
412 if let Ok(src) = sm.span_to_snippet(sp) {
413 if src.starts_with('"') {
416 "consider adding a leading `b`",
425 (_, &ty::Ref(_, _, mutability), _) => {
426 // Check if it can work when put into a ref. For example:
429 // fn bar(x: &mut i32) {}
432 // bar(&x); // error, expected &mut
434 let ref_ty = match mutability {
435 hir::Mutability::Mut => {
436 self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
438 hir::Mutability::Not => {
439 self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
442 if self.can_coerce(ref_ty, expected) {
443 let mut sugg_sp = sp;
444 if let hir::ExprKind::MethodCall(segment, _sp, args) = &expr.kind {
445 let clone_trait = self.tcx.lang_items().clone_trait().unwrap();
446 if let ([arg], Some(true), sym::clone) = (
448 self.tables.borrow().type_dependent_def_id(expr.hir_id).map(|did| {
449 let ai = self.tcx.associated_item(did);
450 ai.container == ty::TraitContainer(clone_trait)
454 // If this expression had a clone call when suggesting borrowing
455 // we want to suggest removing it because it'd now be unnecessary.
459 if let Ok(src) = sm.span_to_snippet(sugg_sp) {
460 let needs_parens = match expr.kind {
461 // parenthesize if needed (Issue #46756)
462 hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true,
463 // parenthesize borrows of range literals (Issue #54505)
464 _ if is_range_literal(self.tcx.sess.source_map(), expr) => true,
467 let sugg_expr = if needs_parens { format!("({})", src) } else { src };
469 if let Some(sugg) = self.can_use_as_ref(expr) {
472 let field_name = if is_struct_pat_shorthand_field {
473 format!("{}: ", sugg_expr)
477 if let Some(hir::Node::Expr(hir::Expr {
478 kind: hir::ExprKind::Assign(left_expr, ..),
480 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
482 if mutability == hir::Mutability::Mut {
483 // Found the following case:
484 // fn foo(opt: &mut Option<String>){ opt = None }
487 // consider dereferencing here: `*opt` |
488 // expected mutable reference, found enum `Option`
489 if let Ok(src) = sm.span_to_snippet(left_expr.span) {
492 "consider dereferencing here to assign to the mutable \
493 borrowed piece of memory",
500 return Some(match mutability {
501 hir::Mutability::Mut => (
503 "consider mutably borrowing here",
504 format!("{}&mut {}", field_name, sugg_expr),
506 hir::Mutability::Not => (
508 "consider borrowing here",
509 format!("{}&{}", field_name, sugg_expr),
516 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
518 &ty::Ref(_, checked, _),
520 self.infcx.can_sub(self.param_env, checked, &expected).is_ok() && !is_macro
523 // We have `&T`, check if what was expected was `T`. If so,
524 // we may want to suggest removing a `&`.
525 if sm.is_imported(expr.span) {
526 if let Ok(code) = sm.span_to_snippet(sp) {
527 if code.starts_with('&') {
530 "consider removing the borrow",
531 code[1..].to_string(),
537 if let Ok(code) = sm.span_to_snippet(expr.span) {
538 return Some((sp, "consider removing the borrow", code));
541 _ if sp == expr.span && !is_macro => {
542 // Check for `Deref` implementations by constructing a predicate to
543 // prove: `<T as Deref>::Output == U`
544 let deref_trait = self.tcx.lang_items().deref_trait().unwrap();
545 let item_def_id = self
547 .associated_items(deref_trait)
548 .in_definition_order()
549 .find(|item| item.kind == ty::AssocKind::Type)
553 ty::Predicate::Projection(ty::Binder::bind(ty::ProjectionPredicate {
554 // `<T as Deref>::Output`
555 projection_ty: ty::ProjectionTy {
557 substs: self.tcx.intern_substs(&[checked_ty.into()]),
564 let obligation = traits::Obligation::new(self.misc(sp), self.param_env, predicate);
565 let impls_deref = self.infcx.predicate_may_hold(&obligation);
567 // For a suggestion to make sense, the type would need to be `Copy`.
568 let is_copy = self.infcx.type_is_copy_modulo_regions(self.param_env, expected, sp);
570 if is_copy && impls_deref {
571 if let Ok(code) = sm.span_to_snippet(sp) {
572 let message = if checked_ty.is_region_ptr() {
573 "consider dereferencing the borrow"
575 "consider dereferencing the type"
577 let suggestion = if is_struct_pat_shorthand_field {
578 format!("{}: *{}", code, code)
582 return Some((sp, message, suggestion));
591 pub fn check_for_cast(
593 err: &mut DiagnosticBuilder<'_>,
594 expr: &hir::Expr<'_>,
595 checked_ty: Ty<'tcx>,
596 expected_ty: Ty<'tcx>,
598 if self.tcx.hir().is_const_context(expr.hir_id) {
599 // Shouldn't suggest `.into()` on `const`s.
600 // FIXME(estebank): modify once we decide to suggest `as` casts
603 if self.tcx.sess.source_map().is_imported(expr.span) {
604 // Ignore if span is from within a macro.
608 // If casting this expression to a given numeric type would be appropriate in case of a type
611 // We want to minimize the amount of casting operations that are suggested, as it can be a
612 // lossy operation with potentially bad side effects, so we only suggest when encountering
613 // an expression that indicates that the original type couldn't be directly changed.
615 // For now, don't suggest casting with `as`.
616 let can_cast = false;
618 let mut prefix = String::new();
619 if let Some(hir::Node::Expr(hir::Expr {
620 kind: hir::ExprKind::Struct(_, fields, _), ..
621 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
623 // `expr` is a literal field for a struct, only suggest if appropriate
624 for field in *fields {
625 if field.expr.hir_id == expr.hir_id && field.is_shorthand {
626 // This is a field literal
627 prefix = format!("{}: ", field.ident);
632 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
636 if let hir::ExprKind::Call(path, args) = &expr.kind {
637 if let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
638 (&path.kind, args.len())
640 // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
641 if let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
642 (&base_ty.kind, path_segment.ident.name)
644 if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
658 if base_ty_path.segments.len() == 1 =>
669 let msg = format!("you can convert an `{}` to `{}`", checked_ty, expected_ty);
670 let cast_msg = format!("you can cast an `{} to `{}`", checked_ty, expected_ty);
671 let try_msg = format!("{} and panic if the converted value wouldn't fit", msg);
672 let lit_msg = format!(
673 "change the type of the numeric literal from `{}` to `{}`",
674 checked_ty, expected_ty,
677 let needs_paren = expr.precedence().order() < (PREC_POSTFIX as i8);
679 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
680 let cast_suggestion = format!(
683 if needs_paren { "(" } else { "" },
685 if needs_paren { ")" } else { "" },
688 let try_into_suggestion = format!(
689 "{}{}{}{}.try_into().unwrap()",
691 if needs_paren { "(" } else { "" },
693 if needs_paren { ")" } else { "" },
695 let into_suggestion = format!(
698 if needs_paren { "(" } else { "" },
700 if needs_paren { ")" } else { "" },
702 let suffix_suggestion = format!(
704 if needs_paren { "(" } else { "" },
705 if let (ty::Int(_), ty::Float(_)) | (ty::Uint(_), ty::Float(_)) =
706 (&expected_ty.kind, &checked_ty.kind,)
708 // Remove fractional part from literal, for example `42.0f32` into `42`
709 let src = src.trim_end_matches(&checked_ty.to_string());
710 src.split('.').next().unwrap()
712 src.trim_end_matches(&checked_ty.to_string())
715 if needs_paren { ")" } else { "" },
717 let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
718 if let hir::ExprKind::Lit(lit) = &expr.kind {
719 lit.node.is_suffixed()
725 let suggest_to_change_suffix_or_into =
726 |err: &mut DiagnosticBuilder<'_>, is_fallible: bool| {
727 let into_sugg = into_suggestion.clone();
730 if literal_is_ty_suffixed(expr) {
732 } else if is_fallible {
737 if literal_is_ty_suffixed(expr) {
738 suffix_suggestion.clone()
739 } else if is_fallible {
744 Applicability::MachineApplicable,
748 match (&expected_ty.kind, &checked_ty.kind) {
749 (&ty::Int(ref exp), &ty::Int(ref found)) => {
750 let is_fallible = match (exp.bit_width(), found.bit_width()) {
751 (Some(exp), Some(found)) if exp < found => true,
752 (None, Some(8 | 16)) => false,
753 (None, _) | (_, None) => true,
756 suggest_to_change_suffix_or_into(err, is_fallible);
759 (&ty::Uint(ref exp), &ty::Uint(ref found)) => {
760 let is_fallible = match (exp.bit_width(), found.bit_width()) {
761 (Some(exp), Some(found)) if exp < found => true,
762 (None, Some(8 | 16)) => false,
763 (None, _) | (_, None) => true,
766 suggest_to_change_suffix_or_into(err, is_fallible);
769 (&ty::Int(_), &ty::Uint(_)) | (&ty::Uint(_), &ty::Int(_)) => {
770 suggest_to_change_suffix_or_into(err, true);
773 (&ty::Float(ref exp), &ty::Float(ref found)) => {
774 if found.bit_width() < exp.bit_width() {
775 suggest_to_change_suffix_or_into(err, false);
776 } else if literal_is_ty_suffixed(expr) {
781 Applicability::MachineApplicable,
784 // Missing try_into implementation for `f64` to `f32`
787 &format!("{}, producing the closest possible value", cast_msg),
789 Applicability::MaybeIncorrect, // lossy conversion
794 (&ty::Uint(_), &ty::Float(_)) | (&ty::Int(_), &ty::Float(_)) => {
795 if literal_is_ty_suffixed(expr) {
800 Applicability::MachineApplicable,
803 // Missing try_into implementation for `{float}` to `{integer}`
806 &format!("{}, rounding the float towards zero", msg),
808 Applicability::MaybeIncorrect, // lossy conversion
811 "if the rounded value cannot be represented by the target \
812 integer type, including `Inf` and `NaN`, casting will cause \
814 (see issue #10184 <https://github.com/rust-lang/rust/issues/10184> \
815 for more information)",
820 (&ty::Float(ref exp), &ty::Uint(ref found)) => {
821 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
822 if exp.bit_width() > found.bit_width().unwrap_or(256) {
826 "{}, producing the floating point representation of the integer",
830 Applicability::MachineApplicable,
832 } else if literal_is_ty_suffixed(expr) {
837 Applicability::MachineApplicable,
840 // Missing try_into implementation for `{integer}` to `{float}`
844 "{}, producing the floating point representation of the integer,
845 rounded if necessary",
849 Applicability::MaybeIncorrect, // lossy conversion
854 (&ty::Float(ref exp), &ty::Int(ref found)) => {
855 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
856 if exp.bit_width() > found.bit_width().unwrap_or(256) {
860 "{}, producing the floating point representation of the integer",
864 Applicability::MachineApplicable,
866 } else if literal_is_ty_suffixed(expr) {
871 Applicability::MachineApplicable,
874 // Missing try_into implementation for `{integer}` to `{float}`
878 "{}, producing the floating point representation of the integer, \
879 rounded if necessary",
883 Applicability::MaybeIncorrect, // lossy conversion