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