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