]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_save_analysis/src/dump_visitor.rs
Rollup merge of #92802 - compiler-errors:deduplicate-stack-trace, r=oli-obk
[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 enum_data = match enum_data {
526             None => return,
527             Some(data) => data,
528         };
529         down_cast_data!(enum_data, DefData, item.span);
530
531         let access = access_from!(self.save_ctxt, item, item.def_id);
532
533         for variant in enum_definition.variants {
534             let name = variant.ident.name.to_string();
535             let qualname = format!("{}::{}", enum_data.qualname, name);
536             let name_span = variant.ident.span;
537
538             match variant.data {
539                 hir::VariantData::Struct(ref fields, ..) => {
540                     let fields_str =
541                         fields.iter().map(|f| f.ident.to_string()).collect::<Vec<_>>().join(", ");
542                     let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
543                     if !self.span.filter_generated(name_span) {
544                         let span = self.span_from_span(name_span);
545                         let id = id_from_hir_id(variant.id, &self.save_ctxt);
546                         let parent = Some(id_from_def_id(item.def_id.to_def_id()));
547                         let attrs = self.tcx.hir().attrs(variant.id);
548
549                         self.dumper.dump_def(
550                             &access,
551                             Def {
552                                 kind: DefKind::StructVariant,
553                                 id,
554                                 span,
555                                 name,
556                                 qualname,
557                                 value,
558                                 parent,
559                                 children: vec![],
560                                 decl_id: None,
561                                 docs: self.save_ctxt.docs_for_attrs(attrs),
562                                 sig: sig::variant_signature(variant, &self.save_ctxt),
563                                 attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),
564                             },
565                         );
566                     }
567                 }
568                 ref v => {
569                     let mut value = format!("{}::{}", enum_data.name, name);
570                     if let hir::VariantData::Tuple(fields, _) = v {
571                         value.push('(');
572                         value.push_str(
573                             &fields
574                                 .iter()
575                                 .map(|f| ty_to_string(&f.ty))
576                                 .collect::<Vec<_>>()
577                                 .join(", "),
578                         );
579                         value.push(')');
580                     }
581                     if !self.span.filter_generated(name_span) {
582                         let span = self.span_from_span(name_span);
583                         let id = id_from_hir_id(variant.id, &self.save_ctxt);
584                         let parent = Some(id_from_def_id(item.def_id.to_def_id()));
585                         let attrs = self.tcx.hir().attrs(variant.id);
586
587                         self.dumper.dump_def(
588                             &access,
589                             Def {
590                                 kind: DefKind::TupleVariant,
591                                 id,
592                                 span,
593                                 name,
594                                 qualname,
595                                 value,
596                                 parent,
597                                 children: vec![],
598                                 decl_id: None,
599                                 docs: self.save_ctxt.docs_for_attrs(attrs),
600                                 sig: sig::variant_signature(variant, &self.save_ctxt),
601                                 attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),
602                             },
603                         );
604                     }
605                 }
606             }
607
608             for field in variant.data.fields() {
609                 self.process_struct_field_def(field, variant.id);
610                 self.visit_ty(field.ty);
611             }
612         }
613         self.process_generic_params(ty_params, &enum_data.qualname, item.hir_id());
614         self.dumper.dump_def(&access, enum_data);
615     }
616
617     fn process_impl(&mut self, item: &'tcx hir::Item<'tcx>, impl_: &'tcx hir::Impl<'tcx>) {
618         if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
619             if !self.span.filter_generated(item.span) {
620                 if let super::Data::RelationData(rel, imp) = impl_data {
621                     self.dumper.dump_relation(rel);
622                     self.dumper.dump_impl(imp);
623                 } else {
624                     span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
625                 }
626             }
627         }
628
629         let map = &self.tcx.hir();
630         self.nest_typeck_results(item.def_id, |v| {
631             v.visit_ty(&impl_.self_ty);
632             if let Some(trait_ref) = &impl_.of_trait {
633                 v.process_path(trait_ref.hir_ref_id, &hir::QPath::Resolved(None, &trait_ref.path));
634             }
635             v.process_generic_params(&impl_.generics, "", item.hir_id());
636             for impl_item in impl_.items {
637                 v.process_impl_item(map.impl_item(impl_item.id), item.def_id.to_def_id());
638             }
639         });
640     }
641
642     fn process_trait(
643         &mut self,
644         item: &'tcx hir::Item<'tcx>,
645         generics: &'tcx hir::Generics<'tcx>,
646         trait_refs: hir::GenericBounds<'tcx>,
647         methods: &'tcx [hir::TraitItemRef],
648     ) {
649         let name = item.ident.to_string();
650         let qualname = format!("::{}", self.tcx.def_path_str(item.def_id.to_def_id()));
651         let mut val = name.clone();
652         if !generics.params.is_empty() {
653             val.push_str(&generic_params_to_string(generics.params));
654         }
655         if !trait_refs.is_empty() {
656             val.push_str(": ");
657             val.push_str(&bounds_to_string(trait_refs));
658         }
659         if !self.span.filter_generated(item.ident.span) {
660             let id = id_from_def_id(item.def_id.to_def_id());
661             let span = self.span_from_span(item.ident.span);
662             let children =
663                 methods.iter().map(|i| id_from_def_id(i.id.def_id.to_def_id())).collect();
664             let attrs = self.tcx.hir().attrs(item.hir_id());
665             self.dumper.dump_def(
666                 &access_from!(self.save_ctxt, item, item.def_id),
667                 Def {
668                     kind: DefKind::Trait,
669                     id,
670                     span,
671                     name,
672                     qualname: qualname.clone(),
673                     value: val,
674                     parent: None,
675                     children,
676                     decl_id: None,
677                     docs: self.save_ctxt.docs_for_attrs(attrs),
678                     sig: sig::item_signature(item, &self.save_ctxt),
679                     attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),
680                 },
681             );
682         }
683
684         // supertraits
685         for super_bound in trait_refs.iter() {
686             let (def_id, sub_span) = match *super_bound {
687                 hir::GenericBound::Trait(ref trait_ref, _) => (
688                     self.lookup_def_id(trait_ref.trait_ref.hir_ref_id),
689                     trait_ref.trait_ref.path.segments.last().unwrap().ident.span,
690                 ),
691                 hir::GenericBound::LangItemTrait(lang_item, span, _, _) => {
692                     (Some(self.tcx.require_lang_item(lang_item, Some(span))), span)
693                 }
694                 hir::GenericBound::Outlives(..) => continue,
695             };
696
697             if let Some(id) = def_id {
698                 if !self.span.filter_generated(sub_span) {
699                     let span = self.span_from_span(sub_span);
700                     self.dumper.dump_ref(Ref {
701                         kind: RefKind::Type,
702                         span: span.clone(),
703                         ref_id: id_from_def_id(id),
704                     });
705
706                     self.dumper.dump_relation(Relation {
707                         kind: RelationKind::SuperTrait,
708                         span,
709                         from: id_from_def_id(id),
710                         to: id_from_def_id(item.def_id.to_def_id()),
711                     });
712                 }
713             }
714         }
715
716         // walk generics and methods
717         self.process_generic_params(generics, &qualname, item.hir_id());
718         for method in methods {
719             let map = &self.tcx.hir();
720             self.process_trait_item(map.trait_item(method.id), item.def_id.to_def_id())
721         }
722     }
723
724     // `item` is the module in question, represented as an( item.
725     fn process_mod(&mut self, item: &'tcx hir::Item<'tcx>) {
726         if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
727             down_cast_data!(mod_data, DefData, item.span);
728             self.dumper.dump_def(&access_from!(self.save_ctxt, item, item.def_id), mod_data);
729         }
730     }
731
732     fn dump_path_ref(&mut self, id: hir::HirId, path: &hir::QPath<'tcx>) {
733         let path_data = self.save_ctxt.get_path_data(id, path);
734         if let Some(path_data) = path_data {
735             self.dumper.dump_ref(path_data);
736         }
737     }
738
739     fn dump_path_segment_ref(&mut self, id: hir::HirId, segment: &hir::PathSegment<'tcx>) {
740         let segment_data = self.save_ctxt.get_path_segment_data_with_id(segment, id);
741         if let Some(segment_data) = segment_data {
742             self.dumper.dump_ref(segment_data);
743         }
744     }
745
746     fn process_path(&mut self, id: hir::HirId, path: &hir::QPath<'tcx>) {
747         if self.span.filter_generated(path.span()) {
748             return;
749         }
750         self.dump_path_ref(id, path);
751
752         // Type arguments
753         let segments = match path {
754             hir::QPath::Resolved(ty, path) => {
755                 if let Some(ty) = ty {
756                     self.visit_ty(ty);
757                 }
758                 path.segments
759             }
760             hir::QPath::TypeRelative(ty, segment) => {
761                 self.visit_ty(ty);
762                 std::slice::from_ref(*segment)
763             }
764             hir::QPath::LangItem(..) => return,
765         };
766         for seg in segments {
767             if let Some(ref generic_args) = seg.args {
768                 for arg in generic_args.args {
769                     if let hir::GenericArg::Type(ref ty) = arg {
770                         self.visit_ty(ty);
771                     }
772                 }
773             }
774         }
775
776         if let hir::QPath::Resolved(_, path) = path {
777             self.write_sub_paths_truncated(path);
778         }
779     }
780
781     fn process_struct_lit(
782         &mut self,
783         ex: &'tcx hir::Expr<'tcx>,
784         path: &'tcx hir::QPath<'tcx>,
785         fields: &'tcx [hir::ExprField<'tcx>],
786         variant: &'tcx ty::VariantDef,
787         rest: Option<&'tcx hir::Expr<'tcx>>,
788     ) {
789         if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
790             if let hir::QPath::Resolved(_, path) = path {
791                 self.write_sub_paths_truncated(path);
792             }
793             down_cast_data!(struct_lit_data, RefData, ex.span);
794             if !generated_code(ex.span) {
795                 self.dumper.dump_ref(struct_lit_data);
796             }
797
798             for field in fields {
799                 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
800                     self.dumper.dump_ref(field_data);
801                 }
802
803                 self.visit_expr(&field.expr)
804             }
805         }
806
807         if let Some(base) = rest {
808             self.visit_expr(&base);
809         }
810     }
811
812     fn process_method_call(
813         &mut self,
814         ex: &'tcx hir::Expr<'tcx>,
815         seg: &'tcx hir::PathSegment<'tcx>,
816         args: &'tcx [hir::Expr<'tcx>],
817     ) {
818         debug!("process_method_call {:?} {:?}", ex, ex.span);
819         if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
820             down_cast_data!(mcd, RefData, ex.span);
821             if !generated_code(ex.span) {
822                 self.dumper.dump_ref(mcd);
823             }
824         }
825
826         // Explicit types in the turbo-fish.
827         if let Some(generic_args) = seg.args {
828             for arg in generic_args.args {
829                 if let hir::GenericArg::Type(ty) = arg {
830                     self.visit_ty(&ty)
831                 };
832             }
833         }
834
835         // walk receiver and args
836         walk_list!(self, visit_expr, args);
837     }
838
839     fn process_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
840         match p.kind {
841             hir::PatKind::Struct(ref _path, fields, _) => {
842                 // FIXME do something with _path?
843                 let adt = match self.save_ctxt.typeck_results().node_type_opt(p.hir_id) {
844                     Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
845                     _ => {
846                         intravisit::walk_pat(self, p);
847                         return;
848                     }
849                 };
850                 let variant = adt.variant_of_res(self.save_ctxt.get_path_res(p.hir_id));
851
852                 for field in fields {
853                     if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
854                         if !self.span.filter_generated(field.ident.span) {
855                             let span = self.span_from_span(field.ident.span);
856                             self.dumper.dump_ref(Ref {
857                                 kind: RefKind::Variable,
858                                 span,
859                                 ref_id: id_from_def_id(variant.fields[index].did),
860                             });
861                         }
862                     }
863                     self.visit_pat(&field.pat);
864                 }
865             }
866             _ => intravisit::walk_pat(self, p),
867         }
868     }
869
870     fn process_var_decl(&mut self, pat: &'tcx hir::Pat<'tcx>) {
871         // The pattern could declare multiple new vars,
872         // we must walk the pattern and collect them all.
873         let mut collector = PathCollector::new(self.tcx);
874         collector.visit_pat(&pat);
875         self.visit_pat(&pat);
876
877         // Process collected paths.
878         for (id, ident, _) in collector.collected_idents {
879             let res = self.save_ctxt.get_path_res(id);
880             match res {
881                 Res::Local(hir_id) => {
882                     let typ = self
883                         .save_ctxt
884                         .typeck_results()
885                         .node_type_opt(hir_id)
886                         .map(|t| t.to_string())
887                         .unwrap_or_default();
888
889                     // Rust uses the id of the pattern for var lookups, so we'll use it too.
890                     if !self.span.filter_generated(ident.span) {
891                         let qualname = format!("{}${}", ident, hir_id);
892                         let id = id_from_hir_id(hir_id, &self.save_ctxt);
893                         let span = self.span_from_span(ident.span);
894
895                         self.dumper.dump_def(
896                             &Access { public: false, reachable: false },
897                             Def {
898                                 kind: DefKind::Local,
899                                 id,
900                                 span,
901                                 name: ident.to_string(),
902                                 qualname,
903                                 value: typ,
904                                 parent: None,
905                                 children: vec![],
906                                 decl_id: None,
907                                 docs: String::new(),
908                                 sig: None,
909                                 attributes: vec![],
910                             },
911                         );
912                     }
913                 }
914                 Res::Def(
915                     HirDefKind::Ctor(..)
916                     | HirDefKind::Const
917                     | HirDefKind::AssocConst
918                     | HirDefKind::Struct
919                     | HirDefKind::Variant
920                     | HirDefKind::TyAlias
921                     | HirDefKind::AssocTy,
922                     _,
923                 )
924                 | Res::SelfTy(..) => {
925                     self.dump_path_segment_ref(id, &hir::PathSegment::from_ident(ident));
926                 }
927                 def => {
928                     error!("unexpected definition kind when processing collected idents: {:?}", def)
929                 }
930             }
931         }
932
933         for (id, ref path) in collector.collected_paths {
934             self.process_path(id, path);
935         }
936     }
937
938     /// Extracts macro use and definition information from the AST node defined
939     /// by the given NodeId, using the expansion information from the node's
940     /// span.
941     ///
942     /// If the span is not macro-generated, do nothing, else use callee and
943     /// callsite spans to record macro definition and use data, using the
944     /// mac_uses and mac_defs sets to prevent multiples.
945     fn process_macro_use(&mut self, _span: Span) {
946         // FIXME if we're not dumping the defs (see below), there is no point
947         // dumping refs either.
948         // let source_span = span.source_callsite();
949         // if !self.macro_calls.insert(source_span) {
950         //     return;
951         // }
952
953         // let data = match self.save_ctxt.get_macro_use_data(span) {
954         //     None => return,
955         //     Some(data) => data,
956         // };
957
958         // self.dumper.macro_use(data);
959
960         // FIXME write the macro def
961         // let mut hasher = DefaultHasher::new();
962         // data.callee_span.hash(&mut hasher);
963         // let hash = hasher.finish();
964         // let qualname = format!("{}::{}", data.name, hash);
965         // Don't write macro definition for imported macros
966         // if !self.mac_defs.contains(&data.callee_span)
967         //     && !data.imported {
968         //     self.mac_defs.insert(data.callee_span);
969         //     if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
970         //         self.dumper.macro_data(MacroData {
971         //             span: sub_span,
972         //             name: data.name.clone(),
973         //             qualname: qualname.clone(),
974         //             // FIXME where do macro docs come from?
975         //             docs: String::new(),
976         //         }.lower(self.tcx));
977         //     }
978         // }
979     }
980
981     fn process_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>, trait_id: DefId) {
982         self.process_macro_use(trait_item.span);
983         let vis_span = trait_item.span.shrink_to_lo();
984         match trait_item.kind {
985             hir::TraitItemKind::Const(ref ty, body) => {
986                 let body = body.map(|b| &self.tcx.hir().body(b).value);
987                 let respan = respan(vis_span, hir::VisibilityKind::Public);
988                 let attrs = self.tcx.hir().attrs(trait_item.hir_id());
989                 self.process_assoc_const(
990                     trait_item.def_id,
991                     trait_item.ident,
992                     &ty,
993                     body,
994                     trait_id,
995                     &respan,
996                     attrs,
997                 );
998             }
999             hir::TraitItemKind::Fn(ref sig, ref trait_fn) => {
1000                 let body =
1001                     if let hir::TraitFn::Provided(body) = trait_fn { Some(*body) } else { None };
1002                 let respan = respan(vis_span, hir::VisibilityKind::Public);
1003                 self.process_method(
1004                     sig,
1005                     body,
1006                     trait_item.def_id,
1007                     trait_item.ident,
1008                     &trait_item.generics,
1009                     &respan,
1010                     trait_item.span,
1011                 );
1012             }
1013             hir::TraitItemKind::Type(ref bounds, ref default_ty) => {
1014                 // FIXME do something with _bounds (for type refs)
1015                 let name = trait_item.ident.name.to_string();
1016                 let qualname =
1017                     format!("::{}", self.tcx.def_path_str(trait_item.def_id.to_def_id()));
1018
1019                 if !self.span.filter_generated(trait_item.ident.span) {
1020                     let span = self.span_from_span(trait_item.ident.span);
1021                     let id = id_from_def_id(trait_item.def_id.to_def_id());
1022                     let attrs = self.tcx.hir().attrs(trait_item.hir_id());
1023
1024                     self.dumper.dump_def(
1025                         &Access { public: true, reachable: true },
1026                         Def {
1027                             kind: DefKind::Type,
1028                             id,
1029                             span,
1030                             name,
1031                             qualname,
1032                             value: self.span.snippet(trait_item.span),
1033                             parent: Some(id_from_def_id(trait_id)),
1034                             children: vec![],
1035                             decl_id: None,
1036                             docs: self.save_ctxt.docs_for_attrs(attrs),
1037                             sig: sig::assoc_type_signature(
1038                                 trait_item.hir_id(),
1039                                 trait_item.ident,
1040                                 Some(bounds),
1041                                 default_ty.as_ref().map(|ty| &**ty),
1042                                 &self.save_ctxt,
1043                             ),
1044                             attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),
1045                         },
1046                     );
1047                 }
1048
1049                 if let Some(default_ty) = default_ty {
1050                     self.visit_ty(default_ty)
1051                 }
1052             }
1053         }
1054     }
1055
1056     fn process_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>, impl_id: DefId) {
1057         self.process_macro_use(impl_item.span);
1058         match impl_item.kind {
1059             hir::ImplItemKind::Const(ref ty, body) => {
1060                 let body = self.tcx.hir().body(body);
1061                 let attrs = self.tcx.hir().attrs(impl_item.hir_id());
1062                 self.process_assoc_const(
1063                     impl_item.def_id,
1064                     impl_item.ident,
1065                     &ty,
1066                     Some(&body.value),
1067                     impl_id,
1068                     &impl_item.vis,
1069                     attrs,
1070                 );
1071             }
1072             hir::ImplItemKind::Fn(ref sig, body) => {
1073                 self.process_method(
1074                     sig,
1075                     Some(body),
1076                     impl_item.def_id,
1077                     impl_item.ident,
1078                     &impl_item.generics,
1079                     &impl_item.vis,
1080                     impl_item.span,
1081                 );
1082             }
1083             hir::ImplItemKind::TyAlias(ref ty) => {
1084                 // FIXME: uses of the assoc type should ideally point to this
1085                 // 'def' and the name here should be a ref to the def in the
1086                 // trait.
1087                 self.visit_ty(ty)
1088             }
1089         }
1090     }
1091
1092     pub(crate) fn process_crate(&mut self) {
1093         let id = hir::CRATE_HIR_ID;
1094         let qualname =
1095             format!("::{}", self.tcx.def_path_str(self.tcx.hir().local_def_id(id).to_def_id()));
1096
1097         let sm = self.tcx.sess.source_map();
1098         let krate_mod = self.tcx.hir().root_module();
1099         let filename = sm.span_to_filename(krate_mod.inner);
1100         let data_id = id_from_hir_id(id, &self.save_ctxt);
1101         let children =
1102             krate_mod.item_ids.iter().map(|i| id_from_def_id(i.def_id.to_def_id())).collect();
1103         let span = self.span_from_span(krate_mod.inner);
1104         let attrs = self.tcx.hir().attrs(id);
1105
1106         self.dumper.dump_def(
1107             &Access { public: true, reachable: true },
1108             Def {
1109                 kind: DefKind::Mod,
1110                 id: data_id,
1111                 name: String::new(),
1112                 qualname,
1113                 span,
1114                 value: filename.prefer_remapped().to_string(),
1115                 children,
1116                 parent: None,
1117                 decl_id: None,
1118                 docs: self.save_ctxt.docs_for_attrs(attrs),
1119                 sig: None,
1120                 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1121             },
1122         );
1123         self.tcx.hir().walk_toplevel_module(self);
1124     }
1125
1126     fn process_bounds(&mut self, bounds: hir::GenericBounds<'tcx>) {
1127         for bound in bounds {
1128             if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1129                 self.process_path(
1130                     trait_ref.trait_ref.hir_ref_id,
1131                     &hir::QPath::Resolved(None, &trait_ref.trait_ref.path),
1132                 )
1133             }
1134         }
1135     }
1136 }
1137
1138 impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> {
1139     type NestedFilter = nested_filter::All;
1140
1141     fn nested_visit_map(&mut self) -> Self::Map {
1142         self.tcx.hir()
1143     }
1144
1145     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1146         self.process_macro_use(item.span);
1147         match item.kind {
1148             hir::ItemKind::Use(path, hir::UseKind::Single) => {
1149                 let sub_span = path.segments.last().unwrap().ident.span;
1150                 if !self.span.filter_generated(sub_span) {
1151                     let access = access_from!(self.save_ctxt, item, item.def_id);
1152                     let ref_id = self.lookup_def_id(item.hir_id()).map(id_from_def_id);
1153                     let span = self.span_from_span(sub_span);
1154                     let parent =
1155                         self.save_ctxt.tcx.parent(item.def_id.to_def_id()).map(id_from_def_id);
1156                     self.dumper.import(
1157                         &access,
1158                         Import {
1159                             kind: ImportKind::Use,
1160                             ref_id,
1161                             span,
1162                             alias_span: None,
1163                             name: item.ident.to_string(),
1164                             value: String::new(),
1165                             parent,
1166                         },
1167                     );
1168                     self.write_sub_paths_truncated(&path);
1169                 }
1170             }
1171             hir::ItemKind::Use(path, hir::UseKind::Glob) => {
1172                 // Make a comma-separated list of names of imported modules.
1173                 let names = self.tcx.names_imported_by_glob_use(item.def_id);
1174                 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1175
1176                 // Otherwise it's a span with wrong macro expansion info, which
1177                 // we don't want to track anyway, since it's probably macro-internal `use`
1178                 if let Some(sub_span) = self.span.sub_span_of_star(item.span) {
1179                     if !self.span.filter_generated(item.span) {
1180                         let access = access_from!(self.save_ctxt, item, item.def_id);
1181                         let span = self.span_from_span(sub_span);
1182                         let parent =
1183                             self.save_ctxt.tcx.parent(item.def_id.to_def_id()).map(id_from_def_id);
1184                         self.dumper.import(
1185                             &access,
1186                             Import {
1187                                 kind: ImportKind::GlobUse,
1188                                 ref_id: None,
1189                                 span,
1190                                 alias_span: None,
1191                                 name: "*".to_owned(),
1192                                 value: names.join(", "),
1193                                 parent,
1194                             },
1195                         );
1196                         self.write_sub_paths(&path);
1197                     }
1198                 }
1199             }
1200             hir::ItemKind::ExternCrate(_) => {
1201                 let name_span = item.ident.span;
1202                 if !self.span.filter_generated(name_span) {
1203                     let span = self.span_from_span(name_span);
1204                     let parent =
1205                         self.save_ctxt.tcx.parent(item.def_id.to_def_id()).map(id_from_def_id);
1206                     self.dumper.import(
1207                         &Access { public: false, reachable: false },
1208                         Import {
1209                             kind: ImportKind::ExternCrate,
1210                             ref_id: None,
1211                             span,
1212                             alias_span: None,
1213                             name: item.ident.to_string(),
1214                             value: String::new(),
1215                             parent,
1216                         },
1217                     );
1218                 }
1219             }
1220             hir::ItemKind::Fn(ref sig, ref ty_params, body) => {
1221                 self.process_fn(item, sig.decl, &sig.header, ty_params, body)
1222             }
1223             hir::ItemKind::Static(ref typ, _, body) => {
1224                 let body = self.tcx.hir().body(body);
1225                 self.process_static_or_const_item(item, typ, &body.value)
1226             }
1227             hir::ItemKind::Const(ref typ, body) => {
1228                 let body = self.tcx.hir().body(body);
1229                 self.process_static_or_const_item(item, typ, &body.value)
1230             }
1231             hir::ItemKind::Struct(ref def, ref ty_params)
1232             | hir::ItemKind::Union(ref def, ref ty_params) => {
1233                 self.process_struct(item, def, ty_params)
1234             }
1235             hir::ItemKind::Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1236             hir::ItemKind::Impl(ref impl_) => self.process_impl(item, impl_),
1237             hir::ItemKind::Trait(_, _, ref generics, ref trait_refs, methods) => {
1238                 self.process_trait(item, generics, trait_refs, methods)
1239             }
1240             hir::ItemKind::Mod(ref m) => {
1241                 self.process_mod(item);
1242                 intravisit::walk_mod(self, m, item.hir_id());
1243             }
1244             hir::ItemKind::TyAlias(ty, ref generics) => {
1245                 let qualname = format!("::{}", self.tcx.def_path_str(item.def_id.to_def_id()));
1246                 let value = ty_to_string(&ty);
1247                 if !self.span.filter_generated(item.ident.span) {
1248                     let span = self.span_from_span(item.ident.span);
1249                     let id = id_from_def_id(item.def_id.to_def_id());
1250                     let attrs = self.tcx.hir().attrs(item.hir_id());
1251
1252                     self.dumper.dump_def(
1253                         &access_from!(self.save_ctxt, item, item.def_id),
1254                         Def {
1255                             kind: DefKind::Type,
1256                             id,
1257                             span,
1258                             name: item.ident.to_string(),
1259                             qualname: qualname.clone(),
1260                             value,
1261                             parent: None,
1262                             children: vec![],
1263                             decl_id: None,
1264                             docs: self.save_ctxt.docs_for_attrs(attrs),
1265                             sig: sig::item_signature(item, &self.save_ctxt),
1266                             attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),
1267                         },
1268                     );
1269                 }
1270
1271                 self.visit_ty(ty);
1272                 self.process_generic_params(generics, &qualname, item.hir_id());
1273             }
1274             _ => intravisit::walk_item(self, item),
1275         }
1276     }
1277
1278     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1279         for param in generics.params {
1280             match param.kind {
1281                 hir::GenericParamKind::Lifetime { .. } => {}
1282                 hir::GenericParamKind::Type { ref default, .. } => {
1283                     self.process_bounds(param.bounds);
1284                     if let Some(ref ty) = default {
1285                         self.visit_ty(ty);
1286                     }
1287                 }
1288                 hir::GenericParamKind::Const { ref ty, ref default } => {
1289                     self.process_bounds(param.bounds);
1290                     self.visit_ty(ty);
1291                     if let Some(default) = default {
1292                         self.visit_anon_const(default);
1293                     }
1294                 }
1295             }
1296         }
1297         for pred in generics.where_clause.predicates {
1298             if let hir::WherePredicate::BoundPredicate(ref wbp) = *pred {
1299                 self.process_bounds(wbp.bounds);
1300                 self.visit_ty(wbp.bounded_ty);
1301             }
1302         }
1303     }
1304
1305     fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
1306         self.process_macro_use(t.span);
1307         match t.kind {
1308             hir::TyKind::Path(ref path) => {
1309                 if generated_code(t.span) {
1310                     return;
1311                 }
1312
1313                 if let Some(id) = self.lookup_def_id(t.hir_id) {
1314                     let sub_span = path.last_segment_span();
1315                     let span = self.span_from_span(sub_span);
1316                     self.dumper.dump_ref(Ref {
1317                         kind: RefKind::Type,
1318                         span,
1319                         ref_id: id_from_def_id(id),
1320                     });
1321                 }
1322
1323                 if let hir::QPath::Resolved(_, path) = path {
1324                     self.write_sub_paths_truncated(path);
1325                 }
1326                 intravisit::walk_qpath(self, path, t.hir_id, t.span);
1327             }
1328             hir::TyKind::Array(ref ty, ref length) => {
1329                 self.visit_ty(ty);
1330                 let map = self.tcx.hir();
1331                 match length {
1332                     // FIXME(generic_arg_infer): We probably want to
1333                     // output the inferred type here? :shrug:
1334                     hir::ArrayLen::Infer(..) => {}
1335                     hir::ArrayLen::Body(anon_const) => self
1336                         .nest_typeck_results(self.tcx.hir().local_def_id(anon_const.hir_id), |v| {
1337                             v.visit_expr(&map.body(anon_const.body).value)
1338                         }),
1339                 }
1340             }
1341             hir::TyKind::OpaqueDef(item_id, _) => {
1342                 let item = self.tcx.hir().item(item_id);
1343                 self.nest_typeck_results(item_id.def_id, |v| v.visit_item(item));
1344             }
1345             _ => intravisit::walk_ty(self, t),
1346         }
1347     }
1348
1349     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1350         debug!("visit_expr {:?}", ex.kind);
1351         self.process_macro_use(ex.span);
1352         match ex.kind {
1353             hir::ExprKind::Struct(ref path, ref fields, ref rest) => {
1354                 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(ex.hir_id);
1355                 let adt = match self.save_ctxt.typeck_results().expr_ty_opt(&hir_expr) {
1356                     Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1357                     _ => {
1358                         intravisit::walk_expr(self, ex);
1359                         return;
1360                     }
1361                 };
1362                 let res = self.save_ctxt.get_path_res(hir_expr.hir_id);
1363                 self.process_struct_lit(ex, path, fields, adt.variant_of_res(res), *rest)
1364             }
1365             hir::ExprKind::MethodCall(ref seg, args, _) => self.process_method_call(ex, seg, args),
1366             hir::ExprKind::Field(ref sub_ex, _) => {
1367                 self.visit_expr(&sub_ex);
1368
1369                 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1370                     down_cast_data!(field_data, RefData, ex.span);
1371                     if !generated_code(ex.span) {
1372                         self.dumper.dump_ref(field_data);
1373                     }
1374                 }
1375             }
1376             hir::ExprKind::Closure(_, ref decl, body, _fn_decl_span, _) => {
1377                 let id = format!("${}", ex.hir_id);
1378
1379                 // walk arg and return types
1380                 for ty in decl.inputs {
1381                     self.visit_ty(ty);
1382                 }
1383
1384                 if let hir::FnRetTy::Return(ref ret_ty) = decl.output {
1385                     self.visit_ty(ret_ty);
1386                 }
1387
1388                 // walk the body
1389                 let map = self.tcx.hir();
1390                 self.nest_typeck_results(self.tcx.hir().local_def_id(ex.hir_id), |v| {
1391                     let body = map.body(body);
1392                     v.process_formals(body.params, &id);
1393                     v.visit_expr(&body.value)
1394                 });
1395             }
1396             hir::ExprKind::Repeat(ref expr, ref length) => {
1397                 self.visit_expr(expr);
1398                 let map = self.tcx.hir();
1399                 match length {
1400                     // FIXME(generic_arg_infer): We probably want to
1401                     // output the inferred type here? :shrug:
1402                     hir::ArrayLen::Infer(..) => {}
1403                     hir::ArrayLen::Body(anon_const) => self
1404                         .nest_typeck_results(self.tcx.hir().local_def_id(anon_const.hir_id), |v| {
1405                             v.visit_expr(&map.body(anon_const.body).value)
1406                         }),
1407                 }
1408             }
1409             // In particular, we take this branch for call and path expressions,
1410             // where we'll index the idents involved just by continuing to walk.
1411             _ => intravisit::walk_expr(self, ex),
1412         }
1413     }
1414
1415     fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
1416         self.process_macro_use(p.span);
1417         self.process_pat(p);
1418     }
1419
1420     fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1421         self.process_var_decl(&arm.pat);
1422         if let Some(hir::Guard::If(expr)) = &arm.guard {
1423             self.visit_expr(expr);
1424         }
1425         self.visit_expr(&arm.body);
1426     }
1427
1428     fn visit_qpath(&mut self, path: &'tcx hir::QPath<'tcx>, id: hir::HirId, _: Span) {
1429         self.process_path(id, path);
1430     }
1431
1432     fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) {
1433         self.process_macro_use(s.span);
1434         intravisit::walk_stmt(self, s)
1435     }
1436
1437     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
1438         self.process_macro_use(l.span);
1439         self.process_var_decl(&l.pat);
1440
1441         // Just walk the initialiser and type (don't want to walk the pattern again).
1442         walk_list!(self, visit_ty, &l.ty);
1443         walk_list!(self, visit_expr, &l.init);
1444     }
1445
1446     fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
1447         let access = access_from!(self.save_ctxt, item, item.def_id);
1448
1449         match item.kind {
1450             hir::ForeignItemKind::Fn(decl, _, ref generics) => {
1451                 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1452                     down_cast_data!(fn_data, DefData, item.span);
1453
1454                     self.process_generic_params(generics, &fn_data.qualname, item.hir_id());
1455                     self.dumper.dump_def(&access, fn_data);
1456                 }
1457
1458                 for ty in decl.inputs {
1459                     self.visit_ty(ty);
1460                 }
1461
1462                 if let hir::FnRetTy::Return(ref ret_ty) = decl.output {
1463                     self.visit_ty(ret_ty);
1464                 }
1465             }
1466             hir::ForeignItemKind::Static(ref ty, _) => {
1467                 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1468                     down_cast_data!(var_data, DefData, item.span);
1469                     self.dumper.dump_def(&access, var_data);
1470                 }
1471
1472                 self.visit_ty(ty);
1473             }
1474             hir::ForeignItemKind::Type => {
1475                 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1476                     down_cast_data!(var_data, DefData, item.span);
1477                     self.dumper.dump_def(&access, var_data);
1478                 }
1479             }
1480         }
1481     }
1482 }