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.
13 use rustc::infer::InferOk;
14 use rustc::traits::ObligationCause;
17 use syntax_pos::{self, Span};
19 use rustc::hir::def::Def;
20 use rustc::ty::{self, Ty, AssociatedItem};
21 use errors::{DiagnosticBuilder, CodeMapper};
23 use super::method::probe;
25 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
26 // Requires that the two types unify, and prints an error message if
28 pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
29 self.demand_suptype_diag(sp, expected, actual).map(|mut e| e.emit());
32 pub fn demand_suptype_diag(&self,
35 actual: Ty<'tcx>) -> Option<DiagnosticBuilder<'tcx>> {
36 let cause = &self.misc(sp);
37 match self.at(cause, self.param_env).sup(expected, actual) {
38 Ok(InferOk { obligations, value: () }) => {
39 self.register_predicates(obligations);
43 Some(self.report_mismatched_types(&cause, expected, actual, e))
48 pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
49 if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
54 pub fn demand_eqtype_diag(&self,
57 actual: Ty<'tcx>) -> Option<DiagnosticBuilder<'tcx>> {
58 self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
61 pub fn demand_eqtype_with_origin(&self,
62 cause: &ObligationCause<'tcx>,
64 actual: Ty<'tcx>) -> Option<DiagnosticBuilder<'tcx>> {
65 match self.at(cause, self.param_env).eq(expected, actual) {
66 Ok(InferOk { obligations, value: () }) => {
67 self.register_predicates(obligations);
71 Some(self.report_mismatched_types(cause, expected, actual, e))
76 // Checks that the type of `expr` can be coerced to `expected`.
78 // NB: This code relies on `self.diverges` to be accurate. In
79 // particular, assignments to `!` will be permitted if the
80 // diverges flag is currently "always".
81 pub fn demand_coerce(&self,
85 let expected = self.resolve_type_vars_with_obligations(expected);
87 if let Err(e) = self.try_coerce(expr, checked_ty, self.diverges.get(), expected) {
88 let cause = self.misc(expr.span);
89 let expr_ty = self.resolve_type_vars_with_obligations(checked_ty);
90 let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e);
91 if let Some(suggestion) = self.check_ref(expr,
94 err.help(&suggestion);
96 let mode = probe::Mode::MethodCall;
97 let suggestions = self.probe_for_return_type(syntax_pos::DUMMY_SP,
102 if suggestions.len() > 0 {
103 err.help(&format!("here are some functions which \
104 might fulfill your needs:\n{}",
105 self.get_best_match(&suggestions).join("\n")));
112 fn format_method_suggestion(&self, method: &AssociatedItem) -> String {
115 if self.has_no_input_arg(method) {
122 fn display_suggested_methods(&self, methods: &[AssociatedItem]) -> Vec<String> {
125 .map(|method| self.format_method_suggestion(&*method))
126 .collect::<Vec<String>>()
129 fn get_best_match(&self, methods: &[AssociatedItem]) -> Vec<String> {
130 let no_argument_methods: Vec<_> =
132 .filter(|ref x| self.has_no_input_arg(&*x))
135 if no_argument_methods.len() > 0 {
136 self.display_suggested_methods(&no_argument_methods)
138 self.display_suggested_methods(&methods)
142 // This function checks if the method isn't static and takes other arguments than `self`.
143 fn has_no_input_arg(&self, method: &AssociatedItem) -> bool {
145 Def::Method(def_id) => {
146 self.tcx.fn_sig(def_id).inputs().skip_binder().len() == 1
152 /// This function is used to determine potential "simple" improvements or users' errors and
153 /// provide them useful help. For example:
156 /// fn some_fn(s: &str) {}
158 /// let x = "hey!".to_owned();
159 /// some_fn(x); // error
162 /// No need to find every potential function which could make a coercion to transform a
163 /// `String` into a `&str` since a `&` would do the trick!
165 /// In addition of this check, it also checks between references mutability state. If the
166 /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
170 checked_ty: Ty<'tcx>,
173 match (&expected.sty, &checked_ty.sty) {
174 (&ty::TyRef(_, _), &ty::TyRef(_, _)) => None,
175 (&ty::TyRef(_, mutability), _) => {
176 // Check if it can work when put into a ref. For example:
179 // fn bar(x: &mut i32) {}
182 // bar(&x); // error, expected &mut
184 let ref_ty = match mutability.mutbl {
185 hir::Mutability::MutMutable => self.tcx.mk_mut_ref(
186 self.tcx.mk_region(ty::ReStatic),
188 hir::Mutability::MutImmutable => self.tcx.mk_imm_ref(
189 self.tcx.mk_region(ty::ReStatic),
192 if self.can_coerce(ref_ty, expected) {
193 // Use the callsite's span if this is a macro call. #41858
194 let sp = self.sess().codemap().call_span_if_macro(expr.span);
195 if let Ok(src) = self.tcx.sess.codemap().span_to_snippet(sp) {
196 return Some(format!("try with `{}{}`",
197 match mutability.mutbl {
198 hir::Mutability::MutMutable => "&mut ",
199 hir::Mutability::MutImmutable => "&",