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