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