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