]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/save/mod.rs
077284a7c4223667ceb88760d02db0d62b960725
[rust.git] / src / librustc_trans / save / mod.rs
1 // Copyright 2012-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 use middle::ty;
12 use middle::def;
13
14 use std::env;
15 use std::fs::{self, File};
16 use std::path::{Path, PathBuf};
17
18 use rustc::ast_map::NodeItem;
19
20 use syntax::{attr};
21 use syntax::ast::{self, NodeId, DefId};
22 use syntax::ast_util;
23 use syntax::codemap::*;
24 use syntax::parse::token::{self, get_ident, keywords};
25 use syntax::visit::{self, Visitor};
26 use syntax::print::pprust::ty_to_string;
27
28 use self::span_utils::SpanUtils;
29
30
31 mod span_utils;
32 mod recorder;
33
34 mod dump_csv;
35
36 pub struct SaveContext<'l, 'tcx: 'l> {
37     tcx: &'l ty::ctxt<'tcx>,
38     span_utils: SpanUtils<'l>,
39 }
40
41 pub struct CrateData {
42     pub name: String,
43     pub number: u32,
44 }
45
46 /// Data for any entity in the Rust language. The actual data contained varied
47 /// with the kind of entity being queried. See the nested structs for details.
48 #[derive(Debug)]
49 pub enum Data {
50     /// Data for all kinds of functions and methods.
51     FunctionData(FunctionData),
52     /// Data for local and global variables (consts and statics), and fields.
53     VariableData(VariableData),
54     /// Data for modules.
55     ModData(ModData),
56     /// Data for Enums.
57     EnumData(EnumData),
58     /// Data for impls.
59     ImplData(ImplData),
60
61     /// Data for the use of some variable (e.g., the use of a local variable, which
62     /// will refere to that variables declaration).
63     VariableRefData(VariableRefData),
64     /// Data for a reference to a type or trait.
65     TypeRefData(TypeRefData),
66     /// Data for a reference to a module.
67     ModRefData(ModRefData),
68     /// Data about a function call.
69     FunctionCallData(FunctionCallData),
70     /// Data about a method call.
71     MethodCallData(MethodCallData),
72 }
73
74 /// Data for all kinds of functions and methods.
75 #[derive(Debug)]
76 pub struct FunctionData {
77     pub id: NodeId,
78     pub name: String,
79     pub qualname: String,
80     pub declaration: Option<DefId>,
81     pub span: Span,
82     pub scope: NodeId,
83 }
84
85 /// Data for local and global variables (consts and statics).
86 #[derive(Debug)]
87 pub struct VariableData {
88     pub id: NodeId,
89     pub name: String,
90     pub qualname: String,
91     pub span: Span,
92     pub scope: NodeId,
93     pub value: String,
94     pub type_value: String,
95 }
96
97 /// Data for modules.
98 #[derive(Debug)]
99 pub struct ModData {
100     pub id: NodeId,
101     pub name: String,
102     pub qualname: String,
103     pub span: Span,
104     pub scope: NodeId,
105     pub filename: String,
106 }
107
108 /// Data for enum declarations.
109 #[derive(Debug)]
110 pub struct EnumData {
111     pub id: NodeId,
112     pub value: String,
113     pub qualname: String,
114     pub span: Span,
115     pub scope: NodeId,
116 }
117
118 #[derive(Debug)]
119 pub struct ImplData {
120     pub id: NodeId,
121     pub span: Span,
122     pub scope: NodeId,
123     // FIXME: I'm not really sure inline data is the best way to do this. Seems
124     // OK in this case, but generalising leads to returning chunks of AST, which
125     // feels wrong.
126     pub trait_ref: Option<TypeRefData>,
127     pub self_ref: Option<TypeRefData>,
128 }
129
130 /// Data for the use of some item (e.g., the use of a local variable, which
131 /// will refer to that variables declaration (by ref_id)).
132 #[derive(Debug)]
133 pub struct VariableRefData {
134     pub name: String,
135     pub span: Span,
136     pub scope: NodeId,
137     pub ref_id: DefId,
138 }
139
140 /// Data for a reference to a type or trait.
141 #[derive(Debug)]
142 pub struct TypeRefData {
143     pub span: Span,
144     pub scope: NodeId,
145     pub ref_id: DefId,
146 }
147
148 /// Data for a reference to a module.
149 #[derive(Debug)]
150 pub struct ModRefData {
151     pub span: Span,
152     pub scope: NodeId,
153     pub ref_id: DefId,
154 }
155
156 /// Data about a function call.
157 #[derive(Debug)]
158 pub struct FunctionCallData {
159     pub span: Span,
160     pub scope: NodeId,
161     pub ref_id: DefId,
162 }
163
164 /// Data about a method call.
165 #[derive(Debug)]
166 pub struct MethodCallData {
167     pub span: Span,
168     pub scope: NodeId,
169     pub ref_id: Option<DefId>,
170     pub decl_id: Option<DefId>,
171 }
172
173
174
175 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
176     pub fn new(tcx: &'l ty::ctxt<'tcx>) -> SaveContext <'l, 'tcx> {
177         let span_utils = SpanUtils::new(&tcx.sess);
178         SaveContext::from_span_utils(tcx, span_utils)
179     }
180
181     pub fn from_span_utils(tcx: &'l ty::ctxt<'tcx>,
182                            span_utils: SpanUtils<'l>)
183                            -> SaveContext<'l, 'tcx> {
184         SaveContext {
185             tcx: tcx,
186             span_utils: span_utils,
187         }
188     }
189
190     // List external crates used by the current crate.
191     pub fn get_external_crates(&self) -> Vec<CrateData> {
192         let mut result = Vec::new();
193
194         self.tcx.sess.cstore.iter_crate_data(|n, cmd| {
195             result.push(CrateData { name: cmd.name.clone(), number: n });
196         });
197
198         result
199     }
200
201     pub fn get_item_data(&self, item: &ast::Item) -> Data {
202         match item.node {
203             ast::ItemFn(..) => {
204                 let name = self.tcx.map.path_to_string(item.id);
205                 let qualname = format!("::{}", name);
206                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
207
208                 Data::FunctionData(FunctionData {
209                     id: item.id,
210                     name: name,
211                     qualname: qualname,
212                     declaration: None,
213                     span: sub_span.unwrap(),
214                     scope: self.enclosing_scope(item.id),
215                 })
216             }
217             ast::ItemStatic(ref typ, mt, ref expr) => {
218                 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
219
220                 // If the variable is immutable, save the initialising expression.
221                 let (value, keyword) = match mt {
222                     ast::MutMutable => (String::from("<mutable>"), keywords::Mut),
223                     ast::MutImmutable => (self.span_utils.snippet(expr.span), keywords::Static),
224                 };
225
226                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
227
228                 Data::VariableData(VariableData {
229                     id: item.id,
230                     name: get_ident(item.ident).to_string(),
231                     qualname: qualname,
232                     span: sub_span.unwrap(),
233                     scope: self.enclosing_scope(item.id),
234                     value: value,
235                     type_value: ty_to_string(&typ),
236                 })
237             }
238             ast::ItemConst(ref typ, ref expr) => {
239                 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
240                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
241
242                 Data::VariableData(VariableData {
243                     id: item.id,
244                     name: get_ident(item.ident).to_string(),
245                     qualname: qualname,
246                     span: sub_span.unwrap(),
247                     scope: self.enclosing_scope(item.id),
248                     value: self.span_utils.snippet(expr.span),
249                     type_value: ty_to_string(&typ),
250                 })
251             }
252             ast::ItemMod(ref m) => {
253                 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
254
255                 let cm = self.tcx.sess.codemap();
256                 let filename = cm.span_to_filename(m.inner);
257
258                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
259
260                 Data::ModData(ModData {
261                     id: item.id,
262                     name: get_ident(item.ident).to_string(),
263                     qualname: qualname,
264                     span: sub_span.unwrap(),
265                     scope: self.enclosing_scope(item.id),
266                     filename: filename,
267                 })
268             },
269             ast::ItemEnum(..) => {
270                 let enum_name = format!("::{}", self.tcx.map.path_to_string(item.id));
271                 let val = self.span_utils.snippet(item.span);
272                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
273
274                 Data::EnumData(EnumData {
275                     id: item.id,
276                     value: val,
277                     span: sub_span.unwrap(),
278                     qualname: enum_name,
279                     scope: self.enclosing_scope(item.id),
280                 })
281             },
282             ast::ItemImpl(_, _, _, ref trait_ref, ref typ, _) => {
283                 let mut type_data = None;
284                 let sub_span;
285
286                 let parent = self.enclosing_scope(item.id);
287
288                 match typ.node {
289                     // Common case impl for a struct or something basic.
290                     ast::TyPath(None, ref path) => {
291                         sub_span = self.span_utils.sub_span_for_type_name(path.span).unwrap();
292                         type_data = self.lookup_ref_id(typ.id).map(|id| TypeRefData {
293                             span: sub_span,
294                             scope: parent,
295                             ref_id: id,
296                         });
297                     },
298                     _ => {
299                         // Less useful case, impl for a compound type.
300                         let span = typ.span;
301                         sub_span = self.span_utils.sub_span_for_type_name(span).unwrap_or(span);
302                     }
303                 }
304
305                 let trait_data =
306                     trait_ref.as_ref().and_then(|tr| self.get_trait_ref_data(tr, parent));
307
308                 Data::ImplData(ImplData {
309                     id: item.id,
310                     span: sub_span,
311                     scope: parent,
312                     trait_ref: trait_data,
313                     self_ref: type_data,
314                 })
315             }
316             _ => {
317                 // FIXME
318                 unimplemented!();
319             }
320         }
321     }
322
323     pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<VariableData> {
324         match field.node.kind {
325             ast::NamedField(ident, _) => {
326                 let name = get_ident(ident);
327                 let qualname = format!("::{}::{}",
328                                        self.tcx.map.path_to_string(scope),
329                                        name);
330                 let typ = self.tcx.node_types().get(&field.node.id).unwrap()
331                                                .to_string();
332                 let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
333                 Some(VariableData {
334                     id: field.node.id,
335                     name: get_ident(ident).to_string(),
336                     qualname: qualname,
337                     span: sub_span.unwrap(),
338                     scope: scope,
339                     value: "".to_owned(),
340                     type_value: typ,
341                 })
342             },
343             _ => None,
344         }
345     }
346
347     // FIXME would be nice to take a MethodItem here, but the ast provides both
348     // trait and impl flavours, so the caller must do the disassembly.
349     pub fn get_method_data(&self,
350                            id: ast::NodeId,
351                            name: ast::Name,
352                            span: Span) -> FunctionData {
353         // The qualname for a method is the trait name or name of the struct in an impl in
354         // which the method is declared in, followed by the method's name.
355         let qualname = match self.tcx.impl_of_method(ast_util::local_def(id)) {
356             Some(impl_id) => match self.tcx.map.get(impl_id.node) {
357                 NodeItem(item) => {
358                     match item.node {
359                         ast::ItemImpl(_, _, _, _, ref ty, _) => {
360                             let mut result = String::from("<");
361                             result.push_str(&ty_to_string(&**ty));
362
363                             match self.tcx.trait_of_item(ast_util::local_def(id)) {
364                                 Some(def_id) => {
365                                     result.push_str(" as ");
366                                     result.push_str(
367                                         &self.tcx.item_path_str(def_id));
368                                 },
369                                 None => {}
370                             }
371                             result.push_str(">");
372                             result
373                         }
374                         _ => {
375                             self.tcx.sess.span_bug(span,
376                                 &format!("Container {} for method {} not an impl?",
377                                          impl_id.node, id));
378                         },
379                     }
380                 },
381                 _ => {
382                     self.tcx.sess.span_bug(span,
383                         &format!("Container {} for method {} is not a node item {:?}",
384                                  impl_id.node, id, self.tcx.map.get(impl_id.node)));
385                 },
386             },
387             None => match self.tcx.trait_of_item(ast_util::local_def(id)) {
388                 Some(def_id) => {
389                     match self.tcx.map.get(def_id.node) {
390                         NodeItem(_) => {
391                             format!("::{}", self.tcx.item_path_str(def_id))
392                         }
393                         _ => {
394                             self.tcx.sess.span_bug(span,
395                                 &format!("Could not find container {} for method {}",
396                                          def_id.node, id));
397                         }
398                     }
399                 },
400                 None => {
401                     self.tcx.sess.span_bug(span,
402                         &format!("Could not find container for method {}", id));
403                 },
404             },
405         };
406
407         let qualname = format!("{}::{}", qualname, &token::get_name(name));
408
409         let decl_id = self.tcx.trait_item_of_item(ast_util::local_def(id))
410             .and_then(|new_id| {
411                 let def_id = new_id.def_id();
412                 if def_id.node != 0 && def_id != ast_util::local_def(id) {
413                     Some(def_id)
414                 } else {
415                     None
416                 }
417             });
418
419         let sub_span = self.span_utils.sub_span_after_keyword(span, keywords::Fn);
420
421         FunctionData {
422             id: id,
423             name: token::get_name(name).to_string(),
424             qualname: qualname,
425             declaration: decl_id,
426             span: sub_span.unwrap(),
427             scope: self.enclosing_scope(id),
428         }
429     }
430
431     pub fn get_trait_ref_data(&self,
432                               trait_ref: &ast::TraitRef,
433                               parent: NodeId)
434                               -> Option<TypeRefData> {
435         self.lookup_ref_id(trait_ref.ref_id).map(|def_id| {
436             let span = trait_ref.path.span;
437             let sub_span = self.span_utils.sub_span_for_type_name(span).unwrap_or(span);
438             TypeRefData {
439                 span: sub_span,
440                 scope: parent,
441                 ref_id: def_id,
442             }
443         })
444     }
445
446     pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
447         match expr.node {
448             ast::ExprField(ref sub_ex, ident) => {
449                 let ty = &self.tcx.expr_ty_adjusted(&sub_ex).sty;
450                 match *ty {
451                     ty::TyStruct(def_id, _) => {
452                         let fields = self.tcx.lookup_struct_fields(def_id);
453                         for f in &fields {
454                             if f.name == ident.node.name {
455                                 let sub_span = self.span_utils.span_for_last_ident(expr.span);
456                                 return Some(Data::VariableRefData(VariableRefData {
457                                     name: get_ident(ident.node).to_string(),
458                                     span: sub_span.unwrap(),
459                                     scope: self.enclosing_scope(expr.id),
460                                     ref_id: f.id,
461                                 }));
462                             }
463                         }
464
465                         self.tcx.sess.span_bug(expr.span,
466                                                &format!("Couldn't find field {} on {:?}",
467                                                         &get_ident(ident.node), ty))
468                     }
469                     _ => {
470                         debug!("Expected struct type, found {:?}", ty);
471                         None
472                     }
473                 }
474             }
475             ast::ExprStruct(ref path, _, _) => {
476                 let ty = &self.tcx.expr_ty_adjusted(expr).sty;
477                 match *ty {
478                     ty::TyStruct(def_id, _) => {
479                         let sub_span = self.span_utils.span_for_last_ident(path.span);
480                         Some(Data::TypeRefData(TypeRefData {
481                             span: sub_span.unwrap(),
482                             scope: self.enclosing_scope(expr.id),
483                             ref_id: def_id,
484                         }))
485                     }
486                     _ => {
487                         // FIXME ty could legitimately be a TyEnum, but then we will fail
488                         // later if we try to look up the fields.
489                         debug!("expected TyStruct, found {:?}", ty);
490                         None
491                     }
492                 }
493             }
494             ast::ExprMethodCall(..) => {
495                 let method_call = ty::MethodCall::expr(expr.id);
496                 let method_id = self.tcx.tables.borrow().method_map[&method_call].def_id;
497                 let (def_id, decl_id) = match self.tcx.impl_or_trait_item(method_id).container() {
498                     ty::ImplContainer(_) => (Some(method_id), None),
499                     ty::TraitContainer(_) => (None, Some(method_id))
500                 };
501                 let sub_span = self.span_utils.sub_span_for_meth_name(expr.span);
502                 let parent = self.enclosing_scope(expr.id);
503                 Some(Data::MethodCallData(MethodCallData {
504                     span: sub_span.unwrap(),
505                     scope: parent,
506                     ref_id: def_id,
507                     decl_id: decl_id,
508                 }))
509             }
510             ast::ExprPath(_, ref path) => {
511                 Some(self.get_path_data(expr.id, path))
512             }
513             _ => {
514                 // FIXME
515                 unimplemented!();
516             }
517         }
518     }
519
520     pub fn get_path_data(&self,
521                          id: NodeId,
522                          path: &ast::Path)
523                          -> Data {
524         let def_map = self.tcx.def_map.borrow();
525         if !def_map.contains_key(&id) {
526             self.tcx.sess.span_bug(path.span,
527                                    &format!("def_map has no key for {} in visit_expr", id));
528         }
529         let def = def_map.get(&id).unwrap().full_def();
530         let sub_span = self.span_utils.span_for_last_ident(path.span);
531         match def {
532             def::DefUpvar(..) |
533             def::DefLocal(..) |
534             def::DefStatic(..) |
535             def::DefConst(..) |
536             def::DefAssociatedConst(..) |
537             def::DefVariant(..) => {
538                 Data::VariableRefData(VariableRefData {
539                     name: self.span_utils.snippet(sub_span.unwrap()),
540                     span: sub_span.unwrap(),
541                     scope: self.enclosing_scope(id),
542                     ref_id: def.def_id(),
543                 })
544             }
545             def::DefStruct(def_id) |
546             def::DefTy(def_id, _) |
547             def::DefTrait(def_id) |
548             def::DefTyParam(_, _, def_id, _) => {
549                 Data::TypeRefData(TypeRefData {
550                     span: sub_span.unwrap(),
551                     ref_id: def_id,
552                     scope: self.enclosing_scope(id),
553                 })
554             }
555             def::DefMethod(decl_id, provenence) => {
556                 let sub_span = self.span_utils.sub_span_for_meth_name(path.span);
557                 let def_id = if decl_id.krate == ast::LOCAL_CRATE {
558                     let ti = self.tcx.impl_or_trait_item(decl_id);
559                     match provenence {
560                         def::FromTrait(def_id) => {
561                             self.tcx.trait_items(def_id)
562                                 .iter()
563                                 .find(|mr| {
564                                     mr.name() == ti.name() && self.trait_method_has_body(mr)
565                                 })
566                                 .map(|mr| mr.def_id())
567                         }
568                         def::FromImpl(def_id) => {
569                             let impl_items = self.tcx.impl_items.borrow();
570                             Some(impl_items.get(&def_id)
571                                            .unwrap()
572                                            .iter()
573                                            .find(|mr| {
574                                                 self.tcx.impl_or_trait_item(mr.def_id()).name()
575                                                     == ti.name()
576                                             })
577                                            .unwrap()
578                                            .def_id())
579                         }
580                     }
581                 } else {
582                     None
583                 };
584                 Data::MethodCallData(MethodCallData {
585                     span: sub_span.unwrap(),
586                     scope: self.enclosing_scope(id),
587                     ref_id: def_id,
588                     decl_id: Some(decl_id),
589                 })
590             },
591             def::DefFn(def_id, _) => {
592                 Data::FunctionCallData(FunctionCallData {
593                     ref_id: def_id,
594                     span: sub_span.unwrap(),
595                     scope: self.enclosing_scope(id),
596                 })
597             }
598             def::DefMod(def_id) => {
599                 Data::ModRefData(ModRefData {
600                     ref_id: def_id,
601                     span: sub_span.unwrap(),
602                     scope: self.enclosing_scope(id),
603                 })
604             }
605             _ => self.tcx.sess.span_bug(path.span,
606                                         &format!("Unexpected def kind while looking \
607                                                   up path in `{}`: `{:?}`",
608                                                  self.span_utils.snippet(path.span),
609                                                  def)),
610         }
611     }
612
613     fn trait_method_has_body(&self, mr: &ty::ImplOrTraitItem) -> bool {
614         let def_id = mr.def_id();
615         if def_id.krate != ast::LOCAL_CRATE {
616             return false;
617         }
618
619         let trait_item = self.tcx.map.expect_trait_item(def_id.node);
620         if let ast::TraitItem_::MethodTraitItem(_, Some(_)) = trait_item.node {
621             true
622         } else {
623             false
624         }
625     }
626
627     pub fn get_field_ref_data(&self,
628                               field_ref: &ast::Field,
629                               struct_id: DefId,
630                               parent: NodeId)
631                               -> VariableRefData {
632         let fields = self.tcx.lookup_struct_fields(struct_id);
633         let field_name = get_ident(field_ref.ident.node).to_string();
634         for f in &fields {
635             if f.name == field_ref.ident.node.name {
636                 // We don't really need a sub-span here, but no harm done
637                 let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
638                 return VariableRefData {
639                     name: field_name,
640                     span: sub_span.unwrap(),
641                     scope: parent,
642                     ref_id: f.id,
643                 };
644             }
645         }
646
647         self.tcx.sess.span_bug(field_ref.span,
648                                &format!("Couldn't find field {}", field_name));
649     }
650
651     pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
652         // FIXME
653         unimplemented!();
654     }
655
656     fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
657         if !self.tcx.def_map.borrow().contains_key(&ref_id) {
658             self.tcx.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
659                                        ref_id));
660         }
661         let def = self.tcx.def_map.borrow().get(&ref_id).unwrap().full_def();
662         match def {
663             def::DefPrimTy(_) => None,
664             _ => Some(def.def_id()),
665         }
666     }
667
668     #[inline]
669     fn enclosing_scope(&self, id: NodeId) -> NodeId {
670         self.tcx.map.get_enclosing_scope(id).unwrap_or(0)
671     }
672 }
673
674 // An AST visitor for collecting paths from patterns.
675 struct PathCollector {
676     // The Row field identifies the kind of pattern.
677     collected_paths: Vec<(NodeId, ast::Path, ast::Mutability, recorder::Row)>,
678 }
679
680 impl PathCollector {
681     fn new() -> PathCollector {
682         PathCollector {
683             collected_paths: vec![],
684         }
685     }
686 }
687
688 impl<'v> Visitor<'v> for PathCollector {
689     fn visit_pat(&mut self, p: &ast::Pat) {
690         if generated_code(p.span) {
691             return;
692         }
693
694         match p.node {
695             ast::PatStruct(ref path, _, _) => {
696                 self.collected_paths.push((p.id,
697                                            path.clone(),
698                                            ast::MutMutable,
699                                            recorder::TypeRef));
700             }
701             ast::PatEnum(ref path, _) |
702             ast::PatQPath(_, ref path) => {
703                 self.collected_paths.push((p.id, path.clone(), ast::MutMutable, recorder::VarRef));
704             }
705             ast::PatIdent(bm, ref path1, _) => {
706                 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
707                        token::get_ident(path1.node),
708                        p.span,
709                        path1.span);
710                 let immut = match bm {
711                     // Even if the ref is mut, you can't change the ref, only
712                     // the data pointed at, so showing the initialising expression
713                     // is still worthwhile.
714                     ast::BindByRef(_) => ast::MutImmutable,
715                     ast::BindByValue(mt) => mt,
716                 };
717                 // collect path for either visit_local or visit_arm
718                 let path = ast_util::ident_to_path(path1.span, path1.node);
719                 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
720             }
721             _ => {}
722         }
723         visit::walk_pat(self, p);
724     }
725 }
726
727 #[allow(deprecated)]
728 pub fn process_crate(tcx: &ty::ctxt,
729                      analysis: &ty::CrateAnalysis,
730                      odir: Option<&Path>) {
731     let krate = tcx.map.krate();
732     if generated_code(krate.span) {
733         return;
734     }
735
736     assert!(analysis.glob_map.is_some());
737     let cratename = match attr::find_crate_name(&krate.attrs) {
738         Some(name) => name.to_string(),
739         None => {
740             info!("Could not find crate name, using 'unknown_crate'");
741             String::from("unknown_crate")
742         },
743     };
744
745     info!("Dumping crate {}", cratename);
746
747     // find a path to dump our data to
748     let mut root_path = match env::var_os("DXR_RUST_TEMP_FOLDER") {
749         Some(val) => PathBuf::from(val),
750         None => match odir {
751             Some(val) => val.join("dxr"),
752             None => PathBuf::from("dxr-temp"),
753         },
754     };
755
756     if let Err(e) = fs::create_dir_all(&root_path) {
757         tcx.sess.err(&format!("Could not create directory {}: {}",
758                               root_path.display(), e));
759     }
760
761     {
762         let disp = root_path.display();
763         info!("Writing output to {}", disp);
764     }
765
766     // Create output file.
767     let mut out_name = cratename.clone();
768     out_name.push_str(".csv");
769     root_path.push(&out_name);
770     let output_file = match File::create(&root_path) {
771         Ok(f) => box f,
772         Err(e) => {
773             let disp = root_path.display();
774             tcx.sess.fatal(&format!("Could not open {}: {}", disp, e));
775         }
776     };
777     root_path.pop();
778
779     let mut visitor = dump_csv::DumpCsvVisitor::new(tcx, analysis, output_file);
780
781     visitor.dump_crate_info(&cratename, krate);
782     visit::walk_crate(&mut visitor, krate);
783 }
784
785 // Utility functions for the module.
786
787 // Helper function to escape quotes in a string
788 fn escape(s: String) -> String {
789     s.replace("\"", "\"\"")
790 }
791
792 // If the expression is a macro expansion or other generated code, run screaming
793 // and don't index.
794 pub fn generated_code(span: Span) -> bool {
795     span.expn_id != NO_EXPANSION || span  == DUMMY_SP
796 }