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