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