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