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