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