]> git.lizzy.rs Git - rust.git/blob - src/librustc_save_analysis/dump_visitor.rs
hir: introduce `QPath::LangItem`
[rust.git] / src / librustc_save_analysis / dump_visitor.rs
1 //! Write the output of rustc's analysis to an implementor of Dump.
2 //!
3 //! Dumping the analysis is implemented by walking the AST and getting a bunch of
4 //! info out from all over the place. We use `DefId`s to identify objects. The
5 //! tricky part is getting syntactic (span, source text) and semantic (reference
6 //! `DefId`s) information for parts of expressions which the compiler has discarded.
7 //! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
8 //! path and a reference to `baz`, but we want spans and references for all three
9 //! idents.
10 //!
11 //! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
12 //! from spans (e.g., the span for `bar` from the above example path).
13 //! DumpVisitor walks the AST and processes it, and Dumper is used for
14 //! recording the output.
15
16 use rustc_ast::ast::{self};
17 use rustc_ast::{token, walk_list};
18 use rustc_data_structures::fx::FxHashSet;
19 use rustc_hir as hir;
20 use rustc_hir::def::{DefKind as HirDefKind, Res};
21 use rustc_hir::def_id::{DefId, LocalDefId};
22 use rustc_hir::intravisit::{self, Visitor};
23 use rustc_hir_pretty::{bounds_to_string, fn_to_string, generic_params_to_string, ty_to_string};
24 use rustc_middle::hir::map::Map;
25 use rustc_middle::span_bug;
26 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
27 use rustc_session::config::Input;
28 use rustc_span::source_map::respan;
29 use rustc_span::symbol::Ident;
30 use rustc_span::*;
31
32 use std::env;
33 use std::path::Path;
34
35 use crate::dumper::{Access, Dumper};
36 use crate::sig;
37 use crate::span_utils::SpanUtils;
38 use crate::{
39     escape, generated_code, id_from_def_id, id_from_hir_id, lower_attributes, PathCollector,
40     SaveContext,
41 };
42
43 use rls_data::{
44     CompilationOptions, CratePreludeData, Def, DefKind, GlobalCrateId, Import, ImportKind, Ref,
45     RefKind, Relation, RelationKind, SpanData,
46 };
47
48 use tracing::{debug, error};
49
50 macro_rules! down_cast_data {
51     ($id:ident, $kind:ident, $sp:expr) => {
52         let $id = if let super::Data::$kind(data) = $id {
53             data
54         } else {
55             span_bug!($sp, "unexpected data kind: {:?}", $id);
56         };
57     };
58 }
59
60 macro_rules! access_from {
61     ($save_ctxt:expr, $item:expr, $id:expr) => {
62         Access {
63             public: $item.vis.node.is_pub(),
64             reachable: $save_ctxt.access_levels.is_reachable($id),
65         }
66     };
67 }
68
69 macro_rules! access_from_vis {
70     ($save_ctxt:expr, $vis:expr, $id:expr) => {
71         Access { public: $vis.node.is_pub(), reachable: $save_ctxt.access_levels.is_reachable($id) }
72     };
73 }
74
75 pub struct DumpVisitor<'tcx> {
76     pub save_ctxt: SaveContext<'tcx>,
77     tcx: TyCtxt<'tcx>,
78     dumper: Dumper,
79
80     span: SpanUtils<'tcx>,
81     // Set of macro definition (callee) spans, and the set
82     // of macro use (callsite) spans. We store these to ensure
83     // we only write one macro def per unique macro definition, and
84     // one macro use per unique callsite span.
85     // mac_defs: FxHashSet<Span>,
86     // macro_calls: FxHashSet<Span>,
87 }
88
89 impl<'tcx> DumpVisitor<'tcx> {
90     pub fn new(save_ctxt: SaveContext<'tcx>) -> DumpVisitor<'tcx> {
91         let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
92         let dumper = Dumper::new(save_ctxt.config.clone());
93         DumpVisitor {
94             tcx: save_ctxt.tcx,
95             save_ctxt,
96             dumper,
97             span: span_utils,
98             // mac_defs: FxHashSet::default(),
99             // macro_calls: FxHashSet::default(),
100         }
101     }
102
103     pub fn analysis(&self) -> &rls_data::Analysis {
104         self.dumper.analysis()
105     }
106
107     fn nest_typeck_results<F>(&mut self, item_def_id: LocalDefId, f: F)
108     where
109         F: FnOnce(&mut Self),
110     {
111         let typeck_results = if self.tcx.has_typeck_results(item_def_id) {
112             Some(self.tcx.typeck(item_def_id))
113         } else {
114             None
115         };
116
117         let old_maybe_typeck_results = self.save_ctxt.maybe_typeck_results;
118         self.save_ctxt.maybe_typeck_results = typeck_results;
119         f(self);
120         self.save_ctxt.maybe_typeck_results = old_maybe_typeck_results;
121     }
122
123     fn span_from_span(&self, span: Span) -> SpanData {
124         self.save_ctxt.span_from_span(span)
125     }
126
127     fn lookup_def_id(&self, ref_id: hir::HirId) -> Option<DefId> {
128         self.save_ctxt.lookup_def_id(ref_id)
129     }
130
131     pub fn dump_crate_info(&mut self, name: &str, krate: &hir::Crate<'_>) {
132         let source_file = self.tcx.sess.local_crate_source_file.as_ref();
133         let crate_root = source_file.map(|source_file| {
134             let source_file = Path::new(source_file);
135             match source_file.file_name() {
136                 Some(_) => source_file.parent().unwrap().display(),
137                 None => source_file.display(),
138             }
139             .to_string()
140         });
141
142         let data = CratePreludeData {
143             crate_id: GlobalCrateId {
144                 name: name.into(),
145                 disambiguator: self
146                     .tcx
147                     .sess
148                     .local_crate_disambiguator()
149                     .to_fingerprint()
150                     .as_value(),
151             },
152             crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
153             external_crates: self.save_ctxt.get_external_crates(),
154             span: self.span_from_span(krate.item.span),
155         };
156
157         self.dumper.crate_prelude(data);
158     }
159
160     pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
161         // Apply possible `remap-path-prefix` remapping to the input source file
162         // (and don't include remapping args anymore)
163         let (program, arguments) = {
164             let remap_arg_indices = {
165                 let mut indices = FxHashSet::default();
166                 // Args are guaranteed to be valid UTF-8 (checked early)
167                 for (i, e) in env::args().enumerate() {
168                     if e.starts_with("--remap-path-prefix=") {
169                         indices.insert(i);
170                     } else if e == "--remap-path-prefix" {
171                         indices.insert(i);
172                         indices.insert(i + 1);
173                     }
174                 }
175                 indices
176             };
177
178             let mut args = env::args()
179                 .enumerate()
180                 .filter(|(i, _)| !remap_arg_indices.contains(i))
181                 .map(|(_, arg)| match input {
182                     Input::File(ref path) if path == Path::new(&arg) => {
183                         let mapped = &self.tcx.sess.local_crate_source_file;
184                         mapped.as_ref().unwrap().to_string_lossy().into()
185                     }
186                     _ => arg,
187                 });
188
189             (args.next().unwrap(), args.collect())
190         };
191
192         let data = CompilationOptions {
193             directory: self.tcx.sess.working_dir.0.clone(),
194             program,
195             arguments,
196             output: self.save_ctxt.compilation_output(crate_name),
197         };
198
199         self.dumper.compilation_opts(data);
200     }
201
202     fn write_segments(&mut self, segments: impl IntoIterator<Item = &'tcx hir::PathSegment<'tcx>>) {
203         for seg in segments {
204             if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
205                 self.dumper.dump_ref(data);
206             }
207         }
208     }
209
210     fn write_sub_paths(&mut self, path: &'tcx hir::Path<'tcx>) {
211         self.write_segments(path.segments)
212     }
213
214     // As write_sub_paths, but does not process the last ident in the path (assuming it
215     // will be processed elsewhere). See note on write_sub_paths about global.
216     fn write_sub_paths_truncated(&mut self, path: &'tcx hir::Path<'tcx>) {
217         if let [segments @ .., _] = path.segments {
218             self.write_segments(segments)
219         }
220     }
221
222     fn process_formals(&mut self, formals: &'tcx [hir::Param<'tcx>], qualname: &str) {
223         for arg in formals {
224             self.visit_pat(&arg.pat);
225             let mut collector = PathCollector::new(self.tcx);
226             collector.visit_pat(&arg.pat);
227
228             for (hir_id, ident, ..) in collector.collected_idents {
229                 let typ = match self.save_ctxt.typeck_results().node_type_opt(hir_id) {
230                     Some(s) => s.to_string(),
231                     None => continue,
232                 };
233                 if !self.span.filter_generated(ident.span) {
234                     let id = id_from_hir_id(hir_id, &self.save_ctxt);
235                     let span = self.span_from_span(ident.span);
236
237                     self.dumper.dump_def(
238                         &Access { public: false, reachable: false },
239                         Def {
240                             kind: DefKind::Local,
241                             id,
242                             span,
243                             name: ident.to_string(),
244                             qualname: format!("{}::{}", qualname, ident.to_string()),
245                             value: typ,
246                             parent: None,
247                             children: vec![],
248                             decl_id: None,
249                             docs: String::new(),
250                             sig: None,
251                             attributes: vec![],
252                         },
253                     );
254                 }
255             }
256         }
257     }
258
259     fn process_method(
260         &mut self,
261         sig: &'tcx hir::FnSig<'tcx>,
262         body: Option<hir::BodyId>,
263         hir_id: hir::HirId,
264         ident: Ident,
265         generics: &'tcx hir::Generics<'tcx>,
266         vis: &hir::Visibility<'tcx>,
267         span: Span,
268     ) {
269         debug!("process_method: {}:{}", hir_id, ident);
270
271         let map = &self.tcx.hir();
272         self.nest_typeck_results(map.local_def_id(hir_id), |v| {
273             if let Some(mut method_data) = v.save_ctxt.get_method_data(hir_id, ident, span) {
274                 if let Some(body) = body {
275                     v.process_formals(map.body(body).params, &method_data.qualname);
276                 }
277                 v.process_generic_params(&generics, &method_data.qualname, hir_id);
278
279                 method_data.value =
280                     fn_to_string(sig.decl, sig.header, Some(ident.name), generics, vis, &[], None);
281                 method_data.sig = sig::method_signature(hir_id, ident, generics, sig, &v.save_ctxt);
282
283                 v.dumper.dump_def(&access_from_vis!(v.save_ctxt, vis, hir_id), method_data);
284             }
285
286             // walk arg and return types
287             for arg in sig.decl.inputs {
288                 v.visit_ty(arg);
289             }
290
291             if let hir::FnRetTy::Return(ref ret_ty) = sig.decl.output {
292                 v.visit_ty(ret_ty)
293             }
294
295             // walk the fn body
296             if let Some(body) = body {
297                 v.visit_expr(&map.body(body).value);
298             }
299         });
300     }
301
302     fn process_struct_field_def(
303         &mut self,
304         field: &'tcx hir::StructField<'tcx>,
305         parent_id: hir::HirId,
306     ) {
307         let field_data = self.save_ctxt.get_field_data(field, parent_id);
308         if let Some(field_data) = field_data {
309             self.dumper.dump_def(&access_from!(self.save_ctxt, field, field.hir_id), field_data);
310         }
311     }
312
313     // Dump generic params bindings, then visit_generics
314     fn process_generic_params(
315         &mut self,
316         generics: &'tcx hir::Generics<'tcx>,
317         prefix: &str,
318         id: hir::HirId,
319     ) {
320         for param in generics.params {
321             match param.kind {
322                 hir::GenericParamKind::Lifetime { .. } => {}
323                 hir::GenericParamKind::Type { .. } => {
324                     let param_ss = param.name.ident().span;
325                     let name = escape(self.span.snippet(param_ss));
326                     // Append $id to name to make sure each one is unique.
327                     let qualname = format!("{}::{}${}", prefix, name, id);
328                     if !self.span.filter_generated(param_ss) {
329                         let id = id_from_hir_id(param.hir_id, &self.save_ctxt);
330                         let span = self.span_from_span(param_ss);
331
332                         self.dumper.dump_def(
333                             &Access { public: false, reachable: false },
334                             Def {
335                                 kind: DefKind::Type,
336                                 id,
337                                 span,
338                                 name,
339                                 qualname,
340                                 value: String::new(),
341                                 parent: None,
342                                 children: vec![],
343                                 decl_id: None,
344                                 docs: String::new(),
345                                 sig: None,
346                                 attributes: vec![],
347                             },
348                         );
349                     }
350                 }
351                 hir::GenericParamKind::Const { .. } => {}
352             }
353         }
354         self.visit_generics(generics);
355     }
356
357     fn process_fn(
358         &mut self,
359         item: &'tcx hir::Item<'tcx>,
360         decl: &'tcx hir::FnDecl<'tcx>,
361         _header: &'tcx hir::FnHeader,
362         ty_params: &'tcx hir::Generics<'tcx>,
363         body: hir::BodyId,
364     ) {
365         let map = &self.tcx.hir();
366         self.nest_typeck_results(map.local_def_id(item.hir_id), |v| {
367             let body = map.body(body);
368             if let Some(fn_data) = v.save_ctxt.get_item_data(item) {
369                 down_cast_data!(fn_data, DefData, item.span);
370                 v.process_formals(body.params, &fn_data.qualname);
371                 v.process_generic_params(ty_params, &fn_data.qualname, item.hir_id);
372
373                 v.dumper.dump_def(&access_from!(v.save_ctxt, item, item.hir_id), fn_data);
374             }
375
376             for arg in decl.inputs {
377                 v.visit_ty(arg)
378             }
379
380             if let hir::FnRetTy::Return(ref ret_ty) = decl.output {
381                 v.visit_ty(ret_ty)
382             }
383
384             v.visit_expr(&body.value);
385         });
386     }
387
388     fn process_static_or_const_item(
389         &mut self,
390         item: &'tcx hir::Item<'tcx>,
391         typ: &'tcx hir::Ty<'tcx>,
392         expr: &'tcx hir::Expr<'tcx>,
393     ) {
394         self.nest_typeck_results(self.tcx.hir().local_def_id(item.hir_id), |v| {
395             if let Some(var_data) = v.save_ctxt.get_item_data(item) {
396                 down_cast_data!(var_data, DefData, item.span);
397                 v.dumper.dump_def(&access_from!(v.save_ctxt, item, item.hir_id), var_data);
398             }
399             v.visit_ty(&typ);
400             v.visit_expr(expr);
401         });
402     }
403
404     fn process_assoc_const(
405         &mut self,
406         hir_id: hir::HirId,
407         ident: Ident,
408         typ: &'tcx hir::Ty<'tcx>,
409         expr: Option<&'tcx hir::Expr<'tcx>>,
410         parent_id: DefId,
411         vis: &hir::Visibility<'tcx>,
412         attrs: &'tcx [ast::Attribute],
413     ) {
414         let qualname =
415             format!("::{}", self.tcx.def_path_str(self.tcx.hir().local_def_id(hir_id).to_def_id()));
416
417         if !self.span.filter_generated(ident.span) {
418             let sig = sig::assoc_const_signature(hir_id, ident.name, typ, expr, &self.save_ctxt);
419             let span = self.span_from_span(ident.span);
420
421             self.dumper.dump_def(
422                 &access_from_vis!(self.save_ctxt, vis, hir_id),
423                 Def {
424                     kind: DefKind::Const,
425                     id: id_from_hir_id(hir_id, &self.save_ctxt),
426                     span,
427                     name: ident.name.to_string(),
428                     qualname,
429                     value: ty_to_string(&typ),
430                     parent: Some(id_from_def_id(parent_id)),
431                     children: vec![],
432                     decl_id: None,
433                     docs: self.save_ctxt.docs_for_attrs(attrs),
434                     sig,
435                     attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
436                 },
437             );
438         }
439
440         // walk type and init value
441         self.nest_typeck_results(self.tcx.hir().local_def_id(hir_id), |v| {
442             v.visit_ty(typ);
443             if let Some(expr) = expr {
444                 v.visit_expr(expr);
445             }
446         });
447     }
448
449     // FIXME tuple structs should generate tuple-specific data.
450     fn process_struct(
451         &mut self,
452         item: &'tcx hir::Item<'tcx>,
453         def: &'tcx hir::VariantData<'tcx>,
454         ty_params: &'tcx hir::Generics<'tcx>,
455     ) {
456         debug!("process_struct {:?} {:?}", item, item.span);
457         let name = item.ident.to_string();
458         let qualname = format!(
459             "::{}",
460             self.tcx.def_path_str(self.tcx.hir().local_def_id(item.hir_id).to_def_id())
461         );
462
463         let kind = match item.kind {
464             hir::ItemKind::Struct(_, _) => DefKind::Struct,
465             hir::ItemKind::Union(_, _) => DefKind::Union,
466             _ => unreachable!(),
467         };
468
469         let (value, fields) = match item.kind {
470             hir::ItemKind::Struct(hir::VariantData::Struct(ref fields, ..), ..)
471             | hir::ItemKind::Union(hir::VariantData::Struct(ref fields, ..), ..) => {
472                 let include_priv_fields = !self.save_ctxt.config.pub_only;
473                 let fields_str = fields
474                     .iter()
475                     .filter_map(|f| {
476                         if include_priv_fields || f.vis.node.is_pub() {
477                             Some(f.ident.to_string())
478                         } else {
479                             None
480                         }
481                     })
482                     .collect::<Vec<_>>()
483                     .join(", ");
484                 let value = format!("{} {{ {} }}", name, fields_str);
485                 (value, fields.iter().map(|f| id_from_hir_id(f.hir_id, &self.save_ctxt)).collect())
486             }
487             _ => (String::new(), vec![]),
488         };
489
490         if !self.span.filter_generated(item.ident.span) {
491             let span = self.span_from_span(item.ident.span);
492             self.dumper.dump_def(
493                 &access_from!(self.save_ctxt, item, item.hir_id),
494                 Def {
495                     kind,
496                     id: id_from_hir_id(item.hir_id, &self.save_ctxt),
497                     span,
498                     name,
499                     qualname: qualname.clone(),
500                     value,
501                     parent: None,
502                     children: fields,
503                     decl_id: None,
504                     docs: self.save_ctxt.docs_for_attrs(&item.attrs),
505                     sig: sig::item_signature(item, &self.save_ctxt),
506                     attributes: lower_attributes(item.attrs.to_vec(), &self.save_ctxt),
507                 },
508             );
509         }
510
511         self.nest_typeck_results(self.tcx.hir().local_def_id(item.hir_id), |v| {
512             for field in def.fields() {
513                 v.process_struct_field_def(field, item.hir_id);
514                 v.visit_ty(&field.ty);
515             }
516
517             v.process_generic_params(ty_params, &qualname, item.hir_id);
518         });
519     }
520
521     fn process_enum(
522         &mut self,
523         item: &'tcx hir::Item<'tcx>,
524         enum_definition: &'tcx hir::EnumDef<'tcx>,
525         ty_params: &'tcx hir::Generics<'tcx>,
526     ) {
527         let enum_data = self.save_ctxt.get_item_data(item);
528         let enum_data = match enum_data {
529             None => return,
530             Some(data) => data,
531         };
532         down_cast_data!(enum_data, DefData, item.span);
533
534         let access = access_from!(self.save_ctxt, item, item.hir_id);
535
536         for variant in enum_definition.variants {
537             let name = variant.ident.name.to_string();
538             let qualname = format!("{}::{}", enum_data.qualname, name);
539             let name_span = variant.ident.span;
540
541             match variant.data {
542                 hir::VariantData::Struct(ref fields, ..) => {
543                     let fields_str =
544                         fields.iter().map(|f| f.ident.to_string()).collect::<Vec<_>>().join(", ");
545                     let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
546                     if !self.span.filter_generated(name_span) {
547                         let span = self.span_from_span(name_span);
548                         let id = id_from_hir_id(variant.id, &self.save_ctxt);
549                         let parent = Some(id_from_hir_id(item.hir_id, &self.save_ctxt));
550
551                         self.dumper.dump_def(
552                             &access,
553                             Def {
554                                 kind: DefKind::StructVariant,
555                                 id,
556                                 span,
557                                 name,
558                                 qualname,
559                                 value,
560                                 parent,
561                                 children: vec![],
562                                 decl_id: None,
563                                 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
564                                 sig: sig::variant_signature(variant, &self.save_ctxt),
565                                 attributes: lower_attributes(
566                                     variant.attrs.to_vec(),
567                                     &self.save_ctxt,
568                                 ),
569                             },
570                         );
571                     }
572                 }
573                 ref v => {
574                     let mut value = format!("{}::{}", enum_data.name, name);
575                     if let &hir::VariantData::Tuple(ref fields, _) = v {
576                         value.push('(');
577                         value.push_str(
578                             &fields
579                                 .iter()
580                                 .map(|f| ty_to_string(&f.ty))
581                                 .collect::<Vec<_>>()
582                                 .join(", "),
583                         );
584                         value.push(')');
585                     }
586                     if !self.span.filter_generated(name_span) {
587                         let span = self.span_from_span(name_span);
588                         let id = id_from_hir_id(variant.id, &self.save_ctxt);
589                         let parent = Some(id_from_hir_id(item.hir_id, &self.save_ctxt));
590
591                         self.dumper.dump_def(
592                             &access,
593                             Def {
594                                 kind: DefKind::TupleVariant,
595                                 id,
596                                 span,
597                                 name,
598                                 qualname,
599                                 value,
600                                 parent,
601                                 children: vec![],
602                                 decl_id: None,
603                                 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
604                                 sig: sig::variant_signature(variant, &self.save_ctxt),
605                                 attributes: lower_attributes(
606                                     variant.attrs.to_vec(),
607                                     &self.save_ctxt,
608                                 ),
609                             },
610                         );
611                     }
612                 }
613             }
614
615             for field in variant.data.fields() {
616                 self.process_struct_field_def(field, variant.id);
617                 self.visit_ty(field.ty);
618             }
619         }
620         self.process_generic_params(ty_params, &enum_data.qualname, item.hir_id);
621         self.dumper.dump_def(&access, enum_data);
622     }
623
624     fn process_impl(
625         &mut self,
626         item: &'tcx hir::Item<'tcx>,
627         generics: &'tcx hir::Generics<'tcx>,
628         trait_ref: &'tcx Option<hir::TraitRef<'tcx>>,
629         typ: &'tcx hir::Ty<'tcx>,
630         impl_items: &'tcx [hir::ImplItemRef<'tcx>],
631     ) {
632         if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
633             if !self.span.filter_generated(item.span) {
634                 if let super::Data::RelationData(rel, imp) = impl_data {
635                     self.dumper.dump_relation(rel);
636                     self.dumper.dump_impl(imp);
637                 } else {
638                     span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
639                 }
640             }
641         }
642
643         let map = &self.tcx.hir();
644         self.nest_typeck_results(map.local_def_id(item.hir_id), |v| {
645             v.visit_ty(&typ);
646             if let &Some(ref trait_ref) = trait_ref {
647                 v.process_path(trait_ref.hir_ref_id, &hir::QPath::Resolved(None, &trait_ref.path));
648             }
649             v.process_generic_params(generics, "", item.hir_id);
650             for impl_item in impl_items {
651                 v.process_impl_item(
652                     map.impl_item(impl_item.id),
653                     map.local_def_id(item.hir_id).to_def_id(),
654                 );
655             }
656         });
657     }
658
659     fn process_trait(
660         &mut self,
661         item: &'tcx hir::Item<'tcx>,
662         generics: &'tcx hir::Generics<'tcx>,
663         trait_refs: hir::GenericBounds<'tcx>,
664         methods: &'tcx [hir::TraitItemRef],
665     ) {
666         let name = item.ident.to_string();
667         let qualname = format!(
668             "::{}",
669             self.tcx.def_path_str(self.tcx.hir().local_def_id(item.hir_id).to_def_id())
670         );
671         let mut val = name.clone();
672         if !generics.params.is_empty() {
673             val.push_str(&generic_params_to_string(generics.params));
674         }
675         if !trait_refs.is_empty() {
676             val.push_str(": ");
677             val.push_str(&bounds_to_string(trait_refs));
678         }
679         if !self.span.filter_generated(item.ident.span) {
680             let id = id_from_hir_id(item.hir_id, &self.save_ctxt);
681             let span = self.span_from_span(item.ident.span);
682             let children =
683                 methods.iter().map(|i| id_from_hir_id(i.id.hir_id, &self.save_ctxt)).collect();
684             self.dumper.dump_def(
685                 &access_from!(self.save_ctxt, item, item.hir_id),
686                 Def {
687                     kind: DefKind::Trait,
688                     id,
689                     span,
690                     name,
691                     qualname: qualname.clone(),
692                     value: val,
693                     parent: None,
694                     children,
695                     decl_id: None,
696                     docs: self.save_ctxt.docs_for_attrs(&item.attrs),
697                     sig: sig::item_signature(item, &self.save_ctxt),
698                     attributes: lower_attributes(item.attrs.to_vec(), &self.save_ctxt),
699                 },
700             );
701         }
702
703         // super-traits
704         for super_bound in trait_refs.iter() {
705             let trait_ref = match *super_bound {
706                 hir::GenericBound::Trait(ref trait_ref, _) => trait_ref,
707                 hir::GenericBound::Outlives(..) => continue,
708                 hir::GenericBound::LangItemTrait(..) => unimplemented!(),
709             };
710
711             let trait_ref = &trait_ref.trait_ref;
712             if let Some(id) = self.lookup_def_id(trait_ref.hir_ref_id) {
713                 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
714                 if !self.span.filter_generated(sub_span) {
715                     let span = self.span_from_span(sub_span);
716                     self.dumper.dump_ref(Ref {
717                         kind: RefKind::Type,
718                         span: span.clone(),
719                         ref_id: id_from_def_id(id),
720                     });
721
722                     self.dumper.dump_relation(Relation {
723                         kind: RelationKind::SuperTrait,
724                         span,
725                         from: id_from_def_id(id),
726                         to: id_from_hir_id(item.hir_id, &self.save_ctxt),
727                     });
728                 }
729             }
730         }
731
732         // walk generics and methods
733         self.process_generic_params(generics, &qualname, item.hir_id);
734         for method in methods {
735             let map = &self.tcx.hir();
736             self.process_trait_item(
737                 map.trait_item(method.id),
738                 map.local_def_id(item.hir_id).to_def_id(),
739             )
740         }
741     }
742
743     // `item` is the module in question, represented as an( item.
744     fn process_mod(&mut self, item: &'tcx hir::Item<'tcx>) {
745         if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
746             down_cast_data!(mod_data, DefData, item.span);
747             self.dumper.dump_def(&access_from!(self.save_ctxt, item, item.hir_id), mod_data);
748         }
749     }
750
751     fn dump_path_ref(&mut self, id: hir::HirId, path: &hir::QPath<'tcx>) {
752         let path_data = self.save_ctxt.get_path_data(id, path);
753         if let Some(path_data) = path_data {
754             self.dumper.dump_ref(path_data);
755         }
756     }
757
758     fn dump_path_segment_ref(&mut self, id: hir::HirId, segment: &hir::PathSegment<'tcx>) {
759         let segment_data = self.save_ctxt.get_path_segment_data_with_id(segment, id);
760         if let Some(segment_data) = segment_data {
761             self.dumper.dump_ref(segment_data);
762         }
763     }
764
765     fn process_path(&mut self, id: hir::HirId, path: &hir::QPath<'tcx>) {
766         let span = match path {
767             hir::QPath::Resolved(_, path) => path.span,
768             hir::QPath::TypeRelative(_, segment) => segment.ident.span,
769             hir::QPath::LangItem(..) => unimplemented!(),
770         };
771         if self.span.filter_generated(span) {
772             return;
773         }
774         self.dump_path_ref(id, path);
775
776         // Type arguments
777         let segments = match path {
778             hir::QPath::Resolved(ty, path) => {
779                 if let Some(ty) = ty {
780                     self.visit_ty(ty);
781                 }
782                 path.segments
783             }
784             hir::QPath::TypeRelative(ty, segment) => {
785                 self.visit_ty(ty);
786                 std::slice::from_ref(*segment)
787             }
788             hir::QPath::LangItem(..) => unimplemented!(),
789         };
790         for seg in segments {
791             if let Some(ref generic_args) = seg.args {
792                 for arg in generic_args.args {
793                     if let hir::GenericArg::Type(ref ty) = arg {
794                         self.visit_ty(ty);
795                     }
796                 }
797             }
798         }
799
800         if let hir::QPath::Resolved(_, path) = path {
801             self.write_sub_paths_truncated(path);
802         }
803     }
804
805     fn process_struct_lit(
806         &mut self,
807         ex: &'tcx hir::Expr<'tcx>,
808         path: &'tcx hir::QPath<'tcx>,
809         fields: &'tcx [hir::Field<'tcx>],
810         variant: &'tcx ty::VariantDef,
811         base: Option<&'tcx hir::Expr<'tcx>>,
812     ) {
813         if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
814             if let hir::QPath::Resolved(_, path) = path {
815                 self.write_sub_paths_truncated(path);
816             }
817             down_cast_data!(struct_lit_data, RefData, ex.span);
818             if !generated_code(ex.span) {
819                 self.dumper.dump_ref(struct_lit_data);
820             }
821
822             for field in fields {
823                 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
824                     self.dumper.dump_ref(field_data);
825                 }
826
827                 self.visit_expr(&field.expr)
828             }
829         }
830
831         walk_list!(self, visit_expr, base);
832     }
833
834     fn process_method_call(
835         &mut self,
836         ex: &'tcx hir::Expr<'tcx>,
837         seg: &'tcx hir::PathSegment<'tcx>,
838         args: &'tcx [hir::Expr<'tcx>],
839     ) {
840         debug!("process_method_call {:?} {:?}", ex, ex.span);
841         if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
842             down_cast_data!(mcd, RefData, ex.span);
843             if !generated_code(ex.span) {
844                 self.dumper.dump_ref(mcd);
845             }
846         }
847
848         // Explicit types in the turbo-fish.
849         if let Some(generic_args) = seg.args {
850             for arg in generic_args.args {
851                 if let hir::GenericArg::Type(ty) = arg {
852                     self.visit_ty(&ty)
853                 };
854             }
855         }
856
857         // walk receiver and args
858         walk_list!(self, visit_expr, args);
859     }
860
861     fn process_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
862         match p.kind {
863             hir::PatKind::Struct(ref _path, fields, _) => {
864                 // FIXME do something with _path?
865                 let adt = match self.save_ctxt.typeck_results().node_type_opt(p.hir_id) {
866                     Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
867                     _ => {
868                         intravisit::walk_pat(self, p);
869                         return;
870                     }
871                 };
872                 let variant = adt.variant_of_res(self.save_ctxt.get_path_res(p.hir_id));
873
874                 for field in fields {
875                     if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
876                         if !self.span.filter_generated(field.ident.span) {
877                             let span = self.span_from_span(field.ident.span);
878                             self.dumper.dump_ref(Ref {
879                                 kind: RefKind::Variable,
880                                 span,
881                                 ref_id: id_from_def_id(variant.fields[index].did),
882                             });
883                         }
884                     }
885                     self.visit_pat(&field.pat);
886                 }
887             }
888             _ => intravisit::walk_pat(self, p),
889         }
890     }
891
892     fn process_var_decl(&mut self, pat: &'tcx hir::Pat<'tcx>) {
893         // The pattern could declare multiple new vars,
894         // we must walk the pattern and collect them all.
895         let mut collector = PathCollector::new(self.tcx);
896         collector.visit_pat(&pat);
897         self.visit_pat(&pat);
898
899         // Process collected paths.
900         for (id, ident, _) in collector.collected_idents {
901             let res = self.save_ctxt.get_path_res(id);
902             match res {
903                 Res::Local(hir_id) => {
904                     let typ = self
905                         .save_ctxt
906                         .typeck_results()
907                         .node_type_opt(hir_id)
908                         .map(|t| t.to_string())
909                         .unwrap_or_default();
910
911                     // Rust uses the id of the pattern for var lookups, so we'll use it too.
912                     if !self.span.filter_generated(ident.span) {
913                         let qualname = format!("{}${}", ident.to_string(), hir_id);
914                         let id = id_from_hir_id(hir_id, &self.save_ctxt);
915                         let span = self.span_from_span(ident.span);
916
917                         self.dumper.dump_def(
918                             &Access { public: false, reachable: false },
919                             Def {
920                                 kind: DefKind::Local,
921                                 id,
922                                 span,
923                                 name: ident.to_string(),
924                                 qualname,
925                                 value: typ,
926                                 parent: None,
927                                 children: vec![],
928                                 decl_id: None,
929                                 docs: String::new(),
930                                 sig: None,
931                                 attributes: vec![],
932                             },
933                         );
934                     }
935                 }
936                 Res::Def(
937                     HirDefKind::Ctor(..)
938                     | HirDefKind::Const
939                     | HirDefKind::AssocConst
940                     | HirDefKind::Struct
941                     | HirDefKind::Variant
942                     | HirDefKind::TyAlias
943                     | HirDefKind::AssocTy,
944                     _,
945                 )
946                 | Res::SelfTy(..) => {
947                     self.dump_path_segment_ref(id, &hir::PathSegment::from_ident(ident));
948                 }
949                 def => {
950                     error!("unexpected definition kind when processing collected idents: {:?}", def)
951                 }
952             }
953         }
954
955         for (id, ref path) in collector.collected_paths {
956             self.process_path(id, path);
957         }
958     }
959
960     /// Extracts macro use and definition information from the AST node defined
961     /// by the given NodeId, using the expansion information from the node's
962     /// span.
963     ///
964     /// If the span is not macro-generated, do nothing, else use callee and
965     /// callsite spans to record macro definition and use data, using the
966     /// mac_uses and mac_defs sets to prevent multiples.
967     fn process_macro_use(&mut self, _span: Span) {
968         // FIXME if we're not dumping the defs (see below), there is no point
969         // dumping refs either.
970         // let source_span = span.source_callsite();
971         // if !self.macro_calls.insert(source_span) {
972         //     return;
973         // }
974
975         // let data = match self.save_ctxt.get_macro_use_data(span) {
976         //     None => return,
977         //     Some(data) => data,
978         // };
979
980         // self.dumper.macro_use(data);
981
982         // FIXME write the macro def
983         // let mut hasher = DefaultHasher::new();
984         // data.callee_span.hash(&mut hasher);
985         // let hash = hasher.finish();
986         // let qualname = format!("{}::{}", data.name, hash);
987         // Don't write macro definition for imported macros
988         // if !self.mac_defs.contains(&data.callee_span)
989         //     && !data.imported {
990         //     self.mac_defs.insert(data.callee_span);
991         //     if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
992         //         self.dumper.macro_data(MacroData {
993         //             span: sub_span,
994         //             name: data.name.clone(),
995         //             qualname: qualname.clone(),
996         //             // FIXME where do macro docs come from?
997         //             docs: String::new(),
998         //         }.lower(self.tcx));
999         //     }
1000         // }
1001     }
1002
1003     fn process_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>, trait_id: DefId) {
1004         self.process_macro_use(trait_item.span);
1005         let vis_span = trait_item.span.shrink_to_lo();
1006         match trait_item.kind {
1007             hir::TraitItemKind::Const(ref ty, body) => {
1008                 let body = body.map(|b| &self.tcx.hir().body(b).value);
1009                 let respan = respan(vis_span, hir::VisibilityKind::Public);
1010                 self.process_assoc_const(
1011                     trait_item.hir_id,
1012                     trait_item.ident,
1013                     &ty,
1014                     body,
1015                     trait_id,
1016                     &respan,
1017                     &trait_item.attrs,
1018                 );
1019             }
1020             hir::TraitItemKind::Fn(ref sig, ref trait_fn) => {
1021                 let body =
1022                     if let hir::TraitFn::Provided(body) = trait_fn { Some(*body) } else { None };
1023                 let respan = respan(vis_span, hir::VisibilityKind::Public);
1024                 self.process_method(
1025                     sig,
1026                     body,
1027                     trait_item.hir_id,
1028                     trait_item.ident,
1029                     &trait_item.generics,
1030                     &respan,
1031                     trait_item.span,
1032                 );
1033             }
1034             hir::TraitItemKind::Type(ref bounds, ref default_ty) => {
1035                 // FIXME do something with _bounds (for type refs)
1036                 let name = trait_item.ident.name.to_string();
1037                 let qualname = format!(
1038                     "::{}",
1039                     self.tcx
1040                         .def_path_str(self.tcx.hir().local_def_id(trait_item.hir_id).to_def_id())
1041                 );
1042
1043                 if !self.span.filter_generated(trait_item.ident.span) {
1044                     let span = self.span_from_span(trait_item.ident.span);
1045                     let id = id_from_hir_id(trait_item.hir_id, &self.save_ctxt);
1046
1047                     self.dumper.dump_def(
1048                         &Access { public: true, reachable: true },
1049                         Def {
1050                             kind: DefKind::Type,
1051                             id,
1052                             span,
1053                             name,
1054                             qualname,
1055                             value: self.span.snippet(trait_item.span),
1056                             parent: Some(id_from_def_id(trait_id)),
1057                             children: vec![],
1058                             decl_id: None,
1059                             docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1060                             sig: sig::assoc_type_signature(
1061                                 trait_item.hir_id,
1062                                 trait_item.ident,
1063                                 Some(bounds),
1064                                 default_ty.as_ref().map(|ty| &**ty),
1065                                 &self.save_ctxt,
1066                             ),
1067                             attributes: lower_attributes(
1068                                 trait_item.attrs.to_vec(),
1069                                 &self.save_ctxt,
1070                             ),
1071                         },
1072                     );
1073                 }
1074
1075                 if let &Some(ref default_ty) = default_ty {
1076                     self.visit_ty(default_ty)
1077                 }
1078             }
1079         }
1080     }
1081
1082     fn process_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>, impl_id: DefId) {
1083         self.process_macro_use(impl_item.span);
1084         match impl_item.kind {
1085             hir::ImplItemKind::Const(ref ty, body) => {
1086                 let body = self.tcx.hir().body(body);
1087                 self.process_assoc_const(
1088                     impl_item.hir_id,
1089                     impl_item.ident,
1090                     &ty,
1091                     Some(&body.value),
1092                     impl_id,
1093                     &impl_item.vis,
1094                     &impl_item.attrs,
1095                 );
1096             }
1097             hir::ImplItemKind::Fn(ref sig, body) => {
1098                 self.process_method(
1099                     sig,
1100                     Some(body),
1101                     impl_item.hir_id,
1102                     impl_item.ident,
1103                     &impl_item.generics,
1104                     &impl_item.vis,
1105                     impl_item.span,
1106                 );
1107             }
1108             hir::ImplItemKind::TyAlias(ref ty) => {
1109                 // FIXME: uses of the assoc type should ideally point to this
1110                 // 'def' and the name here should be a ref to the def in the
1111                 // trait.
1112                 self.visit_ty(ty)
1113             }
1114         }
1115     }
1116
1117     pub(crate) fn process_crate(&mut self, krate: &'tcx hir::Crate<'tcx>) {
1118         let id = hir::CRATE_HIR_ID;
1119         let qualname =
1120             format!("::{}", self.tcx.def_path_str(self.tcx.hir().local_def_id(id).to_def_id()));
1121
1122         let sm = self.tcx.sess.source_map();
1123         let filename = sm.span_to_filename(krate.item.span);
1124         let data_id = id_from_hir_id(id, &self.save_ctxt);
1125         let children = krate
1126             .item
1127             .module
1128             .item_ids
1129             .iter()
1130             .map(|i| id_from_hir_id(i.id, &self.save_ctxt))
1131             .collect();
1132         let span = self.span_from_span(krate.item.span);
1133
1134         self.dumper.dump_def(
1135             &Access { public: true, reachable: true },
1136             Def {
1137                 kind: DefKind::Mod,
1138                 id: data_id,
1139                 name: String::new(),
1140                 qualname,
1141                 span,
1142                 value: filename.to_string(),
1143                 children,
1144                 parent: None,
1145                 decl_id: None,
1146                 docs: self.save_ctxt.docs_for_attrs(krate.item.attrs),
1147                 sig: None,
1148                 attributes: lower_attributes(krate.item.attrs.to_owned(), &self.save_ctxt),
1149             },
1150         );
1151         intravisit::walk_crate(self, krate);
1152     }
1153
1154     fn process_bounds(&mut self, bounds: hir::GenericBounds<'tcx>) {
1155         for bound in bounds {
1156             if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1157                 self.process_path(
1158                     trait_ref.trait_ref.hir_ref_id,
1159                     &hir::QPath::Resolved(None, &trait_ref.trait_ref.path),
1160                 )
1161             }
1162         }
1163     }
1164 }
1165
1166 impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> {
1167     type Map = Map<'tcx>;
1168
1169     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1170         intravisit::NestedVisitorMap::All(self.tcx.hir())
1171     }
1172
1173     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1174         self.process_macro_use(item.span);
1175         match item.kind {
1176             hir::ItemKind::Use(path, hir::UseKind::Single) => {
1177                 let sub_span = path.segments.last().unwrap().ident.span;
1178                 if !self.span.filter_generated(sub_span) {
1179                     let access = access_from!(self.save_ctxt, item, item.hir_id);
1180                     let ref_id = self.lookup_def_id(item.hir_id).map(id_from_def_id);
1181                     let span = self.span_from_span(sub_span);
1182                     let parent = self
1183                         .save_ctxt
1184                         .tcx
1185                         .hir()
1186                         .opt_local_def_id(item.hir_id)
1187                         .and_then(|id| self.save_ctxt.tcx.parent(id.to_def_id()))
1188                         .map(id_from_def_id);
1189                     self.dumper.import(
1190                         &access,
1191                         Import {
1192                             kind: ImportKind::Use,
1193                             ref_id,
1194                             span,
1195                             alias_span: None,
1196                             name: item.ident.to_string(),
1197                             value: String::new(),
1198                             parent,
1199                         },
1200                     );
1201                     self.write_sub_paths_truncated(&path);
1202                 }
1203             }
1204             hir::ItemKind::Use(path, hir::UseKind::Glob) => {
1205                 // Make a comma-separated list of names of imported modules.
1206                 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1207                 let names = self.tcx.names_imported_by_glob_use(def_id);
1208                 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1209
1210                 // Otherwise it's a span with wrong macro expansion info, which
1211                 // we don't want to track anyway, since it's probably macro-internal `use`
1212                 if let Some(sub_span) =
1213                     self.span.sub_span_of_token(item.span, token::BinOp(token::Star))
1214                 {
1215                     if !self.span.filter_generated(item.span) {
1216                         let access = access_from!(self.save_ctxt, item, item.hir_id);
1217                         let span = self.span_from_span(sub_span);
1218                         let parent = self
1219                             .save_ctxt
1220                             .tcx
1221                             .hir()
1222                             .opt_local_def_id(item.hir_id)
1223                             .and_then(|id| self.save_ctxt.tcx.parent(id.to_def_id()))
1224                             .map(id_from_def_id);
1225                         self.dumper.import(
1226                             &access,
1227                             Import {
1228                                 kind: ImportKind::GlobUse,
1229                                 ref_id: None,
1230                                 span,
1231                                 alias_span: None,
1232                                 name: "*".to_owned(),
1233                                 value: names.join(", "),
1234                                 parent,
1235                             },
1236                         );
1237                         self.write_sub_paths(&path);
1238                     }
1239                 }
1240             }
1241             hir::ItemKind::ExternCrate(_) => {
1242                 let name_span = item.ident.span;
1243                 if !self.span.filter_generated(name_span) {
1244                     let span = self.span_from_span(name_span);
1245                     let parent = self
1246                         .save_ctxt
1247                         .tcx
1248                         .hir()
1249                         .opt_local_def_id(item.hir_id)
1250                         .and_then(|id| self.save_ctxt.tcx.parent(id.to_def_id()))
1251                         .map(id_from_def_id);
1252                     self.dumper.import(
1253                         &Access { public: false, reachable: false },
1254                         Import {
1255                             kind: ImportKind::ExternCrate,
1256                             ref_id: None,
1257                             span,
1258                             alias_span: None,
1259                             name: item.ident.to_string(),
1260                             value: String::new(),
1261                             parent,
1262                         },
1263                     );
1264                 }
1265             }
1266             hir::ItemKind::Fn(ref sig, ref ty_params, body) => {
1267                 self.process_fn(item, sig.decl, &sig.header, ty_params, body)
1268             }
1269             hir::ItemKind::Static(ref typ, _, body) => {
1270                 let body = self.tcx.hir().body(body);
1271                 self.process_static_or_const_item(item, typ, &body.value)
1272             }
1273             hir::ItemKind::Const(ref typ, body) => {
1274                 let body = self.tcx.hir().body(body);
1275                 self.process_static_or_const_item(item, typ, &body.value)
1276             }
1277             hir::ItemKind::Struct(ref def, ref ty_params)
1278             | hir::ItemKind::Union(ref def, ref ty_params) => {
1279                 self.process_struct(item, def, ty_params)
1280             }
1281             hir::ItemKind::Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1282             hir::ItemKind::Impl { ref generics, ref of_trait, ref self_ty, ref items, .. } => {
1283                 self.process_impl(item, generics, of_trait, &self_ty, items)
1284             }
1285             hir::ItemKind::Trait(_, _, ref generics, ref trait_refs, methods) => {
1286                 self.process_trait(item, generics, trait_refs, methods)
1287             }
1288             hir::ItemKind::Mod(ref m) => {
1289                 self.process_mod(item);
1290                 intravisit::walk_mod(self, m, item.hir_id);
1291             }
1292             hir::ItemKind::TyAlias(ty, ref generics) => {
1293                 let qualname = format!(
1294                     "::{}",
1295                     self.tcx.def_path_str(self.tcx.hir().local_def_id(item.hir_id).to_def_id())
1296                 );
1297                 let value = ty_to_string(&ty);
1298                 if !self.span.filter_generated(item.ident.span) {
1299                     let span = self.span_from_span(item.ident.span);
1300                     let id = id_from_hir_id(item.hir_id, &self.save_ctxt);
1301
1302                     self.dumper.dump_def(
1303                         &access_from!(self.save_ctxt, item, item.hir_id),
1304                         Def {
1305                             kind: DefKind::Type,
1306                             id,
1307                             span,
1308                             name: item.ident.to_string(),
1309                             qualname: qualname.clone(),
1310                             value,
1311                             parent: None,
1312                             children: vec![],
1313                             decl_id: None,
1314                             docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1315                             sig: sig::item_signature(item, &self.save_ctxt),
1316                             attributes: lower_attributes(item.attrs.to_vec(), &self.save_ctxt),
1317                         },
1318                     );
1319                 }
1320
1321                 self.visit_ty(ty);
1322                 self.process_generic_params(generics, &qualname, item.hir_id);
1323             }
1324             _ => intravisit::walk_item(self, item),
1325         }
1326     }
1327
1328     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1329         for param in generics.params {
1330             match param.kind {
1331                 hir::GenericParamKind::Lifetime { .. } => {}
1332                 hir::GenericParamKind::Type { ref default, .. } => {
1333                     self.process_bounds(param.bounds);
1334                     if let Some(ref ty) = default {
1335                         self.visit_ty(ty);
1336                     }
1337                 }
1338                 hir::GenericParamKind::Const { ref ty } => {
1339                     self.process_bounds(param.bounds);
1340                     self.visit_ty(ty);
1341                 }
1342             }
1343         }
1344         for pred in generics.where_clause.predicates {
1345             if let hir::WherePredicate::BoundPredicate(ref wbp) = *pred {
1346                 self.process_bounds(wbp.bounds);
1347                 self.visit_ty(wbp.bounded_ty);
1348             }
1349         }
1350     }
1351
1352     fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
1353         self.process_macro_use(t.span);
1354         match t.kind {
1355             hir::TyKind::Path(ref path) => {
1356                 if generated_code(t.span) {
1357                     return;
1358                 }
1359
1360                 if let Some(id) = self.lookup_def_id(t.hir_id) {
1361                     let sub_span = match path {
1362                         hir::QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1363                         hir::QPath::TypeRelative(_, segment) => segment.ident.span,
1364                         hir::QPath::LangItem(..) => unimplemented!(),
1365                     };
1366                     let span = self.span_from_span(sub_span);
1367                     self.dumper.dump_ref(Ref {
1368                         kind: RefKind::Type,
1369                         span,
1370                         ref_id: id_from_def_id(id),
1371                     });
1372                 }
1373
1374                 if let hir::QPath::Resolved(_, path) = path {
1375                     self.write_sub_paths_truncated(path);
1376                 }
1377                 intravisit::walk_qpath(self, path, t.hir_id, t.span);
1378             }
1379             hir::TyKind::Array(ref ty, ref anon_const) => {
1380                 self.visit_ty(ty);
1381                 let map = self.tcx.hir();
1382                 self.nest_typeck_results(self.tcx.hir().local_def_id(anon_const.hir_id), |v| {
1383                     v.visit_expr(&map.body(anon_const.body).value)
1384                 });
1385             }
1386             hir::TyKind::OpaqueDef(item_id, _) => {
1387                 let item = self.tcx.hir().item(item_id.id);
1388                 self.nest_typeck_results(self.tcx.hir().local_def_id(item_id.id), |v| {
1389                     v.visit_item(item)
1390                 });
1391             }
1392             _ => intravisit::walk_ty(self, t),
1393         }
1394     }
1395
1396     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1397         debug!("visit_expr {:?}", ex.kind);
1398         self.process_macro_use(ex.span);
1399         match ex.kind {
1400             hir::ExprKind::Struct(ref path, ref fields, ref base) => {
1401                 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(ex.hir_id);
1402                 let adt = match self.save_ctxt.typeck_results().expr_ty_opt(&hir_expr) {
1403                     Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1404                     _ => {
1405                         intravisit::walk_expr(self, ex);
1406                         return;
1407                     }
1408                 };
1409                 let res = self.save_ctxt.get_path_res(hir_expr.hir_id);
1410                 self.process_struct_lit(ex, path, fields, adt.variant_of_res(res), *base)
1411             }
1412             hir::ExprKind::MethodCall(ref seg, _, args, _) => {
1413                 self.process_method_call(ex, seg, args)
1414             }
1415             hir::ExprKind::Field(ref sub_ex, _) => {
1416                 self.visit_expr(&sub_ex);
1417
1418                 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1419                     down_cast_data!(field_data, RefData, ex.span);
1420                     if !generated_code(ex.span) {
1421                         self.dumper.dump_ref(field_data);
1422                     }
1423                 }
1424             }
1425             hir::ExprKind::Closure(_, ref decl, body, _fn_decl_span, _) => {
1426                 let id = format!("${}", ex.hir_id);
1427
1428                 // walk arg and return types
1429                 for ty in decl.inputs {
1430                     self.visit_ty(ty);
1431                 }
1432
1433                 if let hir::FnRetTy::Return(ref ret_ty) = decl.output {
1434                     self.visit_ty(ret_ty);
1435                 }
1436
1437                 // walk the body
1438                 let map = self.tcx.hir();
1439                 self.nest_typeck_results(self.tcx.hir().local_def_id(ex.hir_id), |v| {
1440                     let body = map.body(body);
1441                     v.process_formals(body.params, &id);
1442                     v.visit_expr(&body.value)
1443                 });
1444             }
1445             hir::ExprKind::Repeat(ref expr, ref anon_const) => {
1446                 self.visit_expr(expr);
1447                 let map = self.tcx.hir();
1448                 self.nest_typeck_results(self.tcx.hir().local_def_id(anon_const.hir_id), |v| {
1449                     v.visit_expr(&map.body(anon_const.body).value)
1450                 });
1451             }
1452             // In particular, we take this branch for call and path expressions,
1453             // where we'll index the idents involved just by continuing to walk.
1454             _ => intravisit::walk_expr(self, ex),
1455         }
1456     }
1457
1458     fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
1459         self.process_macro_use(p.span);
1460         self.process_pat(p);
1461     }
1462
1463     fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1464         self.process_var_decl(&arm.pat);
1465         if let Some(hir::Guard::If(expr)) = &arm.guard {
1466             self.visit_expr(expr);
1467         }
1468         self.visit_expr(&arm.body);
1469     }
1470
1471     fn visit_qpath(&mut self, path: &'tcx hir::QPath<'tcx>, id: hir::HirId, _: Span) {
1472         self.process_path(id, path);
1473     }
1474
1475     fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) {
1476         self.process_macro_use(s.span);
1477         intravisit::walk_stmt(self, s)
1478     }
1479
1480     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
1481         self.process_macro_use(l.span);
1482         self.process_var_decl(&l.pat);
1483
1484         // Just walk the initialiser and type (don't want to walk the pattern again).
1485         walk_list!(self, visit_ty, &l.ty);
1486         walk_list!(self, visit_expr, &l.init);
1487     }
1488
1489     fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
1490         let access = access_from!(self.save_ctxt, item, item.hir_id);
1491
1492         match item.kind {
1493             hir::ForeignItemKind::Fn(decl, _, ref generics) => {
1494                 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1495                     down_cast_data!(fn_data, DefData, item.span);
1496
1497                     self.process_generic_params(generics, &fn_data.qualname, item.hir_id);
1498                     self.dumper.dump_def(&access, fn_data);
1499                 }
1500
1501                 for ty in decl.inputs {
1502                     self.visit_ty(ty);
1503                 }
1504
1505                 if let hir::FnRetTy::Return(ref ret_ty) = decl.output {
1506                     self.visit_ty(ret_ty);
1507                 }
1508             }
1509             hir::ForeignItemKind::Static(ref ty, _) => {
1510                 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1511                     down_cast_data!(var_data, DefData, item.span);
1512                     self.dumper.dump_def(&access, var_data);
1513                 }
1514
1515                 self.visit_ty(ty);
1516             }
1517             hir::ForeignItemKind::Type => {
1518                 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1519                     down_cast_data!(var_data, DefData, item.span);
1520                     self.dumper.dump_def(&access, var_data);
1521                 }
1522             }
1523         }
1524     }
1525 }