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