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(&self,
107 checked_ty: Ty<'tcx>,
109 allow_two_phase: AllowTwoPhase)
110 -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx>>) {
111 let expected = self.resolve_type_vars_with_obligations(expected);
113 let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase) {
114 Ok(ty) => return (ty, None),
118 let expr = expr.peel_drop_temps();
119 let cause = self.misc(expr.span);
120 let expr_ty = self.resolve_type_vars_with_obligations(checked_ty);
121 let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e);
123 if self.is_assign_to_bool(expr, expected) {
124 // Error reported in `check_assign` so avoid emitting error again.
126 return (expected, None)
129 self.suggest_compatible_variants(&mut err, expr, expected, expr_ty);
130 self.suggest_ref_or_into(&mut err, expr, expected, expr_ty);
131 self.suggest_boxing_when_appropriate(&mut err, expr, expected, expr_ty);
132 self.suggest_missing_await(&mut err, expr, expected, expr_ty);
134 (expected, Some(err))
137 /// Returns whether the expected type is `bool` and the expression is `x = y`.
138 pub fn is_assign_to_bool(&self, expr: &hir::Expr, expected: Ty<'tcx>) -> bool {
139 if let hir::ExprKind::Assign(..) = expr.kind {
140 return expected == self.tcx.types.bool;
145 /// If the expected type is an enum (Issue #55250) with any variants whose
146 /// sole field is of the found type, suggest such variants. (Issue #42764)
147 fn suggest_compatible_variants(
149 err: &mut DiagnosticBuilder<'_>,
154 if let ty::Adt(expected_adt, substs) = expected.kind {
155 if !expected_adt.is_enum() {
159 let mut compatible_variants = expected_adt.variants
161 .filter(|variant| variant.fields.len() == 1)
162 .filter_map(|variant| {
163 let sole_field = &variant.fields[0];
164 let sole_field_ty = sole_field.ty(self.tcx, substs);
165 if self.can_coerce(expr_ty, sole_field_ty) {
166 let variant_path = self.tcx.def_path_str(variant.def_id);
167 // FIXME #56861: DRYer prelude filtering
168 Some(variant_path.trim_start_matches("std::prelude::v1::").to_string())
174 if compatible_variants.peek().is_some() {
175 let expr_text = print::to_string(print::NO_ANN, |s| s.print_expr(expr));
176 let suggestions = compatible_variants
177 .map(|v| format!("{}({})", v, expr_text));
178 let msg = "try using a variant of the expected type";
179 err.span_suggestions(expr.span, msg, suggestions, Applicability::MaybeIncorrect);
184 pub fn get_conversion_methods(&self, span: Span, expected: Ty<'tcx>, checked_ty: Ty<'tcx>)
186 let mut methods = self.probe_for_return_type(span,
187 probe::Mode::MethodCall,
192 self.has_no_input_arg(m) &&
193 self.tcx.get_attrs(m.def_id).iter()
194 // This special internal attribute is used to whitelist
195 // "identity-like" conversion methods to be suggested here.
197 // FIXME (#46459 and #46460): ideally
198 // `std::convert::Into::into` and `std::borrow:ToOwned` would
199 // also be `#[rustc_conversion_suggestion]`, if not for
200 // method-probing false-positives and -negatives (respectively).
202 // FIXME? Other potential candidate methods: `as_ref` and
204 .find(|a| a.check_name(sym::rustc_conversion_suggestion)).is_some()
210 // This function checks if the method isn't static and takes other arguments than `self`.
211 fn has_no_input_arg(&self, method: &AssocItem) -> bool {
213 ty::AssocKind::Method => {
214 self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1
220 /// Identify some cases where `as_ref()` would be appropriate and suggest it.
222 /// Given the following code:
225 /// fn takes_ref(_: &Foo) {}
226 /// let ref opt = Some(Foo);
228 /// opt.map(|param| takes_ref(param));
230 /// Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.
232 /// It only checks for `Option` and `Result` and won't work with
234 /// opt.map(|param| { takes_ref(param) });
239 ) -> Option<(Span, &'static str, String)> {
240 let path = match expr.kind {
241 hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => path,
245 let local_id = match path.res {
246 hir::def::Res::Local(id) => id,
250 let local_parent = self.tcx.hir().get_parent_node(local_id);
251 let param_hir_id = match self.tcx.hir().find(local_parent) {
252 Some(Node::Param(hir::Param { hir_id, .. })) => hir_id,
256 let param_parent = self.tcx.hir().get_parent_node(*param_hir_id);
257 let (expr_hir_id, closure_fn_decl) = match self.tcx.hir().find(param_parent) {
259 hir::Expr { hir_id, kind: hir::ExprKind::Closure(_, decl, ..), .. }
260 )) => (hir_id, decl),
264 let expr_parent = self.tcx.hir().get_parent_node(*expr_hir_id);
265 let hir = self.tcx.hir().find(expr_parent);
266 let closure_params_len = closure_fn_decl.inputs.len();
267 let (method_path, method_span, method_expr) = match (hir, closure_params_len) {
269 hir::Expr { kind: hir::ExprKind::MethodCall(path, span, expr), .. }
270 )), 1) => (path, span, expr),
274 let self_ty = self.tables.borrow().node_type(method_expr[0].hir_id);
275 let self_ty = format!("{:?}", self_ty);
276 let name = method_path.ident.as_str();
277 let is_as_ref_able = (
278 self_ty.starts_with("&std::option::Option") ||
279 self_ty.starts_with("&std::result::Result") ||
280 self_ty.starts_with("std::option::Option") ||
281 self_ty.starts_with("std::result::Result")
282 ) && (name == "map" || name == "and_then");
283 match (is_as_ref_able, self.sess().source_map().span_to_snippet(*method_span)) {
285 let suggestion = format!("as_ref().{}", src);
286 Some((*method_span, "consider using `as_ref` instead", suggestion))
292 crate fn is_hir_id_from_struct_pattern_shorthand_field(
297 let cm = self.sess().source_map();
298 let parent_id = self.tcx.hir().get_parent_node(hir_id);
299 if let Some(parent) = self.tcx.hir().find(parent_id) {
300 // Account for fields
301 if let Node::Expr(hir::Expr {
302 kind: hir::ExprKind::Struct(_, fields, ..), ..
304 if let Ok(src) = cm.span_to_snippet(sp) {
305 for field in fields {
306 if field.ident.as_str() == src.as_str() && field.is_shorthand {
316 /// This function is used to determine potential "simple" improvements or users' errors and
317 /// provide them useful help. For example:
320 /// fn some_fn(s: &str) {}
322 /// let x = "hey!".to_owned();
323 /// some_fn(x); // error
326 /// No need to find every potential function which could make a coercion to transform a
327 /// `String` into a `&str` since a `&` would do the trick!
329 /// In addition of this check, it also checks between references mutability state. If the
330 /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
335 checked_ty: Ty<'tcx>,
337 ) -> Option<(Span, &'static str, String)> {
338 let cm = self.sess().source_map();
340 if !cm.span_to_filename(sp).is_real() {
341 // Ignore if span is from within a macro #41858, #58298. We previously used the macro
342 // call span, but that breaks down when the type error comes from multiple calls down.
346 let is_struct_pat_shorthand_field = self.is_hir_id_from_struct_pattern_shorthand_field(
351 // If the span is from a macro, then it's hard to extract the text
352 // and make a good suggestion, so don't bother.
353 let is_macro = sp.from_expansion() && sp.desugaring_kind().is_none();
355 // `ExprKind::DropTemps` is semantically irrelevant for these suggestions.
356 let expr = expr.peel_drop_temps();
358 match (&expr.kind, &expected.kind, &checked_ty.kind) {
359 (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (&exp.kind, &check.kind) {
360 (&ty::Str, &ty::Array(arr, _)) |
361 (&ty::Str, &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
362 if let hir::ExprKind::Lit(_) = expr.kind {
363 if let Ok(src) = cm.span_to_snippet(sp) {
364 if src.starts_with("b\"") {
366 "consider removing the leading `b`",
367 src[1..].to_string()));
372 (&ty::Array(arr, _), &ty::Str) |
373 (&ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
374 if let hir::ExprKind::Lit(_) = expr.kind {
375 if let Ok(src) = cm.span_to_snippet(sp) {
376 if src.starts_with("\"") {
378 "consider adding a leading `b`",
379 format!("b{}", src)));
386 (_, &ty::Ref(_, _, mutability), _) => {
387 // Check if it can work when put into a ref. For example:
390 // fn bar(x: &mut i32) {}
393 // bar(&x); // error, expected &mut
395 let ref_ty = match mutability {
396 hir::Mutability::MutMutable => {
397 self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
399 hir::Mutability::MutImmutable => {
400 self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
403 if self.can_coerce(ref_ty, expected) {
404 let mut sugg_sp = sp;
405 if let hir::ExprKind::MethodCall(segment, _sp, args) = &expr.kind {
406 let clone_trait = self.tcx.lang_items().clone_trait().unwrap();
407 if let ([arg], Some(true), "clone") = (
409 self.tables.borrow().type_dependent_def_id(expr.hir_id).map(|did| {
410 let ai = self.tcx.associated_item(did);
411 ai.container == ty::TraitContainer(clone_trait)
413 &segment.ident.as_str()[..],
415 // If this expression had a clone call when suggesting borrowing
416 // we want to suggest removing it because it'd now be unecessary.
420 if let Ok(src) = cm.span_to_snippet(sugg_sp) {
421 let needs_parens = match expr.kind {
422 // parenthesize if needed (Issue #46756)
423 hir::ExprKind::Cast(_, _) |
424 hir::ExprKind::Binary(_, _, _) => true,
425 // parenthesize borrows of range literals (Issue #54505)
426 _ if is_range_literal(self.tcx.sess, expr) => true,
429 let sugg_expr = if needs_parens {
435 if let Some(sugg) = self.can_use_as_ref(expr) {
438 let field_name = if is_struct_pat_shorthand_field {
439 format!("{}: ", sugg_expr)
443 if let Some(hir::Node::Expr(hir::Expr {
444 kind: hir::ExprKind::Assign(left_expr, _),
446 })) = self.tcx.hir().find(
447 self.tcx.hir().get_parent_node(expr.hir_id),
449 if mutability == hir::Mutability::MutMutable {
450 // Found the following case:
451 // fn foo(opt: &mut Option<String>){ opt = None }
454 // consider dereferencing here: `*opt` |
455 // expected mutable reference, found enum `Option`
456 if let Ok(src) = cm.span_to_snippet(left_expr.span) {
459 "consider dereferencing here to assign to the mutable \
460 borrowed piece of memory",
467 return Some(match mutability {
468 hir::Mutability::MutMutable => (
470 "consider mutably borrowing here",
471 format!("{}&mut {}", field_name, sugg_expr),
473 hir::Mutability::MutImmutable => (
475 "consider borrowing here",
476 format!("{}&{}", field_name, sugg_expr),
482 (hir::ExprKind::AddrOf(_, ref expr), _, &ty::Ref(_, checked, _)) if {
483 self.infcx.can_sub(self.param_env, checked, &expected).is_ok() && !is_macro
485 // We have `&T`, check if what was expected was `T`. If so,
486 // we may want to suggest removing a `&`.
487 if !cm.span_to_filename(expr.span).is_real() {
488 if let Ok(code) = cm.span_to_snippet(sp) {
489 if code.chars().next() == Some('&') {
492 "consider removing the borrow",
493 code[1..].to_string(),
499 if let Ok(code) = cm.span_to_snippet(expr.span) {
500 return Some((sp, "consider removing the borrow", code));
503 _ if sp == expr.span && !is_macro => {
504 // Check for `Deref` implementations by constructing a predicate to
505 // prove: `<T as Deref>::Output == U`
506 let deref_trait = self.tcx.lang_items().deref_trait().unwrap();
507 let item_def_id = self.tcx.associated_items(deref_trait).next().unwrap().def_id;
508 let predicate = ty::Predicate::Projection(ty::Binder::bind(ty::ProjectionPredicate {
509 // `<T as Deref>::Output`
510 projection_ty: ty::ProjectionTy {
512 substs: self.tcx.mk_substs_trait(
514 self.fresh_substs_for_item(sp, item_def_id),
522 let obligation = traits::Obligation::new(self.misc(sp), self.param_env, predicate);
523 let impls_deref = self.infcx.predicate_may_hold(&obligation);
525 // For a suggestion to make sense, the type would need to be `Copy`.
526 let is_copy = self.infcx.type_is_copy_modulo_regions(self.param_env, expected, sp);
528 if is_copy && impls_deref {
529 if let Ok(code) = cm.span_to_snippet(sp) {
530 let message = if checked_ty.is_region_ptr() {
531 "consider dereferencing the borrow"
533 "consider dereferencing the type"
535 let suggestion = if is_struct_pat_shorthand_field {
536 format!("{}: *{}", code, code)
540 return Some((sp, message, suggestion));
549 pub fn check_for_cast(
551 err: &mut DiagnosticBuilder<'tcx>,
553 checked_ty: Ty<'tcx>,
554 expected_ty: Ty<'tcx>,
556 if self.tcx.hir().is_const_context(expr.hir_id) {
557 // Shouldn't suggest `.into()` on `const`s.
558 // FIXME(estebank): modify once we decide to suggest `as` casts
561 if !self.tcx.sess.source_map().span_to_filename(expr.span).is_real() {
562 // Ignore if span is from within a macro.
566 // If casting this expression to a given numeric type would be appropriate in case of a type
569 // We want to minimize the amount of casting operations that are suggested, as it can be a
570 // lossy operation with potentially bad side effects, so we only suggest when encountering
571 // an expression that indicates that the original type couldn't be directly changed.
573 // For now, don't suggest casting with `as`.
574 let can_cast = false;
576 let mut prefix = String::new();
577 if let Some(hir::Node::Expr(hir::Expr {
578 kind: hir::ExprKind::Struct(_, fields, _),
580 })) = self.tcx.hir().find(self.tcx.hir().get_parent_node(expr.hir_id)) {
581 // `expr` is a literal field for a struct, only suggest if appropriate
582 for field in fields {
583 if field.expr.hir_id == expr.hir_id && field.is_shorthand {
584 // This is a field literal
585 prefix = format!("{}: ", field.ident);
590 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
594 if let hir::ExprKind::Call(path, args) = &expr.kind {
596 hir::ExprKind::Path(hir::QPath::TypeRelative(base_ty, path_segment)),
598 ) = (&path.kind, args.len()) {
599 // `expr` is a conversion like `u32::from(val)`, do not suggest anything (#63697).
601 hir::TyKind::Path(hir::QPath::Resolved(None, base_ty_path)),
603 ) = (&base_ty.kind, path_segment.ident.name) {
604 if let Some(ident) = &base_ty_path.segments.iter().map(|s| s.ident).next() {
606 sym::i128 | sym::i64 | sym::i32 | sym::i16 | sym::i8 |
607 sym::u128 | sym::u64 | sym::u32 | sym::u16 | sym::u8 |
608 sym::isize | sym::usize
609 if base_ty_path.segments.len() == 1 => {
619 let msg = format!("you can convert an `{}` to `{}`", checked_ty, expected_ty);
620 let cast_msg = format!("you can cast an `{} to `{}`", checked_ty, expected_ty);
621 let try_msg = format!("{} and panic if the converted value wouldn't fit", msg);
622 let lit_msg = format!(
623 "change the type of the numeric literal from `{}` to `{}`",
628 let needs_paren = expr.precedence().order() < (PREC_POSTFIX as i8);
630 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
631 let cast_suggestion = format!(
634 if needs_paren { "(" } else { "" },
636 if needs_paren { ")" } else { "" },
639 let try_into_suggestion = format!(
640 "{}{}{}{}.try_into().unwrap()",
642 if needs_paren { "(" } else { "" },
644 if needs_paren { ")" } else { "" },
646 let into_suggestion = format!(
649 if needs_paren { "(" } else { "" },
651 if needs_paren { ")" } else { "" },
653 let suffix_suggestion = format!(
655 if needs_paren { "(" } else { "" },
656 if let (ty::Int(_), ty::Float(_)) | (ty::Uint(_), ty::Float(_)) = (
660 // Remove fractional part from literal, for example `42.0f32` into `42`
661 let src = src.trim_end_matches(&checked_ty.to_string());
662 src.split(".").next().unwrap()
664 src.trim_end_matches(&checked_ty.to_string())
667 if needs_paren { ")" } else { "" },
669 let literal_is_ty_suffixed = |expr: &hir::Expr| {
670 if let hir::ExprKind::Lit(lit) = &expr.kind {
671 lit.node.is_suffixed()
677 let suggest_to_change_suffix_or_into = |
678 err: &mut DiagnosticBuilder<'_>,
681 let into_sugg = into_suggestion.clone();
684 if literal_is_ty_suffixed(expr) {
686 } else if is_fallible {
691 if literal_is_ty_suffixed(expr) {
692 suffix_suggestion.clone()
693 } else if is_fallible {
698 Applicability::MachineApplicable,
702 match (&expected_ty.kind, &checked_ty.kind) {
703 (&ty::Int(ref exp), &ty::Int(ref found)) => {
704 let is_fallible = match (found.bit_width(), exp.bit_width()) {
705 (Some(found), Some(exp)) if found > exp => true,
706 (None, _) | (_, None) => true,
709 suggest_to_change_suffix_or_into(err, is_fallible);
712 (&ty::Uint(ref exp), &ty::Uint(ref found)) => {
713 let is_fallible = match (found.bit_width(), exp.bit_width()) {
714 (Some(found), Some(exp)) if found > exp => true,
715 (None, _) | (_, None) => true,
718 suggest_to_change_suffix_or_into(err, is_fallible);
721 (&ty::Int(_), &ty::Uint(_)) | (&ty::Uint(_), &ty::Int(_)) => {
722 suggest_to_change_suffix_or_into(err, true);
725 (&ty::Float(ref exp), &ty::Float(ref found)) => {
726 if found.bit_width() < exp.bit_width() {
727 suggest_to_change_suffix_or_into(err, false);
728 } else if literal_is_ty_suffixed(expr) {
733 Applicability::MachineApplicable,
735 } else if can_cast { // Missing try_into implementation for `f64` to `f32`
738 &format!("{}, producing the closest possible value", cast_msg),
740 Applicability::MaybeIncorrect, // lossy conversion
745 (&ty::Uint(_), &ty::Float(_)) | (&ty::Int(_), &ty::Float(_)) => {
746 if literal_is_ty_suffixed(expr) {
751 Applicability::MachineApplicable,
754 // Missing try_into implementation for `{float}` to `{integer}`
757 &format!("{}, rounding the float towards zero", msg),
759 Applicability::MaybeIncorrect // lossy conversion
761 err.warn("if the rounded value cannot be represented by the target \
762 integer type, including `Inf` and `NaN`, casting will cause \
764 (https://github.com/rust-lang/rust/issues/10184)");
768 (&ty::Float(ref exp), &ty::Uint(ref found)) => {
769 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
770 if exp.bit_width() > found.bit_width().unwrap_or(256) {
774 "{}, producing the floating point representation of the integer",
778 Applicability::MachineApplicable
780 } else if literal_is_ty_suffixed(expr) {
785 Applicability::MachineApplicable,
788 // Missing try_into implementation for `{integer}` to `{float}`
792 "{}, producing the floating point representation of the integer,
793 rounded if necessary",
797 Applicability::MaybeIncorrect // lossy conversion
802 (&ty::Float(ref exp), &ty::Int(ref found)) => {
803 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
804 if exp.bit_width() > found.bit_width().unwrap_or(256) {
808 "{}, producing the floating point representation of the integer",
812 Applicability::MachineApplicable
814 } else if literal_is_ty_suffixed(expr) {
819 Applicability::MachineApplicable,
822 // Missing try_into implementation for `{integer}` to `{float}`
826 "{}, producing the floating point representation of the integer, \
827 rounded if necessary",
831 Applicability::MaybeIncorrect // lossy conversion