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