]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/suggest.rs
31ec62ba70a956478917afc6d7ad410e66eb0562
[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_data_structures::sync::Lrc;
17 use rustc::ty::{self, Ty, TyCtxt, ToPolyTraitRef, ToPredicate, TypeFoldable};
18 use hir::def::Def;
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;
24
25 use syntax::ast;
26 use syntax::util::lev_distance::find_best_match_for_name;
27 use errors::DiagnosticBuilder;
28 use syntax_pos::{Span, FileName};
29
30
31 use rustc::hir::def_id::LOCAL_CRATE;
32 use rustc::hir;
33 use rustc::hir::print;
34 use rustc::infer::type_variable::TypeVariableOrigin;
35 use rustc::ty::TyAdt;
36
37 use std::cmp::Ordering;
38
39 use super::{MethodError, NoMatchData, CandidateSource};
40 use super::probe::Mode;
41
42 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
43     fn is_fn_ty(&self, ty: &Ty<'tcx>, span: Span) -> bool {
44         let tcx = self.tcx;
45         match ty.sty {
46             // Not all of these (e.g. unsafe fns) implement FnOnce
47             // so we look for these beforehand
48             ty::TyClosure(..) |
49             ty::TyFnDef(..) |
50             ty::TyFnPtr(_) => true,
51             // If it's not a simple function, look for things which implement FnOnce
52             _ => {
53                 let fn_once = match tcx.lang_items().require(FnOnceTraitLangItem) {
54                     Ok(fn_once) => fn_once,
55                     Err(..) => return false,
56                 };
57
58                 self.autoderef(span, ty).any(|(ty, _)| {
59                     self.probe(|_| {
60                         let fn_once_substs = tcx.mk_substs_trait(ty, &[
61                             self.next_ty_var(TypeVariableOrigin::MiscVariable(span)).into()
62                         ]);
63                         let trait_ref = ty::TraitRef::new(fn_once, fn_once_substs);
64                         let poly_trait_ref = trait_ref.to_poly_trait_ref();
65                         let obligation =
66                             Obligation::misc(span,
67                                              self.body_id,
68                                              self.param_env,
69                                              poly_trait_ref.to_predicate());
70                         self.predicate_may_hold(&obligation)
71                     })
72                 })
73             }
74         }
75     }
76
77     pub fn report_method_error(&self,
78                                span: Span,
79                                rcvr_ty: Ty<'tcx>,
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() {
86             return;
87         }
88
89         let report_candidates = |err: &mut DiagnosticBuilder, mut sources: Vec<CandidateSource>| {
90
91             sources.sort();
92             sources.dedup();
93             // Dynamic limit to avoid hiding just one candidate, which is silly.
94             let limit = if sources.len() == 5 { 5 } else { 4 };
95
96             for (idx, source) in sources.iter().take(limit).enumerate() {
97                 match *source {
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)
102                             .or_else(|| {
103                                 self.associated_item(
104                                     self.tcx.impl_trait_ref(impl_did).unwrap().def_id,
105                                     item_name,
106                                     Namespace::Value,
107                                 )
108                             }).unwrap();
109                         let note_span = self.tcx.hir.span_if_local(item.def_id).or_else(|| {
110                             self.tcx.hir.span_if_local(impl_did)
111                         });
112
113                         let impl_ty = self.impl_self_ty(span, impl_did).ty;
114
115                         let insertion = match self.tcx.impl_trait_ref(impl_did) {
116                             None => String::new(),
117                             Some(trait_ref) => {
118                                 format!(" of the trait `{}`",
119                                         self.tcx.item_path_str(trait_ref.def_id))
120                             }
121                         };
122
123                         let note_str = if sources.len() > 1 {
124                             format!("candidate #{} is defined in an impl{} for the type `{}`",
125                                     idx + 1,
126                                     insertion,
127                                     impl_ty)
128                         } else {
129                             format!("the candidate is defined in an impl{} for the type `{}`",
130                                     insertion,
131                                     impl_ty)
132                         };
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),
136                                           &note_str);
137                         } else {
138                             err.note(&note_str);
139                         }
140                     }
141                     CandidateSource::TraitSource(trait_did) => {
142                         let item = self
143                             .associated_item(trait_did, item_name, Namespace::Value)
144                             .unwrap();
145                         let item_span = self.tcx.sess.source_map()
146                             .def_span(self.tcx.def_span(item.def_id));
147                         if sources.len() > 1 {
148                             span_note!(err,
149                                        item_span,
150                                        "candidate #{} is defined in the trait `{}`",
151                                        idx + 1,
152                                        self.tcx.item_path_str(trait_did));
153                         } else {
154                             span_note!(err,
155                                        item_span,
156                                        "the candidate is defined in the trait `{}`",
157                                        self.tcx.item_path_str(trait_did));
158                         }
159                         err.help(&format!("to disambiguate the method call, write `{}::{}({}{})` \
160                                           instead",
161                                           self.tcx.item_path_str(trait_did),
162                                           item_name,
163                                           if rcvr_ty.is_region_ptr() && args.is_some() {
164                                               if rcvr_ty.is_mutable_pointer() {
165                                                   "&mut "
166                                               } else {
167                                                   "&"
168                                               }
169                                           } else {
170                                               ""
171                                           },
172                                           args.map(|arg| arg.iter()
173                                               .map(|arg| print::to_string(print::NO_ANN,
174                                                                           |s| s.print_expr(arg)))
175                                               .collect::<Vec<_>>()
176                                               .join(", ")).unwrap_or("...".to_owned())));
177                     }
178                 }
179             }
180             if sources.len() > limit {
181                 err.note(&format!("and {} others", sources.len() - limit));
182             }
183         };
184
185         match error {
186             MethodError::NoMatch(NoMatchData {
187                 static_candidates: static_sources,
188                 unsatisfied_predicates,
189                 out_of_scope_traits,
190                 lev_candidate,
191                 mode,
192             }) => {
193                 let tcx = self.tcx;
194
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 {
200                     "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,
205                                                               &item_name.as_str(),
206                                                               None);
207                     }
208                     "variant"
209                 } else {
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"
213                         }
214                         (Some(_), false) => "associated item",
215                         (Some(_), true) | (None, false) => {
216                             "variant or associated item"
217                         }
218                         (None, true) => "variant",
219                     }
220                 };
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)
226                         .into_iter()
227                         .filter(|info| {
228                             self.associated_item(info.def_id, item_name, Namespace::Value).is_some()
229                         });
230                     if let (true, false, Some(expr), Some(_)) = (actual.is_numeric(),
231                                                                  actual.has_concrete_skeleton(),
232                                                                  rcvr_expr,
233                                                                  candidates.next()) {
234                         let mut err = struct_span_err!(
235                             tcx.sess,
236                             span,
237                             E0689,
238                             "can't call {} `{}` on ambiguous numeric type `{}`",
239                             item_kind,
240                             item_name,
241                             ty_string
242                         );
243                         let concrete_type = if actual.is_integral() {
244                             "i32"
245                         } else {
246                             "f32"
247                         };
248                         match expr.node {
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());
252
253                                 err.span_suggestion(lit.span,
254                                                     &format!("you must specify a concrete type for \
255                                                               this numeric value, like `{}`",
256                                                              concrete_type),
257                                                     format!("{}_{}",
258                                                             snippet,
259                                                             concrete_type));
260                             }
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)
266                                             .unwrap();
267                                         let filename = tcx.sess.source_map().span_to_filename(span);
268
269                                         let parent_node = self.tcx.hir.get(
270                                             self.tcx.hir.get_parent_node(node_id),
271                                         );
272                                         let msg = format!(
273                                             "you must specify a type for this binding, like `{}`",
274                                             concrete_type,
275                                         );
276
277                                         match (filename, parent_node) {
278                                             (FileName::Real(_), hir_map::NodeLocal(hir::Local {
279                                                 source: hir::LocalSource::Normal,
280                                                 ty,
281                                                 ..
282                                             })) => {
283                                                 err.span_suggestion(
284                                                     // account for `let x: _ = 42;`
285                                                     //                  ^^^^
286                                                     span.to(ty.as_ref().map(|ty| ty.span)
287                                                         .unwrap_or(span)),
288                                                     &msg,
289                                                     format!("{}: {}", snippet, concrete_type),
290                                                 );
291                                             }
292                                             _ => {
293                                                 err.span_label(span, msg);
294                                             }
295                                         }
296                                     }
297                                 }
298                             }
299                             _ => {}
300                         }
301                         err.emit();
302                         return;
303                     } else {
304                         let mut err = struct_span_err!(
305                             tcx.sess,
306                             span,
307                             E0599,
308                             "no {} named `{}` found for type `{}` in the current scope",
309                             item_kind,
310                             item_name,
311                             ty_string
312                         );
313                         if let Some(suggestion) = suggestion {
314                             err.note(&format!("did you mean `{}::{}`?", ty_string, suggestion));
315                         }
316                         err
317                     }
318                 } else {
319                     tcx.sess.diagnostic().struct_dummy()
320                 };
321
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 {}",
326                                                        item_kind,
327                                                        item_name,
328                                                        if def.is_enum() && !is_method {
329                                                            "here"
330                                                        } else {
331                                                            "for this"
332                                                        }));
333                     }
334                 }
335
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) {
340                         match ty.sty {
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
350                                         // string snippet
351                                     };
352
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",
360                                                               expr_string,
361                                                               item_name));
362                                         } else {
363                                             err.help(&format!("did you mean to write `{0}.{1}` \
364                                                                instead of `{0}.{1}(...)`?",
365                                                               expr_string,
366                                                               item_name));
367                                         }
368                                         err.span_label(span, "field, not a method");
369                                     } else {
370                                         err.span_label(span, "private field, not a method");
371                                     }
372                                     break;
373                                 }
374                             }
375                             _ => {}
376                         }
377                     }
378                 } else {
379                     err.span_label(span, format!("{} not found in `{}`", item_kind, ty_string));
380                 }
381
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",
386                                               $name));
387                         }
388                     }
389
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)) =
394                             expr.node
395                         {
396                             if let Some(segment) = path.segments.last() {
397                                 report_function!(expr.span, segment.ident);
398                             }
399                         }
400                     }
401                 }
402
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");
407                 }
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",
412                                             format!("{}::{}",
413                                                     self.ty_to_string(actual),
414                                                     item_name));
415                     } else {
416                         err.help(&format!("try with `{}::{}`",
417                                           self.ty_to_string(actual), item_name));
418                     }
419
420                     report_candidates(&mut err, static_sources);
421                 } else if static_sources.len() > 1 {
422
423                     report_candidates(&mut err, static_sources);
424                 }
425
426                 if !unsatisfied_predicates.is_empty() {
427                     let bound_list = unsatisfied_predicates.iter()
428                         .map(|p| format!("`{} : {}`", p.self_ty(), p))
429                         .collect::<Vec<_>>()
430                         .join("\n");
431                     err.note(&format!("the method `{}` exists but the following trait bounds \
432                                        were not satisfied:\n{}",
433                                       item_name,
434                                       bound_list));
435                 }
436
437                 if actual.is_numeric() && actual.is_fresh() {
438
439                 } else {
440                     self.suggest_traits_to_import(&mut err,
441                                                   span,
442                                                   rcvr_ty,
443                                                   item_name,
444                                                   rcvr_expr,
445                                                   out_of_scope_traits);
446                 }
447
448                 if let Some(lev_candidate) = lev_candidate {
449                     err.help(&format!("did you mean `{}`?", lev_candidate.ident));
450                 }
451                 err.emit();
452             }
453
454             MethodError::Ambiguity(sources) => {
455                 let mut err = struct_span_err!(self.sess(),
456                                                span,
457                                                E0034,
458                                                "multiple applicable items in scope");
459                 err.span_label(span, format!("multiple `{}` found", item_name));
460
461                 report_candidates(&mut err, sources);
462                 err.emit();
463             }
464
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);
469                 err.emit();
470             }
471
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 {
482                                         "it"
483                                     } else {
484                                         "one_of_them"
485                                     });
486                     self.suggest_use_candidates(&mut err, help, candidates);
487                 }
488                 err.emit();
489             }
490
491             MethodError::BadReturnType => {
492                 bug!("no return type expectations but got BadReturnType")
493             }
494         }
495     }
496
497     fn suggest_use_candidates(&self,
498                               err: &mut DiagnosticBuilder,
499                               mut msg: String,
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 {
510                     ""
511                 } else {
512                     "\n"
513                 };
514                 format!("use {};\n{}", self.tcx.item_path_str(*did), additional_newline)
515             }).collect();
516
517             err.span_suggestions(span, &msg, path_strings);
518         } else {
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 {};`",
523                                             i + 1,
524                                             self.tcx.item_path_str(*trait_did)));
525                 } else {
526                     msg.push_str(&format!("\n`use {};`",
527                                             self.tcx.item_path_str(*trait_did)));
528                 }
529             }
530             if candidates.len() > limit {
531                 msg.push_str(&format!("\nand {} others", candidates.len() - limit));
532             }
533             err.note(&msg[..]);
534         }
535     }
536
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;
542             candidates.sort();
543             candidates.dedup();
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 {
548                                 "trait is"
549                             } else {
550                                 "traits are"
551                             },
552                             one_of_them = if candidates.len() == 1 {
553                                 "it"
554                             } else {
555                                 "one of them"
556                             });
557
558             self.suggest_use_candidates(err, msg, candidates);
559             true
560         } else {
561             false
562         }
563     }
564
565     fn suggest_traits_to_import(&self,
566                                 err: &mut DiagnosticBuilder,
567                                 span: Span,
568                                 rcvr_ty: Ty<'tcx>,
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) {
573             return;
574         }
575
576         let type_is_local = self.type_derefs_to_local(span, rcvr_ty, rcvr_expr);
577
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)
582             .into_iter()
583             .filter(|info| {
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
589                 // here).
590                 (type_is_local || info.def_id.is_local()) &&
591                     self.associated_item(info.def_id, item_name, Namespace::Value)
592                         .filter(|item| {
593                             // We only want to suggest public or local traits (#45781).
594                             item.vis == ty::Visibility::Public || info.def_id.is_local()
595                         })
596                         .is_some()
597             })
598             .collect::<Vec<_>>();
599
600         if !candidates.is_empty() {
601             // sort from most relevant to least relevant
602             candidates.sort_by(|a, b| a.cmp(b).reverse());
603             candidates.dedup();
604
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 {
612                                       "trait defines"
613                                   } else {
614                                       "traits define"
615                                   },
616                                   one_of_them = if candidates.len() == 1 {
617                                       "it"
618                                   } else {
619                                       "one of them"
620                                   },
621                                   name = item_name);
622
623             for (i, trait_info) in candidates.iter().enumerate() {
624                 msg.push_str(&format!("\ncandidate #{}: `{}`",
625                                       i + 1,
626                                       self.tcx.item_path_str(trait_info.def_id)));
627             }
628             err.note(&msg[..]);
629         }
630     }
631
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,
635                             span: Span,
636                             rcvr_ty: Ty<'tcx>,
637                             rcvr_expr: Option<&hir::Expr>)
638                             -> bool {
639         fn is_local(ty: Ty) -> bool {
640             match ty.sty {
641                 ty::TyAdt(def, _) => def.did.is_local(),
642                 ty::TyForeign(did) => did.is_local(),
643
644                 ty::TyDynamic(ref tr, ..) => tr.principal()
645                     .map_or(false, |p| p.def_id().is_local()),
646
647                 ty::TyParam(_) => true,
648
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).
653                 _ => false,
654             }
655         }
656
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));
661         }
662
663         self.autoderef(span, rcvr_ty).any(|(ty, _)| is_local(ty))
664     }
665 }
666
667 #[derive(Copy, Clone)]
668 pub struct TraitInfo {
669     pub def_id: DefId,
670 }
671
672 impl PartialEq for TraitInfo {
673     fn eq(&self, other: &TraitInfo) -> bool {
674         self.cmp(other) == Ordering::Equal
675     }
676 }
677 impl Eq for TraitInfo {}
678 impl PartialOrd for TraitInfo {
679     fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> {
680         Some(self.cmp(other))
681     }
682 }
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
687
688         let lhs = (other.def_id.krate, other.def_id);
689         let rhs = (self.def_id.krate, self.def_id);
690         lhs.cmp(&rhs)
691     }
692 }
693
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()
697 }
698
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;
702
703         let mut traits = vec![];
704
705         // Crate-local:
706         //
707         // meh.
708         struct Visitor<'a, 'tcx: 'a> {
709             map: &'a hir_map::Map<'tcx>,
710             traits: &'a mut Vec<DefId>,
711         }
712         impl<'v, 'a, 'tcx> itemlikevisit::ItemLikeVisitor<'v> for Visitor<'a, 'tcx> {
713             fn visit_item(&mut self, i: &'v hir::Item) {
714                 match i.node {
715                     hir::ItemKind::Trait(..) => {
716                         let def_id = self.map.local_def_id(i.id);
717                         self.traits.push(def_id);
718                     }
719                     _ => {}
720                 }
721             }
722
723             fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
724             }
725
726             fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
727             }
728         }
729         tcx.hir.krate().visit_all_item_likes(&mut Visitor {
730             map: &tcx.hir,
731             traits: &mut traits,
732         });
733
734         // Cross-crate:
735         let mut external_mods = FxHashSet();
736         fn handle_external_def(tcx: TyCtxt,
737                                traits: &mut Vec<DefId>,
738                                external_mods: &mut FxHashSet<DefId>,
739                                def: Def) {
740             let def_id = def.def_id();
741             match def {
742                 Def::Trait(..) => {
743                     traits.push(def_id);
744                 }
745                 Def::Mod(..) => {
746                     if !external_mods.insert(def_id) {
747                         return;
748                     }
749                     for child in tcx.item_children(def_id).iter() {
750                         handle_external_def(tcx, traits, external_mods, child.def)
751                     }
752                 }
753                 _ => {}
754             }
755         }
756         for &cnum in tcx.crates().iter() {
757             let def_id = DefId {
758                 krate: cnum,
759                 index: CRATE_DEF_INDEX,
760             };
761             handle_external_def(tcx, &mut traits, &mut external_mods, Def::Mod(def_id));
762         }
763
764     traits
765 }
766
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))
771     }
772 }
773
774 struct UsePlacementFinder<'a, 'tcx: 'a, 'gcx: 'tcx> {
775     target_module: ast::NodeId,
776     span: Option<Span>,
777     found_use: bool,
778     tcx: TyCtxt<'a, 'gcx, 'tcx>
779 }
780
781 impl<'a, 'tcx, 'gcx> UsePlacementFinder<'a, 'tcx, 'gcx> {
782     fn check(
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 {
788             target_module,
789             span: None,
790             found_use: false,
791             tcx,
792         };
793         hir::intravisit::walk_crate(&mut finder, krate);
794         (finder.span, finder.found_use)
795     }
796 }
797
798 impl<'a, 'tcx, 'gcx> hir::intravisit::Visitor<'tcx> for UsePlacementFinder<'a, 'tcx, 'gcx> {
799     fn visit_mod(
800         &mut self,
801         module: &'tcx hir::Mod,
802         _: Span,
803         node_id: ast::NodeId,
804     ) {
805         if self.span.is_some() {
806             return;
807         }
808         if node_id != self.target_module {
809             hir::intravisit::walk_mod(self, module, node_id);
810             return;
811         }
812         // find a use statement
813         for item_id in &module.item_ids {
814             let item = self.tcx.hir.expect_item(item_id.id);
815             match item.node {
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;
822                         return;
823                     }
824                 },
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());
833                         } else {
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());
838                                 }
839                             }
840                         }
841                     }
842                 },
843             }
844         }
845     }
846     fn nested_visit_map<'this>(
847         &'this mut self
848     ) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> {
849         hir::intravisit::NestedVisitorMap::None
850     }
851 }