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