]> git.lizzy.rs Git - rust.git/blob - src/librustc_save_analysis/dump_visitor.rs
41f91a1d2acc17ac234f00824cd88655868bde26
[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.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         let mut has_self_ref = false;
751         if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
752             down_cast_data!(impl_data, ImplData, item.span);
753             if let Some(ref self_ref) = impl_data.self_ref {
754                 has_self_ref = true;
755                 if !self.span.filter_generated(Some(self_ref.span), item.span) {
756                     self.dumper.type_ref(self_ref.clone().lower(self.tcx));
757                 }
758             }
759             if let Some(ref trait_ref_data) = impl_data.trait_ref {
760                 if !self.span.filter_generated(Some(trait_ref_data.span), item.span) {
761                     self.dumper.type_ref(trait_ref_data.clone().lower(self.tcx));
762                 }
763             }
764
765             if !self.span.filter_generated(Some(impl_data.span), item.span) {
766                 self.dumper.impl_data(ImplData {
767                     id: impl_data.id,
768                     span: impl_data.span,
769                     scope: impl_data.scope,
770                     trait_ref: impl_data.trait_ref.map(|d| d.ref_id.unwrap()),
771                     self_ref: impl_data.self_ref.map(|d| d.ref_id.unwrap())
772                 }.lower(self.tcx));
773             }
774         }
775         if !has_self_ref {
776             self.visit_ty(&typ);
777         }
778         if let &Some(ref trait_ref) = trait_ref {
779             self.process_path(trait_ref.ref_id, &trait_ref.path, Some(recorder::TypeRef));
780         }
781         self.process_generic_params(type_parameters, item.span, "", item.id);
782         for impl_item in impl_items {
783             let map = &self.tcx.hir;
784             self.process_impl_item(impl_item, make_def_id(item.id, map));
785         }
786     }
787
788     fn process_trait(&mut self,
789                      item: &'l ast::Item,
790                      generics: &'l ast::Generics,
791                      trait_refs: &'l ast::TyParamBounds,
792                      methods: &'l [ast::TraitItem]) {
793         let name = item.ident.to_string();
794         let qualname = format!("::{}", self.tcx.node_path_str(item.id));
795         let mut val = name.clone();
796         if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
797             val.push_str(&generics_to_string(generics));
798         }
799         if !trait_refs.is_empty() {
800             val.push_str(": ");
801             val.push_str(&bounds_to_string(trait_refs));
802         }
803         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
804         if !self.span.filter_generated(sub_span, item.span) {
805             self.dumper.trait_data(TraitData {
806                 span: sub_span.expect("No span found for trait"),
807                 id: item.id,
808                 name: name,
809                 qualname: qualname.clone(),
810                 scope: self.cur_scope,
811                 value: val,
812                 items: methods.iter().map(|i| i.id).collect(),
813                 visibility: From::from(&item.vis),
814                 docs: docs_for_attrs(&item.attrs),
815                 sig: self.save_ctxt.sig_base(item),
816             }.lower(self.tcx));
817         }
818
819         // super-traits
820         for super_bound in trait_refs.iter() {
821             let trait_ref = match *super_bound {
822                 ast::TraitTyParamBound(ref trait_ref, _) => {
823                     trait_ref
824                 }
825                 ast::RegionTyParamBound(..) => {
826                     continue;
827                 }
828             };
829
830             let trait_ref = &trait_ref.trait_ref;
831             if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
832                 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
833                 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
834                     self.dumper.type_ref(TypeRefData {
835                         span: sub_span.expect("No span found for trait ref"),
836                         ref_id: Some(id),
837                         scope: self.cur_scope,
838                         qualname: String::new()
839                     }.lower(self.tcx));
840                 }
841
842                 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
843                     let sub_span = sub_span.expect("No span for inheritance");
844                     self.dumper.inheritance(InheritanceData {
845                         span: sub_span,
846                         base_id: id,
847                         deriv_id: item.id
848                     }.lower(self.tcx));
849                 }
850             }
851         }
852
853         // walk generics and methods
854         self.process_generic_params(generics, item.span, &qualname, item.id);
855         for method in methods {
856             let map = &self.tcx.hir;
857             self.process_trait_item(method, make_def_id(item.id, map))
858         }
859     }
860
861     // `item` is the module in question, represented as an item.
862     fn process_mod(&mut self, item: &ast::Item) {
863         if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
864             down_cast_data!(mod_data, ModData, item.span);
865             if !self.span.filter_generated(Some(mod_data.span), item.span) {
866                 self.dumper.mod_data(mod_data.lower(self.tcx));
867             }
868         }
869     }
870
871     fn process_path(&mut self, id: NodeId, path: &ast::Path, ref_kind: Option<recorder::Row>) {
872         let path_data = self.save_ctxt.get_path_data(id, path);
873         if generated_code(path.span) && path_data.is_none() {
874             return;
875         }
876
877         let path_data = match path_data {
878             Some(pd) => pd,
879             None => {
880                 return;
881             }
882         };
883
884         match path_data {
885             Data::VariableRefData(vrd) => {
886                 // FIXME: this whole block duplicates the code in process_def_kind
887                 if !self.span.filter_generated(Some(vrd.span), path.span) {
888                     match ref_kind {
889                         Some(recorder::TypeRef) => {
890                             self.dumper.type_ref(TypeRefData {
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::FnRef) => {
898                             self.dumper.function_ref(FunctionRefData {
899                                 span: vrd.span,
900                                 ref_id: vrd.ref_id,
901                                 scope: vrd.scope
902                             }.lower(self.tcx));
903                         }
904                         Some(recorder::ModRef) => {
905                             self.dumper.mod_ref( ModRefData {
906                                 span: vrd.span,
907                                 ref_id: Some(vrd.ref_id),
908                                 scope: vrd.scope,
909                                 qualname: String::new()
910                             }.lower(self.tcx));
911                         }
912                         Some(recorder::VarRef) | None
913                             => self.dumper.variable_ref(vrd.lower(self.tcx))
914                     }
915                 }
916
917             }
918             Data::TypeRefData(trd) => {
919                 if !self.span.filter_generated(Some(trd.span), path.span) {
920                     self.dumper.type_ref(trd.lower(self.tcx));
921                 }
922             }
923             Data::MethodCallData(mcd) => {
924                 if !self.span.filter_generated(Some(mcd.span), path.span) {
925                     self.dumper.method_call(mcd.lower(self.tcx));
926                 }
927             }
928             Data::FunctionCallData(fcd) => {
929                 if !self.span.filter_generated(Some(fcd.span), path.span) {
930                     self.dumper.function_call(fcd.lower(self.tcx));
931                 }
932             }
933             _ => {
934                span_bug!(path.span, "Unexpected data: {:?}", path_data);
935             }
936         }
937
938         // Modules or types in the path prefix.
939         match self.save_ctxt.get_path_def(id) {
940             Def::Method(did) => {
941                 let ti = self.tcx.associated_item(did);
942                 if ti.kind == ty::AssociatedKind::Method && ti.method_has_self_argument {
943                     self.write_sub_path_trait_truncated(path);
944                 }
945             }
946             Def::Fn(..) |
947             Def::Const(..) |
948             Def::Static(..) |
949             Def::StructCtor(..) |
950             Def::VariantCtor(..) |
951             Def::AssociatedConst(..) |
952             Def::Local(..) |
953             Def::Upvar(..) |
954             Def::Struct(..) |
955             Def::Union(..) |
956             Def::Variant(..) |
957             Def::TyAlias(..) |
958             Def::AssociatedTy(..) => self.write_sub_paths_truncated(path),
959             _ => {}
960         }
961     }
962
963     fn process_struct_lit(&mut self,
964                           ex: &'l ast::Expr,
965                           path: &'l ast::Path,
966                           fields: &'l [ast::Field],
967                           variant: &'l ty::VariantDef,
968                           base: &'l Option<P<ast::Expr>>) {
969         self.write_sub_paths_truncated(path);
970
971         if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
972             down_cast_data!(struct_lit_data, TypeRefData, ex.span);
973             if !self.span.filter_generated(Some(struct_lit_data.span), ex.span) {
974                 self.dumper.type_ref(struct_lit_data.lower(self.tcx));
975             }
976
977             let scope = self.save_ctxt.enclosing_scope(ex.id);
978
979             for field in fields {
980                 if let Some(field_data) = self.save_ctxt
981                                               .get_field_ref_data(field, variant, scope) {
982
983                     if !self.span.filter_generated(Some(field_data.span), field.ident.span) {
984                         self.dumper.variable_ref(field_data.lower(self.tcx));
985                     }
986                 }
987
988                 self.visit_expr(&field.expr)
989             }
990         }
991
992         walk_list!(self, visit_expr, base);
993     }
994
995     fn process_method_call(&mut self, ex: &'l ast::Expr, args: &'l [P<ast::Expr>]) {
996         if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
997             down_cast_data!(mcd, MethodCallData, ex.span);
998             if !self.span.filter_generated(Some(mcd.span), ex.span) {
999                 self.dumper.method_call(mcd.lower(self.tcx));
1000             }
1001         }
1002
1003         // walk receiver and args
1004         walk_list!(self, visit_expr, args);
1005     }
1006
1007     fn process_pat(&mut self, p: &'l ast::Pat) {
1008         match p.node {
1009             PatKind::Struct(ref _path, ref fields, _) => {
1010                 // FIXME do something with _path?
1011                 let adt = match self.save_ctxt.tables.node_id_to_type_opt(p.id) {
1012                     Some(ty) => ty.ty_adt_def().unwrap(),
1013                     None => {
1014                         visit::walk_pat(self, p);
1015                         return;
1016                     }
1017                 };
1018                 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
1019
1020                 for &Spanned { node: ref field, span } in fields {
1021                     let sub_span = self.span.span_for_first_ident(span);
1022                     if let Some(f) = variant.find_field_named(field.ident.name) {
1023                         if !self.span.filter_generated(sub_span, span) {
1024                             self.dumper.variable_ref(VariableRefData {
1025                                 span: sub_span.expect("No span fund for var ref"),
1026                                 ref_id: f.did,
1027                                 scope: self.cur_scope,
1028                                 name: String::new()
1029                             }.lower(self.tcx));
1030                         }
1031                     }
1032                     self.visit_pat(&field.pat);
1033                 }
1034             }
1035             _ => visit::walk_pat(self, p),
1036         }
1037     }
1038
1039
1040     fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
1041         // The local could declare multiple new vars, we must walk the
1042         // pattern and collect them all.
1043         let mut collector = PathCollector::new();
1044         collector.visit_pat(&p);
1045         self.visit_pat(&p);
1046
1047         for &(id, ref p, immut, _) in &collector.collected_paths {
1048             let mut value = match immut {
1049                 ast::Mutability::Immutable => value.to_string(),
1050                 _ => String::new(),
1051             };
1052             let typ = match self.save_ctxt.tables.node_types.get(&id) {
1053                 Some(typ) => {
1054                     let typ = typ.to_string();
1055                     if !value.is_empty() {
1056                         value.push_str(": ");
1057                     }
1058                     value.push_str(&typ);
1059                     typ
1060                 }
1061                 None => String::new(),
1062             };
1063
1064             // Get the span only for the name of the variable (I hope the path
1065             // is only ever a variable name, but who knows?).
1066             let sub_span = self.span.span_for_last_ident(p.span);
1067             // Rust uses the id of the pattern for var lookups, so we'll use it too.
1068             if !self.span.filter_generated(sub_span, p.span) {
1069                 self.dumper.variable(VariableData {
1070                     span: sub_span.expect("No span found for variable"),
1071                     kind: VariableKind::Local,
1072                     id: id,
1073                     name: path_to_string(p),
1074                     qualname: format!("{}${}", path_to_string(p), id),
1075                     value: value,
1076                     type_value: typ,
1077                     scope: CRATE_NODE_ID,
1078                     parent: None,
1079                     visibility: Visibility::Inherited,
1080                     docs: String::new(),
1081                     sig: None,
1082                 }.lower(self.tcx));
1083             }
1084         }
1085     }
1086
1087     /// Extract macro use and definition information from the AST node defined
1088     /// by the given NodeId, using the expansion information from the node's
1089     /// span.
1090     ///
1091     /// If the span is not macro-generated, do nothing, else use callee and
1092     /// callsite spans to record macro definition and use data, using the
1093     /// mac_uses and mac_defs sets to prevent multiples.
1094     fn process_macro_use(&mut self, span: Span, id: NodeId) {
1095         let data = match self.save_ctxt.get_macro_use_data(span, id) {
1096             None => return,
1097             Some(data) => data,
1098         };
1099         let mut hasher = DefaultHasher::new();
1100         data.callee_span.hash(&mut hasher);
1101         let hash = hasher.finish();
1102         let qualname = format!("{}::{}", data.name, hash);
1103         // Don't write macro definition for imported macros
1104         if !self.mac_defs.contains(&data.callee_span)
1105             && !data.imported {
1106             self.mac_defs.insert(data.callee_span);
1107             if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1108                 self.dumper.macro_data(MacroData {
1109                     span: sub_span,
1110                     name: data.name.clone(),
1111                     qualname: qualname.clone(),
1112                     // FIXME where do macro docs come from?
1113                     docs: String::new(),
1114                 }.lower(self.tcx));
1115             }
1116         }
1117         if !self.mac_uses.contains(&data.span) {
1118             self.mac_uses.insert(data.span);
1119             if let Some(sub_span) = self.span.span_for_macro_use_name(data.span) {
1120                 self.dumper.macro_use(MacroUseData {
1121                     span: sub_span,
1122                     name: data.name,
1123                     qualname: qualname,
1124                     scope: data.scope,
1125                     callee_span: data.callee_span,
1126                     imported: data.imported,
1127                 }.lower(self.tcx));
1128             }
1129         }
1130     }
1131
1132     fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1133         self.process_macro_use(trait_item.span, trait_item.id);
1134         match trait_item.node {
1135             ast::TraitItemKind::Const(ref ty, Some(ref expr)) => {
1136                 self.process_assoc_const(trait_item.id,
1137                                          trait_item.ident.name,
1138                                          trait_item.span,
1139                                          &ty,
1140                                          &expr,
1141                                          trait_id,
1142                                          Visibility::Public,
1143                                          &trait_item.attrs);
1144             }
1145             ast::TraitItemKind::Method(ref sig, ref body) => {
1146                 self.process_method(sig,
1147                                     body.as_ref().map(|x| &**x),
1148                                     trait_item.id,
1149                                     trait_item.ident.name,
1150                                     Visibility::Public,
1151                                     &trait_item.attrs,
1152                                     trait_item.span);
1153             }
1154             ast::TraitItemKind::Const(_, None) |
1155             ast::TraitItemKind::Type(..) |
1156             ast::TraitItemKind::Macro(_) => {}
1157         }
1158     }
1159
1160     fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1161         self.process_macro_use(impl_item.span, impl_item.id);
1162         match impl_item.node {
1163             ast::ImplItemKind::Const(ref ty, ref expr) => {
1164                 self.process_assoc_const(impl_item.id,
1165                                          impl_item.ident.name,
1166                                          impl_item.span,
1167                                          &ty,
1168                                          &expr,
1169                                          impl_id,
1170                                          From::from(&impl_item.vis),
1171                                          &impl_item.attrs);
1172             }
1173             ast::ImplItemKind::Method(ref sig, ref body) => {
1174                 self.process_method(sig,
1175                                     Some(body),
1176                                     impl_item.id,
1177                                     impl_item.ident.name,
1178                                     From::from(&impl_item.vis),
1179                                     &impl_item.attrs,
1180                                     impl_item.span);
1181             }
1182             ast::ImplItemKind::Type(_) |
1183             ast::ImplItemKind::Macro(_) => {}
1184         }
1185     }
1186 }
1187
1188 impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, D> {
1189     fn visit_item(&mut self, item: &'l ast::Item) {
1190         use syntax::ast::ItemKind::*;
1191         self.process_macro_use(item.span, item.id);
1192         match item.node {
1193             Use(ref use_item) => {
1194                 match use_item.node {
1195                     ast::ViewPathSimple(ident, ref path) => {
1196                         let sub_span = self.span.span_for_last_ident(path.span);
1197                         let mod_id = match self.lookup_def_id(item.id) {
1198                             Some(def_id) => {
1199                                 let scope = self.cur_scope;
1200                                 self.process_def_kind(item.id, path.span, sub_span, def_id, scope);
1201
1202                                 Some(def_id)
1203                             }
1204                             None => None,
1205                         };
1206
1207                         // 'use' always introduces an alias, if there is not an explicit
1208                         // one, there is an implicit one.
1209                         let sub_span = match self.span.sub_span_after_keyword(use_item.span,
1210                                                                               keywords::As) {
1211                             Some(sub_span) => Some(sub_span),
1212                             None => sub_span,
1213                         };
1214
1215                         if !self.span.filter_generated(sub_span, path.span) {
1216                             self.dumper.use_data(UseData {
1217                                 span: sub_span.expect("No span found for use"),
1218                                 id: item.id,
1219                                 mod_id: mod_id,
1220                                 name: ident.to_string(),
1221                                 scope: self.cur_scope,
1222                                 visibility: From::from(&item.vis),
1223                             }.lower(self.tcx));
1224                         }
1225                         self.write_sub_paths_truncated(path);
1226                     }
1227                     ast::ViewPathGlob(ref path) => {
1228                         // Make a comma-separated list of names of imported modules.
1229                         let mut names = vec![];
1230                         let glob_map = &self.save_ctxt.analysis.glob_map;
1231                         let glob_map = glob_map.as_ref().unwrap();
1232                         if glob_map.contains_key(&item.id) {
1233                             for n in glob_map.get(&item.id).unwrap() {
1234                                 names.push(n.to_string());
1235                             }
1236                         }
1237
1238                         let sub_span = self.span
1239                                            .sub_span_of_token(item.span, token::BinOp(token::Star));
1240                         if !self.span.filter_generated(sub_span, item.span) {
1241                             self.dumper.use_glob(UseGlobData {
1242                                 span: sub_span.expect("No span found for use glob"),
1243                                 id: item.id,
1244                                 names: names,
1245                                 scope: self.cur_scope,
1246                                 visibility: From::from(&item.vis),
1247                             }.lower(self.tcx));
1248                         }
1249                         self.write_sub_paths(path);
1250                     }
1251                     ast::ViewPathList(ref path, ref list) => {
1252                         for plid in list {
1253                             let scope = self.cur_scope;
1254                             let id = plid.node.id;
1255                             if let Some(def_id) = self.lookup_def_id(id) {
1256                                 let span = plid.span;
1257                                 self.process_def_kind(id, span, Some(span), def_id, scope);
1258                             }
1259                         }
1260
1261                         self.write_sub_paths(path);
1262                     }
1263                 }
1264             }
1265             ExternCrate(ref s) => {
1266                 let location = match *s {
1267                     Some(s) => s.to_string(),
1268                     None => item.ident.to_string(),
1269                 };
1270                 let alias_span = self.span.span_for_last_ident(item.span);
1271                 let cnum = match self.sess.cstore.extern_mod_stmt_cnum(item.id) {
1272                     Some(cnum) => cnum,
1273                     None => LOCAL_CRATE,
1274                 };
1275
1276                 if !self.span.filter_generated(alias_span, item.span) {
1277                     self.dumper.extern_crate(ExternCrateData {
1278                         id: item.id,
1279                         name: item.ident.to_string(),
1280                         crate_num: cnum,
1281                         location: location,
1282                         span: alias_span.expect("No span found for extern crate"),
1283                         scope: self.cur_scope,
1284                     }.lower(self.tcx));
1285                 }
1286             }
1287             Fn(ref decl, .., ref ty_params, ref body) =>
1288                 self.process_fn(item, &decl, ty_params, &body),
1289             Static(ref typ, _, ref expr) =>
1290                 self.process_static_or_const_item(item, typ, expr),
1291             Const(ref typ, ref expr) =>
1292                 self.process_static_or_const_item(item, &typ, &expr),
1293             Struct(ref def, ref ty_params) => self.process_struct(item, def, ty_params),
1294             Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1295             Impl(..,
1296                  ref ty_params,
1297                  ref trait_ref,
1298                  ref typ,
1299                  ref impl_items) => {
1300                 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1301             }
1302             Trait(_, ref generics, ref trait_refs, ref methods) =>
1303                 self.process_trait(item, generics, trait_refs, methods),
1304             Mod(ref m) => {
1305                 self.process_mod(item);
1306                 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1307             }
1308             Ty(ref ty, ref ty_params) => {
1309                 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1310                 let value = ty_to_string(&ty);
1311                 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1312                 if !self.span.filter_generated(sub_span, item.span) {
1313                     self.dumper.typedef(TypeDefData {
1314                         span: sub_span.expect("No span found for typedef"),
1315                         name: item.ident.to_string(),
1316                         id: item.id,
1317                         qualname: qualname.clone(),
1318                         value: value,
1319                         visibility: From::from(&item.vis),
1320                         parent: None,
1321                         docs: docs_for_attrs(&item.attrs),
1322                         sig: Some(self.save_ctxt.sig_base(item)),
1323                     }.lower(self.tcx));
1324                 }
1325
1326                 self.visit_ty(&ty);
1327                 self.process_generic_params(ty_params, item.span, &qualname, item.id);
1328             }
1329             Mac(_) => (),
1330             _ => visit::walk_item(self, item),
1331         }
1332     }
1333
1334     fn visit_generics(&mut self, generics: &'l ast::Generics) {
1335         for param in generics.ty_params.iter() {
1336             for bound in param.bounds.iter() {
1337                 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
1338                     self.process_trait_ref(&trait_ref.trait_ref);
1339                 }
1340             }
1341             if let Some(ref ty) = param.default {
1342                 self.visit_ty(&ty);
1343             }
1344         }
1345     }
1346
1347     fn visit_ty(&mut self, t: &'l ast::Ty) {
1348         self.process_macro_use(t.span, t.id);
1349         match t.node {
1350             ast::TyKind::Path(_, ref path) => {
1351                 if generated_code(t.span) {
1352                     return;
1353                 }
1354
1355                 if let Some(id) = self.lookup_def_id(t.id) {
1356                     if let Some(sub_span) = self.span.sub_span_for_type_name(t.span) {
1357                         self.dumper.type_ref(TypeRefData {
1358                             span: sub_span,
1359                             ref_id: Some(id),
1360                             scope: self.cur_scope,
1361                             qualname: String::new()
1362                         }.lower(self.tcx));
1363                     }
1364                 }
1365
1366                 self.write_sub_paths_truncated(path);
1367                 visit::walk_path(self, path);
1368             }
1369             ast::TyKind::Array(ref element, ref length) => {
1370                 self.visit_ty(element);
1371                 self.nest_tables(length.id, |v| v.visit_expr(length));
1372             }
1373             _ => visit::walk_ty(self, t),
1374         }
1375     }
1376
1377     fn visit_expr(&mut self, ex: &'l ast::Expr) {
1378         debug!("visit_expr {:?}", ex.node);
1379         self.process_macro_use(ex.span, ex.id);
1380         match ex.node {
1381             ast::ExprKind::Call(ref _f, ref _args) => {
1382                 // Don't need to do anything for function calls,
1383                 // because just walking the callee path does what we want.
1384                 visit::walk_expr(self, ex);
1385             }
1386             ast::ExprKind::Path(_, ref path) => {
1387                 self.process_path(ex.id, path, None);
1388                 visit::walk_expr(self, ex);
1389             }
1390             ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1391                 let hir_expr = self.save_ctxt.tcx.hir.expect_expr(ex.id);
1392                 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1393                     Some(ty) => ty.ty_adt_def().unwrap(),
1394                     None => {
1395                         visit::walk_expr(self, ex);
1396                         return;
1397                     }
1398                 };
1399                 let def = self.save_ctxt.get_path_def(hir_expr.id);
1400                 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1401             }
1402             ast::ExprKind::MethodCall(.., ref args) => self.process_method_call(ex, args),
1403             ast::ExprKind::Field(ref sub_ex, _) => {
1404                 self.visit_expr(&sub_ex);
1405
1406                 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1407                     down_cast_data!(field_data, VariableRefData, ex.span);
1408                     if !self.span.filter_generated(Some(field_data.span), ex.span) {
1409                         self.dumper.variable_ref(field_data.lower(self.tcx));
1410                     }
1411                 }
1412             }
1413             ast::ExprKind::TupField(ref sub_ex, idx) => {
1414                 self.visit_expr(&sub_ex);
1415
1416                 let hir_node = match self.save_ctxt.tcx.hir.find(sub_ex.id) {
1417                     Some(Node::NodeExpr(expr)) => expr,
1418                     _ => {
1419                         debug!("Missing or weird node for sub-expression {} in {:?}",
1420                                sub_ex.id, ex);
1421                         return;
1422                     }
1423                 };
1424                 let ty = match self.save_ctxt.tables.expr_ty_adjusted_opt(&hir_node) {
1425                     Some(ty) => &ty.sty,
1426                     None => {
1427                         visit::walk_expr(self, ex);
1428                         return;
1429                     }
1430                 };
1431                 match *ty {
1432                     ty::TyAdt(def, _) => {
1433                         let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1434                         if !self.span.filter_generated(sub_span, ex.span) {
1435                             self.dumper.variable_ref(VariableRefData {
1436                                 span: sub_span.expect("No span found for var ref"),
1437                                 ref_id: def.struct_variant().fields[idx.node].did,
1438                                 scope: self.cur_scope,
1439                                 name: String::new()
1440                             }.lower(self.tcx));
1441                         }
1442                     }
1443                     ty::TyTuple(..) => {}
1444                     _ => span_bug!(ex.span,
1445                                    "Expected struct or tuple type, found {:?}",
1446                                    ty),
1447                 }
1448             }
1449             ast::ExprKind::Closure(_, ref decl, ref body, _fn_decl_span) => {
1450                 let mut id = String::from("$");
1451                 id.push_str(&ex.id.to_string());
1452
1453                 // walk arg and return types
1454                 for arg in &decl.inputs {
1455                     self.visit_ty(&arg.ty);
1456                 }
1457
1458                 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1459                     self.visit_ty(&ret_ty);
1460                 }
1461
1462                 // walk the body
1463                 self.nest_tables(ex.id, |v| {
1464                     v.process_formals(&decl.inputs, &id);
1465                     v.nest_scope(ex.id, |v| v.visit_expr(body))
1466                 });
1467             }
1468             ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) |
1469             ast::ExprKind::WhileLet(ref pattern, ref subexpression, ref block, _) => {
1470                 let value = self.span.snippet(subexpression.span);
1471                 self.process_var_decl(pattern, value);
1472                 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1473                 visit::walk_expr(self, subexpression);
1474                 visit::walk_block(self, block);
1475             }
1476             ast::ExprKind::IfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
1477                 let value = self.span.snippet(subexpression.span);
1478                 self.process_var_decl(pattern, value);
1479                 visit::walk_expr(self, subexpression);
1480                 visit::walk_block(self, block);
1481                 opt_else.as_ref().map(|el| visit::walk_expr(self, el));
1482             }
1483             ast::ExprKind::Repeat(ref element, ref count) => {
1484                 self.visit_expr(element);
1485                 self.nest_tables(count.id, |v| v.visit_expr(count));
1486             }
1487             _ => {
1488                 visit::walk_expr(self, ex)
1489             }
1490         }
1491     }
1492
1493     fn visit_mac(&mut self, mac: &'l ast::Mac) {
1494         // These shouldn't exist in the AST at this point, log a span bug.
1495         span_bug!(mac.span, "macro invocation should have been expanded out of AST");
1496     }
1497
1498     fn visit_pat(&mut self, p: &'l ast::Pat) {
1499         self.process_macro_use(p.span, p.id);
1500         self.process_pat(p);
1501     }
1502
1503     fn visit_arm(&mut self, arm: &'l ast::Arm) {
1504         let mut collector = PathCollector::new();
1505         for pattern in &arm.pats {
1506             // collect paths from the arm's patterns
1507             collector.visit_pat(&pattern);
1508             self.visit_pat(&pattern);
1509         }
1510
1511         // This is to get around borrow checking, because we need mut self to call process_path.
1512         let mut paths_to_process = vec![];
1513
1514         // process collected paths
1515         for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1516             match self.save_ctxt.get_path_def(id) {
1517                 Def::Local(def_id) => {
1518                     let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1519                     let mut value = if immut == ast::Mutability::Immutable {
1520                         self.span.snippet(p.span).to_string()
1521                     } else {
1522                         "<mutable>".to_string()
1523                     };
1524                     let typ = self.save_ctxt.tables.node_types
1525                                   .get(&id).map(|t| t.to_string()).unwrap_or(String::new());
1526                     value.push_str(": ");
1527                     value.push_str(&typ);
1528
1529                     assert!(p.segments.len() == 1,
1530                             "qualified path for local variable def in arm");
1531                     if !self.span.filter_generated(Some(p.span), p.span) {
1532                         self.dumper.variable(VariableData {
1533                             span: p.span,
1534                             kind: VariableKind::Local,
1535                             id: id,
1536                             name: path_to_string(p),
1537                             qualname: format!("{}${}", path_to_string(p), id),
1538                             value: value,
1539                             type_value: typ,
1540                             scope: CRATE_NODE_ID,
1541                             parent: None,
1542                             visibility: Visibility::Inherited,
1543                             docs: String::new(),
1544                             sig: None,
1545                         }.lower(self.tcx));
1546                     }
1547                 }
1548                 Def::StructCtor(..) | Def::VariantCtor(..) |
1549                 Def::Const(..) | Def::AssociatedConst(..) |
1550                 Def::Struct(..) | Def::Variant(..) |
1551                 Def::TyAlias(..) | Def::AssociatedTy(..) |
1552                 Def::SelfTy(..) => {
1553                     paths_to_process.push((id, p.clone(), Some(ref_kind)))
1554                 }
1555                 def => error!("unexpected definition kind when processing collected paths: {:?}",
1556                               def),
1557             }
1558         }
1559
1560         for &(id, ref path, ref_kind) in &paths_to_process {
1561             self.process_path(id, path, ref_kind);
1562         }
1563         walk_list!(self, visit_expr, &arm.guard);
1564         self.visit_expr(&arm.body);
1565     }
1566
1567     fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1568         self.process_path(id, p, None);
1569     }
1570
1571     fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1572         self.process_macro_use(s.span, s.id);
1573         visit::walk_stmt(self, s)
1574     }
1575
1576     fn visit_local(&mut self, l: &'l ast::Local) {
1577         self.process_macro_use(l.span, l.id);
1578         let value = l.init.as_ref().map(|i| self.span.snippet(i.span)).unwrap_or(String::new());
1579         self.process_var_decl(&l.pat, value);
1580
1581         // Just walk the initialiser and type (don't want to walk the pattern again).
1582         walk_list!(self, visit_ty, &l.ty);
1583         walk_list!(self, visit_expr, &l.init);
1584     }
1585 }