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