]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/suggest.rs
Rollup merge of #59912 - RalfJung:maybe-uninit, r=Centril
[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;
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(node_id) = path.def {
253                                         let span = tcx.hir().span(node_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(
259                                             self.tcx.hir().get_parent_node(node_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                         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                     }
305                 } else {
306                     tcx.sess.diagnostic().struct_dummy()
307                 };
308
309                 if let Some(def) = actual.ty_adt_def() {
310                     if let Some(full_sp) = tcx.hir().span_if_local(def.did) {
311                         let def_sp = tcx.sess.source_map().def_span(full_sp);
312                         err.span_label(def_sp, format!("{} `{}` not found {}",
313                                                        item_kind,
314                                                        item_name,
315                                                        if def.is_enum() && !is_method {
316                                                            "here"
317                                                        } else {
318                                                            "for this"
319                                                        }));
320                     }
321                 }
322
323                 // If the method name is the name of a field with a function or closure type,
324                 // give a helping note that it has to be called as `(x.f)(...)`.
325                 if let SelfSource::MethodCall(expr) = source {
326                     let field_receiver = self
327                         .autoderef(span, rcvr_ty)
328                         .find_map(|(ty, _)| match ty.sty {
329                             ty::Adt(def, substs) if !def.is_enum() => {
330                                 let variant = &def.non_enum_variant();
331                                 self.tcx.find_field_index(item_name, variant).map(|index| {
332                                     let field = &variant.fields[index];
333                                     let field_ty = field.ty(tcx, substs);
334                                     (field, field_ty)
335                                 })
336                             }
337                             _ => None,
338                         });
339
340                     if let Some((field, field_ty)) = field_receiver {
341                         let scope = self.tcx.hir().get_module_parent_by_hir_id(self.body_id);
342                         let is_accessible = field.vis.is_accessible_from(scope, self.tcx);
343
344                         if is_accessible {
345                             if self.is_fn_ty(&field_ty, span) {
346                                 let expr_span = expr.span.to(item_name.span);
347                                 err.multipart_suggestion(
348                                     &format!(
349                                         "to call the function stored in `{}`, \
350                                          surround the field access with parentheses",
351                                         item_name,
352                                     ),
353                                     vec![
354                                         (expr_span.shrink_to_lo(), '('.to_string()),
355                                         (expr_span.shrink_to_hi(), ')'.to_string()),
356                                     ],
357                                     Applicability::MachineApplicable,
358                                 );
359                             } else {
360                                 let call_expr = self.tcx.hir().expect_expr_by_hir_id(
361                                     self.tcx.hir().get_parent_node_by_hir_id(expr.hir_id),
362                                 );
363
364                                 let span = call_expr.span.trim_start(item_name.span).unwrap();
365
366                                 err.span_suggestion(
367                                     span,
368                                     "remove the arguments",
369                                     String::new(),
370                                     Applicability::MaybeIncorrect,
371                                 );
372                             }
373                         }
374
375                         let field_kind = if is_accessible {
376                             "field"
377                         } else {
378                             "private field"
379                         };
380                         err.span_label(item_name.span, format!("{}, not a method", field_kind));
381                     }
382                 } else {
383                     err.span_label(span, format!("{} not found in `{}`", item_kind, ty_str));
384                     self.tcx.sess.trait_methods_not_found.borrow_mut().insert(orig_span);
385                 }
386
387                 if self.is_fn_ty(&rcvr_ty, span) {
388                     macro_rules! report_function {
389                         ($span:expr, $name:expr) => {
390                             err.note(&format!("{} is a function, perhaps you wish to call it",
391                                               $name));
392                         }
393                     }
394
395                     if let SelfSource::MethodCall(expr) = source {
396                         if let Ok(expr_string) = tcx.sess.source_map().span_to_snippet(expr.span) {
397                             report_function!(expr.span, expr_string);
398                         } else if let ExprKind::Path(QPath::Resolved(_, ref path)) =
399                             expr.node
400                         {
401                             if let Some(segment) = path.segments.last() {
402                                 report_function!(expr.span, segment.ident);
403                             }
404                         }
405                     }
406                 }
407
408                 if !static_sources.is_empty() {
409                     err.note("found the following associated functions; to be used as methods, \
410                               functions must have a `self` parameter");
411                     err.span_label(span, "this is an associated function, not a method");
412                 }
413                 if static_sources.len() == 1 {
414                     if let SelfSource::MethodCall(expr) = source {
415                         err.span_suggestion(expr.span.to(span),
416                                             "use associated function syntax instead",
417                                             format!("{}::{}",
418                                                     self.ty_to_string(actual),
419                                                     item_name),
420                                             Applicability::MachineApplicable);
421                     } else {
422                         err.help(&format!("try with `{}::{}`",
423                                           self.ty_to_string(actual), item_name));
424                     }
425
426                     report_candidates(span, &mut err, static_sources);
427                 } else if static_sources.len() > 1 {
428                     report_candidates(span, &mut err, static_sources);
429                 }
430
431                 if !unsatisfied_predicates.is_empty() {
432                     let mut bound_list = unsatisfied_predicates.iter()
433                         .map(|p| format!("`{} : {}`", p.self_ty(), p))
434                         .collect::<Vec<_>>();
435                     bound_list.sort();
436                     bound_list.dedup();  // #35677
437                     let bound_list = bound_list.join("\n");
438                     err.note(&format!("the method `{}` exists but the following trait bounds \
439                                        were not satisfied:\n{}",
440                                       item_name,
441                                       bound_list));
442                 }
443
444                 if actual.is_numeric() && actual.is_fresh() {
445
446                 } else {
447                     self.suggest_traits_to_import(&mut err,
448                                                   span,
449                                                   rcvr_ty,
450                                                   item_name,
451                                                   source,
452                                                   out_of_scope_traits);
453                 }
454
455                 if actual.is_enum() {
456                     let adt_def = actual.ty_adt_def().expect("enum is not an ADT");
457                     if let Some(suggestion) = lev_distance::find_best_match_for_name(
458                         adt_def.variants.iter().map(|s| &s.ident.name),
459                         &item_name.as_str(),
460                         None,
461                     ) {
462                         err.span_suggestion(
463                             span,
464                             "there is a variant with a similar name",
465                             suggestion.to_string(),
466                             Applicability::MaybeIncorrect,
467                         );
468                     }
469                 }
470
471                 if let Some(lev_candidate) = lev_candidate {
472                     let def = lev_candidate.def();
473                     err.span_suggestion(
474                         span,
475                         &format!(
476                             "there is {} {} with a similar name",
477                             def.article(),
478                             def.kind_name(),
479                         ),
480                         lev_candidate.ident.to_string(),
481                         Applicability::MaybeIncorrect,
482                     );
483                 }
484
485                 err.emit();
486             }
487
488             MethodError::Ambiguity(sources) => {
489                 let mut err = struct_span_err!(self.sess(),
490                                                span,
491                                                E0034,
492                                                "multiple applicable items in scope");
493                 err.span_label(span, format!("multiple `{}` found", item_name));
494
495                 report_candidates(span, &mut err, sources);
496                 err.emit();
497             }
498
499             MethodError::PrivateMatch(def, out_of_scope_traits) => {
500                 let mut err = struct_span_err!(self.tcx.sess, span, E0624,
501                                                "{} `{}` is private", def.kind_name(), item_name);
502                 self.suggest_valid_traits(&mut err, out_of_scope_traits);
503                 err.emit();
504             }
505
506             MethodError::IllegalSizedBound(candidates) => {
507                 let msg = format!("the `{}` method cannot be invoked on a trait object", item_name);
508                 let mut err = self.sess().struct_span_err(span, &msg);
509                 if !candidates.is_empty() {
510                     let help = format!("{an}other candidate{s} {were} found in the following \
511                                         trait{s}, perhaps add a `use` for {one_of_them}:",
512                                     an = if candidates.len() == 1 {"an" } else { "" },
513                                     s = if candidates.len() == 1 { "" } else { "s" },
514                                     were = if candidates.len() == 1 { "was" } else { "were" },
515                                     one_of_them = if candidates.len() == 1 {
516                                         "it"
517                                     } else {
518                                         "one_of_them"
519                                     });
520                     self.suggest_use_candidates(&mut err, help, candidates);
521                 }
522                 err.emit();
523             }
524
525             MethodError::BadReturnType => {
526                 bug!("no return type expectations but got BadReturnType")
527             }
528         }
529     }
530
531     fn suggest_use_candidates(&self,
532                               err: &mut DiagnosticBuilder<'_>,
533                               mut msg: String,
534                               candidates: Vec<DefId>) {
535         let module_did = self.tcx.hir().get_module_parent_by_hir_id(self.body_id);
536         let module_id = self.tcx.hir().as_local_hir_id(module_did).unwrap();
537         let krate = self.tcx.hir().krate();
538         let (span, found_use) = UsePlacementFinder::check(self.tcx, krate, module_id);
539         if let Some(span) = span {
540             let path_strings = candidates.iter().map(|did| {
541                 // Produce an additional newline to separate the new use statement
542                 // from the directly following item.
543                 let additional_newline = if found_use {
544                     ""
545                 } else {
546                     "\n"
547                 };
548                 format!(
549                     "use {};\n{}",
550                     with_crate_prefix(|| self.tcx.def_path_str(*did)),
551                     additional_newline
552                 )
553             });
554
555             err.span_suggestions(span, &msg, path_strings, Applicability::MaybeIncorrect);
556         } else {
557             let limit = if candidates.len() == 5 { 5 } else { 4 };
558             for (i, trait_did) in candidates.iter().take(limit).enumerate() {
559                 if candidates.len() > 1 {
560                     msg.push_str(
561                         &format!(
562                             "\ncandidate #{}: `use {};`",
563                             i + 1,
564                             with_crate_prefix(|| self.tcx.def_path_str(*trait_did))
565                         )
566                     );
567                 } else {
568                     msg.push_str(
569                         &format!(
570                             "\n`use {};`",
571                             with_crate_prefix(|| self.tcx.def_path_str(*trait_did))
572                         )
573                     );
574                 }
575             }
576             if candidates.len() > limit {
577                 msg.push_str(&format!("\nand {} others", candidates.len() - limit));
578             }
579             err.note(&msg[..]);
580         }
581     }
582
583     fn suggest_valid_traits(&self,
584                             err: &mut DiagnosticBuilder<'_>,
585                             valid_out_of_scope_traits: Vec<DefId>) -> bool {
586         if !valid_out_of_scope_traits.is_empty() {
587             let mut candidates = valid_out_of_scope_traits;
588             candidates.sort();
589             candidates.dedup();
590             err.help("items from traits can only be used if the trait is in scope");
591             let msg = format!("the following {traits_are} implemented but not in scope, \
592                                perhaps add a `use` for {one_of_them}:",
593                             traits_are = if candidates.len() == 1 {
594                                 "trait is"
595                             } else {
596                                 "traits are"
597                             },
598                             one_of_them = if candidates.len() == 1 {
599                                 "it"
600                             } else {
601                                 "one of them"
602                             });
603
604             self.suggest_use_candidates(err, msg, candidates);
605             true
606         } else {
607             false
608         }
609     }
610
611     fn suggest_traits_to_import<'b>(&self,
612                                     err: &mut DiagnosticBuilder<'_>,
613                                     span: Span,
614                                     rcvr_ty: Ty<'tcx>,
615                                     item_name: ast::Ident,
616                                     source: SelfSource<'b>,
617                                     valid_out_of_scope_traits: Vec<DefId>) {
618         if self.suggest_valid_traits(err, valid_out_of_scope_traits) {
619             return;
620         }
621
622         let type_is_local = self.type_derefs_to_local(span, rcvr_ty, source);
623
624         // There are no traits implemented, so lets suggest some traits to
625         // implement, by finding ones that have the item name, and are
626         // legal to implement.
627         let mut candidates = all_traits(self.tcx)
628             .into_iter()
629             .filter(|info| {
630                 // We approximate the coherence rules to only suggest
631                 // traits that are legal to implement by requiring that
632                 // either the type or trait is local. Multi-dispatch means
633                 // this isn't perfect (that is, there are cases when
634                 // implementing a trait would be legal but is rejected
635                 // here).
636                 (type_is_local || info.def_id.is_local()) &&
637                     self.associated_item(info.def_id, item_name, Namespace::Value)
638                         .filter(|item| {
639                             // We only want to suggest public or local traits (#45781).
640                             item.vis == ty::Visibility::Public || info.def_id.is_local()
641                         })
642                         .is_some()
643             })
644             .collect::<Vec<_>>();
645
646         if !candidates.is_empty() {
647             // Sort from most relevant to least relevant.
648             candidates.sort_by(|a, b| a.cmp(b).reverse());
649             candidates.dedup();
650
651             // FIXME #21673: this help message could be tuned to the case
652             // of a type parameter: suggest adding a trait bound rather
653             // than implementing.
654             err.help("items from traits can only be used if the trait is implemented and in scope");
655             let mut msg = format!("the following {traits_define} an item `{name}`, \
656                                    perhaps you need to implement {one_of_them}:",
657                                   traits_define = if candidates.len() == 1 {
658                                       "trait defines"
659                                   } else {
660                                       "traits define"
661                                   },
662                                   one_of_them = if candidates.len() == 1 {
663                                       "it"
664                                   } else {
665                                       "one of them"
666                                   },
667                                   name = item_name);
668
669             for (i, trait_info) in candidates.iter().enumerate() {
670                 msg.push_str(&format!("\ncandidate #{}: `{}`",
671                                       i + 1,
672                                       self.tcx.def_path_str(trait_info.def_id)));
673             }
674             err.note(&msg[..]);
675         }
676     }
677
678     /// Checks whether there is a local type somewhere in the chain of
679     /// autoderefs of `rcvr_ty`.
680     fn type_derefs_to_local(&self,
681                             span: Span,
682                             rcvr_ty: Ty<'tcx>,
683                             source: SelfSource<'_>) -> bool {
684         fn is_local(ty: Ty<'_>) -> bool {
685             match ty.sty {
686                 ty::Adt(def, _) => def.did.is_local(),
687                 ty::Foreign(did) => did.is_local(),
688
689                 ty::Dynamic(ref tr, ..) =>
690                     tr.principal().map(|d| d.def_id().is_local()).unwrap_or(false),
691
692                 ty::Param(_) => true,
693
694                 // Everything else (primitive types, etc.) is effectively
695                 // non-local (there are "edge" cases, e.g., `(LocalType,)`, but
696                 // the noise from these sort of types is usually just really
697                 // annoying, rather than any sort of help).
698                 _ => false,
699             }
700         }
701
702         // This occurs for UFCS desugaring of `T::method`, where there is no
703         // receiver expression for the method call, and thus no autoderef.
704         if let SelfSource::QPath(_) = source {
705             return is_local(self.resolve_type_vars_with_obligations(rcvr_ty));
706         }
707
708         self.autoderef(span, rcvr_ty).any(|(ty, _)| is_local(ty))
709     }
710 }
711
712 #[derive(Copy, Clone)]
713 pub enum SelfSource<'a> {
714     QPath(&'a hir::Ty),
715     MethodCall(&'a hir::Expr /* rcvr */),
716 }
717
718 #[derive(Copy, Clone)]
719 pub struct TraitInfo {
720     pub def_id: DefId,
721 }
722
723 impl PartialEq for TraitInfo {
724     fn eq(&self, other: &TraitInfo) -> bool {
725         self.cmp(other) == Ordering::Equal
726     }
727 }
728 impl Eq for TraitInfo {}
729 impl PartialOrd for TraitInfo {
730     fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> {
731         Some(self.cmp(other))
732     }
733 }
734 impl Ord for TraitInfo {
735     fn cmp(&self, other: &TraitInfo) -> Ordering {
736         // Local crates are more important than remote ones (local:
737         // `cnum == 0`), and otherwise we throw in the defid for totality.
738
739         let lhs = (other.def_id.krate, other.def_id);
740         let rhs = (self.def_id.krate, self.def_id);
741         lhs.cmp(&rhs)
742     }
743 }
744
745 /// Retrieves all traits in this crate and any dependent crates.
746 pub fn all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Vec<TraitInfo> {
747     tcx.all_traits(LOCAL_CRATE).iter().map(|&def_id| TraitInfo { def_id }).collect()
748 }
749
750 /// Computes all traits in this crate and any dependent crates.
751 fn compute_all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Vec<DefId> {
752     use hir::itemlikevisit;
753
754     let mut traits = vec![];
755
756     // Crate-local:
757
758     struct Visitor<'a, 'tcx: 'a> {
759         map: &'a hir_map::Map<'tcx>,
760         traits: &'a mut Vec<DefId>,
761     }
762
763     impl<'v, 'a, 'tcx> itemlikevisit::ItemLikeVisitor<'v> for Visitor<'a, 'tcx> {
764         fn visit_item(&mut self, i: &'v hir::Item) {
765             match i.node {
766                 hir::ItemKind::Trait(..) |
767                 hir::ItemKind::TraitAlias(..) => {
768                     let def_id = self.map.local_def_id_from_hir_id(i.hir_id);
769                     self.traits.push(def_id);
770                 }
771                 _ => ()
772             }
773         }
774
775         fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {}
776
777         fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {}
778     }
779
780     tcx.hir().krate().visit_all_item_likes(&mut Visitor {
781         map: &tcx.hir(),
782         traits: &mut traits,
783     });
784
785     // Cross-crate:
786
787     let mut external_mods = FxHashSet::default();
788     fn handle_external_def(tcx: TyCtxt<'_, '_, '_>,
789                            traits: &mut Vec<DefId>,
790                            external_mods: &mut FxHashSet<DefId>,
791                            def: Def) {
792         match def {
793             Def::Trait(def_id) |
794             Def::TraitAlias(def_id) => {
795                 traits.push(def_id);
796             }
797             Def::Mod(def_id) => {
798                 if !external_mods.insert(def_id) {
799                     return;
800                 }
801                 for child in tcx.item_children(def_id).iter() {
802                     handle_external_def(tcx, traits, external_mods, child.def)
803                 }
804             }
805             _ => {}
806         }
807     }
808     for &cnum in tcx.crates().iter() {
809         let def_id = DefId {
810             krate: cnum,
811             index: CRATE_DEF_INDEX,
812         };
813         handle_external_def(tcx, &mut traits, &mut external_mods, Def::Mod(def_id));
814     }
815
816     traits
817 }
818
819 pub fn provide(providers: &mut ty::query::Providers<'_>) {
820     providers.all_traits = |tcx, cnum| {
821         assert_eq!(cnum, LOCAL_CRATE);
822         Lrc::new(compute_all_traits(tcx))
823     }
824 }
825
826 struct UsePlacementFinder<'a, 'tcx: 'a, 'gcx: 'tcx> {
827     target_module: hir::HirId,
828     span: Option<Span>,
829     found_use: bool,
830     tcx: TyCtxt<'a, 'gcx, 'tcx>
831 }
832
833 impl<'a, 'tcx, 'gcx> UsePlacementFinder<'a, 'tcx, 'gcx> {
834     fn check(
835         tcx: TyCtxt<'a, 'gcx, 'tcx>,
836         krate: &'tcx hir::Crate,
837         target_module: hir::HirId,
838     ) -> (Option<Span>, bool) {
839         let mut finder = UsePlacementFinder {
840             target_module,
841             span: None,
842             found_use: false,
843             tcx,
844         };
845         hir::intravisit::walk_crate(&mut finder, krate);
846         (finder.span, finder.found_use)
847     }
848 }
849
850 impl<'a, 'tcx, 'gcx> hir::intravisit::Visitor<'tcx> for UsePlacementFinder<'a, 'tcx, 'gcx> {
851     fn visit_mod(
852         &mut self,
853         module: &'tcx hir::Mod,
854         _: Span,
855         hir_id: hir::HirId,
856     ) {
857         if self.span.is_some() {
858             return;
859         }
860         if hir_id != self.target_module {
861             hir::intravisit::walk_mod(self, module, hir_id);
862             return;
863         }
864         // Find a `use` statement.
865         for item_id in &module.item_ids {
866             let item = self.tcx.hir().expect_item_by_hir_id(item_id.id);
867             match item.node {
868                 hir::ItemKind::Use(..) => {
869                     // Don't suggest placing a `use` before the prelude
870                     // import or other generated ones.
871                     if item.span.ctxt().outer().expn_info().is_none() {
872                         self.span = Some(item.span.shrink_to_lo());
873                         self.found_use = true;
874                         return;
875                     }
876                 },
877                 // Don't place `use` before `extern crate`...
878                 hir::ItemKind::ExternCrate(_) => {}
879                 // ...but do place them before the first other item.
880                 _ => if self.span.map_or(true, |span| item.span < span ) {
881                     if item.span.ctxt().outer().expn_info().is_none() {
882                         // Don't insert between attributes and an item.
883                         if item.attrs.is_empty() {
884                             self.span = Some(item.span.shrink_to_lo());
885                         } else {
886                             // Find the first attribute on the item.
887                             for attr in &item.attrs {
888                                 if self.span.map_or(true, |span| attr.span < span) {
889                                     self.span = Some(attr.span.shrink_to_lo());
890                                 }
891                             }
892                         }
893                     }
894                 },
895             }
896         }
897     }
898
899     fn nested_visit_map<'this>(
900         &'this mut self
901     ) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> {
902         hir::intravisit::NestedVisitorMap::None
903     }
904 }