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.
15 use rustc::hir::map as hir_map;
16 use rustc_data_structures::sync::Lrc;
17 use rustc::ty::{self, Ty, TyCtxt, ToPolyTraitRef, ToPredicate, TypeFoldable};
19 use hir::def_id::{CRATE_DEF_INDEX, DefId};
20 use middle::lang_items::FnOnceTraitLangItem;
21 use namespace::Namespace;
22 use rustc::traits::Obligation;
23 use util::nodemap::FxHashSet;
26 use syntax::util::lev_distance::find_best_match_for_name;
27 use errors::DiagnosticBuilder;
28 use syntax_pos::{Span, FileName};
31 use rustc::hir::def_id::LOCAL_CRATE;
33 use rustc::hir::print;
34 use rustc::infer::type_variable::TypeVariableOrigin;
37 use std::cmp::Ordering;
39 use super::{MethodError, NoMatchData, CandidateSource};
40 use super::probe::Mode;
42 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
43 fn is_fn_ty(&self, ty: &Ty<'tcx>, span: Span) -> bool {
46 // Not all of these (e.g. unsafe fns) implement FnOnce
47 // so we look for these beforehand
50 ty::TyFnPtr(_) => true,
51 // If it's not a simple function, look for things which implement FnOnce
53 let fn_once = match tcx.lang_items().require(FnOnceTraitLangItem) {
54 Ok(fn_once) => fn_once,
55 Err(..) => return false,
58 self.autoderef(span, ty).any(|(ty, _)| {
60 let fn_once_substs = tcx.mk_substs_trait(ty, &[
61 self.next_ty_var(TypeVariableOrigin::MiscVariable(span)).into()
63 let trait_ref = ty::TraitRef::new(fn_once, fn_once_substs);
64 let poly_trait_ref = trait_ref.to_poly_trait_ref();
66 Obligation::misc(span,
69 poly_trait_ref.to_predicate());
70 self.predicate_may_hold(&obligation)
77 pub fn report_method_error(&self,
80 item_name: ast::Ident,
81 rcvr_expr: Option<&hir::Expr>,
82 error: MethodError<'tcx>,
83 args: Option<&'gcx [hir::Expr]>) {
84 // avoid suggestions when we don't know what's going on.
85 if rcvr_ty.references_error() {
89 let report_candidates = |err: &mut DiagnosticBuilder, mut sources: Vec<CandidateSource>| {
93 // Dynamic limit to avoid hiding just one candidate, which is silly.
94 let limit = if sources.len() == 5 { 5 } else { 4 };
96 for (idx, source) in sources.iter().take(limit).enumerate() {
98 CandidateSource::ImplSource(impl_did) => {
99 // Provide the best span we can. Use the item, if local to crate, else
100 // the impl, if local to crate (item may be defaulted), else nothing.
101 let item = self.associated_item(impl_did, item_name, Namespace::Value)
103 self.associated_item(
104 self.tcx.impl_trait_ref(impl_did).unwrap().def_id,
109 let note_span = self.tcx.hir.span_if_local(item.def_id).or_else(|| {
110 self.tcx.hir.span_if_local(impl_did)
113 let impl_ty = self.impl_self_ty(span, impl_did).ty;
115 let insertion = match self.tcx.impl_trait_ref(impl_did) {
116 None => String::new(),
118 format!(" of the trait `{}`",
119 self.tcx.item_path_str(trait_ref.def_id))
123 let note_str = if sources.len() > 1 {
124 format!("candidate #{} is defined in an impl{} for the type `{}`",
129 format!("the candidate is defined in an impl{} for the type `{}`",
133 if let Some(note_span) = note_span {
134 // We have a span pointing to the method. Show note with snippet.
135 err.span_note(self.tcx.sess.source_map().def_span(note_span),
141 CandidateSource::TraitSource(trait_did) => {
143 .associated_item(trait_did, item_name, Namespace::Value)
145 let item_span = self.tcx.sess.source_map()
146 .def_span(self.tcx.def_span(item.def_id));
147 if sources.len() > 1 {
150 "candidate #{} is defined in the trait `{}`",
152 self.tcx.item_path_str(trait_did));
156 "the candidate is defined in the trait `{}`",
157 self.tcx.item_path_str(trait_did));
159 err.help(&format!("to disambiguate the method call, write `{}::{}({}{})` \
161 self.tcx.item_path_str(trait_did),
163 if rcvr_ty.is_region_ptr() && args.is_some() {
164 if rcvr_ty.is_mutable_pointer() {
172 args.map(|arg| arg.iter()
173 .map(|arg| print::to_string(print::NO_ANN,
174 |s| s.print_expr(arg)))
176 .join(", ")).unwrap_or("...".to_owned())));
180 if sources.len() > limit {
181 err.note(&format!("and {} others", sources.len() - limit));
186 MethodError::NoMatch(NoMatchData {
187 static_candidates: static_sources,
188 unsatisfied_predicates,
195 let actual = self.resolve_type_vars_if_possible(&rcvr_ty);
196 let ty_string = self.ty_to_string(actual);
197 let is_method = mode == Mode::MethodCall;
198 let mut suggestion = None;
199 let item_kind = if is_method {
201 } else if actual.is_enum() {
202 if let TyAdt(ref adt_def, _) = actual.sty {
203 let names = adt_def.variants.iter().map(|s| &s.name);
204 suggestion = find_best_match_for_name(names,
210 match (item_name.as_str().chars().next(), actual.is_fresh_ty()) {
211 (Some(name), false) if name.is_lowercase() => {
212 "function or associated item"
214 (Some(_), false) => "associated item",
215 (Some(_), true) | (None, false) => {
216 "variant or associated item"
218 (None, true) => "variant",
221 let mut err = if !actual.references_error() {
222 // Suggest clamping down the type if the method that is being attempted to
223 // be used exists at all, and the type is an ambiuous numeric type
224 // ({integer}/{float}).
225 let mut candidates = all_traits(self.tcx)
228 self.associated_item(info.def_id, item_name, Namespace::Value).is_some()
230 if let (true, false, Some(expr), Some(_)) = (actual.is_numeric(),
231 actual.has_concrete_skeleton(),
234 let mut err = struct_span_err!(
238 "can't call {} `{}` on ambiguous numeric type `{}`",
243 let concrete_type = if actual.is_integral() {
249 hir::ExprKind::Lit(ref lit) => { // numeric literal
250 let snippet = tcx.sess.source_map().span_to_snippet(lit.span)
251 .unwrap_or("<numeric literal>".to_string());
253 err.span_suggestion(lit.span,
254 &format!("you must specify a concrete type for \
255 this numeric value, like `{}`",
261 hir::ExprKind::Path(ref qpath) => { // local binding
262 if let &hir::QPath::Resolved(_, ref path) = &qpath {
263 if let hir::def::Def::Local(node_id) = path.def {
264 let span = tcx.hir.span(node_id);
265 let snippet = tcx.sess.source_map().span_to_snippet(span)
267 let filename = tcx.sess.source_map().span_to_filename(span);
269 let parent_node = self.tcx.hir.get(
270 self.tcx.hir.get_parent_node(node_id),
273 "you must specify a type for this binding, like `{}`",
277 match (filename, parent_node) {
278 (FileName::Real(_), hir_map::NodeLocal(hir::Local {
279 source: hir::LocalSource::Normal,
284 // account for `let x: _ = 42;`
286 span.to(ty.as_ref().map(|ty| ty.span)
289 format!("{}: {}", snippet, concrete_type),
293 err.span_label(span, msg);
304 let mut err = struct_span_err!(
308 "no {} named `{}` found for type `{}` in the current scope",
313 if let Some(suggestion) = suggestion {
314 err.note(&format!("did you mean `{}::{}`?", ty_string, suggestion));
319 tcx.sess.diagnostic().struct_dummy()
322 if let Some(def) = actual.ty_adt_def() {
323 if let Some(full_sp) = tcx.hir.span_if_local(def.did) {
324 let def_sp = tcx.sess.source_map().def_span(full_sp);
325 err.span_label(def_sp, format!("{} `{}` not found {}",
328 if def.is_enum() && !is_method {
336 // If the method name is the name of a field with a function or closure type,
337 // give a helping note that it has to be called as (x.f)(...).
338 if let Some(expr) = rcvr_expr {
339 for (ty, _) in self.autoderef(span, rcvr_ty) {
341 ty::TyAdt(def, substs) if !def.is_enum() => {
342 let variant = &def.non_enum_variant();
343 if let Some(index) = self.tcx.find_field_index(item_name, variant) {
344 let field = &variant.fields[index];
345 let snippet = tcx.sess.source_map().span_to_snippet(expr.span);
346 let expr_string = match snippet {
347 Ok(expr_string) => expr_string,
348 _ => "s".into(), // Default to a generic placeholder for the
349 // expression when we can't generate a
353 let field_ty = field.ty(tcx, substs);
354 let scope = self.tcx.hir.get_module_parent(self.body_id);
355 if field.vis.is_accessible_from(scope, self.tcx) {
356 if self.is_fn_ty(&field_ty, span) {
357 err.help(&format!("use `({0}.{1})(...)` if you \
358 meant to call the function \
359 stored in the `{1}` field",
363 err.help(&format!("did you mean to write `{0}.{1}` \
364 instead of `{0}.{1}(...)`?",
368 err.span_label(span, "field, not a method");
370 err.span_label(span, "private field, not a method");
379 err.span_label(span, format!("{} not found in `{}`", item_kind, ty_string));
382 if self.is_fn_ty(&rcvr_ty, span) {
383 macro_rules! report_function {
384 ($span:expr, $name:expr) => {
385 err.note(&format!("{} is a function, perhaps you wish to call it",
390 if let Some(expr) = rcvr_expr {
391 if let Ok(expr_string) = tcx.sess.source_map().span_to_snippet(expr.span) {
392 report_function!(expr.span, expr_string);
393 } else if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) =
396 if let Some(segment) = path.segments.last() {
397 report_function!(expr.span, segment.ident);
403 if !static_sources.is_empty() {
404 err.note("found the following associated functions; to be used as methods, \
405 functions must have a `self` parameter");
406 err.span_label(span, "this is an associated function, not a method");
408 if static_sources.len() == 1 {
409 if let Some(expr) = rcvr_expr {
410 err.span_suggestion(expr.span.to(span),
411 "use associated function syntax instead",
413 self.ty_to_string(actual),
416 err.help(&format!("try with `{}::{}`",
417 self.ty_to_string(actual), item_name));
420 report_candidates(&mut err, static_sources);
421 } else if static_sources.len() > 1 {
423 report_candidates(&mut err, static_sources);
426 if !unsatisfied_predicates.is_empty() {
427 let bound_list = unsatisfied_predicates.iter()
428 .map(|p| format!("`{} : {}`", p.self_ty(), p))
431 err.note(&format!("the method `{}` exists but the following trait bounds \
432 were not satisfied:\n{}",
437 if actual.is_numeric() && actual.is_fresh() {
440 self.suggest_traits_to_import(&mut err,
445 out_of_scope_traits);
448 if let Some(lev_candidate) = lev_candidate {
449 err.help(&format!("did you mean `{}`?", lev_candidate.ident));
454 MethodError::Ambiguity(sources) => {
455 let mut err = struct_span_err!(self.sess(),
458 "multiple applicable items in scope");
459 err.span_label(span, format!("multiple `{}` found", item_name));
461 report_candidates(&mut err, sources);
465 MethodError::PrivateMatch(def, out_of_scope_traits) => {
466 let mut err = struct_span_err!(self.tcx.sess, span, E0624,
467 "{} `{}` is private", def.kind_name(), item_name);
468 self.suggest_valid_traits(&mut err, out_of_scope_traits);
472 MethodError::IllegalSizedBound(candidates) => {
473 let msg = format!("the `{}` method cannot be invoked on a trait object", item_name);
474 let mut err = self.sess().struct_span_err(span, &msg);
475 if !candidates.is_empty() {
476 let help = format!("{an}other candidate{s} {were} found in the following \
477 trait{s}, perhaps add a `use` for {one_of_them}:",
478 an = if candidates.len() == 1 {"an" } else { "" },
479 s = if candidates.len() == 1 { "" } else { "s" },
480 were = if candidates.len() == 1 { "was" } else { "were" },
481 one_of_them = if candidates.len() == 1 {
486 self.suggest_use_candidates(&mut err, help, candidates);
491 MethodError::BadReturnType => {
492 bug!("no return type expectations but got BadReturnType")
497 fn suggest_use_candidates(&self,
498 err: &mut DiagnosticBuilder,
500 candidates: Vec<DefId>) {
501 let module_did = self.tcx.hir.get_module_parent(self.body_id);
502 let module_id = self.tcx.hir.as_local_node_id(module_did).unwrap();
503 let krate = self.tcx.hir.krate();
504 let (span, found_use) = UsePlacementFinder::check(self.tcx, krate, module_id);
505 if let Some(span) = span {
506 let path_strings = candidates.iter().map(|did| {
507 // produce an additional newline to separate the new use statement
508 // from the directly following item.
509 let additional_newline = if found_use {
514 format!("use {};\n{}", self.tcx.item_path_str(*did), additional_newline)
517 err.span_suggestions(span, &msg, path_strings);
519 let limit = if candidates.len() == 5 { 5 } else { 4 };
520 for (i, trait_did) in candidates.iter().take(limit).enumerate() {
521 if candidates.len() > 1 {
522 msg.push_str(&format!("\ncandidate #{}: `use {};`",
524 self.tcx.item_path_str(*trait_did)));
526 msg.push_str(&format!("\n`use {};`",
527 self.tcx.item_path_str(*trait_did)));
530 if candidates.len() > limit {
531 msg.push_str(&format!("\nand {} others", candidates.len() - limit));
537 fn suggest_valid_traits(&self,
538 err: &mut DiagnosticBuilder,
539 valid_out_of_scope_traits: Vec<DefId>) -> bool {
540 if !valid_out_of_scope_traits.is_empty() {
541 let mut candidates = valid_out_of_scope_traits;
544 err.help("items from traits can only be used if the trait is in scope");
545 let msg = format!("the following {traits_are} implemented but not in scope, \
546 perhaps add a `use` for {one_of_them}:",
547 traits_are = if candidates.len() == 1 {
552 one_of_them = if candidates.len() == 1 {
558 self.suggest_use_candidates(err, msg, candidates);
565 fn suggest_traits_to_import(&self,
566 err: &mut DiagnosticBuilder,
569 item_name: ast::Ident,
570 rcvr_expr: Option<&hir::Expr>,
571 valid_out_of_scope_traits: Vec<DefId>) {
572 if self.suggest_valid_traits(err, valid_out_of_scope_traits) {
576 let type_is_local = self.type_derefs_to_local(span, rcvr_ty, rcvr_expr);
578 // there's no implemented traits, so lets suggest some traits to
579 // implement, by finding ones that have the item name, and are
580 // legal to implement.
581 let mut candidates = all_traits(self.tcx)
584 // we approximate the coherence rules to only suggest
585 // traits that are legal to implement by requiring that
586 // either the type or trait is local. Multidispatch means
587 // this isn't perfect (that is, there are cases when
588 // implementing a trait would be legal but is rejected
590 (type_is_local || info.def_id.is_local()) &&
591 self.associated_item(info.def_id, item_name, Namespace::Value)
593 // We only want to suggest public or local traits (#45781).
594 item.vis == ty::Visibility::Public || info.def_id.is_local()
598 .collect::<Vec<_>>();
600 if !candidates.is_empty() {
601 // sort from most relevant to least relevant
602 candidates.sort_by(|a, b| a.cmp(b).reverse());
605 // FIXME #21673 this help message could be tuned to the case
606 // of a type parameter: suggest adding a trait bound rather
607 // than implementing.
608 err.help("items from traits can only be used if the trait is implemented and in scope");
609 let mut msg = format!("the following {traits_define} an item `{name}`, \
610 perhaps you need to implement {one_of_them}:",
611 traits_define = if candidates.len() == 1 {
616 one_of_them = if candidates.len() == 1 {
623 for (i, trait_info) in candidates.iter().enumerate() {
624 msg.push_str(&format!("\ncandidate #{}: `{}`",
626 self.tcx.item_path_str(trait_info.def_id)));
632 /// Checks whether there is a local type somewhere in the chain of
633 /// autoderefs of `rcvr_ty`.
634 fn type_derefs_to_local(&self,
637 rcvr_expr: Option<&hir::Expr>)
639 fn is_local(ty: Ty) -> bool {
641 ty::TyAdt(def, _) => def.did.is_local(),
642 ty::TyForeign(did) => did.is_local(),
644 ty::TyDynamic(ref tr, ..) => tr.principal()
645 .map_or(false, |p| p.def_id().is_local()),
647 ty::TyParam(_) => true,
649 // everything else (primitive types etc.) is effectively
650 // non-local (there are "edge" cases, e.g. (LocalType,), but
651 // the noise from these sort of types is usually just really
652 // annoying, rather than any sort of help).
657 // This occurs for UFCS desugaring of `T::method`, where there is no
658 // receiver expression for the method call, and thus no autoderef.
659 if rcvr_expr.is_none() {
660 return is_local(self.resolve_type_vars_with_obligations(rcvr_ty));
663 self.autoderef(span, rcvr_ty).any(|(ty, _)| is_local(ty))
667 #[derive(Copy, Clone)]
668 pub struct TraitInfo {
672 impl PartialEq for TraitInfo {
673 fn eq(&self, other: &TraitInfo) -> bool {
674 self.cmp(other) == Ordering::Equal
677 impl Eq for TraitInfo {}
678 impl PartialOrd for TraitInfo {
679 fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> {
680 Some(self.cmp(other))
683 impl Ord for TraitInfo {
684 fn cmp(&self, other: &TraitInfo) -> Ordering {
685 // local crates are more important than remote ones (local:
686 // cnum == 0), and otherwise we throw in the defid for totality
688 let lhs = (other.def_id.krate, other.def_id);
689 let rhs = (self.def_id.krate, self.def_id);
694 /// Retrieve all traits in this crate and any dependent crates.
695 pub fn all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Vec<TraitInfo> {
696 tcx.all_traits(LOCAL_CRATE).iter().map(|&def_id| TraitInfo { def_id }).collect()
699 /// Compute all traits in this crate and any dependent crates.
700 fn compute_all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Vec<DefId> {
701 use rustc::hir::itemlikevisit;
703 let mut traits = vec![];
708 struct Visitor<'a, 'tcx: 'a> {
709 map: &'a hir_map::Map<'tcx>,
710 traits: &'a mut Vec<DefId>,
712 impl<'v, 'a, 'tcx> itemlikevisit::ItemLikeVisitor<'v> for Visitor<'a, 'tcx> {
713 fn visit_item(&mut self, i: &'v hir::Item) {
715 hir::ItemKind::Trait(..) => {
716 let def_id = self.map.local_def_id(i.id);
717 self.traits.push(def_id);
723 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
726 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
729 tcx.hir.krate().visit_all_item_likes(&mut Visitor {
735 let mut external_mods = FxHashSet();
736 fn handle_external_def(tcx: TyCtxt,
737 traits: &mut Vec<DefId>,
738 external_mods: &mut FxHashSet<DefId>,
740 let def_id = def.def_id();
746 if !external_mods.insert(def_id) {
749 for child in tcx.item_children(def_id).iter() {
750 handle_external_def(tcx, traits, external_mods, child.def)
756 for &cnum in tcx.crates().iter() {
759 index: CRATE_DEF_INDEX,
761 handle_external_def(tcx, &mut traits, &mut external_mods, Def::Mod(def_id));
767 pub fn provide(providers: &mut ty::query::Providers) {
768 providers.all_traits = |tcx, cnum| {
769 assert_eq!(cnum, LOCAL_CRATE);
770 Lrc::new(compute_all_traits(tcx))
774 struct UsePlacementFinder<'a, 'tcx: 'a, 'gcx: 'tcx> {
775 target_module: ast::NodeId,
778 tcx: TyCtxt<'a, 'gcx, 'tcx>
781 impl<'a, 'tcx, 'gcx> UsePlacementFinder<'a, 'tcx, 'gcx> {
783 tcx: TyCtxt<'a, 'gcx, 'tcx>,
784 krate: &'tcx hir::Crate,
785 target_module: ast::NodeId,
786 ) -> (Option<Span>, bool) {
787 let mut finder = UsePlacementFinder {
793 hir::intravisit::walk_crate(&mut finder, krate);
794 (finder.span, finder.found_use)
798 impl<'a, 'tcx, 'gcx> hir::intravisit::Visitor<'tcx> for UsePlacementFinder<'a, 'tcx, 'gcx> {
801 module: &'tcx hir::Mod,
803 node_id: ast::NodeId,
805 if self.span.is_some() {
808 if node_id != self.target_module {
809 hir::intravisit::walk_mod(self, module, node_id);
812 // find a use statement
813 for item_id in &module.item_ids {
814 let item = self.tcx.hir.expect_item(item_id.id);
816 hir::ItemKind::Use(..) => {
817 // don't suggest placing a use before the prelude
818 // import or other generated ones
819 if item.span.ctxt().outer().expn_info().is_none() {
820 self.span = Some(item.span.shrink_to_lo());
821 self.found_use = true;
825 // don't place use before extern crate
826 hir::ItemKind::ExternCrate(_) => {}
827 // but place them before the first other item
828 _ => if self.span.map_or(true, |span| item.span < span ) {
829 if item.span.ctxt().outer().expn_info().is_none() {
830 // don't insert between attributes and an item
831 if item.attrs.is_empty() {
832 self.span = Some(item.span.shrink_to_lo());
834 // find the first attribute on the item
835 for attr in &item.attrs {
836 if self.span.map_or(true, |span| attr.span < span) {
837 self.span = Some(attr.span.shrink_to_lo());
846 fn nested_visit_map<'this>(
848 ) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> {
849 hir::intravisit::NestedVisitorMap::None