1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use rustc::infer::InferOk;
13 use rustc::traits::ObligationCause;
16 use syntax::util::parser::PREC_POSTFIX;
19 use rustc::hir::def::Def;
21 use rustc::hir::{Item, ItemKind, print};
22 use rustc::ty::{self, Ty, AssociatedItem};
23 use rustc::ty::adjustment::AllowTwoPhase;
24 use errors::{Applicability, DiagnosticBuilder, SourceMapper};
26 use super::method::probe;
28 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
29 // Requires that the two types unify, and prints an error message if
31 pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
32 self.demand_suptype_diag(sp, expected, actual).map(|mut e| e.emit());
35 pub fn demand_suptype_diag(&self,
38 actual: Ty<'tcx>) -> Option<DiagnosticBuilder<'tcx>> {
39 let cause = &self.misc(sp);
40 match self.at(cause, self.param_env).sup(expected, actual) {
41 Ok(InferOk { obligations, value: () }) => {
42 self.register_predicates(obligations);
46 Some(self.report_mismatched_types(&cause, expected, actual, e))
51 pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
52 if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
57 pub fn demand_eqtype_diag(&self,
60 actual: Ty<'tcx>) -> Option<DiagnosticBuilder<'tcx>> {
61 self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
64 pub fn demand_eqtype_with_origin(&self,
65 cause: &ObligationCause<'tcx>,
67 actual: Ty<'tcx>) -> Option<DiagnosticBuilder<'tcx>> {
68 match self.at(cause, self.param_env).eq(expected, actual) {
69 Ok(InferOk { obligations, value: () }) => {
70 self.register_predicates(obligations);
74 Some(self.report_mismatched_types(cause, expected, actual, e))
79 pub fn demand_coerce(&self,
83 allow_two_phase: AllowTwoPhase)
85 let (ty, err) = self.demand_coerce_diag(expr, checked_ty, expected, allow_two_phase);
86 if let Some(mut err) = err {
92 // Checks that the type of `expr` can be coerced to `expected`.
94 // NB: This code relies on `self.diverges` to be accurate. In
95 // particular, assignments to `!` will be permitted if the
96 // diverges flag is currently "always".
97 pub fn demand_coerce_diag(&self,
101 allow_two_phase: AllowTwoPhase)
102 -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx>>) {
103 let expected = self.resolve_type_vars_with_obligations(expected);
105 let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase) {
106 Ok(ty) => return (ty, None),
110 let cause = self.misc(expr.span);
111 let expr_ty = self.resolve_type_vars_with_obligations(checked_ty);
112 let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e);
114 // If the expected type is an enum with any variants whose sole
115 // field is of the found type, suggest such variants. See Issue
117 if let ty::Adt(expected_adt, substs) = expected.sty {
118 let compatible_variants = expected_adt.variants
120 .filter(|variant| variant.fields.len() == 1)
121 .filter_map(|variant| {
122 let sole_field = &variant.fields[0];
123 let sole_field_ty = sole_field.ty(self.tcx, substs);
124 if self.can_coerce(expr_ty, sole_field_ty) {
125 let variant_path = self.tcx.item_path_str(variant.did);
126 Some(variant_path.trim_left_matches("std::prelude::v1::").to_string())
130 }).collect::<Vec<_>>();
132 if !compatible_variants.is_empty() {
133 let expr_text = print::to_string(print::NO_ANN, |s| s.print_expr(expr));
134 let suggestions = compatible_variants.iter()
135 .map(|v| format!("{}({})", v, expr_text)).collect::<Vec<_>>();
136 err.span_suggestions_with_applicability(
138 "try using a variant of the expected type",
140 Applicability::MaybeIncorrect,
145 self.suggest_ref_or_into(&mut err, expr, expected, expr_ty);
147 (expected, Some(err))
150 pub fn get_conversion_methods(&self, span: Span, expected: Ty<'tcx>, checked_ty: Ty<'tcx>)
151 -> Vec<AssociatedItem> {
152 let mut methods = self.probe_for_return_type(span,
153 probe::Mode::MethodCall,
158 self.has_no_input_arg(m) &&
159 self.tcx.get_attrs(m.def_id).iter()
160 // This special internal attribute is used to whitelist
161 // "identity-like" conversion methods to be suggested here.
163 // FIXME (#46459 and #46460): ideally
164 // `std::convert::Into::into` and `std::borrow:ToOwned` would
165 // also be `#[rustc_conversion_suggestion]`, if not for
166 // method-probing false-positives and -negatives (respectively).
168 // FIXME? Other potential candidate methods: `as_ref` and
170 .find(|a| a.check_name("rustc_conversion_suggestion")).is_some()
176 // This function checks if the method isn't static and takes other arguments than `self`.
177 fn has_no_input_arg(&self, method: &AssociatedItem) -> bool {
179 Def::Method(def_id) => {
180 self.tcx.fn_sig(def_id).inputs().skip_binder().len() == 1
186 /// Identify some cases where `as_ref()` would be appropriate and suggest it.
188 /// Given the following code:
191 /// fn takes_ref(_: &Foo) {}
192 /// let ref opt = Some(Foo);
194 /// opt.map(|arg| takes_ref(arg));
196 /// Suggest using `opt.as_ref().map(|arg| takes_ref(arg));` instead.
198 /// It only checks for `Option` and `Result` and won't work with
200 /// opt.map(|arg| { takes_ref(arg) });
202 fn can_use_as_ref(&self, expr: &hir::Expr) -> Option<(Span, &'static str, String)> {
203 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.node {
204 if let hir::def::Def::Local(id) = path.def {
205 let parent = self.tcx.hir.get_parent_node(id);
206 if let Some(Node::Expr(hir::Expr {
208 node: hir::ExprKind::Closure(_, decl, ..),
210 })) = self.tcx.hir.find(parent) {
211 let parent = self.tcx.hir.get_parent_node(*id);
212 if let (Some(Node::Expr(hir::Expr {
213 node: hir::ExprKind::MethodCall(path, span, expr),
215 })), 1) = (self.tcx.hir.find(parent), decl.inputs.len()) {
216 let self_ty = self.tables.borrow().node_id_to_type(expr[0].hir_id);
217 let self_ty = format!("{:?}", self_ty);
218 let name = path.ident.as_str();
219 let is_as_ref_able = (
220 self_ty.starts_with("&std::option::Option") ||
221 self_ty.starts_with("&std::result::Result") ||
222 self_ty.starts_with("std::option::Option") ||
223 self_ty.starts_with("std::result::Result")
224 ) && (name == "map" || name == "and_then");
226 return Some((span.shrink_to_lo(),
227 "consider using `as_ref` instead",
228 "as_ref().".into()));
237 /// This function is used to determine potential "simple" improvements or users' errors and
238 /// provide them useful help. For example:
241 /// fn some_fn(s: &str) {}
243 /// let x = "hey!".to_owned();
244 /// some_fn(x); // error
247 /// No need to find every potential function which could make a coercion to transform a
248 /// `String` into a `&str` since a `&` would do the trick!
250 /// In addition of this check, it also checks between references mutability state. If the
251 /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
253 pub fn check_ref(&self,
255 checked_ty: Ty<'tcx>,
257 -> Option<(Span, &'static str, String)> {
258 let cm = self.sess().source_map();
259 // Use the callsite's span if this is a macro call. #41858
260 let sp = cm.call_span_if_macro(expr.span);
261 if !cm.span_to_filename(sp).is_real() {
265 match (&expected.sty, &checked_ty.sty) {
266 (&ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (&exp.sty, &check.sty) {
267 (&ty::Str, &ty::Array(arr, _)) |
268 (&ty::Str, &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
269 if let hir::ExprKind::Lit(_) = expr.node {
270 if let Ok(src) = cm.span_to_snippet(sp) {
271 if src.starts_with("b\"") {
273 "consider removing the leading `b`",
274 src[1..].to_string()));
279 (&ty::Array(arr, _), &ty::Str) |
280 (&ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
281 if let hir::ExprKind::Lit(_) = expr.node {
282 if let Ok(src) = cm.span_to_snippet(sp) {
283 if src.starts_with("\"") {
285 "consider adding a leading `b`",
286 format!("b{}", src)));
293 (&ty::Ref(_, _, mutability), _) => {
294 // Check if it can work when put into a ref. For example:
297 // fn bar(x: &mut i32) {}
300 // bar(&x); // error, expected &mut
302 let ref_ty = match mutability {
303 hir::Mutability::MutMutable => self.tcx.mk_mut_ref(
304 self.tcx.mk_region(ty::ReStatic),
306 hir::Mutability::MutImmutable => self.tcx.mk_imm_ref(
307 self.tcx.mk_region(ty::ReStatic),
310 if self.can_coerce(ref_ty, expected) {
311 if let Ok(src) = cm.span_to_snippet(sp) {
312 let sugg_expr = match expr.node { // parenthesize if needed (Issue #46756)
313 hir::ExprKind::Cast(_, _) |
314 hir::ExprKind::Binary(_, _, _) |
315 _ if self.is_range_literal(expr) => format!("({})", src),
318 if let Some(sugg) = self.can_use_as_ref(expr) {
321 return Some(match mutability {
322 hir::Mutability::MutMutable => {
323 (sp, "consider mutably borrowing here", format!("&mut {}",
326 hir::Mutability::MutImmutable => {
327 (sp, "consider borrowing here", format!("&{}", sugg_expr))
333 (_, &ty::Ref(_, checked, _)) => {
334 // We have `&T`, check if what was expected was `T`. If so,
335 // we may want to suggest adding a `*`, or removing
338 // (But, also check check the `expn_info()` to see if this is
339 // a macro; if so, it's hard to extract the text and make a good
340 // suggestion, so don't bother.)
341 if self.infcx.can_sub(self.param_env, checked, &expected).is_ok() &&
342 sp.ctxt().outer().expn_info().is_none() {
345 hir::ExprKind::AddrOf(_, ref expr) => {
346 if !cm.span_to_filename(expr.span).is_real() {
349 if let Ok(code) = cm.span_to_snippet(expr.span) {
350 return Some((sp, "consider removing the borrow", code));
354 // Maybe add `*`? Only if `T: Copy`.
356 if !self.infcx.type_moves_by_default(self.param_env,
359 // do not suggest if the span comes from a macro (#52783)
361 true) = (cm.span_to_snippet(sp), sp == expr.span) {
364 "consider dereferencing the borrow",
365 format!("*{}", code),
378 // This function checks if the specified expression is a built-in range literal
379 // (See: librustc/hir/lowering.rs::LoweringContext::lower_expr() )
380 fn is_range_literal(&self, expr: &hir::Expr) -> bool {
381 use hir::{Path, QPath, ExprKind, TyKind};
383 // TODO how to work out std vs core here?
384 let ops_path = ["{{root}}", "std", "ops"];
386 let is_range_path = |path: &Path| {
387 let ident_names: Vec<_> = path.segments
389 .map(|seg| seg.ident.as_str())
392 if let Some((last, preceding)) = ident_names.split_last() {
393 last.starts_with("Range") &&
394 preceding.len() == 3 &&
396 .zip(ops_path.iter())
397 .all(|(a, b)| a == b)
404 ExprKind::Struct(QPath::Resolved(None, ref path), _, _) |
405 ExprKind::Path(QPath::Resolved(None, ref path)) => {
406 return is_range_path(&path);
409 ExprKind::Call(ref func, _) => {
410 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node {
411 if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node {
412 let calls_new = segment.ident.as_str() == "new";
414 return is_range_path(&path) && calls_new;
425 pub fn check_for_cast(&self,
426 err: &mut DiagnosticBuilder<'tcx>,
428 checked_ty: Ty<'tcx>,
429 expected_ty: Ty<'tcx>)
431 let parent_id = self.tcx.hir.get_parent_node(expr.id);
432 if let Some(parent) = self.tcx.hir.find(parent_id) {
433 // Shouldn't suggest `.into()` on `const`s.
434 if let Node::Item(Item { node: ItemKind::Const(_, _), .. }) = parent {
435 // FIXME(estebank): modify once we decide to suggest `as` casts
440 let will_truncate = "will truncate the source value";
441 let depending_on_isize = "will truncate or zero-extend depending on the bit width of \
443 let depending_on_usize = "will truncate or zero-extend depending on the bit width of \
445 let will_sign_extend = "will sign-extend the source value";
446 let will_zero_extend = "will zero-extend the source value";
448 // If casting this expression to a given numeric type would be appropriate in case of a type
451 // We want to minimize the amount of casting operations that are suggested, as it can be a
452 // lossy operation with potentially bad side effects, so we only suggest when encountering
453 // an expression that indicates that the original type couldn't be directly changed.
455 // For now, don't suggest casting with `as`.
456 let can_cast = false;
458 let needs_paren = expr.precedence().order() < (PREC_POSTFIX as i8);
460 if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
461 let msg = format!("you can cast an `{}` to `{}`", checked_ty, expected_ty);
462 let cast_suggestion = format!("{}{}{} as {}",
463 if needs_paren { "(" } else { "" },
465 if needs_paren { ")" } else { "" },
467 let into_suggestion = format!(
469 if needs_paren { "(" } else { "" },
471 if needs_paren { ")" } else { "" },
473 let literal_is_ty_suffixed = |expr: &hir::Expr| {
474 if let hir::ExprKind::Lit(lit) = &expr.node {
475 lit.node.is_suffixed()
481 let into_sugg = into_suggestion.clone();
482 let suggest_to_change_suffix_or_into = |err: &mut DiagnosticBuilder,
483 note: Option<&str>| {
484 let suggest_msg = if literal_is_ty_suffixed(expr) {
486 "change the type of the numeric literal from `{}` to `{}`",
492 Some(note) => format!("{}, which {}", msg, note),
493 _ => format!("{} in a lossless way", msg),
497 let suffix_suggestion = format!(
499 if needs_paren { "(" } else { "" },
500 src.trim_right_matches(&checked_ty.to_string()),
502 if needs_paren { ")" } else { "" },
505 err.span_suggestion_with_applicability(
508 if literal_is_ty_suffixed(expr) {
513 Applicability::MachineApplicable,
517 match (&expected_ty.sty, &checked_ty.sty) {
518 (&ty::Int(ref exp), &ty::Int(ref found)) => {
519 match (found.bit_width(), exp.bit_width()) {
520 (Some(found), Some(exp)) if found > exp => {
522 err.span_suggestion_with_applicability(
524 &format!("{}, which {}", msg, will_truncate),
526 Applicability::MaybeIncorrect // lossy conversion
530 (None, _) | (_, None) => {
532 err.span_suggestion_with_applicability(
534 &format!("{}, which {}", msg, depending_on_isize),
536 Applicability::MaybeIncorrect // lossy conversion
541 suggest_to_change_suffix_or_into(
543 Some(will_sign_extend),
549 (&ty::Uint(ref exp), &ty::Uint(ref found)) => {
550 match (found.bit_width(), exp.bit_width()) {
551 (Some(found), Some(exp)) if found > exp => {
553 err.span_suggestion_with_applicability(
555 &format!("{}, which {}", msg, will_truncate),
557 Applicability::MaybeIncorrect // lossy conversion
561 (None, _) | (_, None) => {
563 err.span_suggestion_with_applicability(
565 &format!("{}, which {}", msg, depending_on_usize),
567 Applicability::MaybeIncorrect // lossy conversion
572 suggest_to_change_suffix_or_into(
574 Some(will_zero_extend),
580 (&ty::Int(ref exp), &ty::Uint(ref found)) => {
582 match (found.bit_width(), exp.bit_width()) {
583 (Some(found), Some(exp)) if found > exp - 1 => {
584 err.span_suggestion_with_applicability(
586 &format!("{}, which {}", msg, will_truncate),
588 Applicability::MaybeIncorrect // lossy conversion
592 err.span_suggestion_with_applicability(
594 &format!("{}, which {}", msg, will_truncate),
596 Applicability::MaybeIncorrect // lossy conversion
600 err.span_suggestion_with_applicability(
602 &format!("{}, which {}", msg, depending_on_isize),
604 Applicability::MaybeIncorrect // lossy conversion
608 err.span_suggestion_with_applicability(
610 &format!("{}, which {}", msg, depending_on_usize),
612 Applicability::MaybeIncorrect // lossy conversion
616 err.span_suggestion_with_applicability(
618 &format!("{}, which {}", msg, will_zero_extend),
620 Applicability::MachineApplicable
627 (&ty::Uint(ref exp), &ty::Int(ref found)) => {
629 match (found.bit_width(), exp.bit_width()) {
630 (Some(found), Some(exp)) if found - 1 > exp => {
631 err.span_suggestion_with_applicability(
633 &format!("{}, which {}", msg, will_truncate),
635 Applicability::MaybeIncorrect // lossy conversion
639 err.span_suggestion_with_applicability(
641 &format!("{}, which {}", msg, will_sign_extend),
643 Applicability::MachineApplicable // lossy conversion
647 err.span_suggestion_with_applicability(
649 &format!("{}, which {}", msg, depending_on_usize),
651 Applicability::MaybeIncorrect // lossy conversion
655 err.span_suggestion_with_applicability(
657 &format!("{}, which {}", msg, depending_on_isize),
659 Applicability::MaybeIncorrect // lossy conversion
663 err.span_suggestion_with_applicability(
665 &format!("{}, which {}", msg, will_sign_extend),
667 Applicability::MachineApplicable
674 (&ty::Float(ref exp), &ty::Float(ref found)) => {
675 if found.bit_width() < exp.bit_width() {
676 suggest_to_change_suffix_or_into(
681 err.span_suggestion_with_applicability(
683 &format!("{}, producing the closest possible value", msg),
685 Applicability::MaybeIncorrect // lossy conversion
690 (&ty::Uint(_), &ty::Float(_)) | (&ty::Int(_), &ty::Float(_)) => {
692 err.span_suggestion_with_applicability(
694 &format!("{}, rounding the float towards zero", msg),
696 Applicability::MaybeIncorrect // lossy conversion
698 err.warn("casting here will cause undefined behavior if the rounded value \
699 cannot be represented by the target integer type, including \
700 `Inf` and `NaN` (this is a bug and will be fixed)");
704 (&ty::Float(ref exp), &ty::Uint(ref found)) => {
705 // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
706 if exp.bit_width() > found.bit_width().unwrap_or(256) {
707 err.span_suggestion_with_applicability(
709 &format!("{}, producing the floating point representation of the \
713 Applicability::MachineApplicable
716 err.span_suggestion_with_applicability(expr.span,
717 &format!("{}, producing the floating point representation of the \
718 integer, rounded if necessary",
721 Applicability::MaybeIncorrect // lossy conversion
726 (&ty::Float(ref exp), &ty::Int(ref found)) => {
727 // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
728 if exp.bit_width() > found.bit_width().unwrap_or(256) {
729 err.span_suggestion_with_applicability(
731 &format!("{}, producing the floating point representation of the \
735 Applicability::MachineApplicable
738 err.span_suggestion_with_applicability(
740 &format!("{}, producing the floating point representation of the \
741 integer, rounded if necessary",
744 Applicability::MaybeIncorrect // lossy conversion