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