1 use crate::check::FnCtxt;
2 use rustc::infer::InferOk;
3 use rustc::traits::{self, ObligationCause, ObligationCauseCode};
5 use syntax::util::parser::PREC_POSTFIX;
8 use rustc::hir::def::Def;
10 use rustc::hir::{Item, ItemKind, print};
11 use rustc::ty::{self, Ty, AssociatedItem};
12 use rustc::ty::adjustment::AllowTwoPhase;
13 use errors::{Applicability, DiagnosticBuilder};
15 use super::method::probe;
17 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, '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 cause = self.misc(expr.span);
119 let expr_ty = self.resolve_type_vars_with_obligations(checked_ty);
120 let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e);
122 if self.is_assign_to_bool(expr, expected) {
123 // Error reported in `check_assign` so avoid emitting error again.
125 return (expected, None)
128 self.suggest_compatible_variants(&mut err, expr, expected, expr_ty);
129 self.suggest_ref_or_into(&mut err, expr, expected, expr_ty);
131 (expected, Some(err))
134 /// Returns whether the expected type is `bool` and the expression is `x = y`.
135 pub fn is_assign_to_bool(&self, expr: &hir::Expr, expected: Ty<'tcx>) -> bool {
136 if let hir::ExprKind::Assign(..) = expr.node {
137 return expected == self.tcx.types.bool;
142 /// If the expected type is an enum (Issue #55250) with any variants whose
143 /// sole field is of the found type, suggest such variants. (Issue #42764)
144 fn suggest_compatible_variants(
146 err: &mut DiagnosticBuilder<'_>,
151 if let ty::Adt(expected_adt, substs) = expected.sty {
152 if !expected_adt.is_enum() {
156 let mut compatible_variants = expected_adt.variants
158 .filter(|variant| variant.fields.len() == 1)
159 .filter_map(|variant| {
160 let sole_field = &variant.fields[0];
161 let sole_field_ty = sole_field.ty(self.tcx, substs);
162 if self.can_coerce(expr_ty, sole_field_ty) {
163 let variant_path = self.tcx.def_path_str(variant.def_id);
164 // FIXME #56861: DRYer prelude filtering
165 Some(variant_path.trim_start_matches("std::prelude::v1::").to_string())
171 if compatible_variants.peek().is_some() {
172 let expr_text = print::to_string(print::NO_ANN, |s| s.print_expr(expr));
173 let suggestions = compatible_variants
174 .map(|v| format!("{}({})", v, expr_text));
175 let msg = "try using a variant of the expected type";
176 err.span_suggestions(expr.span, msg, suggestions, Applicability::MaybeIncorrect);
181 pub fn get_conversion_methods(&self, span: Span, expected: Ty<'tcx>, checked_ty: Ty<'tcx>)
182 -> Vec<AssociatedItem> {
183 let mut methods = self.probe_for_return_type(span,
184 probe::Mode::MethodCall,
189 self.has_no_input_arg(m) &&
190 self.tcx.get_attrs(m.def_id).iter()
191 // This special internal attribute is used to whitelist
192 // "identity-like" conversion methods to be suggested here.
194 // FIXME (#46459 and #46460): ideally
195 // `std::convert::Into::into` and `std::borrow:ToOwned` would
196 // also be `#[rustc_conversion_suggestion]`, if not for
197 // method-probing false-positives and -negatives (respectively).
199 // FIXME? Other potential candidate methods: `as_ref` and
201 .find(|a| a.check_name("rustc_conversion_suggestion")).is_some()
207 // This function checks if the method isn't static and takes other arguments than `self`.
208 fn has_no_input_arg(&self, method: &AssociatedItem) -> bool {
210 Def::Method(def_id) => {
211 self.tcx.fn_sig(def_id).inputs().skip_binder().len() == 1
217 /// Identify some cases where `as_ref()` would be appropriate and suggest it.
219 /// Given the following code:
222 /// fn takes_ref(_: &Foo) {}
223 /// let ref opt = Some(Foo);
225 /// opt.map(|arg| takes_ref(arg));
227 /// Suggest using `opt.as_ref().map(|arg| takes_ref(arg));` instead.
229 /// It only checks for `Option` and `Result` and won't work with
231 /// opt.map(|arg| { takes_ref(arg) });
236 ) -> Option<(Span, &'static str, String)> {
237 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.node {
238 if let hir::def::Def::Local(id) = path.def {
239 let parent = self.tcx.hir().get_parent_node_by_hir_id(id);
240 if let Some(Node::Expr(hir::Expr {
242 node: hir::ExprKind::Closure(_, decl, ..),
244 })) = self.tcx.hir().find_by_hir_id(parent) {
245 let parent = self.tcx.hir().get_parent_node_by_hir_id(*hir_id);
246 if let (Some(Node::Expr(hir::Expr {
247 node: hir::ExprKind::MethodCall(path, span, expr),
249 })), 1) = (self.tcx.hir().find_by_hir_id(parent), decl.inputs.len()) {
250 let self_ty = self.tables.borrow().node_type(expr[0].hir_id);
251 let self_ty = format!("{:?}", self_ty);
252 let name = path.ident.as_str();
253 let is_as_ref_able = (
254 self_ty.starts_with("&std::option::Option") ||
255 self_ty.starts_with("&std::result::Result") ||
256 self_ty.starts_with("std::option::Option") ||
257 self_ty.starts_with("std::result::Result")
258 ) && (name == "map" || name == "and_then");
259 match (is_as_ref_able, self.sess().source_map().span_to_snippet(*span)) {
261 return Some((*span, "consider using `as_ref` instead",
262 format!("as_ref().{}", src)));
273 fn is_hir_id_from_struct_pattern_shorthand_field(&self, hir_id: hir::HirId, sp: Span) -> bool {
274 let cm = self.sess().source_map();
275 let parent_id = self.tcx.hir().get_parent_node_by_hir_id(hir_id);
276 if let Some(parent) = self.tcx.hir().find_by_hir_id(parent_id) {
277 // Account for fields
278 if let Node::Expr(hir::Expr {
279 node: hir::ExprKind::Struct(_, fields, ..), ..
281 if let Ok(src) = cm.span_to_snippet(sp) {
282 for field in fields {
283 if field.ident.as_str() == src.as_str() && field.is_shorthand {
293 /// This function is used to determine potential "simple" improvements or users' errors and
294 /// provide them useful help. For example:
297 /// fn some_fn(s: &str) {}
299 /// let x = "hey!".to_owned();
300 /// some_fn(x); // error
303 /// No need to find every potential function which could make a coercion to transform a
304 /// `String` into a `&str` since a `&` would do the trick!
306 /// In addition of this check, it also checks between references mutability state. If the
307 /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
309 pub fn check_ref(&self,
311 checked_ty: Ty<'tcx>,
313 -> Option<(Span, &'static str, String)> {
314 let cm = self.sess().source_map();
316 if !cm.span_to_filename(sp).is_real() {
317 // Ignore if span is from within a macro #41858, #58298. We previously used the macro
318 // call span, but that breaks down when the type error comes from multiple calls down.
322 let is_struct_pat_shorthand_field = self.is_hir_id_from_struct_pattern_shorthand_field(
327 // Check the `expn_info()` to see if this is a macro; if so, it's hard to
328 // extract the text and make a good suggestion, so don't bother.
329 let is_macro = sp.ctxt().outer().expn_info().is_some();
331 match (&expr.node, &expected.sty, &checked_ty.sty) {
332 (_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (&exp.sty, &check.sty) {
333 (&ty::Str, &ty::Array(arr, _)) |
334 (&ty::Str, &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
335 if let hir::ExprKind::Lit(_) = expr.node {
336 if let Ok(src) = cm.span_to_snippet(sp) {
337 if src.starts_with("b\"") {
339 "consider removing the leading `b`",
340 src[1..].to_string()));
345 (&ty::Array(arr, _), &ty::Str) |
346 (&ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
347 if let hir::ExprKind::Lit(_) = expr.node {
348 if let Ok(src) = cm.span_to_snippet(sp) {
349 if src.starts_with("\"") {
351 "consider adding a leading `b`",
352 format!("b{}", src)));
359 (_, &ty::Ref(_, _, mutability), _) => {
360 // Check if it can work when put into a ref. For example:
363 // fn bar(x: &mut i32) {}
366 // bar(&x); // error, expected &mut
368 let ref_ty = match mutability {
369 hir::Mutability::MutMutable => {
370 self.tcx.mk_mut_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
372 hir::Mutability::MutImmutable => {
373 self.tcx.mk_imm_ref(self.tcx.mk_region(ty::ReStatic), checked_ty)
376 if self.can_coerce(ref_ty, expected) {
377 if let Ok(src) = cm.span_to_snippet(sp) {
378 let needs_parens = match expr.node {
379 // parenthesize if needed (Issue #46756)
380 hir::ExprKind::Cast(_, _) |
381 hir::ExprKind::Binary(_, _, _) => true,
382 // parenthesize borrows of range literals (Issue #54505)
383 _ if self.is_range_literal(expr) => true,
386 let sugg_expr = if needs_parens {
392 if let Some(sugg) = self.can_use_as_ref(expr) {
395 let field_name = if is_struct_pat_shorthand_field {
396 format!("{}: ", sugg_expr)
400 return Some(match mutability {
401 hir::Mutability::MutMutable => (
403 "consider mutably borrowing here",
404 format!("{}&mut {}", field_name, sugg_expr),
406 hir::Mutability::MutImmutable => (
408 "consider borrowing here",
409 format!("{}&{}", field_name, sugg_expr),
415 (hir::ExprKind::AddrOf(_, ref expr), _, &ty::Ref(_, checked, _)) if {
416 self.infcx.can_sub(self.param_env, checked, &expected).is_ok() && !is_macro
418 // We have `&T`, check if what was expected was `T`. If so,
419 // we may want to suggest removing a `&`.
420 if !cm.span_to_filename(expr.span).is_real() {
421 if let Ok(code) = cm.span_to_snippet(sp) {
422 if code.chars().next() == Some('&') {
425 "consider removing the borrow",
426 code[1..].to_string(),
432 if let Ok(code) = cm.span_to_snippet(expr.span) {
433 return Some((sp, "consider removing the borrow", code));
436 _ if sp == expr.span && !is_macro => {
437 // Check for `Deref` implementations by constructing a predicate to
438 // prove: `<T as Deref>::Output == U`
439 let deref_trait = self.tcx.lang_items().deref_trait().unwrap();
440 let item_def_id = self.tcx.associated_items(deref_trait).next().unwrap().def_id;
441 let predicate = ty::Predicate::Projection(ty::Binder::bind(ty::ProjectionPredicate {
442 // `<T as Deref>::Output`
443 projection_ty: ty::ProjectionTy {
445 substs: self.tcx.mk_substs_trait(
447 self.fresh_substs_for_item(sp, item_def_id),
455 let obligation = traits::Obligation::new(self.misc(sp), self.param_env, predicate);
456 let impls_deref = self.infcx.predicate_may_hold(&obligation);
458 // For a suggestion to make sense, the type would need to be `Copy`.
459 let is_copy = self.infcx.type_is_copy_modulo_regions(self.param_env, expected, sp);
461 if is_copy && impls_deref {
462 if let Ok(code) = cm.span_to_snippet(sp) {
463 let message = if checked_ty.is_region_ptr() {
464 "consider dereferencing the borrow"
466 "consider dereferencing the type"
468 let suggestion = if is_struct_pat_shorthand_field {
469 format!("{}: *{}", code, code)
473 return Some((sp, message, suggestion));
482 /// This function checks if the specified expression is a built-in range literal.
483 /// (See: `LoweringContext::lower_expr()` in `src/librustc/hir/lowering.rs`).
484 fn is_range_literal(&self, expr: &hir::Expr) -> bool {
485 use hir::{Path, QPath, ExprKind, TyKind};
487 // We support `::std::ops::Range` and `::core::ops::Range` prefixes
488 let is_range_path = |path: &Path| {
489 let mut segs = path.segments.iter()
490 .map(|seg| seg.ident.as_str());
492 if let (Some(root), Some(std_core), Some(ops), Some(range), None) =
493 (segs.next(), segs.next(), segs.next(), segs.next(), segs.next())
495 // "{{root}}" is the equivalent of `::` prefix in Path
496 root == "{{root}}" && (std_core == "std" || std_core == "core")
497 && ops == "ops" && range.starts_with("Range")
503 let span_is_range_literal = |span: &Span| {
504 // Check whether a span corresponding to a range expression
505 // is a range literal, rather than an explicit struct or `new()` call.
506 let source_map = self.tcx.sess.source_map();
507 let end_point = source_map.end_point(*span);
509 if let Ok(end_string) = source_map.span_to_snippet(end_point) {
510 !(end_string.ends_with("}") || end_string.ends_with(")"))
517 // All built-in range literals but `..=` and `..` desugar to Structs
518 ExprKind::Struct(ref qpath, _, _) => {
519 if let QPath::Resolved(None, ref path) = **qpath {
520 return is_range_path(&path) && span_is_range_literal(&expr.span);
523 // `..` desugars to its struct path
524 ExprKind::Path(QPath::Resolved(None, ref path)) => {
525 return is_range_path(&path) && span_is_range_literal(&expr.span);
528 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`
529 ExprKind::Call(ref func, _) => {
530 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node {
531 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node {
532 let call_to_new = segment.ident.as_str() == "new";
534 return is_range_path(&path) && span_is_range_literal(&expr.span)
546 pub fn check_for_cast(
548 err: &mut DiagnosticBuilder<'tcx>,
550 checked_ty: Ty<'tcx>,
551 expected_ty: Ty<'tcx>,
553 let parent_id = self.tcx.hir().get_parent_node_by_hir_id(expr.hir_id);
554 if let Some(parent) = self.tcx.hir().find_by_hir_id(parent_id) {
555 // Shouldn't suggest `.into()` on `const`s.
556 if let Node::Item(Item { node: ItemKind::Const(_, _), .. }) = parent {
557 // FIXME(estebank): modify once we decide to suggest `as` casts
562 // If casting this expression to a given numeric type would be appropriate in case of a type
565 // We want to minimize the amount of casting operations that are suggested, as it can be a
566 // lossy operation with potentially bad side effects, so we only suggest when encountering
567 // an expression that indicates that the original type couldn't be directly changed.
569 // For now, don't suggest casting with `as`.
570 let can_cast = false;
572 let mut prefix = String::new();
573 if let Some(hir::Node::Expr(hir::Expr {
574 node: hir::ExprKind::Struct(_, fields, _),
576 })) = self.tcx.hir().find_by_hir_id(self.tcx.hir().get_parent_node_by_hir_id(expr.hir_id)) {
577 // `expr` is a literal field for a struct, only suggest if appropriate
578 for field in fields {
579 if field.expr.hir_id == expr.hir_id && field.is_shorthand {
580 // This is a field literal
581 prefix = format!("{}: ", field.ident);
586 // Likely a field was meant, but this field wasn't found. Do not suggest anything.
591 let msg = format!("you can convert an `{}` to `{}`", checked_ty, expected_ty);
592 let cast_msg = format!("you can cast an `{} to `{}`", checked_ty, expected_ty);
593 let try_msg = format!("{} or panic if it the converted value wouldn't fit", msg);
594 let lit_msg = format!(
595 "change the type of the numeric literal from `{}` to `{}`",
600 let needs_paren = expr.precedence().order() < (PREC_POSTFIX as i8);
602 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
603 let cast_suggestion = format!(
606 if needs_paren { "(" } else { "" },
608 if needs_paren { ")" } else { "" },
611 let try_into_suggestion = format!(
612 "{}{}{}{}.try_into().unwrap()",
614 if needs_paren { "(" } else { "" },
616 if needs_paren { ")" } else { "" },
618 let into_suggestion = format!(
621 if needs_paren { "(" } else { "" },
623 if needs_paren { ")" } else { "" },
625 let suffix_suggestion = format!(
627 if needs_paren { "(" } else { "" },
628 if let (ty::Int(_), ty::Float(_)) | (ty::Uint(_), ty::Float(_)) = (
632 // Remove fractional part from literal, for example `42.0f32` into `42`
633 let src = src.trim_end_matches(&checked_ty.to_string());
634 src.split(".").next().unwrap()
636 src.trim_end_matches(&checked_ty.to_string())
639 if needs_paren { ")" } else { "" },
641 let literal_is_ty_suffixed = |expr: &hir::Expr| {
642 if let hir::ExprKind::Lit(lit) = &expr.node {
643 lit.node.is_suffixed()
649 let suggest_to_change_suffix_or_into = |
650 err: &mut DiagnosticBuilder<'_>,
653 let into_sugg = into_suggestion.clone();
656 if literal_is_ty_suffixed(expr) {
658 } else if is_fallible {
663 if literal_is_ty_suffixed(expr) {
664 suffix_suggestion.clone()
665 } else if is_fallible {
670 Applicability::MachineApplicable,
674 match (&expected_ty.sty, &checked_ty.sty) {
675 (&ty::Int(ref exp), &ty::Int(ref found)) => {
676 let is_fallible = match (found.bit_width(), exp.bit_width()) {
677 (Some(found), Some(exp)) if found > exp => true,
678 (None, _) | (_, None) => true,
681 suggest_to_change_suffix_or_into(err, is_fallible);
684 (&ty::Uint(ref exp), &ty::Uint(ref found)) => {
685 let is_fallible = match (found.bit_width(), exp.bit_width()) {
686 (Some(found), Some(exp)) if found > exp => true,
687 (None, _) | (_, None) => true,
690 suggest_to_change_suffix_or_into(err, is_fallible);
693 (&ty::Int(_), &ty::Uint(_)) | (&ty::Uint(_), &ty::Int(_)) => {
694 suggest_to_change_suffix_or_into(err, true);
697 (&ty::Float(ref exp), &ty::Float(ref found)) => {
698 if found.bit_width() < exp.bit_width() {
699 suggest_to_change_suffix_or_into(err, false);
700 } else if literal_is_ty_suffixed(expr) {
705 Applicability::MachineApplicable,
707 } else if can_cast { // Missing try_into implementation for `f64` to `f32`
710 &format!("{}, producing the closest possible value", cast_msg),
712 Applicability::MaybeIncorrect, // lossy conversion
717 (&ty::Uint(_), &ty::Float(_)) | (&ty::Int(_), &ty::Float(_)) => {
718 if literal_is_ty_suffixed(expr) {
723 Applicability::MachineApplicable,
726 // Missing try_into implementation for `{float}` to `{integer}`
729 &format!("{}, rounding the float towards zero", msg),
731 Applicability::MaybeIncorrect // lossy conversion
733 err.warn("if the rounded value cannot be represented by the target \
734 integer type, including `Inf` and `NaN`, casting will cause \
736 (https://github.com/rust-lang/rust/issues/10184)");
740 (&ty::Float(ref exp), &ty::Uint(ref found)) => {
741 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
742 if exp.bit_width() > found.bit_width().unwrap_or(256) {
746 "{}, producing the floating point representation of the integer",
750 Applicability::MachineApplicable
752 } else if literal_is_ty_suffixed(expr) {
757 Applicability::MachineApplicable,
760 // Missing try_into implementation for `{integer}` to `{float}`
764 "{}, producing the floating point representation of the integer,
765 rounded if necessary",
769 Applicability::MaybeIncorrect // lossy conversion
774 (&ty::Float(ref exp), &ty::Int(ref found)) => {
775 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
776 if exp.bit_width() > found.bit_width().unwrap_or(256) {
780 "{}, producing the floating point representation of the integer",
784 Applicability::MachineApplicable
786 } else if literal_is_ty_suffixed(expr) {
791 Applicability::MachineApplicable,
794 // Missing try_into implementation for `{integer}` to `{float}`
798 "{}, producing the floating point representation of the integer, \
799 rounded if necessary",
803 Applicability::MaybeIncorrect // lossy conversion