]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/suggest.rs
Improve error message when duplicate names for type and trait method
[rust.git] / src / librustc_typeck / check / method / suggest.rs
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.
4 //
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.
10
11 //! Give useful errors and suggestions to users when an item can't be
12 //! found or is otherwise invalid.
13
14 use check::FnCtxt;
15 use rustc::hir::map as hir_map;
16 use rustc::ty::{self, Ty, TyCtxt, ToPolyTraitRef, ToPredicate, TypeFoldable};
17 use hir::def::Def;
18 use hir::def_id::{CRATE_DEF_INDEX, DefId};
19 use middle::lang_items::FnOnceTraitLangItem;
20 use rustc::traits::{Obligation, SelectionContext};
21 use util::nodemap::FxHashSet;
22
23 use syntax::ast;
24 use errors::DiagnosticBuilder;
25 use syntax_pos::Span;
26
27 use rustc::hir;
28 use rustc::hir::print;
29 use rustc::infer::type_variable::TypeVariableOrigin;
30
31 use std::cell;
32 use std::cmp::Ordering;
33
34 use super::{MethodError, NoMatchData, CandidateSource};
35 use super::probe::Mode;
36
37 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
38     fn is_fn_ty(&self, ty: &Ty<'tcx>, span: Span) -> bool {
39         let tcx = self.tcx;
40         match ty.sty {
41             // Not all of these (e.g. unsafe fns) implement FnOnce
42             // so we look for these beforehand
43             ty::TyClosure(..) |
44             ty::TyFnDef(..) |
45             ty::TyFnPtr(_) => true,
46             // If it's not a simple function, look for things which implement FnOnce
47             _ => {
48                 let fn_once = match tcx.lang_items.require(FnOnceTraitLangItem) {
49                     Ok(fn_once) => fn_once,
50                     Err(..) => return false,
51                 };
52
53                 self.autoderef(span, ty).any(|(ty, _)| {
54                     self.probe(|_| {
55                         let fn_once_substs = tcx.mk_substs_trait(ty,
56                             &[self.next_ty_var(TypeVariableOrigin::MiscVariable(span))]);
57                         let trait_ref = ty::TraitRef::new(fn_once, fn_once_substs);
58                         let poly_trait_ref = trait_ref.to_poly_trait_ref();
59                         let obligation =
60                             Obligation::misc(span,
61                                              self.body_id,
62                                              self.param_env,
63                                              poly_trait_ref.to_predicate());
64                         SelectionContext::new(self).evaluate_obligation(&obligation)
65                     })
66                 })
67             }
68         }
69     }
70
71     pub fn report_method_error(&self,
72                                span: Span,
73                                rcvr_ty: Ty<'tcx>,
74                                item_name: ast::Name,
75                                rcvr_expr: Option<&hir::Expr>,
76                                error: MethodError<'tcx>,
77                                args: Option<&'gcx [hir::Expr]>) {
78         // avoid suggestions when we don't know what's going on.
79         if rcvr_ty.references_error() {
80             return;
81         }
82
83         let report_candidates = |err: &mut DiagnosticBuilder, mut sources: Vec<CandidateSource>| {
84
85             sources.sort();
86             sources.dedup();
87             // Dynamic limit to avoid hiding just one candidate, which is silly.
88             let limit = if sources.len() == 5 { 5 } else { 4 };
89
90             for (idx, source) in sources.iter().take(limit).enumerate() {
91                 match *source {
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.associated_item(impl_did, item_name)
96                             .or_else(|| {
97                                 self.associated_item(
98                                     self.tcx.impl_trait_ref(impl_did).unwrap().def_id,
99
100                                     item_name
101                                 )
102                             }).unwrap();
103                         let note_span = self.tcx.hir.span_if_local(item.def_id).or_else(|| {
104                             self.tcx.hir.span_if_local(impl_did)
105                         });
106
107                         let impl_ty = self.impl_self_ty(span, impl_did).ty;
108
109                         let insertion = match self.tcx.impl_trait_ref(impl_did) {
110                             None => format!(""),
111                             Some(trait_ref) => {
112                                 format!(" of the trait `{}`",
113                                         self.tcx.item_path_str(trait_ref.def_id))
114                             }
115                         };
116
117                         let note_str = format!("candidate #{} is defined in an impl{} \
118                                                 for the type `{}`",
119                                                idx + 1,
120                                                insertion,
121                                                impl_ty);
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, &note_str);
125                         } else {
126                             err.note(&note_str);
127                         }
128                     }
129                     CandidateSource::TraitSource(trait_did) => {
130                         let item = self.associated_item(trait_did, item_name).unwrap();
131                         let item_span = self.tcx.def_span(item.def_id);
132                         span_note!(err,
133                                    item_span,
134                                    "candidate #{} is defined in the trait `{}`",
135                                    idx + 1,
136                                    self.tcx.item_path_str(trait_did));
137                         err.help(&format!("to disambiguate the method call, write `{}::{}({}{})` \
138                                           instead",
139                                           self.tcx.item_path_str(trait_did),
140                                           item_name,
141                                           if rcvr_ty.is_region_ptr() && args.is_some() {
142                                               if rcvr_ty.is_mutable_pointer() {
143                                                   "&mut "
144                                               } else {
145                                                   "&"
146                                               }
147                                           } else {
148                                               ""
149                                           },
150                                           args.map(|arg| arg.iter()
151                                               .map(|arg| print::to_string(print::NO_ANN,
152                                                                           |s| s.print_expr(arg)))
153                                               .collect::<Vec<_>>()
154                                               .join(", ")).unwrap_or("...".to_owned())));
155                     }
156                 }
157             }
158             if sources.len() > limit {
159                 err.note(&format!("and {} others", sources.len() - limit));
160             }
161         };
162
163         match error {
164             MethodError::NoMatch(NoMatchData { static_candidates: static_sources,
165                                                unsatisfied_predicates,
166                                                out_of_scope_traits,
167                                                mode,
168                                                .. }) => {
169                 let tcx = self.tcx;
170
171                 let actual = self.resolve_type_vars_if_possible(&rcvr_ty);
172                 let mut err = if !actual.references_error() {
173                     struct_span_err!(tcx.sess, span, E0599,
174                                      "no {} named `{}` found for type `{}` in the \
175                                       current scope",
176                                      if mode == Mode::MethodCall {
177                                          "method"
178                                      } else {
179                                          match item_name.as_str().chars().next() {
180                                              Some(name) => {
181                                                  if name.is_lowercase() {
182                                                      "function or associated item"
183                                                  } else {
184                                                      "associated item"
185                                                  }
186                                              },
187                                              None => {
188                                                  ""
189                                              },
190                                          }
191                                      },
192                                      item_name,
193                                      self.ty_to_string(actual))
194                 } else {
195                     self.tcx.sess.diagnostic().struct_dummy()
196                 };
197
198                 // If the method name is the name of a field with a function or closure type,
199                 // give a helping note that it has to be called as (x.f)(...).
200                 if let Some(expr) = rcvr_expr {
201                     for (ty, _) in self.autoderef(span, rcvr_ty) {
202                         match ty.sty {
203                             ty::TyAdt(def, substs) if !def.is_enum() => {
204                                 if let Some(field) = def.struct_variant()
205                                     .find_field_named(item_name) {
206                                     let snippet = tcx.sess.codemap().span_to_snippet(expr.span);
207                                     let expr_string = match snippet {
208                                         Ok(expr_string) => expr_string,
209                                         _ => "s".into(), // Default to a generic placeholder for the
210                                         // expression when we can't generate a
211                                         // string snippet
212                                     };
213
214                                     let field_ty = field.ty(tcx, substs);
215                                     let scope = self.tcx.hir.get_module_parent(self.body_id);
216                                     if field.vis.is_accessible_from(scope, self.tcx) {
217                                         if self.is_fn_ty(&field_ty, span) {
218                                             err.help(&format!("use `({0}.{1})(...)` if you \
219                                                                meant to call the function \
220                                                                stored in the `{1}` field",
221                                                               expr_string,
222                                                               item_name));
223                                         } else {
224                                             err.help(&format!("did you mean to write `{0}.{1}` \
225                                                                instead of `{0}.{1}(...)`?",
226                                                               expr_string,
227                                                               item_name));
228                                         }
229                                         err.span_label(span, "field, not a method");
230                                     } else {
231                                         err.span_label(span, "private field, not a method");
232                                     }
233                                     break;
234                                 }
235                             }
236                             _ => {}
237                         }
238                     }
239                 }
240
241                 if self.is_fn_ty(&rcvr_ty, span) {
242                     macro_rules! report_function {
243                         ($span:expr, $name:expr) => {
244                             err.note(&format!("{} is a function, perhaps you wish to call it",
245                                               $name));
246                         }
247                     }
248
249                     if let Some(expr) = rcvr_expr {
250                         if let Ok(expr_string) = tcx.sess.codemap().span_to_snippet(expr.span) {
251                             report_function!(expr.span, expr_string);
252                         } else if let hir::ExprPath(hir::QPath::Resolved(_, ref path)) = expr.node {
253                             if let Some(segment) = path.segments.last() {
254                                 report_function!(expr.span, segment.name);
255                             }
256                         }
257                     }
258                 }
259
260                 if !static_sources.is_empty() {
261                     err.note("found the following associated functions; to be used as methods, \
262                               functions must have a `self` parameter");
263
264                     report_candidates(&mut err, static_sources);
265                 }
266
267                 if !unsatisfied_predicates.is_empty() {
268                     let bound_list = unsatisfied_predicates.iter()
269                         .map(|p| format!("`{} : {}`", p.self_ty(), p))
270                         .collect::<Vec<_>>()
271                         .join("\n");
272                     err.note(&format!("the method `{}` exists but the following trait bounds \
273                                        were not satisfied:\n{}",
274                                       item_name,
275                                       bound_list));
276                 }
277
278                 self.suggest_traits_to_import(&mut err,
279                                               span,
280                                               rcvr_ty,
281                                               item_name,
282                                               rcvr_expr,
283                                               out_of_scope_traits);
284                 err.emit();
285             }
286
287             MethodError::Ambiguity(sources) => {
288                 let mut err = struct_span_err!(self.sess(),
289                                                span,
290                                                E0034,
291                                                "multiple applicable items in scope");
292                 err.span_label(span, format!("multiple `{}` found", item_name));
293
294                 report_candidates(&mut err, sources);
295                 err.emit();
296             }
297
298             MethodError::ClosureAmbiguity(trait_def_id) => {
299                 let msg = format!("the `{}` method from the `{}` trait cannot be explicitly \
300                                    invoked on this closure as we have not yet inferred what \
301                                    kind of closure it is",
302                                   item_name,
303                                   self.tcx.item_path_str(trait_def_id));
304                 let msg = if let Some(callee) = rcvr_expr {
305                     format!("{}; use overloaded call notation instead (e.g., `{}()`)",
306                             msg,
307                             self.tcx.hir.node_to_pretty_string(callee.id))
308                 } else {
309                     msg
310                 };
311                 self.sess().span_err(span, &msg);
312             }
313
314             MethodError::PrivateMatch(def, out_of_scope_traits) => {
315                 let mut err = struct_span_err!(self.tcx.sess, span, E0624,
316                                                "{} `{}` is private", def.kind_name(), item_name);
317                 self.suggest_valid_traits(&mut err, out_of_scope_traits);
318                 err.emit();
319             }
320
321             MethodError::IllegalSizedBound(candidates) => {
322                 let msg = format!("the `{}` method cannot be invoked on a trait object", item_name);
323                 let mut err = self.sess().struct_span_err(span, &msg);
324                 if !candidates.is_empty() {
325                     let help = format!("{an}other candidate{s} {were} found in the following \
326                                         trait{s}, perhaps add a `use` for {one_of_them}:",
327                                     an = if candidates.len() == 1 {"an" } else { "" },
328                                     s = if candidates.len() == 1 { "" } else { "s" },
329                                     were = if candidates.len() == 1 { "was" } else { "were" },
330                                     one_of_them = if candidates.len() == 1 {
331                                         "it"
332                                     } else {
333                                         "one_of_them"
334                                     });
335                     self.suggest_use_candidates(&mut err, help, candidates);
336                 }
337                 err.emit();
338             }
339         }
340     }
341
342     fn suggest_use_candidates(&self,
343                               err: &mut DiagnosticBuilder,
344                               mut msg: String,
345                               candidates: Vec<DefId>) {
346         let limit = if candidates.len() == 5 { 5 } else { 4 };
347         for (i, trait_did) in candidates.iter().take(limit).enumerate() {
348             msg.push_str(&format!("\ncandidate #{}: `use {};`",
349                                     i + 1,
350                                     self.tcx.item_path_str(*trait_did)));
351         }
352         if candidates.len() > limit {
353             msg.push_str(&format!("\nand {} others", candidates.len() - limit));
354         }
355         err.note(&msg[..]);
356     }
357
358     fn suggest_valid_traits(&self,
359                             err: &mut DiagnosticBuilder,
360                             valid_out_of_scope_traits: Vec<DefId>) -> bool {
361         if !valid_out_of_scope_traits.is_empty() {
362             let mut candidates = valid_out_of_scope_traits;
363             candidates.sort();
364             candidates.dedup();
365             err.help("items from traits can only be used if the trait is in scope");
366             let msg = format!("the following {traits_are} implemented but not in scope, \
367                                perhaps add a `use` for {one_of_them}:",
368                             traits_are = if candidates.len() == 1 {
369                                 "trait is"
370                             } else {
371                                 "traits are"
372                             },
373                             one_of_them = if candidates.len() == 1 {
374                                 "it"
375                             } else {
376                                 "one of them"
377                             });
378
379             self.suggest_use_candidates(err, msg, candidates);
380             true
381         } else {
382             false
383         }
384     }
385
386     fn suggest_traits_to_import(&self,
387                                 err: &mut DiagnosticBuilder,
388                                 span: Span,
389                                 rcvr_ty: Ty<'tcx>,
390                                 item_name: ast::Name,
391                                 rcvr_expr: Option<&hir::Expr>,
392                                 valid_out_of_scope_traits: Vec<DefId>) {
393         if self.suggest_valid_traits(err, valid_out_of_scope_traits) {
394             return;
395         }
396
397         let type_is_local = self.type_derefs_to_local(span, rcvr_ty, rcvr_expr);
398
399         // there's no implemented traits, so lets suggest some traits to
400         // implement, by finding ones that have the item name, and are
401         // legal to implement.
402         let mut candidates = all_traits(self.tcx)
403             .filter(|info| {
404                 // we approximate the coherence rules to only suggest
405                 // traits that are legal to implement by requiring that
406                 // either the type or trait is local. Multidispatch means
407                 // this isn't perfect (that is, there are cases when
408                 // implementing a trait would be legal but is rejected
409                 // here).
410                 (type_is_local || info.def_id.is_local())
411                     && self.associated_item(info.def_id, item_name).is_some()
412             })
413             .collect::<Vec<_>>();
414
415         if !candidates.is_empty() {
416             // sort from most relevant to least relevant
417             candidates.sort_by(|a, b| a.cmp(b).reverse());
418             candidates.dedup();
419
420             // FIXME #21673 this help message could be tuned to the case
421             // of a type parameter: suggest adding a trait bound rather
422             // than implementing.
423             err.help("items from traits can only be used if the trait is implemented and in scope");
424             let mut msg = format!("the following {traits_define} an item `{name}`, \
425                                    perhaps you need to implement {one_of_them}:",
426                                   traits_define = if candidates.len() == 1 {
427                                       "trait defines"
428                                   } else {
429                                       "traits define"
430                                   },
431                                   one_of_them = if candidates.len() == 1 {
432                                       "it"
433                                   } else {
434                                       "one of them"
435                                   },
436                                   name = item_name);
437
438             for (i, trait_info) in candidates.iter().enumerate() {
439                 msg.push_str(&format!("\ncandidate #{}: `{}`",
440                                       i + 1,
441                                       self.tcx.item_path_str(trait_info.def_id)));
442             }
443             err.note(&msg[..]);
444         }
445     }
446
447     /// Checks whether there is a local type somewhere in the chain of
448     /// autoderefs of `rcvr_ty`.
449     fn type_derefs_to_local(&self,
450                             span: Span,
451                             rcvr_ty: Ty<'tcx>,
452                             rcvr_expr: Option<&hir::Expr>)
453                             -> bool {
454         fn is_local(ty: Ty) -> bool {
455             match ty.sty {
456                 ty::TyAdt(def, _) => def.did.is_local(),
457
458                 ty::TyDynamic(ref tr, ..) => tr.principal()
459                     .map_or(false, |p| p.def_id().is_local()),
460
461                 ty::TyParam(_) => true,
462
463                 // everything else (primitive types etc.) is effectively
464                 // non-local (there are "edge" cases, e.g. (LocalType,), but
465                 // the noise from these sort of types is usually just really
466                 // annoying, rather than any sort of help).
467                 _ => false,
468             }
469         }
470
471         // This occurs for UFCS desugaring of `T::method`, where there is no
472         // receiver expression for the method call, and thus no autoderef.
473         if rcvr_expr.is_none() {
474             return is_local(self.resolve_type_vars_with_obligations(rcvr_ty));
475         }
476
477         self.autoderef(span, rcvr_ty).any(|(ty, _)| is_local(ty))
478     }
479 }
480
481 pub type AllTraitsVec = Vec<DefId>;
482
483 #[derive(Copy, Clone)]
484 pub struct TraitInfo {
485     pub def_id: DefId,
486 }
487
488 impl TraitInfo {
489     fn new(def_id: DefId) -> TraitInfo {
490         TraitInfo { def_id: def_id }
491     }
492 }
493 impl PartialEq for TraitInfo {
494     fn eq(&self, other: &TraitInfo) -> bool {
495         self.cmp(other) == Ordering::Equal
496     }
497 }
498 impl Eq for TraitInfo {}
499 impl PartialOrd for TraitInfo {
500     fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> {
501         Some(self.cmp(other))
502     }
503 }
504 impl Ord for TraitInfo {
505     fn cmp(&self, other: &TraitInfo) -> Ordering {
506         // local crates are more important than remote ones (local:
507         // cnum == 0), and otherwise we throw in the defid for totality
508
509         let lhs = (other.def_id.krate, other.def_id);
510         let rhs = (self.def_id.krate, self.def_id);
511         lhs.cmp(&rhs)
512     }
513 }
514
515 /// Retrieve all traits in this crate and any dependent crates.
516 pub fn all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> AllTraits<'a> {
517     if tcx.all_traits.borrow().is_none() {
518         use rustc::hir::itemlikevisit;
519
520         let mut traits = vec![];
521
522         // Crate-local:
523         //
524         // meh.
525         struct Visitor<'a, 'tcx: 'a> {
526             map: &'a hir_map::Map<'tcx>,
527             traits: &'a mut AllTraitsVec,
528         }
529         impl<'v, 'a, 'tcx> itemlikevisit::ItemLikeVisitor<'v> for Visitor<'a, 'tcx> {
530             fn visit_item(&mut self, i: &'v hir::Item) {
531                 match i.node {
532                     hir::ItemTrait(..) => {
533                         let def_id = self.map.local_def_id(i.id);
534                         self.traits.push(def_id);
535                     }
536                     _ => {}
537                 }
538             }
539
540             fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
541             }
542
543             fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
544             }
545         }
546         tcx.hir.krate().visit_all_item_likes(&mut Visitor {
547             map: &tcx.hir,
548             traits: &mut traits,
549         });
550
551         // Cross-crate:
552         let mut external_mods = FxHashSet();
553         fn handle_external_def(tcx: TyCtxt,
554                                traits: &mut AllTraitsVec,
555                                external_mods: &mut FxHashSet<DefId>,
556                                def: Def) {
557             let def_id = def.def_id();
558             match def {
559                 Def::Trait(..) => {
560                     traits.push(def_id);
561                 }
562                 Def::Mod(..) => {
563                     if !external_mods.insert(def_id) {
564                         return;
565                     }
566                     for child in tcx.sess.cstore.item_children(def_id, tcx.sess) {
567                         handle_external_def(tcx, traits, external_mods, child.def)
568                     }
569                 }
570                 _ => {}
571             }
572         }
573         for cnum in tcx.sess.cstore.crates() {
574             let def_id = DefId {
575                 krate: cnum,
576                 index: CRATE_DEF_INDEX,
577             };
578             handle_external_def(tcx, &mut traits, &mut external_mods, Def::Mod(def_id));
579         }
580
581         *tcx.all_traits.borrow_mut() = Some(traits);
582     }
583
584     let borrow = tcx.all_traits.borrow();
585     assert!(borrow.is_some());
586     AllTraits {
587         borrow: borrow,
588         idx: 0,
589     }
590 }
591
592 pub struct AllTraits<'a> {
593     borrow: cell::Ref<'a, Option<AllTraitsVec>>,
594     idx: usize,
595 }
596
597 impl<'a> Iterator for AllTraits<'a> {
598     type Item = TraitInfo;
599
600     fn next(&mut self) -> Option<TraitInfo> {
601         let AllTraits { ref borrow, ref mut idx } = *self;
602         // ugh.
603         borrow.as_ref().unwrap().get(*idx).map(|info| {
604             *idx += 1;
605             TraitInfo::new(*info)
606         })
607     }
608 }