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