]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/suggest.rs
Auto merge of #35856 - phimuemue:master, r=brson
[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 CrateCtxt;
15
16 use check::{FnCtxt};
17 use rustc::hir::map as hir_map;
18 use rustc::ty::{self, Ty, ToPolyTraitRef, ToPredicate, TypeFoldable};
19 use middle::cstore;
20 use hir::def::Def;
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};
26
27 use syntax::ast;
28 use errors::DiagnosticBuilder;
29 use syntax_pos::Span;
30
31 use rustc::hir::print as pprust;
32 use rustc::hir;
33 use rustc::hir::Expr_;
34
35 use std::cell;
36 use std::cmp::Ordering;
37
38 use super::{MethodError, NoMatchData, CandidateSource};
39 use super::probe::Mode;
40
41 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
42     fn is_fn_ty(&self, ty: &Ty<'tcx>, span: Span) -> bool {
43         let tcx = self.tcx;
44         match ty.sty {
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
49             _ => {
50                 let fn_once = match tcx.lang_items.require(FnOnceTraitLangItem) {
51                     Ok(fn_once) => fn_once,
52                     Err(..) => return false
53                 };
54
55                 self.autoderef(span, ty).any(|(ty, _)| self.probe(|_| {
56                     let fn_once_substs =
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,
61                                                       self.body_id,
62                                                       poly_trait_ref
63                                                       .to_predicate());
64                     SelectionContext::new(self).evaluate_obligation(&obligation)
65                 }))
66             }
67         }
68     }
69
70     pub fn report_method_error(&self,
71                                span: Span,
72                                rcvr_ty: Ty<'tcx>,
73                                item_name: ast::Name,
74                                rcvr_expr: Option<&hir::Expr>,
75                                error: MethodError<'tcx>)
76     {
77         // avoid suggestions when we don't know what's going on.
78         if rcvr_ty.references_error() {
79             return
80         }
81
82         let report_candidates = |err: &mut DiagnosticBuilder,
83                                  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.impl_item(impl_did, item_name)
96                             .or_else(|| {
97                                 self.trait_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.map.span_if_local(item.def_id()).or_else(|| {
104                             self.tcx.map.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.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 `{}`",
134                                    idx + 1,
135                                    self.tcx.item_path_str(trait_did));
136                     }
137                 }
138             }
139             if sources.len() > limit {
140                 err.note(&format!("and {} others", sources.len() - limit));
141             }
142         };
143
144         match error {
145             MethodError::NoMatch(NoMatchData { static_candidates: static_sources,
146                                                unsatisfied_predicates,
147                                                out_of_scope_traits,
148                                                mode, .. }) => {
149                 let tcx = self.tcx;
150
151                 let mut err = self.type_error_struct(
152                     span,
153                     |actual| {
154                         format!("no {} named `{}` found for type `{}` \
155                                  in the current scope",
156                                 if mode == Mode::MethodCall { "method" }
157                                 else { "associated item" },
158                                 item_name,
159                                 actual)
160                     },
161                     rcvr_ty);
162
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
174                                                     // string snippet
175                                 };
176
177                                 let field_ty = field.ty(tcx, substs);
178
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));
184                                 } else {
185                                     err.span_note(span, &format!(
186                                         "did you mean to write `{0}.{1}`?",
187                                         expr_string, item_name));
188                                 }
189                                 break;
190                             }
191                         }
192                     }
193                 }
194
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",
199                                          $name));
200                         }
201                     }
202
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);
206                         }
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);
210                             }
211                         }
212                     }
213                 }
214
215                 if !static_sources.is_empty() {
216                     err.note(
217                         "found the following associated functions; to be used as \
218                          methods, functions must have a `self` parameter");
219
220                     report_candidates(&mut err, static_sources);
221                 }
222
223                 if !unsatisfied_predicates.is_empty() {
224                     let bound_list = unsatisfied_predicates.iter()
225                         .map(|p| format!("`{} : {}`",
226                                          p.self_ty(),
227                                          p))
228                         .collect::<Vec<_>>()
229                         .join(", ");
230                     err.note(
231                         &format!("the method `{}` exists but the \
232                                  following trait bounds were not satisfied: {}",
233                                  item_name,
234                                  bound_list));
235                 }
236
237                 self.suggest_traits_to_import(&mut err, span, rcvr_ty, item_name,
238                                               rcvr_expr, out_of_scope_traits);
239                 err.emit();
240             }
241
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));
246
247                 report_candidates(&mut err, sources);
248                 err.emit();
249             }
250
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",
255                                    item_name,
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))
260                 } else {
261                     msg
262                 };
263                 self.sess().span_err(span, &msg);
264             }
265
266             MethodError::PrivateMatch(def) => {
267                 let msg = format!("{} `{}` is private", def.kind_name(), item_name);
268                 self.tcx.sess.span_err(span, &msg);
269             }
270         }
271     }
272
273     fn suggest_traits_to_import(&self,
274                                 err: &mut DiagnosticBuilder,
275                                 span: Span,
276                                 rcvr_ty: Ty<'tcx>,
277                                 item_name: ast::Name,
278                                 rcvr_expr: Option<&hir::Expr>,
279                                 valid_out_of_scope_traits: Vec<DefId>)
280     {
281         if !valid_out_of_scope_traits.is_empty() {
282             let mut candidates = valid_out_of_scope_traits;
283             candidates.sort();
284             candidates.dedup();
285             let msg = format!(
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"});
291
292             err.help(&msg[..]);
293
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 {}`",
297                                   i + 1,
298                                   self.tcx.item_path_str(*trait_did)));
299             }
300             if candidates.len() > limit {
301                 err.note(&format!("and {} others", candidates.len() - limit));
302             }
303             return
304         }
305
306         let type_is_local = self.type_derefs_to_local(span, rcvr_ty, rcvr_expr);
307
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)
312             .filter(|info| {
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
318                 // here).
319                 (type_is_local || info.def_id.is_local())
320                     && self.trait_item(info.def_id, item_name).is_some()
321             })
322             .collect::<Vec<_>>();
323
324         if !candidates.is_empty() {
325             // sort from most relevant to least relevant
326             candidates.sort_by(|a, b| a.cmp(b).reverse());
327             candidates.dedup();
328
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.
332             let msg = format!(
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"},
338                 name = item_name);
339
340             err.help(&msg[..]);
341
342             for (i, trait_info) in candidates.iter().enumerate() {
343                 err.help(&format!("candidate #{}: `{}`",
344                                   i + 1,
345                                   self.tcx.item_path_str(trait_info.def_id)));
346             }
347         }
348     }
349
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,
353                             span: Span,
354                             rcvr_ty: Ty<'tcx>,
355                             rcvr_expr: Option<&hir::Expr>) -> bool {
356         fn is_local(ty: Ty) -> bool {
357             match ty.sty {
358                 ty::TyEnum(def, _) | ty::TyStruct(def, _) => def.did.is_local(),
359
360                 ty::TyTrait(ref tr) => tr.principal.def_id().is_local(),
361
362                 ty::TyParam(_) => true,
363
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).
368                 _ => false
369             }
370         }
371
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));
376         }
377
378         self.autoderef(span, rcvr_ty).any(|(ty, _)| is_local(ty))
379     }
380 }
381
382 pub type AllTraitsVec = Vec<TraitInfo>;
383
384 #[derive(Copy, Clone)]
385 pub struct TraitInfo {
386     pub def_id: DefId,
387 }
388
389 impl TraitInfo {
390     fn new(def_id: DefId) -> TraitInfo {
391         TraitInfo {
392             def_id: def_id,
393         }
394     }
395 }
396 impl PartialEq for TraitInfo {
397     fn eq(&self, other: &TraitInfo) -> bool {
398         self.cmp(other) == Ordering::Equal
399     }
400 }
401 impl Eq for TraitInfo {}
402 impl PartialOrd for TraitInfo {
403     fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> { Some(self.cmp(other)) }
404 }
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
409
410         let lhs = (other.def_id.krate, other.def_id);
411         let rhs = (self.def_id.krate, self.def_id);
412         lhs.cmp(&rhs)
413     }
414 }
415
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;
420
421         let mut traits = vec![];
422
423         // Crate-local:
424         //
425         // meh.
426         struct Visitor<'a, 'tcx:'a> {
427             map: &'a hir_map::Map<'tcx>,
428             traits: &'a mut AllTraitsVec,
429         }
430         impl<'v, 'a, 'tcx> intravisit::Visitor<'v> for Visitor<'a, 'tcx> {
431             fn visit_item(&mut self, i: &'v hir::Item) {
432                 match i.node {
433                     hir::ItemTrait(..) => {
434                         let def_id = self.map.local_def_id(i.id);
435                         self.traits.push(TraitInfo::new(def_id));
436                     }
437                     _ => {}
438                 }
439             }
440         }
441         ccx.tcx.map.krate().visit_all_items(&mut Visitor {
442             map: &ccx.tcx.map,
443             traits: &mut traits
444         });
445
446         // Cross-crate:
447         let mut external_mods = FnvHashSet();
448         fn handle_external_def(traits: &mut AllTraitsVec,
449                                external_mods: &mut FnvHashSet<DefId>,
450                                ccx: &CrateCtxt,
451                                cstore: &for<'a> cstore::CrateStore<'a>,
452                                dl: cstore::DefLike) {
453             match dl {
454                 cstore::DlDef(Def::Trait(did)) => {
455                     traits.push(TraitInfo::new(did));
456                 }
457                 cstore::DlDef(Def::Mod(did)) => {
458                     if !external_mods.insert(did) {
459                         return;
460                     }
461                     for child in cstore.item_children(did) {
462                         handle_external_def(traits, external_mods,
463                                             ccx, cstore, child.def)
464                     }
465                 }
466                 _ => {}
467             }
468         }
469         let cstore = &*ccx.tcx.sess.cstore;
470
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)
475             }
476         }
477
478         *ccx.all_traits.borrow_mut() = Some(traits);
479     }
480
481     let borrow = ccx.all_traits.borrow();
482     assert!(borrow.is_some());
483     AllTraits {
484         borrow: borrow,
485         idx: 0
486     }
487 }
488
489 pub struct AllTraits<'a> {
490     borrow: cell::Ref<'a, Option<AllTraitsVec>>,
491     idx: usize
492 }
493
494 impl<'a> Iterator for AllTraits<'a> {
495     type Item = TraitInfo;
496
497     fn next(&mut self) -> Option<TraitInfo> {
498         let AllTraits { ref borrow, ref mut idx } = *self;
499         // ugh.
500         borrow.as_ref().unwrap().get(*idx).map(|info| {
501             *idx += 1;
502             *info
503         })
504     }
505 }