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