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