]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/save/dump_csv.rs
f291413cedc7ede8ab25fdb8277f70409164ed7a
[rust.git] / src / librustc_trans / save / dump_csv.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 //! Output a CSV file containing the output from rustc's analysis. 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 //! Recorder is used for recording the output in csv format. FmtStrs separates
27 //! the format of the output away from extracting it from the compiler.
28 //! DumpCsvVisitor walks the AST and processes it.
29
30
31 use super::{escape, generated_code, recorder, SaveContext, PathCollector, Data};
32
33 use session::Session;
34
35 use middle::def;
36 use middle::ty::{self, Ty};
37
38 use std::fs::File;
39 use std::path::Path;
40
41 use syntax::ast::{self, NodeId, DefId};
42 use syntax::codemap::*;
43 use syntax::parse::token::{self, get_ident, keywords};
44 use syntax::owned_slice::OwnedSlice;
45 use syntax::visit::{self, Visitor};
46 use syntax::print::pprust::{path_to_string, ty_to_string};
47 use syntax::ptr::P;
48
49 use super::span_utils::SpanUtils;
50 use super::recorder::{Recorder, FmtStrs};
51
52 macro_rules! down_cast_data {
53     ($id:ident, $kind:ident, $this:ident, $sp:expr) => {
54         let $id = if let super::Data::$kind(data) = $id {
55             data
56         } else {
57             $this.sess.span_bug($sp, &format!("unexpected data kind: {:?}", $id));
58         };
59     };
60 }
61
62 pub struct DumpCsvVisitor<'l, 'tcx: 'l> {
63     save_ctxt: SaveContext<'l, 'tcx>,
64     sess: &'l Session,
65     tcx: &'l ty::ctxt<'tcx>,
66     analysis: &'l ty::CrateAnalysis,
67
68     span: SpanUtils<'l>,
69     fmt: FmtStrs<'l>,
70
71     cur_scope: NodeId
72 }
73
74 impl <'l, 'tcx> DumpCsvVisitor<'l, 'tcx> {
75     pub fn new(tcx: &'l ty::ctxt<'tcx>,
76                analysis: &'l ty::CrateAnalysis,
77                output_file: Box<File>) -> DumpCsvVisitor<'l, 'tcx> {
78         let span_utils = SpanUtils::new(&tcx.sess);
79         DumpCsvVisitor {
80             sess: &tcx.sess,
81             tcx: tcx,
82             save_ctxt: SaveContext::from_span_utils(tcx, span_utils.clone()),
83             analysis: analysis,
84             span: span_utils.clone(),
85             fmt: FmtStrs::new(box Recorder {
86                                 out: output_file,
87                                 dump_spans: false,
88                               }, span_utils),
89             cur_scope: 0
90         }
91     }
92
93     fn nest<F>(&mut self, scope_id: NodeId, f: F) where
94         F: FnOnce(&mut DumpCsvVisitor<'l, 'tcx>),
95     {
96         let parent_scope = self.cur_scope;
97         self.cur_scope = scope_id;
98         f(self);
99         self.cur_scope = parent_scope;
100     }
101
102     pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
103         // The current crate.
104         self.fmt.crate_str(krate.span, name);
105
106         // Dump info about all the external crates referenced from this crate.
107         for c in &self.save_ctxt.get_external_crates() {
108             self.fmt.external_crate_str(krate.span, &c.name, c.number);
109         }
110         self.fmt.recorder.record("end_external_crates\n");
111     }
112
113     // Return all non-empty prefixes of a path.
114     // For each prefix, we return the span for the last segment in the prefix and
115     // a str representation of the entire prefix.
116     fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
117         let spans = self.span.spans_for_path_segments(path);
118
119         // Paths to enums seem to not match their spans - the span includes all the
120         // variants too. But they seem to always be at the end, so I hope we can cope with
121         // always using the first ones. So, only error out if we don't have enough spans.
122         // What could go wrong...?
123         if spans.len() < path.segments.len() {
124             error!("Mis-calculated spans for path '{}'. \
125                     Found {} spans, expected {}. Found spans:",
126                    path_to_string(path), spans.len(), path.segments.len());
127             for s in &spans {
128                 let loc = self.sess.codemap().lookup_char_pos(s.lo);
129                 error!("    '{}' in {}, line {}",
130                        self.span.snippet(*s), loc.file.name, loc.line);
131             }
132             return vec!();
133         }
134
135         let mut result: Vec<(Span, String)> = vec!();
136
137         let mut segs = vec!();
138         for (i, (seg, span)) in path.segments.iter().zip(&spans).enumerate() {
139             segs.push(seg.clone());
140             let sub_path = ast::Path{span: *span, // span for the last segment
141                                      global: path.global,
142                                      segments: segs};
143             let qualname = if i == 0 && path.global {
144                 format!("::{}", path_to_string(&sub_path))
145             } else {
146                 path_to_string(&sub_path)
147             };
148             result.push((*span, qualname));
149             segs = sub_path.segments;
150         }
151
152         result
153     }
154
155     // The global arg allows us to override the global-ness of the path (which
156     // actually means 'does the path start with `::`', rather than 'is the path
157     // semantically global). We use the override for `use` imports (etc.) where
158     // the syntax is non-global, but the semantics are global.
159     fn write_sub_paths(&mut self, path: &ast::Path, global: bool) {
160         let sub_paths = self.process_path_prefixes(path);
161         for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
162             let qualname = if i == 0 && global && !path.global {
163                 format!("::{}", qualname)
164             } else {
165                 qualname.clone()
166             };
167             self.fmt.sub_mod_ref_str(path.span,
168                                      *span,
169                                      &qualname,
170                                      self.cur_scope);
171         }
172     }
173
174     // As write_sub_paths, but does not process the last ident in the path (assuming it
175     // will be processed elsewhere). See note on write_sub_paths about global.
176     fn write_sub_paths_truncated(&mut self, path: &ast::Path, global: bool) {
177         let sub_paths = self.process_path_prefixes(path);
178         let len = sub_paths.len();
179         if len <= 1 {
180             return;
181         }
182
183         let sub_paths = &sub_paths[..len-1];
184         for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
185             let qualname = if i == 0 && global && !path.global {
186                 format!("::{}", qualname)
187             } else {
188                 qualname.clone()
189             };
190             self.fmt.sub_mod_ref_str(path.span,
191                                      *span,
192                                      &qualname,
193                                      self.cur_scope);
194         }
195     }
196
197     // As write_sub_paths, but expects a path of the form module_path::trait::method
198     // Where trait could actually be a struct too.
199     fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
200         let sub_paths = self.process_path_prefixes(path);
201         let len = sub_paths.len();
202         if len <= 1 {
203             return;
204         }
205         let sub_paths = &sub_paths[.. (len-1)];
206
207         // write the trait part of the sub-path
208         let (ref span, ref qualname) = sub_paths[len-2];
209         self.fmt.sub_type_ref_str(path.span,
210                                   *span,
211                                   &qualname);
212
213         // write the other sub-paths
214         if len <= 2 {
215             return;
216         }
217         let sub_paths = &sub_paths[..len-2];
218         for &(ref span, ref qualname) in sub_paths {
219             self.fmt.sub_mod_ref_str(path.span,
220                                      *span,
221                                      &qualname,
222                                      self.cur_scope);
223         }
224     }
225
226     // looks up anything, not just a type
227     fn lookup_type_ref(&self, ref_id: NodeId) -> Option<DefId> {
228         if !self.tcx.def_map.borrow().contains_key(&ref_id) {
229             self.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
230                                   ref_id));
231         }
232         let def = self.tcx.def_map.borrow().get(&ref_id).unwrap().full_def();
233         match def {
234             def::DefPrimTy(_) => None,
235             _ => Some(def.def_id()),
236         }
237     }
238
239     fn lookup_def_kind(&self, ref_id: NodeId, span: Span) -> Option<recorder::Row> {
240         let def_map = self.tcx.def_map.borrow();
241         if !def_map.contains_key(&ref_id) {
242             self.sess.span_bug(span, &format!("def_map has no key for {} in lookup_def_kind",
243                                              ref_id));
244         }
245         let def = def_map.get(&ref_id).unwrap().full_def();
246         match def {
247             def::DefMod(_) |
248             def::DefForeignMod(_) => Some(recorder::ModRef),
249             def::DefStruct(_) => Some(recorder::TypeRef),
250             def::DefTy(..) |
251             def::DefAssociatedTy(..) |
252             def::DefTrait(_) => Some(recorder::TypeRef),
253             def::DefStatic(_, _) |
254             def::DefConst(_) |
255             def::DefAssociatedConst(..) |
256             def::DefLocal(_) |
257             def::DefVariant(_, _, _) |
258             def::DefUpvar(..) => Some(recorder::VarRef),
259
260             def::DefFn(..) => Some(recorder::FnRef),
261
262             def::DefSelfTy(..) |
263             def::DefRegion(_) |
264             def::DefLabel(_) |
265             def::DefTyParam(..) |
266             def::DefUse(_) |
267             def::DefMethod(..) |
268             def::DefPrimTy(_) => {
269                 self.sess.span_bug(span, &format!("lookup_def_kind for unexpected item: {:?}",
270                                                  def));
271             },
272         }
273     }
274
275     fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str) {
276         for arg in formals {
277             self.visit_pat(&arg.pat);
278             let mut collector = PathCollector::new();
279             collector.visit_pat(&arg.pat);
280             let span_utils = self.span.clone();
281             for &(id, ref p, _, _) in &collector.collected_paths {
282                 let typ = self.tcx.node_types().get(&id).unwrap().to_string();
283                 // get the span only for the name of the variable (I hope the path is only ever a
284                 // variable name, but who knows?)
285                 self.fmt.formal_str(p.span,
286                                     span_utils.span_for_last_ident(p.span),
287                                     id,
288                                     qualname,
289                                     &path_to_string(p),
290                                     &typ);
291             }
292         }
293     }
294
295     fn process_method(&mut self,
296                       sig: &ast::MethodSig,
297                       body: Option<&ast::Block>,
298                       id: ast::NodeId,
299                       name: ast::Name,
300                       span: Span) {
301         if generated_code(span) {
302             return;
303         }
304
305         debug!("process_method: {}:{}", id, token::get_name(name));
306
307         let method_data = self.save_ctxt.get_method_data(id, name, span);
308
309         if body.is_some() {
310             self.fmt.method_str(span,
311                                 Some(method_data.span),
312                                 method_data.id,
313                                 &method_data.qualname,
314                                 method_data.declaration,
315                                 method_data.scope);
316             self.process_formals(&sig.decl.inputs, &method_data.qualname);
317         } else {
318             self.fmt.method_decl_str(span,
319                                      Some(method_data.span),
320                                      method_data.id,
321                                      &method_data.qualname,
322                                      method_data.scope);
323         }
324
325         // walk arg and return types
326         for arg in &sig.decl.inputs {
327             self.visit_ty(&arg.ty);
328         }
329
330         if let ast::Return(ref ret_ty) = sig.decl.output {
331             self.visit_ty(ret_ty);
332         }
333
334         // walk the fn body
335         if let Some(body) = body {
336             self.nest(id, |v| v.visit_block(body));
337         }
338
339         self.process_generic_params(&sig.generics,
340                                     span,
341                                     &method_data.qualname,
342                                     id);
343     }
344
345     fn process_trait_ref(&mut self, trait_ref: &ast::TraitRef) {
346         let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref, self.cur_scope);
347         if let Some(trait_ref_data) = trait_ref_data {
348             self.fmt.ref_str(recorder::TypeRef,
349                              trait_ref.path.span,
350                              Some(trait_ref_data.span),
351                              trait_ref_data.ref_id,
352                              trait_ref_data.scope);
353             visit::walk_path(self, &trait_ref.path);
354         }
355     }
356
357     fn process_struct_field_def(&mut self,
358                                 field: &ast::StructField,
359                                 parent_id: NodeId) {
360         let field_data = self.save_ctxt.get_field_data(field, parent_id);
361         if let Some(field_data) = field_data {
362             self.fmt.field_str(field.span,
363                                Some(field_data.span),
364                                field_data.id,
365                                &field_data.name,
366                                &field_data.qualname,
367                                &field_data.type_value,
368                                field_data.scope);
369         }
370     }
371
372     // Dump generic params bindings, then visit_generics
373     fn process_generic_params(&mut self,
374                               generics:&ast::Generics,
375                               full_span: Span,
376                               prefix: &str,
377                               id: NodeId) {
378         // We can't only use visit_generics since we don't have spans for param
379         // bindings, so we reparse the full_span to get those sub spans.
380         // However full span is the entire enum/fn/struct block, so we only want
381         // the first few to match the number of generics we're looking for.
382         let param_sub_spans = self.span.spans_for_ty_params(full_span,
383                                                            (generics.ty_params.len() as isize));
384         for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
385             // Append $id to name to make sure each one is unique
386             let name = format!("{}::{}${}",
387                                prefix,
388                                escape(self.span.snippet(param_ss)),
389                                id);
390             self.fmt.typedef_str(full_span,
391                                  Some(param_ss),
392                                  param.id,
393                                  &name,
394                                  "");
395         }
396         self.visit_generics(generics);
397     }
398
399     fn process_fn(&mut self,
400                   item: &ast::Item,
401                   decl: &ast::FnDecl,
402                   ty_params: &ast::Generics,
403                   body: &ast::Block) {
404         let fn_data = self.save_ctxt.get_item_data(item);
405         down_cast_data!(fn_data, FunctionData, self, item.span);
406         self.fmt.fn_str(item.span,
407                         Some(fn_data.span),
408                         fn_data.id,
409                         &fn_data.qualname,
410                         fn_data.scope);
411
412
413         self.process_formals(&decl.inputs, &fn_data.qualname);
414         self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
415
416         for arg in &decl.inputs {
417             self.visit_ty(&arg.ty);
418         }
419
420         if let ast::Return(ref ret_ty) = decl.output {
421             self.visit_ty(&ret_ty);
422         }
423
424         self.nest(item.id, |v| v.visit_block(&body));
425     }
426
427     fn process_static_or_const_item(&mut self,
428                                     item: &ast::Item,
429                                     typ: &ast::Ty,
430                                     expr: &ast::Expr)
431     {
432         let var_data = self.save_ctxt.get_item_data(item);
433         down_cast_data!(var_data, VariableData, self, item.span);
434         self.fmt.static_str(item.span,
435                             Some(var_data.span),
436                             var_data.id,
437                             &var_data.name,
438                             &var_data.qualname,
439                             &var_data.value,
440                             &var_data.type_value,
441                             var_data.scope);
442
443         self.visit_ty(&typ);
444         self.visit_expr(expr);
445     }
446
447     fn process_const(&mut self,
448                      id: ast::NodeId,
449                      ident: &ast::Ident,
450                      span: Span,
451                      typ: &ast::Ty,
452                      expr: &ast::Expr)
453     {
454         let qualname = format!("::{}", self.tcx.map.path_to_string(id));
455
456         let sub_span = self.span.sub_span_after_keyword(span,
457                                                         keywords::Const);
458
459         self.fmt.static_str(span,
460                             sub_span,
461                             id,
462                             &get_ident((*ident).clone()),
463                             &qualname,
464                             &self.span.snippet(expr.span),
465                             &ty_to_string(&*typ),
466                             self.cur_scope);
467
468         // walk type and init value
469         self.visit_ty(typ);
470         self.visit_expr(expr);
471     }
472
473     fn process_struct(&mut self,
474                       item: &ast::Item,
475                       def: &ast::StructDef,
476                       ty_params: &ast::Generics) {
477         let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
478
479         let ctor_id = match def.ctor_id {
480             Some(node_id) => node_id,
481             None => ast::DUMMY_NODE_ID,
482         };
483         let val = self.span.snippet(item.span);
484         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
485         self.fmt.struct_str(item.span,
486                             sub_span,
487                             item.id,
488                             ctor_id,
489                             &qualname,
490                             self.cur_scope,
491                             &val);
492
493         // fields
494         for field in &def.fields {
495             self.process_struct_field_def(field, item.id);
496             self.visit_ty(&field.node.ty);
497         }
498
499         self.process_generic_params(ty_params, item.span, &qualname, item.id);
500     }
501
502     fn process_enum(&mut self,
503                     item: &ast::Item,
504                     enum_definition: &ast::EnumDef,
505                     ty_params: &ast::Generics) {
506         let enum_data = self.save_ctxt.get_item_data(item);
507         down_cast_data!(enum_data, EnumData, self, item.span);
508         self.fmt.enum_str(item.span,
509                           Some(enum_data.span),
510                           enum_data.id,
511                           &enum_data.qualname,
512                           enum_data.scope,
513                           &enum_data.value);
514
515         for variant in &enum_definition.variants {
516             let name = &get_ident(variant.node.name);
517             let mut qualname = enum_data.qualname.clone();
518             qualname.push_str("::");
519             qualname.push_str(name);
520             let val = self.span.snippet(variant.span);
521             match variant.node.kind {
522                 ast::TupleVariantKind(ref args) => {
523                     // first ident in span is the variant's name
524                     self.fmt.tuple_variant_str(variant.span,
525                                                self.span.span_for_first_ident(variant.span),
526                                                variant.node.id,
527                                                name,
528                                                &qualname,
529                                                &enum_data.qualname,
530                                                &val,
531                                                enum_data.id);
532                     for arg in args {
533                         self.visit_ty(&*arg.ty);
534                     }
535                 }
536                 ast::StructVariantKind(ref struct_def) => {
537                     let ctor_id = match struct_def.ctor_id {
538                         Some(node_id) => node_id,
539                         None => ast::DUMMY_NODE_ID,
540                     };
541                     self.fmt.struct_variant_str(variant.span,
542                                                 self.span.span_for_first_ident(variant.span),
543                                                 variant.node.id,
544                                                 ctor_id,
545                                                 &qualname,
546                                                 &enum_data.qualname,
547                                                 &val,
548                                                 enum_data.id);
549
550                     for field in &struct_def.fields {
551                         self.process_struct_field_def(field, variant.node.id);
552                         self.visit_ty(&*field.node.ty);
553                     }
554                 }
555             }
556         }
557         self.process_generic_params(ty_params, item.span, &enum_data.qualname, enum_data.id);
558     }
559
560     fn process_impl(&mut self,
561                     item: &ast::Item,
562                     type_parameters: &ast::Generics,
563                     trait_ref: &Option<ast::TraitRef>,
564                     typ: &ast::Ty,
565                     impl_items: &[P<ast::ImplItem>]) {
566         let impl_data = self.save_ctxt.get_item_data(item);
567         down_cast_data!(impl_data, ImplData, self, item.span);
568         match impl_data.self_ref {
569             Some(ref self_ref) => {
570                 self.fmt.ref_str(recorder::TypeRef,
571                                  item.span,
572                                  Some(self_ref.span),
573                                  self_ref.ref_id,
574                                  self_ref.scope);
575             }
576             None => {
577                 self.visit_ty(&typ);
578             }
579         }
580         if let Some(ref trait_ref_data) = impl_data.trait_ref {
581             self.fmt.ref_str(recorder::TypeRef,
582                              item.span,
583                              Some(trait_ref_data.span),
584                              trait_ref_data.ref_id,
585                              trait_ref_data.scope);
586             visit::walk_path(self, &trait_ref.as_ref().unwrap().path);
587         }
588
589         self.fmt.impl_str(item.span,
590                           Some(impl_data.span),
591                           impl_data.id,
592                           impl_data.self_ref.map(|data| data.ref_id),
593                           impl_data.trait_ref.map(|data| data.ref_id),
594                           impl_data.scope);
595
596         self.process_generic_params(type_parameters, item.span, "", item.id);
597         for impl_item in impl_items {
598             self.visit_impl_item(impl_item);
599         }
600     }
601
602     fn process_trait(&mut self,
603                      item: &ast::Item,
604                      generics: &ast::Generics,
605                      trait_refs: &OwnedSlice<ast::TyParamBound>,
606                      methods: &[P<ast::TraitItem>]) {
607         let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
608         let val = self.span.snippet(item.span);
609         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
610         self.fmt.trait_str(item.span,
611                            sub_span,
612                            item.id,
613                            &qualname,
614                            self.cur_scope,
615                            &val);
616
617         // super-traits
618         for super_bound in trait_refs.iter() {
619             let trait_ref = match *super_bound {
620                 ast::TraitTyParamBound(ref trait_ref, _) => {
621                     trait_ref
622                 }
623                 ast::RegionTyParamBound(..) => {
624                     continue;
625                 }
626             };
627
628             let trait_ref = &trait_ref.trait_ref;
629             match self.lookup_type_ref(trait_ref.ref_id) {
630                 Some(id) => {
631                     let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
632                     self.fmt.ref_str(recorder::TypeRef,
633                                      trait_ref.path.span,
634                                      sub_span,
635                                      id,
636                                      self.cur_scope);
637                     self.fmt.inherit_str(trait_ref.path.span,
638                                          sub_span,
639                                          id,
640                                          item.id);
641                 },
642                 None => ()
643             }
644         }
645
646         // walk generics and methods
647         self.process_generic_params(generics, item.span, &qualname, item.id);
648         for method in methods {
649             self.visit_trait_item(method)
650         }
651     }
652
653     fn process_mod(&mut self,
654                    item: &ast::Item) {  // The module in question, represented as an item.
655         let mod_data = self.save_ctxt.get_item_data(item);
656         down_cast_data!(mod_data, ModData, self, item.span);
657         self.fmt.mod_str(item.span,
658                          Some(mod_data.span),
659                          mod_data.id,
660                          &mod_data.qualname,
661                          mod_data.scope,
662                          &mod_data.filename);
663     }
664
665     fn process_path(&mut self,
666                     id: NodeId,
667                     path: &ast::Path,
668                     ref_kind: Option<recorder::Row>) {
669         if generated_code(path.span) {
670             return;
671         }
672
673         let path_data = self.save_ctxt.get_path_data(id, path);
674         match path_data {
675             Data::VariableRefData(ref vrd) => {
676                 self.fmt.ref_str(ref_kind.unwrap_or(recorder::VarRef),
677                                                     path.span,
678                                                     Some(vrd.span),
679                                                     vrd.ref_id,
680                                                     vrd.scope);
681
682             }
683             Data::TypeRefData(ref trd) => {
684                 self.fmt.ref_str(recorder::TypeRef,
685                                  path.span,
686                                  Some(trd.span),
687                                  trd.ref_id,
688                                  trd.scope);
689             }
690             Data::MethodCallData(ref mcd) => {
691                 self.fmt.meth_call_str(path.span,
692                                        Some(mcd.span),
693                                        mcd.ref_id,
694                                        mcd.decl_id,
695                                        mcd.scope);
696             }
697             Data::FunctionCallData(fcd) => {
698                 self.fmt.fn_call_str(path.span,
699                                      Some(fcd.span),
700                                      fcd.ref_id,
701                                      fcd.scope);
702             }
703             _ => {
704                 self.sess.span_bug(path.span,
705                                    &format!("Unexpected data: {:?}", path_data));
706             }
707         }
708
709         // Modules or types in the path prefix.
710         let def_map = self.tcx.def_map.borrow();
711         let def = def_map.get(&id).unwrap().full_def();
712         match def {
713             def::DefMethod(did, _) => {
714                 let ti = self.tcx.impl_or_trait_item(did);
715                 if let ty::MethodTraitItem(m) = ti {
716                     if m.explicit_self == ty::StaticExplicitSelfCategory {
717                         self.write_sub_path_trait_truncated(path);
718                     }
719                 }
720             }
721             def::DefLocal(_) |
722             def::DefStatic(_,_) |
723             def::DefConst(..) |
724             def::DefAssociatedConst(..) |
725             def::DefStruct(_) |
726             def::DefVariant(..) |
727             def::DefFn(..) => self.write_sub_paths_truncated(path, false),
728             _ => {},
729         }
730     }
731
732     fn process_struct_lit(&mut self,
733                           ex: &ast::Expr,
734                           path: &ast::Path,
735                           fields: &Vec<ast::Field>,
736                           base: &Option<P<ast::Expr>>) {
737         if generated_code(path.span) {
738             return
739         }
740
741         self.write_sub_paths_truncated(path, false);
742
743         if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
744             down_cast_data!(struct_lit_data, TypeRefData, self, ex.span);
745             self.fmt.ref_str(recorder::TypeRef,
746                              ex.span,
747                              Some(struct_lit_data.span),
748                              struct_lit_data.ref_id,
749                              struct_lit_data.scope);
750             let struct_def = struct_lit_data.ref_id;
751             let scope = self.save_ctxt.enclosing_scope(ex.id);
752
753             for field in fields {
754                 if generated_code(field.ident.span) {
755                     continue;
756                 }
757
758                 let field_data = self.save_ctxt.get_field_ref_data(field,
759                                                                    struct_def,
760                                                                    scope);
761                 self.fmt.ref_str(recorder::VarRef,
762                                  field.ident.span,
763                                  Some(field_data.span),
764                                  field_data.ref_id,
765                                  field_data.scope);
766
767                 self.visit_expr(&field.expr)
768             }
769         }
770
771         visit::walk_expr_opt(self, base)
772     }
773
774     fn process_method_call(&mut self,
775                            ex: &ast::Expr,
776                            args: &Vec<P<ast::Expr>>) {
777         if let Some(call_data) = self.save_ctxt.get_expr_data(ex) {
778             down_cast_data!(call_data, MethodCallData, self, ex.span);
779             self.fmt.meth_call_str(ex.span,
780                                    Some(call_data.span),
781                                    call_data.ref_id,
782                                    call_data.decl_id,
783                                    call_data.scope);
784         }
785
786         // walk receiver and args
787         visit::walk_exprs(self, &args);
788     }
789
790     fn process_pat(&mut self, p:&ast::Pat) {
791         if generated_code(p.span) {
792             return;
793         }
794
795         match p.node {
796             ast::PatStruct(ref path, ref fields, _) => {
797                 visit::walk_path(self, path);
798
799                 let def = self.tcx.def_map.borrow().get(&p.id).unwrap().full_def();
800                 let struct_def = match def {
801                     def::DefConst(..) | def::DefAssociatedConst(..) => None,
802                     def::DefVariant(_, variant_id, _) => Some(variant_id),
803                     _ => {
804                         match self.tcx.node_id_to_type(p.id).ty_to_def_id() {
805                             None => {
806                                 self.sess.span_bug(p.span,
807                                                    &format!("Could not find struct_def for `{}`",
808                                                             self.span.snippet(p.span)));
809                             }
810                             Some(def_id) => Some(def_id),
811                         }
812                     }
813                 };
814
815                 if let Some(struct_def) = struct_def {
816                     let struct_fields = self.tcx.lookup_struct_fields(struct_def);
817                     for &Spanned { node: ref field, span } in fields {
818                         if generated_code(span) {
819                             continue;
820                         }
821
822                         let sub_span = self.span.span_for_first_ident(span);
823                         for f in &struct_fields {
824                             if f.name == field.ident.name {
825                                 self.fmt.ref_str(recorder::VarRef,
826                                                  span,
827                                                  sub_span,
828                                                  f.id,
829                                                  self.cur_scope);
830                                 break;
831                             }
832                         }
833                         self.visit_pat(&field.pat);
834                     }
835                 }
836             }
837             _ => visit::walk_pat(self, p)
838         }
839     }
840 }
841
842 impl<'l, 'tcx, 'v> Visitor<'v> for DumpCsvVisitor<'l, 'tcx> {
843     fn visit_item(&mut self, item: &ast::Item) {
844         if generated_code(item.span) {
845             return
846         }
847
848         match item.node {
849             ast::ItemUse(ref use_item) => {
850                 match use_item.node {
851                     ast::ViewPathSimple(ident, ref path) => {
852                         let sub_span = self.span.span_for_last_ident(path.span);
853                         let mod_id = match self.lookup_type_ref(item.id) {
854                             Some(def_id) => {
855                                 match self.lookup_def_kind(item.id, path.span) {
856                                     Some(kind) => self.fmt.ref_str(kind,
857                                                                    path.span,
858                                                                    sub_span,
859                                                                    def_id,
860                                                                    self.cur_scope),
861                                     None => {},
862                                 }
863                                 Some(def_id)
864                             },
865                             None => None,
866                         };
867
868                         // 'use' always introduces an alias, if there is not an explicit
869                         // one, there is an implicit one.
870                         let sub_span =
871                             match self.span.sub_span_after_keyword(use_item.span, keywords::As) {
872                                 Some(sub_span) => Some(sub_span),
873                                 None => sub_span,
874                             };
875
876                         self.fmt.use_alias_str(path.span,
877                                                sub_span,
878                                                item.id,
879                                                mod_id,
880                                                &get_ident(ident),
881                                                self.cur_scope);
882                         self.write_sub_paths_truncated(path, true);
883                     }
884                     ast::ViewPathGlob(ref path) => {
885                         // Make a comma-separated list of names of imported modules.
886                         let mut name_string = String::new();
887                         let glob_map = &self.analysis.glob_map;
888                         let glob_map = glob_map.as_ref().unwrap();
889                         if glob_map.contains_key(&item.id) {
890                             for n in glob_map.get(&item.id).unwrap() {
891                                 if !name_string.is_empty() {
892                                     name_string.push_str(", ");
893                                 }
894                                 name_string.push_str(n.as_str());
895                             }
896                         }
897
898                         let sub_span = self.span.sub_span_of_token(path.span,
899                                                                    token::BinOp(token::Star));
900                         self.fmt.use_glob_str(path.span,
901                                               sub_span,
902                                               item.id,
903                                               &name_string,
904                                               self.cur_scope);
905                         self.write_sub_paths(path, true);
906                     }
907                     ast::ViewPathList(ref path, ref list) => {
908                         for plid in list {
909                             match plid.node {
910                                 ast::PathListIdent { id, .. } => {
911                                     match self.lookup_type_ref(id) {
912                                         Some(def_id) =>
913                                             match self.lookup_def_kind(id, plid.span) {
914                                                 Some(kind) => {
915                                                     self.fmt.ref_str(
916                                                         kind, plid.span,
917                                                         Some(plid.span),
918                                                         def_id, self.cur_scope);
919                                                 }
920                                                 None => ()
921                                             },
922                                         None => ()
923                                     }
924                                 },
925                                 ast::PathListMod { .. } => ()
926                             }
927                         }
928
929                         self.write_sub_paths(path, true);
930                     }
931                 }
932             }
933             ast::ItemExternCrate(ref s) => {
934                 let name = get_ident(item.ident);
935                 let name = &name;
936                 let location = match *s {
937                     Some(s) => s.to_string(),
938                     None => name.to_string(),
939                 };
940                 let alias_span = self.span.span_for_last_ident(item.span);
941                 let cnum = match self.sess.cstore.find_extern_mod_stmt_cnum(item.id) {
942                     Some(cnum) => cnum,
943                     None => 0,
944                 };
945                 self.fmt.extern_crate_str(item.span,
946                                           alias_span,
947                                           item.id,
948                                           cnum,
949                                           name,
950                                           &location,
951                                           self.cur_scope);
952             }
953             ast::ItemFn(ref decl, _, _, _, ref ty_params, ref body) =>
954                 self.process_fn(item, &**decl, ty_params, &**body),
955             ast::ItemStatic(ref typ, _, ref expr) =>
956                 self.process_static_or_const_item(item, typ, expr),
957             ast::ItemConst(ref typ, ref expr) =>
958                 self.process_static_or_const_item(item, &typ, &expr),
959             ast::ItemStruct(ref def, ref ty_params) => self.process_struct(item, &**def, ty_params),
960             ast::ItemEnum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
961             ast::ItemImpl(_, _,
962                           ref ty_params,
963                           ref trait_ref,
964                           ref typ,
965                           ref impl_items) => {
966                 self.process_impl(item,
967                                   ty_params,
968                                   trait_ref,
969                                   &typ,
970                                   impl_items)
971             }
972             ast::ItemTrait(_, ref generics, ref trait_refs, ref methods) =>
973                 self.process_trait(item, generics, trait_refs, methods),
974             ast::ItemMod(ref m) => {
975                 self.process_mod(item);
976                 self.nest(item.id, |v| visit::walk_mod(v, m));
977             }
978             ast::ItemTy(ref ty, ref ty_params) => {
979                 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
980                 let value = ty_to_string(&**ty);
981                 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
982                 self.fmt.typedef_str(item.span,
983                                      sub_span,
984                                      item.id,
985                                      &qualname,
986                                      &value);
987
988                 self.visit_ty(&**ty);
989                 self.process_generic_params(ty_params, item.span, &qualname, item.id);
990             },
991             ast::ItemMac(_) => (),
992             _ => visit::walk_item(self, item),
993         }
994     }
995
996     fn visit_generics(&mut self, generics: &ast::Generics) {
997         for param in generics.ty_params.iter() {
998             for bound in param.bounds.iter() {
999                 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
1000                     self.process_trait_ref(&trait_ref.trait_ref);
1001                 }
1002             }
1003             if let Some(ref ty) = param.default {
1004                 self.visit_ty(&**ty);
1005             }
1006         }
1007     }
1008
1009     fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
1010         match trait_item.node {
1011             ast::ConstTraitItem(ref ty, Some(ref expr)) => {
1012                 self.process_const(trait_item.id, &trait_item.ident,
1013                                    trait_item.span, &*ty, &*expr);
1014             }
1015             ast::MethodTraitItem(ref sig, ref body) => {
1016                 self.process_method(sig,
1017                                     body.as_ref().map(|x| &**x),
1018                                     trait_item.id,
1019                                     trait_item.ident.name,
1020                                     trait_item.span);
1021             }
1022             ast::ConstTraitItem(_, None) |
1023             ast::TypeTraitItem(..) => {}
1024         }
1025     }
1026
1027     fn visit_impl_item(&mut self, impl_item: &ast::ImplItem) {
1028         match impl_item.node {
1029             ast::ConstImplItem(ref ty, ref expr) => {
1030                 self.process_const(impl_item.id, &impl_item.ident,
1031                                    impl_item.span, &ty, &expr);
1032             }
1033             ast::MethodImplItem(ref sig, ref body) => {
1034                 self.process_method(sig,
1035                                     Some(body),
1036                                     impl_item.id,
1037                                     impl_item.ident.name,
1038                                     impl_item.span);
1039             }
1040             ast::TypeImplItem(_) |
1041             ast::MacImplItem(_) => {}
1042         }
1043     }
1044
1045     fn visit_ty(&mut self, t: &ast::Ty) {
1046         if generated_code(t.span) {
1047             return
1048         }
1049
1050         match t.node {
1051             ast::TyPath(_, ref path) => {
1052                 match self.lookup_type_ref(t.id) {
1053                     Some(id) => {
1054                         let sub_span = self.span.sub_span_for_type_name(t.span);
1055                         self.fmt.ref_str(recorder::TypeRef,
1056                                          t.span,
1057                                          sub_span,
1058                                          id,
1059                                          self.cur_scope);
1060                     },
1061                     None => ()
1062                 }
1063
1064                 self.write_sub_paths_truncated(path, false);
1065
1066                 visit::walk_path(self, path);
1067             },
1068             _ => visit::walk_ty(self, t),
1069         }
1070     }
1071
1072     fn visit_expr(&mut self, ex: &ast::Expr) {
1073         if generated_code(ex.span) {
1074             return
1075         }
1076
1077         match ex.node {
1078             ast::ExprCall(ref _f, ref _args) => {
1079                 // Don't need to do anything for function calls,
1080                 // because just walking the callee path does what we want.
1081                 visit::walk_expr(self, ex);
1082             }
1083             ast::ExprPath(_, ref path) => {
1084                 self.process_path(ex.id, path, None);
1085                 visit::walk_expr(self, ex);
1086             }
1087             ast::ExprStruct(ref path, ref fields, ref base) =>
1088                 self.process_struct_lit(ex, path, fields, base),
1089             ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, args),
1090             ast::ExprField(ref sub_ex, _) => {
1091                 if generated_code(sub_ex.span) {
1092                     return
1093                 }
1094
1095                 self.visit_expr(&sub_ex);
1096
1097                 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1098                     down_cast_data!(field_data, VariableRefData, self, ex.span);
1099                     self.fmt.ref_str(recorder::VarRef,
1100                                      ex.span,
1101                                      Some(field_data.span),
1102                                      field_data.ref_id,
1103                                      field_data.scope);
1104                 }
1105             },
1106             ast::ExprTupField(ref sub_ex, idx) => {
1107                 if generated_code(sub_ex.span) {
1108                     return
1109                 }
1110
1111                 self.visit_expr(&**sub_ex);
1112
1113                 let ty = &self.tcx.expr_ty_adjusted(&**sub_ex).sty;
1114                 match *ty {
1115                     ty::TyStruct(def_id, _) => {
1116                         let fields = self.tcx.lookup_struct_fields(def_id);
1117                         for (i, f) in fields.iter().enumerate() {
1118                             if i == idx.node {
1119                                 let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1120                                 self.fmt.ref_str(recorder::VarRef,
1121                                                  ex.span,
1122                                                  sub_span,
1123                                                  f.id,
1124                                                  self.cur_scope);
1125                                 break;
1126                             }
1127                         }
1128                     }
1129                     ty::TyTuple(_) => {}
1130                     _ => self.sess.span_bug(ex.span,
1131                                             &format!("Expected struct or tuple \
1132                                                       type, found {:?}", ty)),
1133                 }
1134             },
1135             ast::ExprClosure(_, ref decl, ref body) => {
1136                 if generated_code(body.span) {
1137                     return
1138                 }
1139
1140                 let mut id = String::from("$");
1141                 id.push_str(&ex.id.to_string());
1142                 self.process_formals(&decl.inputs, &id);
1143
1144                 // walk arg and return types
1145                 for arg in &decl.inputs {
1146                     self.visit_ty(&*arg.ty);
1147                 }
1148
1149                 if let ast::Return(ref ret_ty) = decl.output {
1150                     self.visit_ty(&**ret_ty);
1151                 }
1152
1153                 // walk the body
1154                 self.nest(ex.id, |v| v.visit_block(&**body));
1155             },
1156             _ => {
1157                 visit::walk_expr(self, ex)
1158             }
1159         }
1160     }
1161
1162     fn visit_mac(&mut self, _: &ast::Mac) {
1163         // Just stop, macros are poison to us.
1164     }
1165
1166     fn visit_pat(&mut self, p: &ast::Pat) {
1167         self.process_pat(p);
1168     }
1169
1170     fn visit_arm(&mut self, arm: &ast::Arm) {
1171         let mut collector = PathCollector::new();
1172         for pattern in &arm.pats {
1173             // collect paths from the arm's patterns
1174             collector.visit_pat(&pattern);
1175             self.visit_pat(&pattern);
1176         }
1177
1178         // This is to get around borrow checking, because we need mut self to call process_path.
1179         let mut paths_to_process = vec![];
1180
1181         // process collected paths
1182         for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1183             let def_map = self.tcx.def_map.borrow();
1184             if !def_map.contains_key(&id) {
1185                 self.sess.span_bug(p.span,
1186                                    &format!("def_map has no key for {} in visit_arm",
1187                                            id));
1188             }
1189             let def = def_map.get(&id).unwrap().full_def();
1190             match def {
1191                 def::DefLocal(id)  => {
1192                     let value = if immut == ast::MutImmutable {
1193                         self.span.snippet(p.span).to_string()
1194                     } else {
1195                         "<mutable>".to_string()
1196                     };
1197
1198                     assert!(p.segments.len() == 1, "qualified path for local variable def in arm");
1199                     self.fmt.variable_str(p.span,
1200                                           Some(p.span),
1201                                           id,
1202                                           &path_to_string(p),
1203                                           &value,
1204                                           "")
1205                 }
1206                 def::DefVariant(..) | def::DefTy(..) | def::DefStruct(..) => {
1207                     paths_to_process.push((id, p.clone(), Some(ref_kind)))
1208                 }
1209                 // FIXME(nrc) what are these doing here?
1210                 def::DefStatic(_, _) |
1211                 def::DefConst(..) |
1212                 def::DefAssociatedConst(..) => {}
1213                 _ => error!("unexpected definition kind when processing collected paths: {:?}",
1214                             def)
1215             }
1216         }
1217
1218         for &(id, ref path, ref_kind) in &paths_to_process {
1219             self.process_path(id, path, ref_kind);
1220         }
1221         visit::walk_expr_opt(self, &arm.guard);
1222         self.visit_expr(&arm.body);
1223     }
1224
1225     fn visit_stmt(&mut self, s: &ast::Stmt) {
1226         if generated_code(s.span) {
1227             return
1228         }
1229
1230         visit::walk_stmt(self, s)
1231     }
1232
1233     fn visit_local(&mut self, l: &ast::Local) {
1234         if generated_code(l.span) {
1235             return
1236         }
1237
1238         // The local could declare multiple new vars, we must walk the
1239         // pattern and collect them all.
1240         let mut collector = PathCollector::new();
1241         collector.visit_pat(&l.pat);
1242         self.visit_pat(&l.pat);
1243
1244         let value = self.span.snippet(l.span);
1245
1246         for &(id, ref p, immut, _) in &collector.collected_paths {
1247             let value = if immut == ast::MutImmutable {
1248                 value.to_string()
1249             } else {
1250                 "<mutable>".to_string()
1251             };
1252             let types = self.tcx.node_types();
1253             let typ = types.get(&id).unwrap().to_string();
1254             // Get the span only for the name of the variable (I hope the path
1255             // is only ever a variable name, but who knows?).
1256             let sub_span = self.span.span_for_last_ident(p.span);
1257             // Rust uses the id of the pattern for var lookups, so we'll use it too.
1258             self.fmt.variable_str(p.span,
1259                                   sub_span,
1260                                   id,
1261                                   &path_to_string(p),
1262                                   &value,
1263                                   &typ);
1264         }
1265
1266         // Just walk the initialiser and type (don't want to walk the pattern again).
1267         visit::walk_ty_opt(self, &l.ty);
1268         visit::walk_expr_opt(self, &l.init);
1269     }
1270 }