]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/suggest.rs
rustc: factor most DefId-containing variants out of Def and into DefKind.
[rust.git] / src / librustc_typeck / check / method / suggest.rs
1 //! Give useful errors and suggestions to users when an item can't be
2 //! found or is otherwise invalid.
3
4 use crate::check::FnCtxt;
5 use crate::middle::lang_items::FnOnceTraitLangItem;
6 use crate::namespace::Namespace;
7 use crate::util::nodemap::FxHashSet;
8 use errors::{Applicability, DiagnosticBuilder};
9 use rustc_data_structures::sync::Lrc;
10 use rustc::hir::{self, ExprKind, Node, QPath};
11 use rustc::hir::def::{Def, DefKind};
12 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
13 use rustc::hir::map as hir_map;
14 use rustc::hir::print;
15 use rustc::infer::type_variable::TypeVariableOrigin;
16 use rustc::traits::Obligation;
17 use rustc::ty::{self, Ty, TyCtxt, ToPolyTraitRef, ToPredicate, TypeFoldable};
18 use rustc::ty::print::with_crate_prefix;
19 use syntax_pos::{Span, FileName};
20 use syntax::ast;
21 use syntax::util::lev_distance;
22
23 use std::cmp::Ordering;
24
25 use super::{MethodError, NoMatchData, CandidateSource};
26 use super::probe::Mode;
27
28 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
29     fn is_fn_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
30         let tcx = self.tcx;
31         match ty.sty {
32             // Not all of these (e.g., unsafe fns) implement `FnOnce`,
33             // so we look for these beforehand.
34             ty::Closure(..) |
35             ty::FnDef(..) |
36             ty::FnPtr(_) => true,
37             // If it's not a simple function, look for things which implement `FnOnce`.
38             _ => {
39                 let fn_once = match tcx.lang_items().require(FnOnceTraitLangItem) {
40                     Ok(fn_once) => fn_once,
41                     Err(..) => return false,
42                 };
43
44                 self.autoderef(span, ty).any(|(ty, _)| {
45                     self.probe(|_| {
46                         let fn_once_substs = tcx.mk_substs_trait(ty, &[
47                             self.next_ty_var(TypeVariableOrigin::MiscVariable(span)).into()
48                         ]);
49                         let trait_ref = ty::TraitRef::new(fn_once, fn_once_substs);
50                         let poly_trait_ref = trait_ref.to_poly_trait_ref();
51                         let obligation =
52                             Obligation::misc(span,
53                                              self.body_id,
54                                              self.param_env,
55                                              poly_trait_ref.to_predicate());
56                         self.predicate_may_hold(&obligation)
57                     })
58                 })
59             }
60         }
61     }
62
63     pub fn report_method_error<'b>(
64         &self,
65         span: Span,
66         rcvr_ty: Ty<'tcx>,
67         item_name: ast::Ident,
68         source: SelfSource<'b>,
69         error: MethodError<'tcx>,
70         args: Option<&'gcx [hir::Expr]>,
71     ) {
72         let orig_span = span;
73         let mut span = span;
74         // Avoid suggestions when we don't know what's going on.
75         if rcvr_ty.references_error() {
76             return;
77         }
78
79         let report_candidates = |
80             span: Span,
81             err: &mut DiagnosticBuilder<'_>,
82             mut sources: Vec<CandidateSource>,
83         | {
84             sources.sort();
85             sources.dedup();
86             // Dynamic limit to avoid hiding just one candidate, which is silly.
87             let limit = if sources.len() == 5 { 5 } else { 4 };
88
89             for (idx, source) in sources.iter().take(limit).enumerate() {
90                 match *source {
91                     CandidateSource::ImplSource(impl_did) => {
92                         // Provide the best span we can. Use the item, if local to crate, else
93                         // the impl, if local to crate (item may be defaulted), else nothing.
94                         let item = self.associated_item(impl_did, item_name, Namespace::Value)
95                             .or_else(|| {
96                                 self.associated_item(
97                                     self.tcx.impl_trait_ref(impl_did).unwrap().def_id,
98                                     item_name,
99                                     Namespace::Value,
100                                 )
101                             }).unwrap();
102                         let note_span = self.tcx.hir().span_if_local(item.def_id).or_else(|| {
103                             self.tcx.hir().span_if_local(impl_did)
104                         });
105
106                         let impl_ty = self.impl_self_ty(span, impl_did).ty;
107
108                         let insertion = match self.tcx.impl_trait_ref(impl_did) {
109                             None => String::new(),
110                             Some(trait_ref) => {
111                                 format!(" of the trait `{}`",
112                                         self.tcx.def_path_str(trait_ref.def_id))
113                             }
114                         };
115
116                         let note_str = if sources.len() > 1 {
117                             format!("candidate #{} is defined in an impl{} for the type `{}`",
118                                     idx + 1,
119                                     insertion,
120                                     impl_ty)
121                         } else {
122                             format!("the candidate is defined in an impl{} for the type `{}`",
123                                     insertion,
124                                     impl_ty)
125                         };
126                         if let Some(note_span) = note_span {
127                             // We have a span pointing to the method. Show note with snippet.
128                             err.span_note(self.tcx.sess.source_map().def_span(note_span),
129                                           &note_str);
130                         } else {
131                             err.note(&note_str);
132                         }
133                     }
134                     CandidateSource::TraitSource(trait_did) => {
135                         let item = self
136                             .associated_item(trait_did, item_name, Namespace::Value)
137                             .unwrap();
138                         let item_span = self.tcx.sess.source_map()
139                             .def_span(self.tcx.def_span(item.def_id));
140                         if sources.len() > 1 {
141                             span_note!(err,
142                                        item_span,
143                                        "candidate #{} is defined in the trait `{}`",
144                                        idx + 1,
145                                        self.tcx.def_path_str(trait_did));
146                         } else {
147                             span_note!(err,
148                                        item_span,
149                                        "the candidate is defined in the trait `{}`",
150                                        self.tcx.def_path_str(trait_did));
151                         }
152                         err.help(&format!("to disambiguate the method call, write `{}::{}({}{})` \
153                                           instead",
154                                           self.tcx.def_path_str(trait_did),
155                                           item_name,
156                                           if rcvr_ty.is_region_ptr() && args.is_some() {
157                                               if rcvr_ty.is_mutable_pointer() {
158                                                   "&mut "
159                                               } else {
160                                                   "&"
161                                               }
162                                           } else {
163                                               ""
164                                           },
165                                           args.map(|arg| arg.iter()
166                                               .map(|arg| print::to_string(print::NO_ANN,
167                                                                           |s| s.print_expr(arg)))
168                                               .collect::<Vec<_>>()
169                                               .join(", ")).unwrap_or_else(|| "...".to_owned())));
170                     }
171                 }
172             }
173             if sources.len() > limit {
174                 err.note(&format!("and {} others", sources.len() - limit));
175             }
176         };
177
178         match error {
179             MethodError::NoMatch(NoMatchData {
180                 static_candidates: static_sources,
181                 unsatisfied_predicates,
182                 out_of_scope_traits,
183                 lev_candidate,
184                 mode,
185             }) => {
186                 let tcx = self.tcx;
187
188                 let actual = self.resolve_type_vars_if_possible(&rcvr_ty);
189                 let ty_str = self.ty_to_string(actual);
190                 let is_method = mode == Mode::MethodCall;
191                 let item_kind = if is_method {
192                     "method"
193                 } else if actual.is_enum() {
194                     "variant or associated item"
195                 } else {
196                     match (item_name.as_str().chars().next(), actual.is_fresh_ty()) {
197                         (Some(name), false) if name.is_lowercase() => {
198                             "function or associated item"
199                         }
200                         (Some(_), false) => "associated item",
201                         (Some(_), true) | (None, false) => {
202                             "variant or associated item"
203                         }
204                         (None, true) => "variant",
205                     }
206                 };
207                 let mut err = if !actual.references_error() {
208                     // Suggest clamping down the type if the method that is being attempted to
209                     // be used exists at all, and the type is an ambiuous numeric type
210                     // ({integer}/{float}).
211                     let mut candidates = all_traits(self.tcx)
212                         .into_iter()
213                         .filter_map(|info|
214                             self.associated_item(info.def_id, item_name, Namespace::Value)
215                         );
216                     if let (true, false, SelfSource::MethodCall(expr), Some(_)) =
217                            (actual.is_numeric(),
218                             actual.has_concrete_skeleton(),
219                             source,
220                             candidates.next()) {
221                         let mut err = struct_span_err!(
222                             tcx.sess,
223                             span,
224                             E0689,
225                             "can't call {} `{}` on ambiguous numeric type `{}`",
226                             item_kind,
227                             item_name,
228                             ty_str
229                         );
230                         let concrete_type = if actual.is_integral() {
231                             "i32"
232                         } else {
233                             "f32"
234                         };
235                         match expr.node {
236                             ExprKind::Lit(ref lit) => {
237                                 // numeric literal
238                                 let snippet = tcx.sess.source_map().span_to_snippet(lit.span)
239                                     .unwrap_or_else(|_| "<numeric literal>".to_owned());
240
241                                 err.span_suggestion(
242                                     lit.span,
243                                     &format!("you must specify a concrete type for \
244                                               this numeric value, like `{}`", concrete_type),
245                                     format!("{}_{}", snippet, concrete_type),
246                                     Applicability::MaybeIncorrect,
247                                 );
248                             }
249                             ExprKind::Path(ref qpath) => {
250                                 // local binding
251                                 if let &QPath::Resolved(_, ref path) = &qpath {
252                                     if let hir::def::Def::Local(hir_id) = path.def {
253                                         let span = tcx.hir().span_by_hir_id(hir_id);
254                                         let snippet = tcx.sess.source_map().span_to_snippet(span)
255                                             .unwrap();
256                                         let filename = tcx.sess.source_map().span_to_filename(span);
257
258                                         let parent_node = self.tcx.hir().get_by_hir_id(
259                                             self.tcx.hir().get_parent_node_by_hir_id(hir_id),
260                                         );
261                                         let msg = format!(
262                                             "you must specify a type for this binding, like `{}`",
263                                             concrete_type,
264                                         );
265
266                                         match (filename, parent_node) {
267                                             (FileName::Real(_), Node::Local(hir::Local {
268                                                 source: hir::LocalSource::Normal,
269                                                 ty,
270                                                 ..
271                                             })) => {
272                                                 err.span_suggestion(
273                                                     // account for `let x: _ = 42;`
274                                                     //                  ^^^^
275                                                     span.to(ty.as_ref().map(|ty| ty.span)
276                                                         .unwrap_or(span)),
277                                                     &msg,
278                                                     format!("{}: {}", snippet, concrete_type),
279                                                     Applicability::MaybeIncorrect,
280                                                 );
281                                             }
282                                             _ => {
283                                                 err.span_label(span, msg);
284                                             }
285                                         }
286                                     }
287                                 }
288                             }
289                             _ => {}
290                         }
291                         err.emit();
292                         return;
293                     } else {
294                         span = item_name.span;
295                         let mut err = struct_span_err!(
296                             tcx.sess,
297                             span,
298                             E0599,
299                             "no {} named `{}` found for type `{}` in the current scope",
300                             item_kind,
301                             item_name,
302                             ty_str
303                         );
304                         if let Some(span) = tcx.sess.confused_type_with_std_module.borrow()
305                             .get(&span)
306                         {
307                             if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*span) {
308                                 err.span_suggestion(
309                                     *span,
310                                     "you are looking for the module in `std`, \
311                                      not the primitive type",
312                                     format!("std::{}", snippet),
313                                     Applicability::MachineApplicable,
314                                 );
315                             }
316                         }
317                         err
318                     }
319                 } else {
320                     tcx.sess.diagnostic().struct_dummy()
321                 };
322
323                 if let Some(def) = actual.ty_adt_def() {
324                     if let Some(full_sp) = tcx.hir().span_if_local(def.did) {
325                         let def_sp = tcx.sess.source_map().def_span(full_sp);
326                         err.span_label(def_sp, format!("{} `{}` not found {}",
327                                                        item_kind,
328                                                        item_name,
329                                                        if def.is_enum() && !is_method {
330                                                            "here"
331                                                        } else {
332                                                            "for this"
333                                                        }));
334                     }
335                 }
336
337                 // If the method name is the name of a field with a function or closure type,
338                 // give a helping note that it has to be called as `(x.f)(...)`.
339                 if let SelfSource::MethodCall(expr) = source {
340                     let field_receiver = self
341                         .autoderef(span, rcvr_ty)
342                         .find_map(|(ty, _)| match ty.sty {
343                             ty::Adt(def, substs) if !def.is_enum() => {
344                                 let variant = &def.non_enum_variant();
345                                 self.tcx.find_field_index(item_name, variant).map(|index| {
346                                     let field = &variant.fields[index];
347                                     let field_ty = field.ty(tcx, substs);
348                                     (field, field_ty)
349                                 })
350                             }
351                             _ => None,
352                         });
353
354                     if let Some((field, field_ty)) = field_receiver {
355                         let scope = self.tcx.hir().get_module_parent_by_hir_id(self.body_id);
356                         let is_accessible = field.vis.is_accessible_from(scope, self.tcx);
357
358                         if is_accessible {
359                             if self.is_fn_ty(&field_ty, span) {
360                                 let expr_span = expr.span.to(item_name.span);
361                                 err.multipart_suggestion(
362                                     &format!(
363                                         "to call the function stored in `{}`, \
364                                          surround the field access with parentheses",
365                                         item_name,
366                                     ),
367                                     vec![
368                                         (expr_span.shrink_to_lo(), '('.to_string()),
369                                         (expr_span.shrink_to_hi(), ')'.to_string()),
370                                     ],
371                                     Applicability::MachineApplicable,
372                                 );
373                             } else {
374                                 let call_expr = self.tcx.hir().expect_expr_by_hir_id(
375                                     self.tcx.hir().get_parent_node_by_hir_id(expr.hir_id),
376                                 );
377
378                                 let span = call_expr.span.trim_start(item_name.span).unwrap();
379
380                                 err.span_suggestion(
381                                     span,
382                                     "remove the arguments",
383                                     String::new(),
384                                     Applicability::MaybeIncorrect,
385                                 );
386                             }
387                         }
388
389                         let field_kind = if is_accessible {
390                             "field"
391                         } else {
392                             "private field"
393                         };
394                         err.span_label(item_name.span, format!("{}, not a method", field_kind));
395                     }
396                 } else {
397                     err.span_label(span, format!("{} not found in `{}`", item_kind, ty_str));
398                     self.tcx.sess.trait_methods_not_found.borrow_mut().insert(orig_span);
399                 }
400
401                 if self.is_fn_ty(&rcvr_ty, span) {
402                     macro_rules! report_function {
403                         ($span:expr, $name:expr) => {
404                             err.note(&format!("{} is a function, perhaps you wish to call it",
405                                               $name));
406                         }
407                     }
408
409                     if let SelfSource::MethodCall(expr) = source {
410                         if let Ok(expr_string) = tcx.sess.source_map().span_to_snippet(expr.span) {
411                             report_function!(expr.span, expr_string);
412                         } else if let ExprKind::Path(QPath::Resolved(_, ref path)) =
413                             expr.node
414                         {
415                             if let Some(segment) = path.segments.last() {
416                                 report_function!(expr.span, segment.ident);
417                             }
418                         }
419                     }
420                 }
421
422                 if !static_sources.is_empty() {
423                     err.note("found the following associated functions; to be used as methods, \
424                               functions must have a `self` parameter");
425                     err.span_label(span, "this is an associated function, not a method");
426                 }
427                 if static_sources.len() == 1 {
428                     if let SelfSource::MethodCall(expr) = source {
429                         err.span_suggestion(expr.span.to(span),
430                                             "use associated function syntax instead",
431                                             format!("{}::{}",
432                                                     self.ty_to_string(actual),
433                                                     item_name),
434                                             Applicability::MachineApplicable);
435                     } else {
436                         err.help(&format!("try with `{}::{}`",
437                                           self.ty_to_string(actual), item_name));
438                     }
439
440                     report_candidates(span, &mut err, static_sources);
441                 } else if static_sources.len() > 1 {
442                     report_candidates(span, &mut err, static_sources);
443                 }
444
445                 if !unsatisfied_predicates.is_empty() {
446                     let mut bound_list = unsatisfied_predicates.iter()
447                         .map(|p| format!("`{} : {}`", p.self_ty(), p))
448                         .collect::<Vec<_>>();
449                     bound_list.sort();
450                     bound_list.dedup();  // #35677
451                     let bound_list = bound_list.join("\n");
452                     err.note(&format!("the method `{}` exists but the following trait bounds \
453                                        were not satisfied:\n{}",
454                                       item_name,
455                                       bound_list));
456                 }
457
458                 if actual.is_numeric() && actual.is_fresh() {
459
460                 } else {
461                     self.suggest_traits_to_import(&mut err,
462                                                   span,
463                                                   rcvr_ty,
464                                                   item_name,
465                                                   source,
466                                                   out_of_scope_traits);
467                 }
468
469                 if actual.is_enum() {
470                     let adt_def = actual.ty_adt_def().expect("enum is not an ADT");
471                     if let Some(suggestion) = lev_distance::find_best_match_for_name(
472                         adt_def.variants.iter().map(|s| &s.ident.name),
473                         &item_name.as_str(),
474                         None,
475                     ) {
476                         err.span_suggestion(
477                             span,
478                             "there is a variant with a similar name",
479                             suggestion.to_string(),
480                             Applicability::MaybeIncorrect,
481                         );
482                     }
483                 }
484
485                 if let Some(lev_candidate) = lev_candidate {
486                     let def = lev_candidate.def();
487                     err.span_suggestion(
488                         span,
489                         &format!(
490                             "there is {} {} with a similar name",
491                             def.article(),
492                             def.kind_name(),
493                         ),
494                         lev_candidate.ident.to_string(),
495                         Applicability::MaybeIncorrect,
496                     );
497                 }
498
499                 err.emit();
500             }
501
502             MethodError::Ambiguity(sources) => {
503                 let mut err = struct_span_err!(self.sess(),
504                                                span,
505                                                E0034,
506                                                "multiple applicable items in scope");
507                 err.span_label(span, format!("multiple `{}` found", item_name));
508
509                 report_candidates(span, &mut err, sources);
510                 err.emit();
511             }
512
513             MethodError::PrivateMatch(def, out_of_scope_traits) => {
514                 let mut err = struct_span_err!(self.tcx.sess, span, E0624,
515                                                "{} `{}` is private", def.kind_name(), item_name);
516                 self.suggest_valid_traits(&mut err, out_of_scope_traits);
517                 err.emit();
518             }
519
520             MethodError::IllegalSizedBound(candidates) => {
521                 let msg = format!("the `{}` method cannot be invoked on a trait object", item_name);
522                 let mut err = self.sess().struct_span_err(span, &msg);
523                 if !candidates.is_empty() {
524                     let help = format!("{an}other candidate{s} {were} found in the following \
525                                         trait{s}, perhaps add a `use` for {one_of_them}:",
526                                     an = if candidates.len() == 1 {"an" } else { "" },
527                                     s = if candidates.len() == 1 { "" } else { "s" },
528                                     were = if candidates.len() == 1 { "was" } else { "were" },
529                                     one_of_them = if candidates.len() == 1 {
530                                         "it"
531                                     } else {
532                                         "one_of_them"
533                                     });
534                     self.suggest_use_candidates(&mut err, help, candidates);
535                 }
536                 err.emit();
537             }
538
539             MethodError::BadReturnType => {
540                 bug!("no return type expectations but got BadReturnType")
541             }
542         }
543     }
544
545     fn suggest_use_candidates(&self,
546                               err: &mut DiagnosticBuilder<'_>,
547                               mut msg: String,
548                               candidates: Vec<DefId>) {
549         let module_did = self.tcx.hir().get_module_parent_by_hir_id(self.body_id);
550         let module_id = self.tcx.hir().as_local_hir_id(module_did).unwrap();
551         let krate = self.tcx.hir().krate();
552         let (span, found_use) = UsePlacementFinder::check(self.tcx, krate, module_id);
553         if let Some(span) = span {
554             let path_strings = candidates.iter().map(|did| {
555                 // Produce an additional newline to separate the new use statement
556                 // from the directly following item.
557                 let additional_newline = if found_use {
558                     ""
559                 } else {
560                     "\n"
561                 };
562                 format!(
563                     "use {};\n{}",
564                     with_crate_prefix(|| self.tcx.def_path_str(*did)),
565                     additional_newline
566                 )
567             });
568
569             err.span_suggestions(span, &msg, path_strings, Applicability::MaybeIncorrect);
570         } else {
571             let limit = if candidates.len() == 5 { 5 } else { 4 };
572             for (i, trait_did) in candidates.iter().take(limit).enumerate() {
573                 if candidates.len() > 1 {
574                     msg.push_str(
575                         &format!(
576                             "\ncandidate #{}: `use {};`",
577                             i + 1,
578                             with_crate_prefix(|| self.tcx.def_path_str(*trait_did))
579                         )
580                     );
581                 } else {
582                     msg.push_str(
583                         &format!(
584                             "\n`use {};`",
585                             with_crate_prefix(|| self.tcx.def_path_str(*trait_did))
586                         )
587                     );
588                 }
589             }
590             if candidates.len() > limit {
591                 msg.push_str(&format!("\nand {} others", candidates.len() - limit));
592             }
593             err.note(&msg[..]);
594         }
595     }
596
597     fn suggest_valid_traits(&self,
598                             err: &mut DiagnosticBuilder<'_>,
599                             valid_out_of_scope_traits: Vec<DefId>) -> bool {
600         if !valid_out_of_scope_traits.is_empty() {
601             let mut candidates = valid_out_of_scope_traits;
602             candidates.sort();
603             candidates.dedup();
604             err.help("items from traits can only be used if the trait is in scope");
605             let msg = format!("the following {traits_are} implemented but not in scope, \
606                                perhaps add a `use` for {one_of_them}:",
607                             traits_are = if candidates.len() == 1 {
608                                 "trait is"
609                             } else {
610                                 "traits are"
611                             },
612                             one_of_them = if candidates.len() == 1 {
613                                 "it"
614                             } else {
615                                 "one of them"
616                             });
617
618             self.suggest_use_candidates(err, msg, candidates);
619             true
620         } else {
621             false
622         }
623     }
624
625     fn suggest_traits_to_import<'b>(&self,
626                                     err: &mut DiagnosticBuilder<'_>,
627                                     span: Span,
628                                     rcvr_ty: Ty<'tcx>,
629                                     item_name: ast::Ident,
630                                     source: SelfSource<'b>,
631                                     valid_out_of_scope_traits: Vec<DefId>) {
632         if self.suggest_valid_traits(err, valid_out_of_scope_traits) {
633             return;
634         }
635
636         let type_is_local = self.type_derefs_to_local(span, rcvr_ty, source);
637
638         // There are no traits implemented, so lets suggest some traits to
639         // implement, by finding ones that have the item name, and are
640         // legal to implement.
641         let mut candidates = all_traits(self.tcx)
642             .into_iter()
643             .filter(|info| {
644                 // We approximate the coherence rules to only suggest
645                 // traits that are legal to implement by requiring that
646                 // either the type or trait is local. Multi-dispatch means
647                 // this isn't perfect (that is, there are cases when
648                 // implementing a trait would be legal but is rejected
649                 // here).
650                 (type_is_local || info.def_id.is_local()) &&
651                     self.associated_item(info.def_id, item_name, Namespace::Value)
652                         .filter(|item| {
653                             // We only want to suggest public or local traits (#45781).
654                             item.vis == ty::Visibility::Public || info.def_id.is_local()
655                         })
656                         .is_some()
657             })
658             .collect::<Vec<_>>();
659
660         if !candidates.is_empty() {
661             // Sort from most relevant to least relevant.
662             candidates.sort_by(|a, b| a.cmp(b).reverse());
663             candidates.dedup();
664
665             // FIXME #21673: this help message could be tuned to the case
666             // of a type parameter: suggest adding a trait bound rather
667             // than implementing.
668             err.help("items from traits can only be used if the trait is implemented and in scope");
669             let mut msg = format!("the following {traits_define} an item `{name}`, \
670                                    perhaps you need to implement {one_of_them}:",
671                                   traits_define = if candidates.len() == 1 {
672                                       "trait defines"
673                                   } else {
674                                       "traits define"
675                                   },
676                                   one_of_them = if candidates.len() == 1 {
677                                       "it"
678                                   } else {
679                                       "one of them"
680                                   },
681                                   name = item_name);
682
683             for (i, trait_info) in candidates.iter().enumerate() {
684                 msg.push_str(&format!("\ncandidate #{}: `{}`",
685                                       i + 1,
686                                       self.tcx.def_path_str(trait_info.def_id)));
687             }
688             err.note(&msg[..]);
689         }
690     }
691
692     /// Checks whether there is a local type somewhere in the chain of
693     /// autoderefs of `rcvr_ty`.
694     fn type_derefs_to_local(&self,
695                             span: Span,
696                             rcvr_ty: Ty<'tcx>,
697                             source: SelfSource<'_>) -> bool {
698         fn is_local(ty: Ty<'_>) -> bool {
699             match ty.sty {
700                 ty::Adt(def, _) => def.did.is_local(),
701                 ty::Foreign(did) => did.is_local(),
702
703                 ty::Dynamic(ref tr, ..) =>
704                     tr.principal().map(|d| d.def_id().is_local()).unwrap_or(false),
705
706                 ty::Param(_) => true,
707
708                 // Everything else (primitive types, etc.) is effectively
709                 // non-local (there are "edge" cases, e.g., `(LocalType,)`, but
710                 // the noise from these sort of types is usually just really
711                 // annoying, rather than any sort of help).
712                 _ => false,
713             }
714         }
715
716         // This occurs for UFCS desugaring of `T::method`, where there is no
717         // receiver expression for the method call, and thus no autoderef.
718         if let SelfSource::QPath(_) = source {
719             return is_local(self.resolve_type_vars_with_obligations(rcvr_ty));
720         }
721
722         self.autoderef(span, rcvr_ty).any(|(ty, _)| is_local(ty))
723     }
724 }
725
726 #[derive(Copy, Clone)]
727 pub enum SelfSource<'a> {
728     QPath(&'a hir::Ty),
729     MethodCall(&'a hir::Expr /* rcvr */),
730 }
731
732 #[derive(Copy, Clone)]
733 pub struct TraitInfo {
734     pub def_id: DefId,
735 }
736
737 impl PartialEq for TraitInfo {
738     fn eq(&self, other: &TraitInfo) -> bool {
739         self.cmp(other) == Ordering::Equal
740     }
741 }
742 impl Eq for TraitInfo {}
743 impl PartialOrd for TraitInfo {
744     fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> {
745         Some(self.cmp(other))
746     }
747 }
748 impl Ord for TraitInfo {
749     fn cmp(&self, other: &TraitInfo) -> Ordering {
750         // Local crates are more important than remote ones (local:
751         // `cnum == 0`), and otherwise we throw in the defid for totality.
752
753         let lhs = (other.def_id.krate, other.def_id);
754         let rhs = (self.def_id.krate, self.def_id);
755         lhs.cmp(&rhs)
756     }
757 }
758
759 /// Retrieves all traits in this crate and any dependent crates.
760 pub fn all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Vec<TraitInfo> {
761     tcx.all_traits(LOCAL_CRATE).iter().map(|&def_id| TraitInfo { def_id }).collect()
762 }
763
764 /// Computes all traits in this crate and any dependent crates.
765 fn compute_all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Vec<DefId> {
766     use hir::itemlikevisit;
767
768     let mut traits = vec![];
769
770     // Crate-local:
771
772     struct Visitor<'a, 'tcx: 'a> {
773         map: &'a hir_map::Map<'tcx>,
774         traits: &'a mut Vec<DefId>,
775     }
776
777     impl<'v, 'a, 'tcx> itemlikevisit::ItemLikeVisitor<'v> for Visitor<'a, 'tcx> {
778         fn visit_item(&mut self, i: &'v hir::Item) {
779             match i.node {
780                 hir::ItemKind::Trait(..) |
781                 hir::ItemKind::TraitAlias(..) => {
782                     let def_id = self.map.local_def_id_from_hir_id(i.hir_id);
783                     self.traits.push(def_id);
784                 }
785                 _ => ()
786             }
787         }
788
789         fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {}
790
791         fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {}
792     }
793
794     tcx.hir().krate().visit_all_item_likes(&mut Visitor {
795         map: &tcx.hir(),
796         traits: &mut traits,
797     });
798
799     // Cross-crate:
800
801     let mut external_mods = FxHashSet::default();
802     fn handle_external_def(tcx: TyCtxt<'_, '_, '_>,
803                            traits: &mut Vec<DefId>,
804                            external_mods: &mut FxHashSet<DefId>,
805                            def: Def) {
806         match def {
807             Def::Def(DefKind::Trait, def_id) |
808             Def::Def(DefKind::TraitAlias, def_id) => {
809                 traits.push(def_id);
810             }
811             Def::Def(DefKind::Mod, def_id) => {
812                 if !external_mods.insert(def_id) {
813                     return;
814                 }
815                 for child in tcx.item_children(def_id).iter() {
816                     handle_external_def(tcx, traits, external_mods, child.def)
817                 }
818             }
819             _ => {}
820         }
821     }
822     for &cnum in tcx.crates().iter() {
823         let def_id = DefId {
824             krate: cnum,
825             index: CRATE_DEF_INDEX,
826         };
827         handle_external_def(tcx, &mut traits, &mut external_mods, Def::Def(DefKind::Mod, def_id));
828     }
829
830     traits
831 }
832
833 pub fn provide(providers: &mut ty::query::Providers<'_>) {
834     providers.all_traits = |tcx, cnum| {
835         assert_eq!(cnum, LOCAL_CRATE);
836         Lrc::new(compute_all_traits(tcx))
837     }
838 }
839
840 struct UsePlacementFinder<'a, 'tcx: 'a, 'gcx: 'tcx> {
841     target_module: hir::HirId,
842     span: Option<Span>,
843     found_use: bool,
844     tcx: TyCtxt<'a, 'gcx, 'tcx>
845 }
846
847 impl<'a, 'tcx, 'gcx> UsePlacementFinder<'a, 'tcx, 'gcx> {
848     fn check(
849         tcx: TyCtxt<'a, 'gcx, 'tcx>,
850         krate: &'tcx hir::Crate,
851         target_module: hir::HirId,
852     ) -> (Option<Span>, bool) {
853         let mut finder = UsePlacementFinder {
854             target_module,
855             span: None,
856             found_use: false,
857             tcx,
858         };
859         hir::intravisit::walk_crate(&mut finder, krate);
860         (finder.span, finder.found_use)
861     }
862 }
863
864 impl<'a, 'tcx, 'gcx> hir::intravisit::Visitor<'tcx> for UsePlacementFinder<'a, 'tcx, 'gcx> {
865     fn visit_mod(
866         &mut self,
867         module: &'tcx hir::Mod,
868         _: Span,
869         hir_id: hir::HirId,
870     ) {
871         if self.span.is_some() {
872             return;
873         }
874         if hir_id != self.target_module {
875             hir::intravisit::walk_mod(self, module, hir_id);
876             return;
877         }
878         // Find a `use` statement.
879         for item_id in &module.item_ids {
880             let item = self.tcx.hir().expect_item_by_hir_id(item_id.id);
881             match item.node {
882                 hir::ItemKind::Use(..) => {
883                     // Don't suggest placing a `use` before the prelude
884                     // import or other generated ones.
885                     if item.span.ctxt().outer().expn_info().is_none() {
886                         self.span = Some(item.span.shrink_to_lo());
887                         self.found_use = true;
888                         return;
889                     }
890                 },
891                 // Don't place `use` before `extern crate`...
892                 hir::ItemKind::ExternCrate(_) => {}
893                 // ...but do place them before the first other item.
894                 _ => if self.span.map_or(true, |span| item.span < span ) {
895                     if item.span.ctxt().outer().expn_info().is_none() {
896                         // Don't insert between attributes and an item.
897                         if item.attrs.is_empty() {
898                             self.span = Some(item.span.shrink_to_lo());
899                         } else {
900                             // Find the first attribute on the item.
901                             for attr in &item.attrs {
902                                 if self.span.map_or(true, |span| attr.span < span) {
903                                     self.span = Some(attr.span.shrink_to_lo());
904                                 }
905                             }
906                         }
907                     }
908                 },
909             }
910         }
911     }
912
913     fn nested_visit_map<'this>(
914         &'this mut self
915     ) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> {
916         hir::intravisit::NestedVisitorMap::None
917     }
918 }