1 use crate::check::FnCtxt;
2 use rustc_infer::infer::InferOk;
3 use rustc_infer::traits::{self, ObligationCause};
5 use rustc::ty::adjustment::AllowTwoPhase;
6 use rustc::ty::{self, AssocItem, Ty};
7 use rustc_ast::util::parser::PREC_POSTFIX;
8 use rustc_errors::{Applicability, DiagnosticBuilder};
10 use rustc_hir::{is_range_literal, print, Node};
11 use rustc_span::symbol::sym;
14 use super::method::probe;
16 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
17 pub fn emit_coerce_suggestions(
19 err: &mut DiagnosticBuilder<'_>,
24 self.annotate_expected_due_to_let_ty(err, expr);
25 self.suggest_compatible_variants(err, expr, expected, expr_ty);
26 self.suggest_ref_or_into(err, expr, expected, expr_ty);
27 if self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty) {
30 self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty);
31 self.suggest_missing_await(err, expr, expected, expr_ty);
34 // Requires that the two types unify, and prints an error message if
36 pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
37 self.demand_suptype_diag(sp, expected, actual).map(|mut e| e.emit());
40 pub fn demand_suptype_diag(
45 ) -> Option<DiagnosticBuilder<'tcx>> {
46 self.demand_suptype_with_origin(&self.misc(sp), expected, actual)
49 pub fn demand_suptype_with_origin(
51 cause: &ObligationCause<'tcx>,
54 ) -> Option<DiagnosticBuilder<'tcx>> {
55 match self.at(cause, self.param_env).sup(expected, actual) {
56 Ok(InferOk { obligations, value: () }) => {
57 self.register_predicates(obligations);
60 Err(e) => Some(self.report_mismatched_types(&cause, expected, actual, e)),
64 pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
65 if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
70 pub fn demand_eqtype_diag(
75 ) -> Option<DiagnosticBuilder<'tcx>> {
76 self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
79 pub fn demand_eqtype_with_origin(
81 cause: &ObligationCause<'tcx>,
84 ) -> Option<DiagnosticBuilder<'tcx>> {
85 match self.at(cause, self.param_env).eq(expected, actual) {
86 Ok(InferOk { obligations, value: () }) => {
87 self.register_predicates(obligations);
90 Err(e) => Some(self.report_mismatched_types(cause, expected, actual, e)),
99 allow_two_phase: AllowTwoPhase,
101 let (ty, err) = self.demand_coerce_diag(expr, checked_ty, expected, allow_two_phase);
102 if let Some(mut err) = err {
108 // Checks that the type of `expr` can be coerced to `expected`.
110 // N.B., this code relies on `self.diverges` to be accurate. In
111 // particular, assignments to `!` will be permitted if the
112 // diverges flag is currently "always".
113 pub fn demand_coerce_diag(
115 expr: &hir::Expr<'_>,
116 checked_ty: Ty<'tcx>,
118 allow_two_phase: AllowTwoPhase,
119 ) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx>>) {
120 let expected = self.resolve_vars_with_obligations(expected);
122 let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase) {
123 Ok(ty) => return (ty, None),
127 let expr = expr.peel_drop_temps();
128 let cause = self.misc(expr.span);
129 let expr_ty = self.resolve_vars_with_obligations(checked_ty);
130 let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e);
132 if self.is_assign_to_bool(expr, expected) {
133 // Error reported in `check_assign` so avoid emitting error again.
135 return (expected, None);
138 self.emit_coerce_suggestions(&mut err, expr, expr_ty, expected);
140 (expected, Some(err))
143 fn annotate_expected_due_to_let_ty(
145 err: &mut DiagnosticBuilder<'_>,
146 expr: &hir::Expr<'_>,
148 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
149 if let Some(hir::Node::Local(hir::Local { ty: Some(ty), init: Some(init), .. })) =
150 self.tcx.hir().find(parent)
152 if init.hir_id == expr.hir_id {
153 // Point at `let` assignment type.
154 err.span_label(ty.span, "expected due to this");
159 /// Returns whether the expected type is `bool` and the expression is `x = y`.
160 pub fn is_assign_to_bool(&self, expr: &hir::Expr<'_>, expected: Ty<'tcx>) -> bool {
161 if let hir::ExprKind::Assign(..) = expr.kind {
162 return expected == self.tcx.types.bool;
167 /// If the expected type is an enum (Issue #55250) with any variants whose
168 /// sole field is of the found type, suggest such variants. (Issue #42764)
169 fn suggest_compatible_variants(
171 err: &mut DiagnosticBuilder<'_>,
172 expr: &hir::Expr<'_>,
176 if let ty::Adt(expected_adt, substs) = expected.kind {
177 if !expected_adt.is_enum() {
181 let mut compatible_variants = expected_adt
184 .filter(|variant| variant.fields.len() == 1)
185 .filter_map(|variant| {
186 let sole_field = &variant.fields[0];
187 let sole_field_ty = sole_field.ty(self.tcx, substs);
188 if self.can_coerce(expr_ty, sole_field_ty) {
189 let variant_path = self.tcx.def_path_str(variant.def_id);
190 // FIXME #56861: DRYer prelude filtering
191 Some(variant_path.trim_start_matches("std::prelude::v1::").to_string())
198 if compatible_variants.peek().is_some() {
200 self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or_else(|_| {
201 print::to_string(print::NO_ANN, |s| s.print_expr(expr))
203 let suggestions = compatible_variants.map(|v| format!("{}({})", v, expr_text));
204 let msg = "try using a variant of the expected enum";
205 err.span_suggestions(expr.span, msg, suggestions, Applicability::MaybeIncorrect);
210 pub fn get_conversion_methods(
214 checked_ty: Ty<'tcx>,
215 ) -> Vec<AssocItem> {
216 let mut methods = self.probe_for_return_type(
218 probe::Mode::MethodCall,
224 self.has_no_input_arg(m)
229 // This special internal attribute is used to whitelist
230 // "identity-like" conversion methods to be suggested here.
232 // FIXME (#46459 and #46460): ideally
233 // `std::convert::Into::into` and `std::borrow:ToOwned` would
234 // also be `#[rustc_conversion_suggestion]`, if not for
235 // method-probing false-positives and -negatives (respectively).
237 // FIXME? Other potential candidate methods: `as_ref` and
239 .find(|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::Method => {
250 self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1
256 /// Identify some cases where `as_ref()` would be appropriate and suggest it.
258 /// Given the following code:
261 /// fn takes_ref(_: &Foo) {}
262 /// let ref opt = Some(Foo);
264 /// opt.map(|param| takes_ref(param));
266 /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
268 /// It only checks for `Option` and `Result` and won't work with
270 /// opt.map(|param| { takes_ref(param) });
272 fn can_use_as_ref(&self, expr: &hir::Expr<'_>) -> Option<(Span, &'static str, String)> {
273 let path = match expr.kind {
274 hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => path,
278 let local_id = match path.res {
279 hir::def::Res::Local(id) => id,
283 let local_parent = self.tcx.hir().get_parent_node(local_id);
284 let param_hir_id = match self.tcx.hir().find(local_parent) {
285 Some(Node::Param(hir::Param { hir_id, .. })) => hir_id,
289 let param_parent = self.tcx.hir().get_parent_node(*param_hir_id);
290 let (expr_hir_id, closure_fn_decl) = match self.tcx.hir().find(param_parent) {
291 Some(Node::Expr(hir::Expr {
293 kind: hir::ExprKind::Closure(_, decl, ..),
295 })) => (hir_id, decl),
299 let expr_parent = self.tcx.hir().get_parent_node(*expr_hir_id);
300 let hir = self.tcx.hir().find(expr_parent);
301 let closure_params_len = closure_fn_decl.inputs.len();
302 let (method_path, method_span, method_expr) = match (hir, closure_params_len) {
304 Some(Node::Expr(hir::Expr {
305 kind: hir::ExprKind::MethodCall(path, span, expr),
309 ) => (path, span, expr),
313 let self_ty = self.tables.borrow().node_type(method_expr[0].hir_id);
314 let self_ty = format!("{:?}", self_ty);
315 let name = method_path.ident.as_str();
316 let is_as_ref_able = (self_ty.starts_with("&std::option::Option")
317 || self_ty.starts_with("&std::result::Result")
318 || self_ty.starts_with("std::option::Option")
319 || self_ty.starts_with("std::result::Result"))
320 && (name == "map" || name == "and_then");
321 match (is_as_ref_able, self.sess().source_map().span_to_snippet(*method_span)) {
323 let suggestion = format!("as_ref().{}", src);
324 Some((*method_span, "consider using `as_ref` instead", suggestion))
330 crate fn is_hir_id_from_struct_pattern_shorthand_field(
335 let sm = self.sess().source_map();
336 let parent_id = self.tcx.hir().get_parent_node(hir_id);
337 if let Some(parent) = self.tcx.hir().find(parent_id) {
338 // Account for fields
339 if let Node::Expr(hir::Expr { kind: hir::ExprKind::Struct(_, fields, ..), .. }) = parent
341 if let Ok(src) = sm.span_to_snippet(sp) {
342 for field in *fields {
343 if field.ident.as_str() == src && field.is_shorthand {
353 /// This function is used to determine potential "simple" improvements or users' errors and
354 /// provide them useful help. For example:
357 /// fn some_fn(s: &str) {}
359 /// let x = "hey!".to_owned();
360 /// some_fn(x); // error
363 /// No need to find every potential function which could make a coercion to transform a
364 /// `String` into a `&str` since a `&` would do the trick!
366 /// In addition of this check, it also checks between references mutability state. If the
367 /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
371 expr: &hir::Expr<'_>,
372 checked_ty: Ty<'tcx>,
374 ) -> Option<(Span, &'static str, String)> {
375 let sm = self.sess().source_map();
377 if !sm.span_to_filename(sp).is_real() {
378 // Ignore if span is from within a macro #41858, #58298. We previously used the macro
379 // call span, but that breaks down when the type error comes from multiple calls down.
383 let is_struct_pat_shorthand_field =
384 self.is_hir_id_from_struct_pattern_shorthand_field(expr.hir_id, sp);
386 // If the span is from a macro, then it's hard to extract the text
387 // and make a good suggestion, so don't bother.
388 let is_macro = sp.from_expansion() && sp.desugaring_kind().is_none();
390 // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
391 let expr = expr.peel_drop_temps();
393 match (&expr.kind, &expected.kind, &checked_ty.kind) {
394 (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (&exp.kind, &check.kind) {
395 (&ty::Str, &ty::Array(arr, _)) | (&ty::Str, &ty::Slice(arr))
396 if arr == self.tcx.types.u8 =>
398 if let hir::ExprKind::Lit(_) = expr.kind {
399 if let Ok(src) = sm.span_to_snippet(sp) {
400 if src.starts_with("b\"") {
403 "consider removing the leading `b`",
404 src[1..].to_string(),
410 (&ty::Array(arr, _), &ty::Str) | (&ty::Slice(arr), &ty::Str)
411 if arr == self.tcx.types.u8 =>
413 if let hir::ExprKind::Lit(_) = expr.kind {
414 if let Ok(src) = sm.span_to_snippet(sp) {
415 if src.starts_with('"') {
418 "consider adding a leading `b`",
427 (_, &ty::Ref(_, _, mutability), _) => {
428 // Check if it can work when put into a ref. For example:
431 // fn bar(x: &mut i32) {}
434 // bar(&x); // error, expected &mut
436 let ref_ty = match mutability {
437 hir::Mutability::Mut => {
438 self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
440 hir::Mutability::Not => {
441 self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
444 if self.can_coerce(ref_ty, expected) {
445 let mut sugg_sp = sp;
446 if let hir::ExprKind::MethodCall(segment, _sp, args) = &expr.kind {
447 let clone_trait = self.tcx.lang_items().clone_trait().unwrap();
448 if let ([arg], Some(true), sym::clone) = (
450 self.tables.borrow().type_dependent_def_id(expr.hir_id).map(|did| {
451 let ai = self.tcx.associated_item(did);
452 ai.container == ty::TraitContainer(clone_trait)
456 // If this expression had a clone call when suggesting borrowing
457 // we want to suggest removing it because it'd now be unnecessary.
461 if let Ok(src) = sm.span_to_snippet(sugg_sp) {
462 let needs_parens = match expr.kind {
463 // parenthesize if needed (Issue #46756)
464 hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true,
465 // parenthesize borrows of range literals (Issue #54505)
466 _ if is_range_literal(self.tcx.sess.source_map(), expr) => true,
469 let sugg_expr = if needs_parens { format!("({})", src) } else { src };
471 if let Some(sugg) = self.can_use_as_ref(expr) {
474 let field_name = if is_struct_pat_shorthand_field {
475 format!("{}: ", sugg_expr)
479 if let Some(hir::Node::Expr(hir::Expr {
480 kind: hir::ExprKind::Assign(left_expr, ..),
482 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
484 if mutability == hir::Mutability::Mut {
485 // Found the following case:
486 // fn foo(opt: &mut Option<String>){ opt = None }
489 // consider dereferencing here: `*opt` |
490 // expected mutable reference, found enum `Option`
491 if let Ok(src) = sm.span_to_snippet(left_expr.span) {
494 "consider dereferencing here to assign to the mutable \
495 borrowed piece of memory",
502 return Some(match mutability {
503 hir::Mutability::Mut => (
505 "consider mutably borrowing here",
506 format!("{}&mut {}", field_name, sugg_expr),
508 hir::Mutability::Not => (
510 "consider borrowing here",
511 format!("{}&{}", field_name, sugg_expr),
518 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
520 &ty::Ref(_, checked, _),
522 self.infcx.can_sub(self.param_env, checked, &expected).is_ok() && !is_macro
525 // We have `&T`, check if what was expected was `T`. If so,
526 // we may want to suggest removing a `&`.
527 if !sm.span_to_filename(expr.span).is_real() {
528 if let Ok(code) = sm.span_to_snippet(sp) {
529 if code.chars().next() == Some('&') {
532 "consider removing the borrow",
533 code[1..].to_string(),
539 if let Ok(code) = sm.span_to_snippet(expr.span) {
540 return Some((sp, "consider removing the borrow", code));
543 _ if sp == expr.span && !is_macro => {
544 // Check for `Deref` implementations by constructing a predicate to
545 // prove: `<T as Deref>::Output == U`
546 let deref_trait = self.tcx.lang_items().deref_trait().unwrap();
547 let item_def_id = self
549 .associated_items(deref_trait)
550 .in_definition_order()
551 .find(|item| item.kind == ty::AssocKind::Type)
555 ty::Predicate::Projection(ty::Binder::bind(ty::ProjectionPredicate {
556 // `<T as Deref>::Output`
557 projection_ty: ty::ProjectionTy {
559 substs: self.tcx.intern_substs(&[checked_ty.into()]),
566 let obligation = traits::Obligation::new(self.misc(sp), self.param_env, predicate);
567 let impls_deref = self.infcx.predicate_may_hold(&obligation);
569 // For a suggestion to make sense, the type would need to be `Copy`.
570 let is_copy = self.infcx.type_is_copy_modulo_regions(self.param_env, expected, sp);
572 if is_copy && impls_deref {
573 if let Ok(code) = sm.span_to_snippet(sp) {
574 let message = if checked_ty.is_region_ptr() {
575 "consider dereferencing the borrow"
577 "consider dereferencing the type"
579 let suggestion = if is_struct_pat_shorthand_field {
580 format!("{}: *{}", code, code)
584 return Some((sp, message, suggestion));
593 pub fn check_for_cast(
595 err: &mut DiagnosticBuilder<'_>,
596 expr: &hir::Expr<'_>,
597 checked_ty: Ty<'tcx>,
598 expected_ty: Ty<'tcx>,
600 if self.tcx.hir().is_const_context(expr.hir_id) {
601 // Shouldn't suggest `.into()` on `const`s.
602 // FIXME(estebank): modify once we decide to suggest `as` casts
605 if !self.tcx.sess.source_map().span_to_filename(expr.span).is_real() {
606 // Ignore if span is from within a macro.
610 // If casting this expression to a given numeric type would be appropriate in case of a type
613 // We want to minimize the amount of casting operations that are suggested, as it can be a
614 // lossy operation with potentially bad side effects, so we only suggest when encountering
615 // an expression that indicates that the original type couldn't be directly changed.
617 // For now, don't suggest casting with `as`.
618 let can_cast = false;
620 let mut prefix = String::new();
621 if let Some(hir::Node::Expr(hir::Expr {
622 kind: hir::ExprKind::Struct(_, fields, _), ..
623 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id))
625 // `expr` is a literal field for a struct, only suggest if appropriate
626 for field in *fields {
627 if field.expr.hir_id == expr.hir_id && field.is_shorthand {
628 // This is a field literal
629 prefix = format!("{}: ", field.ident);
634 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
638 if let hir::ExprKind::Call(path, args) = &expr.kind {
639 if let (hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)), 1) =
640 (&path.kind, args.len())
642 // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
643 if let (hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)), sym::from) =
644 (&base_ty.kind, path_segment.ident.name)
646 if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
660 if base_ty_path.segments.len() == 1 =>
671 let msg = format!("you can convert an `{}` to `{}`", checked_ty, expected_ty);
672 let cast_msg = format!("you can cast an `{} to `{}`", checked_ty, expected_ty);
673 let try_msg = format!("{} and panic if the converted value wouldn't fit", msg);
674 let lit_msg = format!(
675 "change the type of the numeric literal from `{}` to `{}`",
676 checked_ty, expected_ty,
679 let needs_paren = expr.precedence().order() < (PREC_POSTFIX as i8);
681 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
682 let cast_suggestion = format!(
685 if needs_paren { "(" } else { "" },
687 if needs_paren { ")" } else { "" },
690 let try_into_suggestion = format!(
691 "{}{}{}{}.try_into().unwrap()",
693 if needs_paren { "(" } else { "" },
695 if needs_paren { ")" } else { "" },
697 let into_suggestion = format!(
700 if needs_paren { "(" } else { "" },
702 if needs_paren { ")" } else { "" },
704 let suffix_suggestion = format!(
706 if needs_paren { "(" } else { "" },
707 if let (ty::Int(_), ty::Float(_)) | (ty::Uint(_), ty::Float(_)) =
708 (&expected_ty.kind, &checked_ty.kind,)
710 // Remove fractional part from literal, for example `42.0f32` into `42`
711 let src = src.trim_end_matches(&checked_ty.to_string());
712 src.split('.').next().unwrap()
714 src.trim_end_matches(&checked_ty.to_string())
717 if needs_paren { ")" } else { "" },
719 let literal_is_ty_suffixed = |expr: &hir::Expr<'_>| {
720 if let hir::ExprKind::Lit(lit) = &expr.kind {
721 lit.node.is_suffixed()
727 let suggest_to_change_suffix_or_into =
728 |err: &mut DiagnosticBuilder<'_>, is_fallible: bool| {
729 let into_sugg = into_suggestion.clone();
732 if literal_is_ty_suffixed(expr) {
734 } else if is_fallible {
739 if literal_is_ty_suffixed(expr) {
740 suffix_suggestion.clone()
741 } else if is_fallible {
746 Applicability::MachineApplicable,
750 match (&expected_ty.kind, &checked_ty.kind) {
751 (&ty::Int(ref exp), &ty::Int(ref found)) => {
752 let is_fallible = match (found.bit_width(), exp.bit_width()) {
753 (Some(found), Some(exp)) if found > exp => true,
754 (None, _) | (_, None) => true,
757 suggest_to_change_suffix_or_into(err, is_fallible);
760 (&ty::Uint(ref exp), &ty::Uint(ref found)) => {
761 let is_fallible = match (found.bit_width(), exp.bit_width()) {
762 (Some(found), Some(exp)) if found > exp => true,
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