]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/save/dump_csv.rs
Remove unused imports
[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::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::owned_slice::OwnedSlice;
45 use syntax::visit::{self, Visitor};
46 use syntax::print::pprust::{path_to_string, ty_to_string};
47 use syntax::ptr::P;
48
49 use rustc_front::lowering::{lower_expr, LoweringContext};
50
51 use super::span_utils::SpanUtils;
52 use super::recorder::{Recorder, FmtStrs};
53
54 macro_rules! down_cast_data {
55     ($id:ident, $kind:ident, $this:ident, $sp:expr) => {
56         let $id = if let super::Data::$kind(data) = $id {
57             data
58         } else {
59             $this.sess.span_bug($sp, &format!("unexpected data kind: {:?}", $id));
60         }
61     };
62 }
63
64 pub struct DumpCsvVisitor<'l, 'tcx: 'l> {
65     save_ctxt: SaveContext<'l, 'tcx>,
66     sess: &'l Session,
67     tcx: &'l ty::ctxt<'tcx>,
68     analysis: &'l ty::CrateAnalysis<'l>,
69
70     span: SpanUtils<'l>,
71     fmt: FmtStrs<'l, 'tcx>,
72
73     cur_scope: NodeId,
74 }
75
76 impl <'l, 'tcx> DumpCsvVisitor<'l, 'tcx> {
77     pub fn new(tcx: &'l ty::ctxt<'tcx>,
78                lcx: &'l LoweringContext<'l>,
79                analysis: &'l ty::CrateAnalysis<'l>,
80                output_file: Box<File>)
81                -> DumpCsvVisitor<'l, 'tcx> {
82         let span_utils = SpanUtils::new(&tcx.sess);
83         DumpCsvVisitor {
84             sess: &tcx.sess,
85             tcx: tcx,
86             save_ctxt: SaveContext::from_span_utils(tcx, lcx, 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                               },
93                               span_utils,
94                               tcx),
95             cur_scope: 0,
96         }
97     }
98
99     fn nest<F>(&mut self, scope_id: NodeId, f: F)
100         where F: FnOnce(&mut DumpCsvVisitor<'l, 'tcx>)
101     {
102         let parent_scope = self.cur_scope;
103         self.cur_scope = scope_id;
104         f(self);
105         self.cur_scope = parent_scope;
106     }
107
108     pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
109         let source_file = self.tcx.sess.local_crate_source_file.as_ref();
110         let crate_root = match source_file {
111             Some(source_file) => match source_file.file_name() {
112                 Some(_) => source_file.parent().unwrap().display().to_string(),
113                 None => source_file.display().to_string(),
114             },
115             None => "<no source>".to_owned(),
116         };
117
118         // The current crate.
119         self.fmt.crate_str(krate.span, name, &crate_root);
120
121         // Dump info about all the external crates referenced from this crate.
122         for c in &self.save_ctxt.get_external_crates() {
123             self.fmt.external_crate_str(krate.span, &c.name, c.number);
124         }
125         self.fmt.recorder.record("end_external_crates\n");
126     }
127
128     // Return all non-empty prefixes of a path.
129     // For each prefix, we return the span for the last segment in the prefix and
130     // a str representation of the entire prefix.
131     fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
132         let spans = self.span.spans_for_path_segments(path);
133
134         // Paths to enums seem to not match their spans - the span includes all the
135         // variants too. But they seem to always be at the end, so I hope we can cope with
136         // always using the first ones. So, only error out if we don't have enough spans.
137         // What could go wrong...?
138         if spans.len() < path.segments.len() {
139             error!("Mis-calculated spans for path '{}'. Found {} spans, expected {}. Found spans:",
140                    path_to_string(path),
141                    spans.len(),
142                    path.segments.len());
143             for s in &spans {
144                 let loc = self.sess.codemap().lookup_char_pos(s.lo);
145                 error!("    '{}' in {}, line {}",
146                        self.span.snippet(*s),
147                        loc.file.name,
148                        loc.line);
149             }
150             return vec!();
151         }
152
153         let mut result: Vec<(Span, String)> = vec!();
154
155         let mut segs = vec!();
156         for (i, (seg, span)) in path.segments.iter().zip(&spans).enumerate() {
157             segs.push(seg.clone());
158             let sub_path = ast::Path {
159                 span: *span, // span for the last segment
160                 global: path.global,
161                 segments: segs,
162             };
163             let qualname = if i == 0 && path.global {
164                 format!("::{}", path_to_string(&sub_path))
165             } else {
166                 path_to_string(&sub_path)
167             };
168             result.push((*span, qualname));
169             segs = sub_path.segments;
170         }
171
172         result
173     }
174
175     // The global arg allows us to override the global-ness of the path (which
176     // actually means 'does the path start with `::`', rather than 'is the path
177     // semantically global). We use the override for `use` imports (etc.) where
178     // the syntax is non-global, but the semantics are global.
179     fn write_sub_paths(&mut self, path: &ast::Path, global: bool) {
180         let sub_paths = self.process_path_prefixes(path);
181         for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
182             let qualname = if i == 0 && global && !path.global {
183                 format!("::{}", qualname)
184             } else {
185                 qualname.clone()
186             };
187             self.fmt.sub_mod_ref_str(path.span, *span, &qualname, self.cur_scope);
188         }
189     }
190
191     // As write_sub_paths, but does not process the last ident in the path (assuming it
192     // will be processed elsewhere). See note on write_sub_paths about global.
193     fn write_sub_paths_truncated(&mut self, path: &ast::Path, global: bool) {
194         let sub_paths = self.process_path_prefixes(path);
195         let len = sub_paths.len();
196         if len <= 1 {
197             return;
198         }
199
200         let sub_paths = &sub_paths[..len-1];
201         for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
202             let qualname = if i == 0 && global && !path.global {
203                 format!("::{}", qualname)
204             } else {
205                 qualname.clone()
206             };
207             self.fmt.sub_mod_ref_str(path.span, *span, &qualname, self.cur_scope);
208         }
209     }
210
211     // As write_sub_paths, but expects a path of the form module_path::trait::method
212     // Where trait could actually be a struct too.
213     fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
214         let sub_paths = self.process_path_prefixes(path);
215         let len = sub_paths.len();
216         if len <= 1 {
217             return;
218         }
219         let sub_paths = &sub_paths[.. (len-1)];
220
221         // write the trait part of the sub-path
222         let (ref span, ref qualname) = sub_paths[len-2];
223         self.fmt.sub_type_ref_str(path.span, *span, &qualname);
224
225         // write the other sub-paths
226         if len <= 2 {
227             return;
228         }
229         let sub_paths = &sub_paths[..len-2];
230         for &(ref span, ref qualname) in sub_paths {
231             self.fmt.sub_mod_ref_str(path.span, *span, &qualname, self.cur_scope);
232         }
233     }
234
235     // looks up anything, not just a type
236     fn lookup_type_ref(&self, ref_id: NodeId) -> Option<DefId> {
237         if !self.tcx.def_map.borrow().contains_key(&ref_id) {
238             self.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
239                                    ref_id));
240         }
241         let def = self.tcx.def_map.borrow().get(&ref_id).unwrap().full_def();
242         match def {
243             def::DefPrimTy(..) => None,
244             def::DefSelfTy(..) => None,
245             _ => Some(def.def_id()),
246         }
247     }
248
249     fn lookup_def_kind(&self, ref_id: NodeId, span: Span) -> Option<recorder::Row> {
250         let def_map = self.tcx.def_map.borrow();
251         if !def_map.contains_key(&ref_id) {
252             self.sess.span_bug(span,
253                                &format!("def_map has no key for {} in lookup_def_kind",
254                                         ref_id));
255         }
256         let def = def_map.get(&ref_id).unwrap().full_def();
257         match def {
258             def::DefMod(_) |
259             def::DefForeignMod(_) => Some(recorder::ModRef),
260             def::DefStruct(_) => Some(recorder::TypeRef),
261             def::DefTy(..) |
262             def::DefAssociatedTy(..) |
263             def::DefTrait(_) => Some(recorder::TypeRef),
264             def::DefStatic(_, _) |
265             def::DefConst(_) |
266             def::DefAssociatedConst(..) |
267             def::DefLocal(..) |
268             def::DefVariant(_, _, _) |
269             def::DefUpvar(..) => Some(recorder::VarRef),
270
271             def::DefFn(..) => Some(recorder::FnRef),
272
273             def::DefSelfTy(..) |
274             def::DefLabel(_) |
275             def::DefTyParam(..) |
276             def::DefUse(_) |
277             def::DefMethod(..) |
278             def::DefPrimTy(_) |
279             def::DefErr => {
280                 self.sess.span_bug(span,
281                                    &format!("lookup_def_kind for unexpected item: {:?}", def));
282             }
283         }
284     }
285
286     fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str) {
287         for arg in formals {
288             self.visit_pat(&arg.pat);
289             let mut collector = PathCollector::new();
290             collector.visit_pat(&arg.pat);
291             let span_utils = self.span.clone();
292             for &(id, ref p, _, _) in &collector.collected_paths {
293                 let typ = self.tcx.node_types().get(&id).unwrap().to_string();
294                 // get the span only for the name of the variable (I hope the path is only ever a
295                 // variable name, but who knows?)
296                 self.fmt.formal_str(p.span,
297                                     span_utils.span_for_last_ident(p.span),
298                                     id,
299                                     qualname,
300                                     &path_to_string(p),
301                                     &typ);
302             }
303         }
304     }
305
306     fn process_method(&mut self,
307                       sig: &ast::MethodSig,
308                       body: Option<&ast::Block>,
309                       id: ast::NodeId,
310                       name: ast::Name,
311                       span: Span) {
312         if generated_code(span) {
313             return;
314         }
315
316         debug!("process_method: {}:{}", id, name);
317
318         let method_data = self.save_ctxt.get_method_data(id, name, span);
319
320         if body.is_some() {
321             self.fmt.method_str(span,
322                                 Some(method_data.span),
323                                 method_data.id,
324                                 &method_data.qualname,
325                                 method_data.declaration,
326                                 method_data.scope);
327             self.process_formals(&sig.decl.inputs, &method_data.qualname);
328         } else {
329             self.fmt.method_decl_str(span,
330                                      Some(method_data.span),
331                                      method_data.id,
332                                      &method_data.qualname,
333                                      method_data.scope);
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         self.process_generic_params(&sig.generics, span, &method_data.qualname, id);
351     }
352
353     fn process_trait_ref(&mut self, trait_ref: &ast::TraitRef) {
354         let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref, self.cur_scope);
355         if let Some(trait_ref_data) = trait_ref_data {
356             self.fmt.ref_str(recorder::TypeRef,
357                              trait_ref.path.span,
358                              Some(trait_ref_data.span),
359                              trait_ref_data.ref_id,
360                              trait_ref_data.scope);
361             visit::walk_path(self, &trait_ref.path);
362         }
363     }
364
365     fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
366         let field_data = self.save_ctxt.get_field_data(field, parent_id);
367         if let Some(field_data) = field_data {
368             self.fmt.field_str(field.span,
369                                Some(field_data.span),
370                                field_data.id,
371                                &field_data.name,
372                                &field_data.qualname,
373                                &field_data.type_value,
374                                field_data.scope);
375         }
376     }
377
378     // Dump generic params bindings, then visit_generics
379     fn process_generic_params(&mut self,
380                               generics: &ast::Generics,
381                               full_span: Span,
382                               prefix: &str,
383                               id: NodeId) {
384         // We can't only use visit_generics since we don't have spans for param
385         // bindings, so we reparse the full_span to get those sub spans.
386         // However full span is the entire enum/fn/struct block, so we only want
387         // the first few to match the number of generics we're looking for.
388         let param_sub_spans = self.span.spans_for_ty_params(full_span,
389                                                             (generics.ty_params.len() as isize));
390         for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
391             // Append $id to name to make sure each one is unique
392             let name = format!("{}::{}${}",
393                                prefix,
394                                escape(self.span.snippet(param_ss)),
395                                id);
396             self.fmt.typedef_str(full_span, Some(param_ss), param.id, &name, "");
397         }
398         self.visit_generics(generics);
399     }
400
401     fn process_fn(&mut self,
402                   item: &ast::Item,
403                   decl: &ast::FnDecl,
404                   ty_params: &ast::Generics,
405                   body: &ast::Block) {
406         let fn_data = self.save_ctxt.get_item_data(item);
407         down_cast_data!(fn_data, FunctionData, self, item.span);
408         self.fmt.fn_str(item.span,
409                         Some(fn_data.span),
410                         fn_data.id,
411                         &fn_data.qualname,
412                         fn_data.scope);
413
414
415         self.process_formals(&decl.inputs, &fn_data.qualname);
416         self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
417
418         for arg in &decl.inputs {
419             self.visit_ty(&arg.ty);
420         }
421
422         if let ast::Return(ref ret_ty) = decl.output {
423             self.visit_ty(&ret_ty);
424         }
425
426         self.nest(item.id, |v| v.visit_block(&body));
427     }
428
429     fn process_static_or_const_item(&mut self, item: &ast::Item, typ: &ast::Ty, expr: &ast::Expr) {
430         let var_data = self.save_ctxt.get_item_data(item);
431         down_cast_data!(var_data, VariableData, self, item.span);
432         self.fmt.static_str(item.span,
433                             Some(var_data.span),
434                             var_data.id,
435                             &var_data.name,
436                             &var_data.qualname,
437                             &var_data.value,
438                             &var_data.type_value,
439                             var_data.scope);
440
441         self.visit_ty(&typ);
442         self.visit_expr(expr);
443     }
444
445     fn process_const(&mut self,
446                      id: ast::NodeId,
447                      name: ast::Name,
448                      span: Span,
449                      typ: &ast::Ty,
450                      expr: &ast::Expr) {
451         let qualname = format!("::{}", self.tcx.map.path_to_string(id));
452
453         let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
454
455         self.fmt.static_str(span,
456                             sub_span,
457                             id,
458                             &name.as_str(),
459                             &qualname,
460                             &self.span.snippet(expr.span),
461                             &ty_to_string(&*typ),
462                             self.cur_scope);
463
464         // walk type and init value
465         self.visit_ty(typ);
466         self.visit_expr(expr);
467     }
468
469     fn process_struct(&mut self,
470                       item: &ast::Item,
471                       def: &ast::VariantData,
472                       ty_params: &ast::Generics) {
473         let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
474
475         let val = self.span.snippet(item.span);
476         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
477         self.fmt.struct_str(item.span,
478                             sub_span,
479                             item.id,
480                             def.id(),
481                             &qualname,
482                             self.cur_scope,
483                             &val);
484
485         // fields
486         for field in def.fields() {
487             self.process_struct_field_def(field, item.id);
488             self.visit_ty(&field.node.ty);
489         }
490
491         self.process_generic_params(ty_params, item.span, &qualname, item.id);
492     }
493
494     fn process_enum(&mut self,
495                     item: &ast::Item,
496                     enum_definition: &ast::EnumDef,
497                     ty_params: &ast::Generics) {
498         let enum_data = self.save_ctxt.get_item_data(item);
499         down_cast_data!(enum_data, EnumData, self, item.span);
500         self.fmt.enum_str(item.span,
501                           Some(enum_data.span),
502                           enum_data.id,
503                           &enum_data.qualname,
504                           enum_data.scope,
505                           &enum_data.value);
506
507         for variant in &enum_definition.variants {
508             let name = &variant.node.name.name.as_str();
509             let mut qualname = enum_data.qualname.clone();
510             qualname.push_str("::");
511             qualname.push_str(name);
512             let val = self.span.snippet(variant.span);
513
514             self.fmt.struct_variant_str(variant.span,
515                                         self.span.span_for_first_ident(variant.span),
516                                         variant.node.data.id(),
517                                         variant.node.data.id(),
518                                         &qualname,
519                                         &enum_data.qualname,
520                                         &val,
521                                         enum_data.id);
522
523             for field in variant.node.data.fields() {
524                 self.process_struct_field_def(field, variant.node.data.id());
525                 self.visit_ty(&*field.node.ty);
526             }
527         }
528         self.process_generic_params(ty_params, item.span, &enum_data.qualname, enum_data.id);
529     }
530
531     fn process_impl(&mut self,
532                     item: &ast::Item,
533                     type_parameters: &ast::Generics,
534                     trait_ref: &Option<ast::TraitRef>,
535                     typ: &ast::Ty,
536                     impl_items: &[P<ast::ImplItem>]) {
537         let impl_data = self.save_ctxt.get_item_data(item);
538         down_cast_data!(impl_data, ImplData, self, item.span);
539         match impl_data.self_ref {
540             Some(ref self_ref) => {
541                 self.fmt.ref_str(recorder::TypeRef,
542                                  item.span,
543                                  Some(self_ref.span),
544                                  self_ref.ref_id,
545                                  self_ref.scope);
546             }
547             None => {
548                 self.visit_ty(&typ);
549             }
550         }
551         if let Some(ref trait_ref_data) = impl_data.trait_ref {
552             self.fmt.ref_str(recorder::TypeRef,
553                              item.span,
554                              Some(trait_ref_data.span),
555                              trait_ref_data.ref_id,
556                              trait_ref_data.scope);
557             visit::walk_path(self, &trait_ref.as_ref().unwrap().path);
558         }
559
560         self.fmt.impl_str(item.span,
561                           Some(impl_data.span),
562                           impl_data.id,
563                           impl_data.self_ref.map(|data| data.ref_id),
564                           impl_data.trait_ref.map(|data| data.ref_id),
565                           impl_data.scope);
566
567         self.process_generic_params(type_parameters, item.span, "", item.id);
568         for impl_item in impl_items {
569             self.visit_impl_item(impl_item);
570         }
571     }
572
573     fn process_trait(&mut self,
574                      item: &ast::Item,
575                      generics: &ast::Generics,
576                      trait_refs: &OwnedSlice<ast::TyParamBound>,
577                      methods: &[P<ast::TraitItem>]) {
578         let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
579         let val = self.span.snippet(item.span);
580         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
581         self.fmt.trait_str(item.span,
582                            sub_span,
583                            item.id,
584                            &qualname,
585                            self.cur_scope,
586                            &val);
587
588         // super-traits
589         for super_bound in trait_refs.iter() {
590             let trait_ref = match *super_bound {
591                 ast::TraitTyParamBound(ref trait_ref, _) => {
592                     trait_ref
593                 }
594                 ast::RegionTyParamBound(..) => {
595                     continue;
596                 }
597             };
598
599             let trait_ref = &trait_ref.trait_ref;
600             match self.lookup_type_ref(trait_ref.ref_id) {
601                 Some(id) => {
602                     let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
603                     self.fmt.ref_str(recorder::TypeRef,
604                                      trait_ref.path.span,
605                                      sub_span,
606                                      id,
607                                      self.cur_scope);
608                     self.fmt.inherit_str(trait_ref.path.span, sub_span, id, item.id);
609                 }
610                 None => (),
611             }
612         }
613
614         // walk generics and methods
615         self.process_generic_params(generics, item.span, &qualname, item.id);
616         for method in methods {
617             self.visit_trait_item(method)
618         }
619     }
620
621     // `item` is the module in question, represented as an item.
622     fn process_mod(&mut self, item: &ast::Item) {
623         let mod_data = self.save_ctxt.get_item_data(item);
624         down_cast_data!(mod_data, ModData, self, item.span);
625         self.fmt.mod_str(item.span,
626                          Some(mod_data.span),
627                          mod_data.id,
628                          &mod_data.qualname,
629                          mod_data.scope,
630                          &mod_data.filename);
631     }
632
633     fn process_path(&mut self, id: NodeId, path: &ast::Path, ref_kind: Option<recorder::Row>) {
634         if generated_code(path.span) {
635             return;
636         }
637
638         let path_data = self.save_ctxt.get_path_data(id, path);
639         let path_data = match path_data {
640             Some(pd) => pd,
641             None => {
642                 self.tcx.sess.span_bug(path.span,
643                                        &format!("Unexpected def kind while looking up path in \
644                                                  `{}`",
645                                                 self.span.snippet(path.span)))
646             }
647         };
648         match path_data {
649             Data::VariableRefData(ref vrd) => {
650                 self.fmt.ref_str(ref_kind.unwrap_or(recorder::VarRef),
651                                  path.span,
652                                  Some(vrd.span),
653                                  vrd.ref_id,
654                                  vrd.scope);
655
656             }
657             Data::TypeRefData(ref trd) => {
658                 self.fmt.ref_str(recorder::TypeRef,
659                                  path.span,
660                                  Some(trd.span),
661                                  trd.ref_id,
662                                  trd.scope);
663             }
664             Data::MethodCallData(ref mcd) => {
665                 self.fmt.meth_call_str(path.span,
666                                        Some(mcd.span),
667                                        mcd.ref_id,
668                                        mcd.decl_id,
669                                        mcd.scope);
670             }
671             Data::FunctionCallData(fcd) => {
672                 self.fmt.fn_call_str(path.span, Some(fcd.span), fcd.ref_id, fcd.scope);
673             }
674             _ => {
675                 self.sess.span_bug(path.span,
676                                    &format!("Unexpected data: {:?}", path_data));
677             }
678         }
679
680         // Modules or types in the path prefix.
681         let def_map = self.tcx.def_map.borrow();
682         let def = def_map.get(&id).unwrap().full_def();
683         match def {
684             def::DefMethod(did) => {
685                 let ti = self.tcx.impl_or_trait_item(did);
686                 if let ty::MethodTraitItem(m) = ti {
687                     if m.explicit_self == ty::StaticExplicitSelfCategory {
688                         self.write_sub_path_trait_truncated(path);
689                     }
690                 }
691             }
692             def::DefLocal(..) |
693             def::DefStatic(_,_) |
694             def::DefConst(..) |
695             def::DefAssociatedConst(..) |
696             def::DefStruct(_) |
697             def::DefVariant(..) |
698             def::DefFn(..) => self.write_sub_paths_truncated(path, false),
699             _ => {}
700         }
701     }
702
703     fn process_struct_lit(&mut self,
704                           ex: &ast::Expr,
705                           path: &ast::Path,
706                           fields: &Vec<ast::Field>,
707                           variant: ty::VariantDef,
708                           base: &Option<P<ast::Expr>>) {
709         if generated_code(path.span) {
710             return
711         }
712
713         self.write_sub_paths_truncated(path, false);
714
715         if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
716             down_cast_data!(struct_lit_data, TypeRefData, self, ex.span);
717             self.fmt.ref_str(recorder::TypeRef,
718                              ex.span,
719                              Some(struct_lit_data.span),
720                              struct_lit_data.ref_id,
721                              struct_lit_data.scope);
722             let scope = self.save_ctxt.enclosing_scope(ex.id);
723
724             for field in fields {
725                 if generated_code(field.ident.span) {
726                     continue;
727                 }
728
729                 let field_data = self.save_ctxt.get_field_ref_data(field, variant, scope);
730                 self.fmt.ref_str(recorder::VarRef,
731                                  field.ident.span,
732                                  Some(field_data.span),
733                                  field_data.ref_id,
734                                  field_data.scope);
735
736                 self.visit_expr(&field.expr)
737             }
738         }
739
740         walk_list!(self, visit_expr, base);
741     }
742
743     fn process_method_call(&mut self, ex: &ast::Expr, args: &Vec<P<ast::Expr>>) {
744         if let Some(call_data) = self.save_ctxt.get_expr_data(ex) {
745             down_cast_data!(call_data, MethodCallData, self, ex.span);
746             self.fmt.meth_call_str(ex.span,
747                                    Some(call_data.span),
748                                    call_data.ref_id,
749                                    call_data.decl_id,
750                                    call_data.scope);
751         }
752
753         // walk receiver and args
754         walk_list!(self, visit_expr, args);
755     }
756
757     fn process_pat(&mut self, p: &ast::Pat) {
758         if generated_code(p.span) {
759             return;
760         }
761
762         match p.node {
763             ast::PatStruct(ref path, ref fields, _) => {
764                 visit::walk_path(self, path);
765                 let adt = self.tcx.node_id_to_type(p.id).ty_adt_def().unwrap();
766                 let def = self.tcx.def_map.borrow()[&p.id].full_def();
767                 let variant = adt.variant_of_def(def);
768
769                 for &Spanned { node: ref field, span } in fields {
770                     if generated_code(span) {
771                         continue;
772                     }
773
774                     let sub_span = self.span.span_for_first_ident(span);
775                     if let Some(f) = variant.find_field_named(field.ident.name) {
776                         self.fmt.ref_str(recorder::VarRef, span, sub_span, f.did, self.cur_scope);
777                     }
778                     self.visit_pat(&field.pat);
779                 }
780             }
781             _ => visit::walk_pat(self, p),
782         }
783     }
784
785
786     fn process_var_decl(&mut self, p: &ast::Pat, value: String) {
787         // The local could declare multiple new vars, we must walk the
788         // pattern and collect them all.
789         let mut collector = PathCollector::new();
790         collector.visit_pat(&p);
791         self.visit_pat(&p);
792
793         for &(id, ref p, immut, _) in &collector.collected_paths {
794             let value = if immut == ast::MutImmutable {
795                 value.to_string()
796             } else {
797                 "<mutable>".to_string()
798             };
799             let types = self.tcx.node_types();
800             let typ = types.get(&id).unwrap().to_string();
801             // Get the span only for the name of the variable (I hope the path
802             // is only ever a variable name, but who knows?).
803             let sub_span = self.span.span_for_last_ident(p.span);
804             // Rust uses the id of the pattern for var lookups, so we'll use it too.
805             self.fmt.variable_str(p.span,
806                                   sub_span,
807                                   id,
808                                   &path_to_string(p),
809                                   &value,
810                                   &typ);
811         }
812     }
813 }
814
815 impl<'l, 'tcx, 'v> Visitor<'v> for DumpCsvVisitor<'l, 'tcx> {
816     fn visit_item(&mut self, item: &ast::Item) {
817         if generated_code(item.span) {
818             return
819         }
820
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         if generated_code(t.span) {
1016             return
1017         }
1018
1019         match t.node {
1020             ast::TyPath(_, ref path) => {
1021                 match self.lookup_type_ref(t.id) {
1022                     Some(id) => {
1023                         let sub_span = self.span.sub_span_for_type_name(t.span);
1024                         self.fmt.ref_str(recorder::TypeRef, t.span, sub_span, id, self.cur_scope);
1025                     }
1026                     None => (),
1027                 }
1028
1029                 self.write_sub_paths_truncated(path, false);
1030
1031                 visit::walk_path(self, path);
1032             }
1033             _ => visit::walk_ty(self, t),
1034         }
1035     }
1036
1037     fn visit_expr(&mut self, ex: &ast::Expr) {
1038         if generated_code(ex.span) {
1039             return
1040         }
1041
1042         match ex.node {
1043             ast::ExprCall(ref _f, ref _args) => {
1044                 // Don't need to do anything for function calls,
1045                 // because just walking the callee path does what we want.
1046                 visit::walk_expr(self, ex);
1047             }
1048             ast::ExprPath(_, ref path) => {
1049                 self.process_path(ex.id, path, None);
1050                 visit::walk_expr(self, ex);
1051             }
1052             ast::ExprStruct(ref path, ref fields, ref base) => {
1053                 let hir_expr = lower_expr(self.save_ctxt.lcx, ex);
1054                 let adt = self.tcx.expr_ty(&hir_expr).ty_adt_def().unwrap();
1055                 let def = self.tcx.resolve_expr(&hir_expr);
1056                 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1057             }
1058             ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, args),
1059             ast::ExprField(ref sub_ex, _) => {
1060                 if generated_code(sub_ex.span) {
1061                     return
1062                 }
1063
1064                 self.visit_expr(&sub_ex);
1065
1066                 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1067                     down_cast_data!(field_data, VariableRefData, self, ex.span);
1068                     self.fmt.ref_str(recorder::VarRef,
1069                                      ex.span,
1070                                      Some(field_data.span),
1071                                      field_data.ref_id,
1072                                      field_data.scope);
1073                 }
1074             }
1075             ast::ExprTupField(ref sub_ex, idx) => {
1076                 if generated_code(sub_ex.span) {
1077                     return
1078                 }
1079
1080                 self.visit_expr(&**sub_ex);
1081
1082                 let hir_node = lower_expr(self.save_ctxt.lcx, sub_ex);
1083                 let ty = &self.tcx.expr_ty_adjusted(&hir_node).sty;
1084                 match *ty {
1085                     ty::TyStruct(def, _) => {
1086                         let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1087                         self.fmt.ref_str(recorder::VarRef,
1088                                          ex.span,
1089                                          sub_span,
1090                                          def.struct_variant().fields[idx.node].did,
1091                                          self.cur_scope);
1092                     }
1093                     ty::TyTuple(_) => {}
1094                     _ => self.sess.span_bug(ex.span,
1095                                             &format!("Expected struct or tuple type, found {:?}",
1096                                                      ty)),
1097                 }
1098             }
1099             ast::ExprClosure(_, ref decl, ref body) => {
1100                 if generated_code(body.span) {
1101                     return
1102                 }
1103
1104                 let mut id = String::from("$");
1105                 id.push_str(&ex.id.to_string());
1106                 self.process_formals(&decl.inputs, &id);
1107
1108                 // walk arg and return types
1109                 for arg in &decl.inputs {
1110                     self.visit_ty(&*arg.ty);
1111                 }
1112
1113                 if let ast::Return(ref ret_ty) = decl.output {
1114                     self.visit_ty(&**ret_ty);
1115                 }
1116
1117                 // walk the body
1118                 self.nest(ex.id, |v| v.visit_block(&**body));
1119             }
1120             ast::ExprForLoop(ref pattern, ref subexpression, ref block, _) |
1121             ast::ExprWhileLet(ref pattern, ref subexpression, ref block, _) => {
1122                 let value = self.span.snippet(mk_sp(ex.span.lo, subexpression.span.hi));
1123                 self.process_var_decl(pattern, value);
1124                 visit::walk_expr(self, subexpression);
1125                 visit::walk_block(self, block);
1126             }
1127             ast::ExprIfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
1128                 let value = self.span.snippet(mk_sp(ex.span.lo, subexpression.span.hi));
1129                 self.process_var_decl(pattern, value);
1130                 visit::walk_expr(self, subexpression);
1131                 visit::walk_block(self, block);
1132                 opt_else.as_ref().map(|el| visit::walk_expr(self, el));
1133             }
1134             _ => {
1135                 visit::walk_expr(self, ex)
1136             }
1137         }
1138     }
1139
1140     fn visit_mac(&mut self, _: &ast::Mac) {
1141         // Just stop, macros are poison to us.
1142     }
1143
1144     fn visit_pat(&mut self, p: &ast::Pat) {
1145         self.process_pat(p);
1146     }
1147
1148     fn visit_arm(&mut self, arm: &ast::Arm) {
1149         let mut collector = PathCollector::new();
1150         for pattern in &arm.pats {
1151             // collect paths from the arm's patterns
1152             collector.visit_pat(&pattern);
1153             self.visit_pat(&pattern);
1154         }
1155
1156         // This is to get around borrow checking, because we need mut self to call process_path.
1157         let mut paths_to_process = vec![];
1158
1159         // process collected paths
1160         for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1161             let def_map = self.tcx.def_map.borrow();
1162             if !def_map.contains_key(&id) {
1163                 self.sess.span_bug(p.span,
1164                                    &format!("def_map has no key for {} in visit_arm", id));
1165             }
1166             let def = def_map.get(&id).unwrap().full_def();
1167             match def {
1168                 def::DefLocal(_, id) => {
1169                     let value = if immut == ast::MutImmutable {
1170                         self.span.snippet(p.span).to_string()
1171                     } else {
1172                         "<mutable>".to_string()
1173                     };
1174
1175                     assert!(p.segments.len() == 1,
1176                             "qualified path for local variable def in arm");
1177                     self.fmt.variable_str(p.span, Some(p.span), id, &path_to_string(p), &value, "")
1178                 }
1179                 def::DefVariant(..) | def::DefTy(..) | def::DefStruct(..) => {
1180                     paths_to_process.push((id, p.clone(), Some(ref_kind)))
1181                 }
1182                 // FIXME(nrc) what are these doing here?
1183                 def::DefStatic(_, _) |
1184                 def::DefConst(..) |
1185                 def::DefAssociatedConst(..) => {}
1186                 _ => error!("unexpected definition kind when processing collected paths: {:?}",
1187                             def),
1188             }
1189         }
1190
1191         for &(id, ref path, ref_kind) in &paths_to_process {
1192             self.process_path(id, path, ref_kind);
1193         }
1194         walk_list!(self, visit_expr, &arm.guard);
1195         self.visit_expr(&arm.body);
1196     }
1197
1198     fn visit_stmt(&mut self, s: &ast::Stmt) {
1199         if generated_code(s.span) {
1200             return
1201         }
1202
1203         visit::walk_stmt(self, s)
1204     }
1205
1206     fn visit_local(&mut self, l: &ast::Local) {
1207         if generated_code(l.span) {
1208             return
1209         }
1210
1211         let value = self.span.snippet(l.span);
1212         self.process_var_decl(&l.pat, value);
1213
1214         // Just walk the initialiser and type (don't want to walk the pattern again).
1215         walk_list!(self, visit_ty, &l.ty);
1216         walk_list!(self, visit_expr, &l.init);
1217     }
1218 }