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