1 // Copyright 2014 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.
11 //! Give useful errors and suggestions to users when an item can't be
12 //! found or is otherwise invalid.
17 use rustc::hir::map as hir_map;
18 use rustc::ty::{self, Ty, ToPolyTraitRef, ToPredicate, TypeFoldable};
21 use hir::def_id::DefId;
22 use middle::lang_items::FnOnceTraitLangItem;
23 use rustc::ty::subst::Substs;
24 use rustc::traits::{Obligation, SelectionContext};
25 use util::nodemap::{FnvHashSet};
28 use errors::DiagnosticBuilder;
31 use rustc::hir::print as pprust;
33 use rustc::hir::Expr_;
36 use std::cmp::Ordering;
38 use super::{MethodError, NoMatchData, CandidateSource};
39 use super::probe::Mode;
41 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
42 fn is_fn_ty(&self, ty: &Ty<'tcx>, span: Span) -> bool {
45 // Not all of these (e.g. unsafe fns) implement FnOnce
46 // so we look for these beforehand
47 ty::TyClosure(..) | ty::TyFnDef(..) | ty::TyFnPtr(_) => true,
48 // If it's not a simple function, look for things which implement FnOnce
50 let fn_once = match tcx.lang_items.require(FnOnceTraitLangItem) {
51 Ok(fn_once) => fn_once,
52 Err(..) => return false
55 self.autoderef(span, ty).any(|(ty, _)| self.probe(|_| {
57 Substs::new_trait(tcx, ty, &[self.next_ty_var()]);
58 let trait_ref = ty::TraitRef::new(fn_once, fn_once_substs);
59 let poly_trait_ref = trait_ref.to_poly_trait_ref();
60 let obligation = Obligation::misc(span,
64 SelectionContext::new(self).evaluate_obligation(&obligation)
70 pub fn report_method_error(&self,
74 rcvr_expr: Option<&hir::Expr>,
75 error: MethodError<'tcx>)
77 // avoid suggestions when we don't know what's going on.
78 if rcvr_ty.references_error() {
82 let report_candidates = |err: &mut DiagnosticBuilder,
83 mut sources: Vec<CandidateSource>| {
87 // Dynamic limit to avoid hiding just one candidate, which is silly.
88 let limit = if sources.len() == 5 { 5 } else { 4 };
90 for (idx, source) in sources.iter().take(limit).enumerate() {
92 CandidateSource::ImplSource(impl_did) => {
93 // Provide the best span we can. Use the item, if local to crate, else
94 // the impl, if local to crate (item may be defaulted), else nothing.
95 let item = self.impl_item(impl_did, item_name)
98 self.tcx.impl_trait_ref(impl_did).unwrap().def_id,
103 let note_span = self.tcx.map.span_if_local(item.def_id()).or_else(|| {
104 self.tcx.map.span_if_local(impl_did)
107 let impl_ty = self.impl_self_ty(span, impl_did).ty;
109 let insertion = match self.tcx.impl_trait_ref(impl_did) {
112 format!(" of the trait `{}`",
113 self.tcx.item_path_str(trait_ref.def_id))
117 let note_str = format!("candidate #{} is defined in an impl{} \
122 if let Some(note_span) = note_span {
123 // We have a span pointing to the method. Show note with snippet.
124 err.span_note(note_span, ¬e_str);
129 CandidateSource::TraitSource(trait_did) => {
130 let item = self.trait_item(trait_did, item_name).unwrap();
131 let item_span = self.tcx.map.def_id_span(item.def_id(), span);
132 span_note!(err, item_span,
133 "candidate #{} is defined in the trait `{}`",
135 self.tcx.item_path_str(trait_did));
139 if sources.len() > limit {
140 err.note(&format!("and {} others", sources.len() - limit));
145 MethodError::NoMatch(NoMatchData { static_candidates: static_sources,
146 unsatisfied_predicates,
151 let mut err = self.type_error_struct(
154 format!("no {} named `{}` found for type `{}` \
155 in the current scope",
156 if mode == Mode::MethodCall { "method" }
157 else { "associated item" },
163 // If the method name is the name of a field with a function or closure type,
164 // give a helping note that it has to be called as (x.f)(...).
165 if let Some(expr) = rcvr_expr {
166 for (ty, _) in self.autoderef(span, rcvr_ty) {
167 if let ty::TyStruct(def, substs) = ty.sty {
168 if let Some(field) = def.struct_variant().find_field_named(item_name) {
169 let snippet = tcx.sess.codemap().span_to_snippet(expr.span);
170 let expr_string = match snippet {
171 Ok(expr_string) => expr_string,
172 _ => "s".into() // Default to a generic placeholder for the
173 // expression when we can't generate a
177 let field_ty = field.ty(tcx, substs);
179 if self.is_fn_ty(&field_ty, span) {
180 err.span_note(span, &format!(
181 "use `({0}.{1})(...)` if you meant to call the function \
182 stored in the `{1}` field",
183 expr_string, item_name));
185 err.span_note(span, &format!(
186 "did you mean to write `{0}.{1}`?",
187 expr_string, item_name));
195 if self.is_fn_ty(&rcvr_ty, span) {
196 macro_rules! report_function {
197 ($span:expr, $name:expr) => {
198 err.note(&format!("{} is a function, perhaps you wish to call it",
203 if let Some(expr) = rcvr_expr {
204 if let Ok (expr_string) = tcx.sess.codemap().span_to_snippet(expr.span) {
205 report_function!(expr.span, expr_string);
207 else if let Expr_::ExprPath(_, path) = expr.node.clone() {
208 if let Some(segment) = path.segments.last() {
209 report_function!(expr.span, segment.name);
215 if !static_sources.is_empty() {
217 "found the following associated functions; to be used as \
218 methods, functions must have a `self` parameter");
220 report_candidates(&mut err, static_sources);
223 if !unsatisfied_predicates.is_empty() {
224 let bound_list = unsatisfied_predicates.iter()
225 .map(|p| format!("`{} : {}`",
231 &format!("the method `{}` exists but the \
232 following trait bounds were not satisfied: {}",
237 self.suggest_traits_to_import(&mut err, span, rcvr_ty, item_name,
238 rcvr_expr, out_of_scope_traits);
242 MethodError::Ambiguity(sources) => {
243 let mut err = struct_span_err!(self.sess(), span, E0034,
244 "multiple applicable items in scope");
245 err.span_label(span, &format!("multiple `{}` found", item_name));
247 report_candidates(&mut err, sources);
251 MethodError::ClosureAmbiguity(trait_def_id) => {
252 let msg = format!("the `{}` method from the `{}` trait cannot be explicitly \
253 invoked on this closure as we have not yet inferred what \
254 kind of closure it is",
256 self.tcx.item_path_str(trait_def_id));
257 let msg = if let Some(callee) = rcvr_expr {
258 format!("{}; use overloaded call notation instead (e.g., `{}()`)",
259 msg, pprust::expr_to_string(callee))
263 self.sess().span_err(span, &msg);
266 MethodError::PrivateMatch(def) => {
267 let msg = format!("{} `{}` is private", def.kind_name(), item_name);
268 self.tcx.sess.span_err(span, &msg);
273 fn suggest_traits_to_import(&self,
274 err: &mut DiagnosticBuilder,
277 item_name: ast::Name,
278 rcvr_expr: Option<&hir::Expr>,
279 valid_out_of_scope_traits: Vec<DefId>)
281 if !valid_out_of_scope_traits.is_empty() {
282 let mut candidates = valid_out_of_scope_traits;
286 "items from traits can only be used if the trait is in scope; \
287 the following {traits_are} implemented but not in scope, \
288 perhaps add a `use` for {one_of_them}:",
289 traits_are = if candidates.len() == 1 {"trait is"} else {"traits are"},
290 one_of_them = if candidates.len() == 1 {"it"} else {"one of them"});
294 let limit = if candidates.len() == 5 { 5 } else { 4 };
295 for (i, trait_did) in candidates.iter().take(limit).enumerate() {
296 err.help(&format!("candidate #{}: `use {}`",
298 self.tcx.item_path_str(*trait_did)));
300 if candidates.len() > limit {
301 err.note(&format!("and {} others", candidates.len() - limit));
306 let type_is_local = self.type_derefs_to_local(span, rcvr_ty, rcvr_expr);
308 // there's no implemented traits, so lets suggest some traits to
309 // implement, by finding ones that have the item name, and are
310 // legal to implement.
311 let mut candidates = all_traits(self.ccx)
313 // we approximate the coherence rules to only suggest
314 // traits that are legal to implement by requiring that
315 // either the type or trait is local. Multidispatch means
316 // this isn't perfect (that is, there are cases when
317 // implementing a trait would be legal but is rejected
319 (type_is_local || info.def_id.is_local())
320 && self.trait_item(info.def_id, item_name).is_some()
322 .collect::<Vec<_>>();
324 if !candidates.is_empty() {
325 // sort from most relevant to least relevant
326 candidates.sort_by(|a, b| a.cmp(b).reverse());
329 // FIXME #21673 this help message could be tuned to the case
330 // of a type parameter: suggest adding a trait bound rather
331 // than implementing.
333 "items from traits can only be used if the trait is implemented and in scope; \
334 the following {traits_define} an item `{name}`, \
335 perhaps you need to implement {one_of_them}:",
336 traits_define = if candidates.len() == 1 {"trait defines"} else {"traits define"},
337 one_of_them = if candidates.len() == 1 {"it"} else {"one of them"},
342 for (i, trait_info) in candidates.iter().enumerate() {
343 err.help(&format!("candidate #{}: `{}`",
345 self.tcx.item_path_str(trait_info.def_id)));
350 /// Checks whether there is a local type somewhere in the chain of
351 /// autoderefs of `rcvr_ty`.
352 fn type_derefs_to_local(&self,
355 rcvr_expr: Option<&hir::Expr>) -> bool {
356 fn is_local(ty: Ty) -> bool {
358 ty::TyEnum(def, _) | ty::TyStruct(def, _) => def.did.is_local(),
360 ty::TyTrait(ref tr) => tr.principal.def_id().is_local(),
362 ty::TyParam(_) => true,
364 // everything else (primitive types etc.) is effectively
365 // non-local (there are "edge" cases, e.g. (LocalType,), but
366 // the noise from these sort of types is usually just really
367 // annoying, rather than any sort of help).
372 // This occurs for UFCS desugaring of `T::method`, where there is no
373 // receiver expression for the method call, and thus no autoderef.
374 if rcvr_expr.is_none() {
375 return is_local(self.resolve_type_vars_with_obligations(rcvr_ty));
378 self.autoderef(span, rcvr_ty).any(|(ty, _)| is_local(ty))
382 pub type AllTraitsVec = Vec<TraitInfo>;
384 #[derive(Copy, Clone)]
385 pub struct TraitInfo {
390 fn new(def_id: DefId) -> TraitInfo {
396 impl PartialEq for TraitInfo {
397 fn eq(&self, other: &TraitInfo) -> bool {
398 self.cmp(other) == Ordering::Equal
401 impl Eq for TraitInfo {}
402 impl PartialOrd for TraitInfo {
403 fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> { Some(self.cmp(other)) }
405 impl Ord for TraitInfo {
406 fn cmp(&self, other: &TraitInfo) -> Ordering {
407 // local crates are more important than remote ones (local:
408 // cnum == 0), and otherwise we throw in the defid for totality
410 let lhs = (other.def_id.krate, other.def_id);
411 let rhs = (self.def_id.krate, self.def_id);
416 /// Retrieve all traits in this crate and any dependent crates.
417 pub fn all_traits<'a>(ccx: &'a CrateCtxt) -> AllTraits<'a> {
418 if ccx.all_traits.borrow().is_none() {
419 use rustc::hir::intravisit;
421 let mut traits = vec![];
426 struct Visitor<'a, 'tcx:'a> {
427 map: &'a hir_map::Map<'tcx>,
428 traits: &'a mut AllTraitsVec,
430 impl<'v, 'a, 'tcx> intravisit::Visitor<'v> for Visitor<'a, 'tcx> {
431 fn visit_item(&mut self, i: &'v hir::Item) {
433 hir::ItemTrait(..) => {
434 let def_id = self.map.local_def_id(i.id);
435 self.traits.push(TraitInfo::new(def_id));
441 ccx.tcx.map.krate().visit_all_items(&mut Visitor {
447 let mut external_mods = FnvHashSet();
448 fn handle_external_def(traits: &mut AllTraitsVec,
449 external_mods: &mut FnvHashSet<DefId>,
451 cstore: &for<'a> cstore::CrateStore<'a>,
452 dl: cstore::DefLike) {
454 cstore::DlDef(Def::Trait(did)) => {
455 traits.push(TraitInfo::new(did));
457 cstore::DlDef(Def::Mod(did)) => {
458 if !external_mods.insert(did) {
461 for child in cstore.item_children(did) {
462 handle_external_def(traits, external_mods,
463 ccx, cstore, child.def)
469 let cstore = &*ccx.tcx.sess.cstore;
471 for cnum in ccx.tcx.sess.cstore.crates() {
472 for child in cstore.crate_top_level_items(cnum) {
473 handle_external_def(&mut traits, &mut external_mods,
474 ccx, cstore, child.def)
478 *ccx.all_traits.borrow_mut() = Some(traits);
481 let borrow = ccx.all_traits.borrow();
482 assert!(borrow.is_some());
489 pub struct AllTraits<'a> {
490 borrow: cell::Ref<'a, Option<AllTraitsVec>>,
494 impl<'a> Iterator for AllTraits<'a> {
495 type Item = TraitInfo;
497 fn next(&mut self) -> Option<TraitInfo> {
498 let AllTraits { ref borrow, ref mut idx } = *self;
500 borrow.as_ref().unwrap().get(*idx).map(|info| {