1 use crate::check::FnCtxt;
2 use rustc::infer::InferOk;
3 use rustc::traits::{self, ObligationCause, ObligationCauseCode};
5 use syntax::symbol::sym;
6 use syntax::util::parser::PREC_POSTFIX;
10 use rustc::hir::{print, lowering::is_range_literal};
11 use rustc::ty::{self, Ty, AssocItem};
12 use rustc::ty::adjustment::AllowTwoPhase;
13 use errors::{Applicability, DiagnosticBuilder};
15 use super::method::probe;
17 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
18 // Requires that the two types unify, and prints an error message if
20 pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
21 self.demand_suptype_diag(sp, expected, actual).map(|mut e| e.emit());
24 pub fn demand_suptype_diag(&self,
27 actual: Ty<'tcx>) -> Option<DiagnosticBuilder<'tcx>> {
28 let cause = &self.misc(sp);
29 match self.at(cause, self.param_env).sup(expected, actual) {
30 Ok(InferOk { obligations, value: () }) => {
31 self.register_predicates(obligations);
35 Some(self.report_mismatched_types(&cause, expected, actual, e))
40 pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
41 if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
46 pub fn demand_eqtype_diag(&self,
49 actual: Ty<'tcx>) -> Option<DiagnosticBuilder<'tcx>> {
50 self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
53 pub fn demand_eqtype_with_origin(&self,
54 cause: &ObligationCause<'tcx>,
56 actual: Ty<'tcx>) -> Option<DiagnosticBuilder<'tcx>> {
57 match self.at(cause, self.param_env).eq(expected, actual) {
58 Ok(InferOk { obligations, value: () }) => {
59 self.register_predicates(obligations);
63 Some(self.report_mismatched_types(cause, expected, actual, e))
68 pub fn demand_eqtype_pat(
73 match_expr_span: Option<Span>,
75 let cause = if let Some(span) = match_expr_span {
78 ObligationCauseCode::MatchExpressionArmPattern { span, ty: expected },
83 self.demand_eqtype_with_origin(&cause, expected, actual).map(|mut err| err.emit());
87 pub fn demand_coerce(&self,
91 allow_two_phase: AllowTwoPhase)
93 let (ty, err) = self.demand_coerce_diag(expr, checked_ty, expected, allow_two_phase);
94 if let Some(mut err) = err {
100 // Checks that the type of `expr` can be coerced to `expected`.
102 // N.B., this code relies on `self.diverges` to be accurate. In
103 // particular, assignments to `!` will be permitted if the
104 // diverges flag is currently "always".
105 pub fn demand_coerce_diag(
108 checked_ty: Ty<'tcx>,
110 allow_two_phase: AllowTwoPhase,
111 ) -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx>>) {
112 let expected = self.resolve_vars_with_obligations(expected);
114 let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase) {
115 Ok(ty) => return (ty, None),
119 let expr = expr.peel_drop_temps();
120 let cause = self.misc(expr.span);
121 let expr_ty = self.resolve_vars_with_obligations(checked_ty);
122 let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e);
124 if self.is_assign_to_bool(expr, expected) {
125 // Error reported in `check_assign` so avoid emitting error again.
127 return (expected, None)
130 self.annotate_expected_due_to_let_ty(&mut err, expr);
131 self.suggest_compatible_variants(&mut err, expr, expected, expr_ty);
132 self.suggest_ref_or_into(&mut err, expr, expected, expr_ty);
133 self.suggest_boxing_when_appropriate(&mut err, expr, expected, expr_ty);
134 self.suggest_missing_await(&mut err, expr, expected, expr_ty);
136 (expected, Some(err))
139 fn annotate_expected_due_to_let_ty(&self, err: &mut DiagnosticBuilder<'_>, expr: &hir::Expr) {
140 let parent = self.tcx.hir().get_parent_node(expr.hir_id);
141 if let Some(hir::Node::Local(hir::Local {
145 })) = self.tcx.hir().find(parent) {
146 if init.hir_id == expr.hir_id {
147 // Point at `let` assignment type.
148 err.span_label(ty.span, "expected due to this");
153 /// Returns whether the expected type is `bool` and the expression is `x = y`.
154 pub fn is_assign_to_bool(&self, expr: &hir::Expr, expected: Ty<'tcx>) -> bool {
155 if let hir::ExprKind::Assign(..) = expr.kind {
156 return expected == self.tcx.types.bool;
161 /// If the expected type is an enum (Issue #55250) with any variants whose
162 /// sole field is of the found type, suggest such variants. (Issue #42764)
163 fn suggest_compatible_variants(
165 err: &mut DiagnosticBuilder<'_>,
170 if let ty::Adt(expected_adt, substs) = expected.kind {
171 if !expected_adt.is_enum() {
175 let mut compatible_variants = expected_adt.variants
177 .filter(|variant| variant.fields.len() == 1)
178 .filter_map(|variant| {
179 let sole_field = &variant.fields[0];
180 let sole_field_ty = sole_field.ty(self.tcx, substs);
181 if self.can_coerce(expr_ty, sole_field_ty) {
182 let variant_path = self.tcx.def_path_str(variant.def_id);
183 // FIXME #56861: DRYer prelude filtering
184 Some(variant_path.trim_start_matches("std::prelude::v1::").to_string())
190 if compatible_variants.peek().is_some() {
191 let expr_text = self.tcx.sess
193 .span_to_snippet(expr.span)
194 .unwrap_or_else(|_| {
195 print::to_string(print::NO_ANN, |s| s.print_expr(expr))
197 let suggestions = compatible_variants
198 .map(|v| format!("{}({})", v, expr_text));
199 let msg = "try using a variant of the expected enum";
200 err.span_suggestions(expr.span, msg, suggestions, Applicability::MaybeIncorrect);
205 pub fn get_conversion_methods(&self, span: Span, expected: Ty<'tcx>, checked_ty: Ty<'tcx>)
207 let mut methods = self.probe_for_return_type(span,
208 probe::Mode::MethodCall,
213 self.has_no_input_arg(m) &&
214 self.tcx.get_attrs(m.def_id).iter()
215 // This special internal attribute is used to whitelist
216 // "identity-like" conversion methods to be suggested here.
218 // FIXME (#46459 and #46460): ideally
219 // `std::convert::Into::into` and `std::borrow:ToOwned` would
220 // also be `#[rustc_conversion_suggestion]`, if not for
221 // method-probing false-positives and -negatives (respectively).
223 // FIXME? Other potential candidate methods: `as_ref` and
225 .find(|a| a.check_name(sym::rustc_conversion_suggestion)).is_some()
231 // This function checks if the method isn't static and takes other arguments than `self`.
232 fn has_no_input_arg(&self, method: &AssocItem) -> bool {
234 ty::AssocKind::Method => {
235 self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1
241 /// Identify some cases where `as_ref()` would be appropriate and suggest it.
243 /// Given the following code:
246 /// fn takes_ref(_: &Foo) {}
247 /// let ref opt = Some(Foo);
249 /// opt.map(|param| takes_ref(param));
251 /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
253 /// It only checks for `Option` and `Result` and won't work with
255 /// opt.map(|param| { takes_ref(param) });
260 ) -> Option<(Span, &'static str, String)> {
261 let path = match expr.kind {
262 hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => path,
266 let local_id = match path.res {
267 hir::def::Res::Local(id) => id,
271 let local_parent = self.tcx.hir().get_parent_node(local_id);
272 let param_hir_id = match self.tcx.hir().find(local_parent) {
273 Some(Node::Param(hir::Param { hir_id, .. })) => hir_id,
277 let param_parent = self.tcx.hir().get_parent_node(*param_hir_id);
278 let (expr_hir_id, closure_fn_decl) = match self.tcx.hir().find(param_parent) {
280 hir::Expr { hir_id, kind: hir::ExprKind::Closure(_, decl, ..), .. }
281 )) => (hir_id, decl),
285 let expr_parent = self.tcx.hir().get_parent_node(*expr_hir_id);
286 let hir = self.tcx.hir().find(expr_parent);
287 let closure_params_len = closure_fn_decl.inputs.len();
288 let (method_path, method_span, method_expr) = match (hir, closure_params_len) {
290 hir::Expr { kind: hir::ExprKind::MethodCall(path, span, expr), .. }
291 )), 1) => (path, span, expr),
295 let self_ty = self.tables.borrow().node_type(method_expr[0].hir_id);
296 let self_ty = format!("{:?}", self_ty);
297 let name = method_path.ident.as_str();
298 let is_as_ref_able = (
299 self_ty.starts_with("&std::option::Option") ||
300 self_ty.starts_with("&std::result::Result") ||
301 self_ty.starts_with("std::option::Option") ||
302 self_ty.starts_with("std::result::Result")
303 ) && (name == "map" || name == "and_then");
304 match (is_as_ref_able, self.sess().source_map().span_to_snippet(*method_span)) {
306 let suggestion = format!("as_ref().{}", src);
307 Some((*method_span, "consider using `as_ref` instead", suggestion))
313 crate fn is_hir_id_from_struct_pattern_shorthand_field(
318 let cm = self.sess().source_map();
319 let parent_id = self.tcx.hir().get_parent_node(hir_id);
320 if let Some(parent) = self.tcx.hir().find(parent_id) {
321 // Account for fields
322 if let Node::Expr(hir::Expr {
323 kind: hir::ExprKind::Struct(_, fields, ..), ..
325 if let Ok(src) = cm.span_to_snippet(sp) {
326 for field in fields {
327 if field.ident.as_str() == src && field.is_shorthand {
337 /// This function is used to determine potential "simple" improvements or users' errors and
338 /// provide them useful help. For example:
341 /// fn some_fn(s: &str) {}
343 /// let x = "hey!".to_owned();
344 /// some_fn(x); // error
347 /// No need to find every potential function which could make a coercion to transform a
348 /// `String` into a `&str` since a `&` would do the trick!
350 /// In addition of this check, it also checks between references mutability state. If the
351 /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
356 checked_ty: Ty<'tcx>,
358 ) -> Option<(Span, &'static str, String)> {
359 let cm = self.sess().source_map();
361 if !cm.span_to_filename(sp).is_real() {
362 // Ignore if span is from within a macro #41858, #58298. We previously used the macro
363 // call span, but that breaks down when the type error comes from multiple calls down.
367 let is_struct_pat_shorthand_field = self.is_hir_id_from_struct_pattern_shorthand_field(
372 // If the span is from a macro, then it's hard to extract the text
373 // and make a good suggestion, so don't bother.
374 let is_macro = sp.from_expansion() && sp.desugaring_kind().is_none();
376 // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
377 let expr = expr.peel_drop_temps();
379 match (&expr.kind, &expected.kind, &checked_ty.kind) {
380 (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (&exp.kind, &check.kind) {
381 (&ty::Str, &ty::Array(arr, _)) |
382 (&ty::Str, &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
383 if let hir::ExprKind::Lit(_) = expr.kind {
384 if let Ok(src) = cm.span_to_snippet(sp) {
385 if src.starts_with("b\"") {
387 "consider removing the leading `b`",
388 src[1..].to_string()));
393 (&ty::Array(arr, _), &ty::Str) |
394 (&ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
395 if let hir::ExprKind::Lit(_) = expr.kind {
396 if let Ok(src) = cm.span_to_snippet(sp) {
397 if src.starts_with("\"") {
399 "consider adding a leading `b`",
400 format!("b{}", src)));
407 (_, &ty::Ref(_, _, mutability), _) => {
408 // Check if it can work when put into a ref. For example:
411 // fn bar(x: &mut i32) {}
414 // bar(&x); // error, expected &mut
416 let ref_ty = match mutability {
417 hir::Mutability::Mutable => {
418 self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
420 hir::Mutability::Immutable => {
421 self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
424 if self.can_coerce(ref_ty, expected) {
425 let mut sugg_sp = sp;
426 if let hir::ExprKind::MethodCall(segment, _sp, args) = &expr.kind {
427 let clone_trait = self.tcx.lang_items().clone_trait().unwrap();
428 if let ([arg], Some(true), sym::clone) = (
430 self.tables.borrow().type_dependent_def_id(expr.hir_id).map(|did| {
431 let ai = self.tcx.associated_item(did);
432 ai.container == ty::TraitContainer(clone_trait)
436 // If this expression had a clone call when suggesting borrowing
437 // we want to suggest removing it because it'd now be unnecessary.
441 if let Ok(src) = cm.span_to_snippet(sugg_sp) {
442 let needs_parens = match expr.kind {
443 // parenthesize if needed (Issue #46756)
444 hir::ExprKind::Cast(_, _) |
445 hir::ExprKind::Binary(_, _, _) => true,
446 // parenthesize borrows of range literals (Issue #54505)
447 _ if is_range_literal(self.tcx.sess, expr) => true,
450 let sugg_expr = if needs_parens {
456 if let Some(sugg) = self.can_use_as_ref(expr) {
459 let field_name = if is_struct_pat_shorthand_field {
460 format!("{}: ", sugg_expr)
464 if let Some(hir::Node::Expr(hir::Expr {
465 kind: hir::ExprKind::Assign(left_expr, _),
467 })) = self.tcx.hir().find(
468 self.tcx.hir().get_parent_node(expr.hir_id),
470 if mutability == hir::Mutability::Mutable {
471 // Found the following case:
472 // fn foo(opt: &mut Option<String>){ opt = None }
475 // consider dereferencing here: `*opt` |
476 // expected mutable reference, found enum `Option`
477 if let Ok(src) = cm.span_to_snippet(left_expr.span) {
480 "consider dereferencing here to assign to the mutable \
481 borrowed piece of memory",
488 return Some(match mutability {
489 hir::Mutability::Mutable => (
491 "consider mutably borrowing here",
492 format!("{}&mut {}", field_name, sugg_expr),
494 hir::Mutability::Immutable => (
496 "consider borrowing here",
497 format!("{}&{}", field_name, sugg_expr),
504 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref expr),
506 &ty::Ref(_, checked, _)
508 self.infcx.can_sub(self.param_env, checked, &expected).is_ok() && !is_macro
510 // We have `&T`, check if what was expected was `T`. If so,
511 // we may want to suggest removing a `&`.
512 if !cm.span_to_filename(expr.span).is_real() {
513 if let Ok(code) = cm.span_to_snippet(sp) {
514 if code.chars().next() == Some('&') {
517 "consider removing the borrow",
518 code[1..].to_string(),
524 if let Ok(code) = cm.span_to_snippet(expr.span) {
525 return Some((sp, "consider removing the borrow", code));
528 _ if sp == expr.span && !is_macro => {
529 // Check for `Deref` implementations by constructing a predicate to
530 // prove: `<T as Deref>::Output == U`
531 let deref_trait = self.tcx.lang_items().deref_trait().unwrap();
532 let item_def_id = self.tcx.associated_items(deref_trait).next().unwrap().def_id;
533 let predicate = ty::Predicate::Projection(ty::Binder::bind(ty::ProjectionPredicate {
534 // `<T as Deref>::Output`
535 projection_ty: ty::ProjectionTy {
537 substs: self.tcx.mk_substs_trait(
539 self.fresh_substs_for_item(sp, item_def_id),
547 let obligation = traits::Obligation::new(self.misc(sp), self.param_env, predicate);
548 let impls_deref = self.infcx.predicate_may_hold(&obligation);
550 // For a suggestion to make sense, the type would need to be `Copy`.
551 let is_copy = self.infcx.type_is_copy_modulo_regions(self.param_env, expected, sp);
553 if is_copy && impls_deref {
554 if let Ok(code) = cm.span_to_snippet(sp) {
555 let message = if checked_ty.is_region_ptr() {
556 "consider dereferencing the borrow"
558 "consider dereferencing the type"
560 let suggestion = if is_struct_pat_shorthand_field {
561 format!("{}: *{}", code, code)
565 return Some((sp, message, suggestion));
574 pub fn check_for_cast(
576 err: &mut DiagnosticBuilder<'_>,
578 checked_ty: Ty<'tcx>,
579 expected_ty: Ty<'tcx>,
581 if self.tcx.hir().is_const_context(expr.hir_id) {
582 // Shouldn't suggest `.into()` on `const`s.
583 // FIXME(estebank): modify once we decide to suggest `as` casts
586 if !self.tcx.sess.source_map().span_to_filename(expr.span).is_real() {
587 // Ignore if span is from within a macro.
591 // If casting this expression to a given numeric type would be appropriate in case of a type
594 // We want to minimize the amount of casting operations that are suggested, as it can be a
595 // lossy operation with potentially bad side effects, so we only suggest when encountering
596 // an expression that indicates that the original type couldn't be directly changed.
598 // For now, don't suggest casting with `as`.
599 let can_cast = false;
601 let mut prefix = String::new();
602 if let Some(hir::Node::Expr(hir::Expr {
603 kind: hir::ExprKind::Struct(_, fields, _),
605 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id)) {
606 // `expr` is a literal field for a struct, only suggest if appropriate
607 for field in fields {
608 if field.expr.hir_id == expr.hir_id && field.is_shorthand {
609 // This is a field literal
610 prefix = format!("{}: ", field.ident);
615 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
619 if let hir::ExprKind::Call(path, args) = &expr.kind {
621 hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)),
623 ) = (&path.kind, args.len()) {
624 // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
626 hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)),
628 ) = (&base_ty.kind, path_segment.ident.name) {
629 if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
631 sym::i128 | sym::i64 | sym::i32 | sym::i16 | sym::i8 |
632 sym::u128 | sym::u64 | sym::u32 | sym::u16 | sym::u8 |
633 sym::isize | sym::usize
634 if base_ty_path.segments.len() == 1 => {
644 let msg = format!("you can convert an `{}` to `{}`", checked_ty, expected_ty);
645 let cast_msg = format!("you can cast an `{} to `{}`", checked_ty, expected_ty);
646 let try_msg = format!("{} and panic if the converted value wouldn't fit", msg);
647 let lit_msg = format!(
648 "change the type of the numeric literal from `{}` to `{}`",
653 let needs_paren = expr.precedence().order() < (PREC_POSTFIX as i8);
655 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
656 let cast_suggestion = format!(
659 if needs_paren { "(" } else { "" },
661 if needs_paren { ")" } else { "" },
664 let try_into_suggestion = format!(
665 "{}{}{}{}.try_into().unwrap()",
667 if needs_paren { "(" } else { "" },
669 if needs_paren { ")" } else { "" },
671 let into_suggestion = format!(
674 if needs_paren { "(" } else { "" },
676 if needs_paren { ")" } else { "" },
678 let suffix_suggestion = format!(
680 if needs_paren { "(" } else { "" },
681 if let (ty::Int(_), ty::Float(_)) | (ty::Uint(_), ty::Float(_)) = (
685 // Remove fractional part from literal, for example `42.0f32` into `42`
686 let src = src.trim_end_matches(&checked_ty.to_string());
687 src.split(".").next().unwrap()
689 src.trim_end_matches(&checked_ty.to_string())
692 if needs_paren { ")" } else { "" },
694 let literal_is_ty_suffixed = |expr: &hir::Expr| {
695 if let hir::ExprKind::Lit(lit) = &expr.kind {
696 lit.node.is_suffixed()
702 let suggest_to_change_suffix_or_into = |
703 err: &mut DiagnosticBuilder<'_>,
706 let into_sugg = into_suggestion.clone();
709 if literal_is_ty_suffixed(expr) {
711 } else if is_fallible {
716 if literal_is_ty_suffixed(expr) {
717 suffix_suggestion.clone()
718 } else if is_fallible {
723 Applicability::MachineApplicable,
727 match (&expected_ty.kind, &checked_ty.kind) {
728 (&ty::Int(ref exp), &ty::Int(ref found)) => {
729 let is_fallible = match (found.bit_width(), exp.bit_width()) {
730 (Some(found), Some(exp)) if found > exp => true,
731 (None, _) | (_, None) => true,
734 suggest_to_change_suffix_or_into(err, is_fallible);
737 (&ty::Uint(ref exp), &ty::Uint(ref found)) => {
738 let is_fallible = match (found.bit_width(), exp.bit_width()) {
739 (Some(found), Some(exp)) if found > exp => true,
740 (None, _) | (_, None) => true,
743 suggest_to_change_suffix_or_into(err, is_fallible);
746 (&ty::Int(_), &ty::Uint(_)) | (&ty::Uint(_), &ty::Int(_)) => {
747 suggest_to_change_suffix_or_into(err, true);
750 (&ty::Float(ref exp), &ty::Float(ref found)) => {
751 if found.bit_width() < exp.bit_width() {
752 suggest_to_change_suffix_or_into(err, false);
753 } else if literal_is_ty_suffixed(expr) {
758 Applicability::MachineApplicable,
760 } else if can_cast { // Missing try_into implementation for `f64` to `f32`
763 &format!("{}, producing the closest possible value", cast_msg),
765 Applicability::MaybeIncorrect, // lossy conversion
770 (&ty::Uint(_), &ty::Float(_)) | (&ty::Int(_), &ty::Float(_)) => {
771 if literal_is_ty_suffixed(expr) {
776 Applicability::MachineApplicable,
779 // Missing try_into implementation for `{float}` to `{integer}`
782 &format!("{}, rounding the float towards zero", msg),
784 Applicability::MaybeIncorrect // lossy conversion
786 err.warn("if the rounded value cannot be represented by the target \
787 integer type, including `Inf` and `NaN`, casting will cause \
789 (https://github.com/rust-lang/rust/issues/10184)");
793 (&ty::Float(ref exp), &ty::Uint(ref found)) => {
794 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
795 if exp.bit_width() > found.bit_width().unwrap_or(256) {
799 "{}, producing the floating point representation of the integer",
803 Applicability::MachineApplicable
805 } else if literal_is_ty_suffixed(expr) {
810 Applicability::MachineApplicable,
813 // Missing try_into implementation for `{integer}` to `{float}`
817 "{}, producing the floating point representation of the integer,
818 rounded if necessary",
822 Applicability::MaybeIncorrect // lossy conversion
827 (&ty::Float(ref exp), &ty::Int(ref found)) => {
828 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
829 if exp.bit_width() > found.bit_width().unwrap_or(256) {
833 "{}, producing the floating point representation of the integer",
837 Applicability::MachineApplicable
839 } else if literal_is_ty_suffixed(expr) {
844 Applicability::MachineApplicable,
847 // Missing try_into implementation for `{integer}` to `{float}`
851 "{}, producing the floating point representation of the integer, \
852 rounded if necessary",
856 Applicability::MaybeIncorrect // lossy conversion