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