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