]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/save/mod.rs
Rebasing and bug fixing
[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 session::Session;
12 use middle::ty;
13 use middle::def;
14
15 use std::env;
16 use std::fs::{self, File};
17 use std::path::{Path, PathBuf};
18
19 use syntax::{attr};
20 use syntax::ast::{self, NodeId, DefId};
21 use syntax::ast_util;
22 use syntax::codemap::*;
23 use syntax::parse::token::{self, get_ident, keywords};
24 use syntax::visit::{self, Visitor};
25 use syntax::print::pprust::ty_to_string;
26
27 use util::ppaux;
28
29 use self::span_utils::SpanUtils;
30
31
32 mod span_utils;
33 mod recorder;
34
35 mod dump_csv;
36
37 pub struct SaveContext<'l, 'tcx: 'l> {
38     sess: &'l Session,
39     analysis: &'l ty::CrateAnalysis<'tcx>,
40     span_utils: SpanUtils<'l>,
41 }
42
43 pub struct CrateData {
44     pub name: String,
45     pub number: u32,
46 }
47
48 /// Data for any entity in the Rust language. The actual data contained varied
49 /// with the kind of entity being queried. See the nested structs for details.
50 #[derive(Debug)]
51 pub enum Data {
52     /// Data for all kinds of functions and methods.
53     FunctionData(FunctionData),
54     /// Data for local and global variables (consts and statics), and fields.
55     VariableData(VariableData),
56     /// Data for modules.
57     ModData(ModData),
58     /// Data for Enums.
59     EnumData(EnumData),
60     /// Data for impls.
61     ImplData(ImplData),
62
63     /// Data for the use of some variable (e.g., the use of a local variable, which
64     /// will refere to that variables declaration).
65     VariableRefData(VariableRefData),
66     /// Data for a reference to a type or trait.
67     TypeRefData(TypeRefData),
68 }
69
70 /// Data for all kinds of functions and methods.
71 #[derive(Debug)]
72 pub struct FunctionData {
73     pub id: NodeId,
74     pub name: String,
75     pub qualname: String,
76     pub declaration: Option<DefId>,
77     pub span: Span,
78     pub scope: NodeId,
79 }
80
81 /// Data for local and global variables (consts and statics).
82 #[derive(Debug)]
83 pub struct VariableData {
84     pub id: NodeId,
85     pub name: String,
86     pub qualname: String,
87     pub span: Span,
88     pub scope: NodeId,
89     pub value: String,
90     pub type_value: String,
91 }
92
93 /// Data for modules.
94 #[derive(Debug)]
95 pub struct ModData {
96     pub id: NodeId,
97     pub name: String,
98     pub qualname: String,
99     pub span: Span,
100     pub scope: NodeId,
101     pub filename: String,
102 }
103
104 /// Data for enum declarations.
105 #[derive(Debug)]
106 pub struct EnumData {
107     pub id: NodeId,
108     pub value: String,
109     pub qualname: String,
110     pub span: Span,
111     pub scope: NodeId,
112 }
113
114 #[derive(Debug)]
115 pub struct ImplData {
116     pub id: NodeId,
117     pub span: Span,
118     pub scope: NodeId,
119     // FIXME: I'm not really sure inline data is the best way to do this. Seems
120     // OK in this case, but generalising leads to returning chunks of AST, which
121     // feels wrong.
122     pub trait_ref: Option<TypeRefData>,
123     pub self_ref: Option<TypeRefData>,
124 }
125
126 /// Data for the use of some item (e.g., the use of a local variable, which
127 /// will refere to that variables declaration (by ref_id)).
128 #[derive(Debug)]
129 pub struct VariableRefData {
130     pub name: String,
131     pub span: Span,
132     pub scope: NodeId,
133     pub ref_id: DefId,
134 }
135
136 /// Data for a reference to a type or trait.
137 #[derive(Debug)]
138 pub struct TypeRefData {
139     pub span: Span,
140     pub scope: NodeId,
141     pub ref_id: DefId,
142 }
143
144
145 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
146     pub fn new(sess: &'l Session,
147                analysis: &'l ty::CrateAnalysis<'tcx>,
148                span_utils: SpanUtils<'l>)
149                -> SaveContext<'l, 'tcx> {
150         SaveContext {
151             sess: sess,
152             analysis: analysis,
153             span_utils: span_utils,
154         }
155     }
156
157     // List external crates used by the current crate.
158     pub fn get_external_crates(&self) -> Vec<CrateData> {
159         let mut result = Vec::new();
160
161         self.sess.cstore.iter_crate_data(|n, cmd| {
162             result.push(CrateData { name: cmd.name.clone(), number: n });
163         });
164
165         result
166     }
167
168     pub fn get_item_data(&self, item: &ast::Item) -> Data {
169         match item.node {
170             ast::ItemFn(..) => {
171                 let name = self.analysis.ty_cx.map.path_to_string(item.id);
172                 let qualname = format!("::{}", name);
173                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
174
175                 Data::FunctionData(FunctionData {
176                     id: item.id,
177                     name: name,
178                     qualname: qualname,
179                     declaration: None,
180                     span: sub_span.unwrap(),
181                     scope: self.analysis.ty_cx.map.get_parent(item.id),
182                 })
183             }
184             ast::ItemStatic(ref typ, mt, ref expr) => {
185                 let qualname = format!("::{}", self.analysis.ty_cx.map.path_to_string(item.id));
186
187                 // If the variable is immutable, save the initialising expression.
188                 let (value, keyword) = match mt {
189                     ast::MutMutable => (String::from("<mutable>"), keywords::Mut),
190                     ast::MutImmutable => (self.span_utils.snippet(expr.span), keywords::Static),
191                 };
192
193                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
194
195                 Data::VariableData(VariableData {
196                     id: item.id,
197                     name: get_ident(item.ident).to_string(),
198                     qualname: qualname,
199                     span: sub_span.unwrap(),
200                     scope: self.analysis.ty_cx.map.get_parent(item.id),
201                     value: value,
202                     type_value: ty_to_string(&typ),
203                 })
204             }
205             ast::ItemConst(ref typ, ref expr) => {
206                 let qualname = format!("::{}", self.analysis.ty_cx.map.path_to_string(item.id));
207                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
208
209                 Data::VariableData(VariableData {
210                     id: item.id,
211                     name: get_ident(item.ident).to_string(),
212                     qualname: qualname,
213                     span: sub_span.unwrap(),
214                     scope: self.analysis.ty_cx.map.get_parent(item.id),
215                     value: self.span_utils.snippet(expr.span),
216                     type_value: ty_to_string(&typ),
217                 })
218             }
219             ast::ItemMod(ref m) => {
220                 let qualname = format!("::{}", self.analysis.ty_cx.map.path_to_string(item.id));
221
222                 let cm = self.sess.codemap();
223                 let filename = cm.span_to_filename(m.inner);
224
225                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
226
227                 Data::ModData(ModData {
228                     id: item.id,
229                     name: get_ident(item.ident).to_string(),
230                     qualname: qualname,
231                     span: sub_span.unwrap(),
232                     scope: self.analysis.ty_cx.map.get_parent(item.id),
233                     filename: filename,
234                 })
235             },
236             ast::ItemEnum(..) => {
237                 let enum_name = format!("::{}", self.analysis.ty_cx.map.path_to_string(item.id));
238                 let val = self.span_utils.snippet(item.span);
239                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
240
241                 Data::EnumData(EnumData {
242                     id: item.id,
243                     value: val,
244                     span: sub_span.unwrap(),
245                     qualname: enum_name,
246                     scope: self.analysis.ty_cx.map.get_parent(item.id),
247                 })
248             },
249             ast::ItemImpl(_, _, _, ref trait_ref, ref typ, _) => {
250                 let mut type_data = None;
251                 let sub_span;
252
253                 let parent = self.analysis.ty_cx.map.get_parent(item.id);
254
255                 match typ.node {
256                     // Common case impl for a struct or something basic.
257                     ast::TyPath(None, ref path) => {
258                         sub_span = self.span_utils.sub_span_for_type_name(path.span);
259                         type_data = self.lookup_ref_id(typ.id).map(|id| TypeRefData {
260                             span: sub_span.unwrap(),
261                             scope: parent,
262                             ref_id: id,
263                         });
264                     },
265                     _ => {
266                         // Less useful case, impl for a compound type.
267                         sub_span = self.span_utils.sub_span_for_type_name(typ.span);
268                     }
269                 }
270
271                 let trait_data =
272                     trait_ref.as_ref().and_then(|tr| self.get_trait_ref_data(tr, parent));
273
274                 Data::ImplData(ImplData {
275                     id: item.id,
276                     span: sub_span.unwrap(),
277                     scope: parent,
278                     trait_ref: trait_data,
279                     self_ref: type_data,
280                 })
281             }
282             _ => {
283                 // FIXME
284                 unimplemented!();
285             }
286         }
287     }
288
289     // FIXME: we ought to be able to get the parent id ourselves, but we can't
290     // for now.
291     pub fn get_field_data(&self, field: &ast::StructField, parent: NodeId) -> Option<Data> {
292         match field.node.kind {
293             ast::NamedField(ident, _) => {
294                 let name = get_ident(ident);
295                 let qualname = format!("::{}::{}",
296                                        self.analysis.ty_cx.map.path_to_string(parent),
297                                        name);
298                 let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
299                                               *self.analysis.ty_cx.node_types()
300                                                   .get(&field.node.id).unwrap());
301                 let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
302                 Some(Data::VariableData(VariableData {
303                     id: field.node.id,
304                     name: get_ident(ident).to_string(),
305                     qualname: qualname,
306                     span: sub_span.unwrap(),
307                     scope: parent,
308                     value: "".to_owned(),
309                     type_value: typ,
310                 }))
311             },
312             _ => None,
313         }
314     }
315
316     // FIXME: we ought to be able to get the parent id ourselves, but we can't
317     // for now.
318     pub fn get_trait_ref_data(&self,
319                               trait_ref: &ast::TraitRef,
320                               parent: NodeId)
321                               -> Option<TypeRefData> {
322         self.lookup_ref_id(trait_ref.ref_id).map(|def_id| {
323             let sub_span = self.span_utils.sub_span_for_type_name(trait_ref.path.span);
324             TypeRefData {
325                 span: sub_span.unwrap(),
326                 scope: parent,
327                 ref_id: def_id,
328             }
329         })
330     }
331
332     pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
333         match expr.node {
334             ast::ExprField(ref sub_ex, ident) => {
335                 let ty = &ty::expr_ty_adjusted(&self.analysis.ty_cx, &sub_ex).sty;
336                 match *ty {
337                     ty::TyStruct(def_id, _) => {
338                         let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, def_id);
339                         for f in &fields {
340                             if f.name == ident.node.name {
341                                 let sub_span = self.span_utils.span_for_last_ident(expr.span);
342                                 return Some(Data::VariableRefData(VariableRefData {
343                                     name: get_ident(ident.node).to_string(),
344                                     span: sub_span.unwrap(),
345                                     scope: self.analysis.ty_cx.map.get_parent(expr.id),
346                                     ref_id: f.id,
347                                 }));
348                             }
349                         }
350
351                         self.sess.span_bug(expr.span,
352                                            &format!("Couldn't find field {} on {:?}",
353                                                     &get_ident(ident.node),
354                                                     ty))
355                     }
356                     _ => {
357                         debug!("Expected struct type, found {:?}", ty);
358                         None
359                     }
360                 }
361             }
362             ast::ExprStruct(ref path, _, _) => {
363                 let ty = &ty::expr_ty_adjusted(&self.analysis.ty_cx, expr).sty;
364                 match *ty {
365                     ty::TyStruct(def_id, _) => {
366                         let sub_span = self.span_utils.span_for_last_ident(path.span);
367                         Some(Data::TypeRefData(TypeRefData {
368                             span: sub_span.unwrap(),
369                             scope: self.analysis.ty_cx.map.get_parent(expr.id),
370                             ref_id: def_id,
371                         }))
372                     }
373                     _ => {
374                         // FIXME ty could legitimately be a TyEnum, but then we will fail
375                         // later if we try to look up the fields.
376                         debug!("expected TyStruct, found {:?}", ty);
377                         None
378                     }
379                 }
380             }
381             _ => {
382                 // FIXME
383                 unimplemented!();
384             }
385         }
386     }
387
388     pub fn get_field_ref_data(&self,
389                               field_ref: &ast::Field,
390                               struct_id: DefId,
391                               parent: NodeId)
392                               -> VariableRefData {
393         let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_id);
394         let field_name = get_ident(field_ref.ident.node).to_string();
395         for f in &fields {
396             if f.name == field_ref.ident.node.name {
397                 // We don't really need a sub-span here, but no harm done
398                 let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
399                 return VariableRefData {
400                     name: field_name,
401                     span: sub_span.unwrap(),
402                     scope: parent,
403                     ref_id: f.id,
404                 };
405             }
406         }
407
408         self.sess.span_bug(field_ref.span,
409                            &format!("Couldn't find field {}", field_name));
410     }
411
412     pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
413         // FIXME
414         unimplemented!();
415     }
416
417     fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
418         if !self.analysis.ty_cx.def_map.borrow().contains_key(&ref_id) {
419             self.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
420                                   ref_id));
421         }
422         let def = self.analysis.ty_cx.def_map.borrow().get(&ref_id).unwrap().full_def();
423         match def {
424             def::DefPrimTy(_) => None,
425             _ => Some(def.def_id()),
426         }
427     }
428
429 }
430
431 // An AST visitor for collecting paths from patterns.
432 struct PathCollector {
433     // The Row field identifies the kind of pattern.
434     collected_paths: Vec<(NodeId, ast::Path, ast::Mutability, recorder::Row)>,
435 }
436
437 impl PathCollector {
438     fn new() -> PathCollector {
439         PathCollector {
440             collected_paths: vec![],
441         }
442     }
443 }
444
445 impl<'v> Visitor<'v> for PathCollector {
446     fn visit_pat(&mut self, p: &ast::Pat) {
447         if generated_code(p.span) {
448             return;
449         }
450
451         match p.node {
452             ast::PatStruct(ref path, _, _) => {
453                 self.collected_paths.push((p.id,
454                                            path.clone(),
455                                            ast::MutMutable,
456                                            recorder::TypeRef));
457             }
458             ast::PatEnum(ref path, _) |
459             ast::PatQPath(_, ref path) => {
460                 self.collected_paths.push((p.id, path.clone(), ast::MutMutable, recorder::VarRef));
461             }
462             ast::PatIdent(bm, ref path1, _) => {
463                 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
464                        token::get_ident(path1.node),
465                        p.span,
466                        path1.span);
467                 let immut = match bm {
468                     // Even if the ref is mut, you can't change the ref, only
469                     // the data pointed at, so showing the initialising expression
470                     // is still worthwhile.
471                     ast::BindByRef(_) => ast::MutImmutable,
472                     ast::BindByValue(mt) => mt,
473                 };
474                 // collect path for either visit_local or visit_arm
475                 let path = ast_util::ident_to_path(path1.span, path1.node);
476                 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
477             }
478             _ => {}
479         }
480         visit::walk_pat(self, p);
481     }
482 }
483
484 #[allow(deprecated)]
485 pub fn process_crate(sess: &Session,
486                      krate: &ast::Crate,
487                      analysis: &ty::CrateAnalysis,
488                      odir: Option<&Path>) {
489     if generated_code(krate.span) {
490         return;
491     }
492
493     assert!(analysis.glob_map.is_some());
494     let cratename = match attr::find_crate_name(&krate.attrs) {
495         Some(name) => name.to_string(),
496         None => {
497             info!("Could not find crate name, using 'unknown_crate'");
498             String::from("unknown_crate")
499         },
500     };
501
502     info!("Dumping crate {}", cratename);
503
504     // find a path to dump our data to
505     let mut root_path = match env::var_os("DXR_RUST_TEMP_FOLDER") {
506         Some(val) => PathBuf::from(val),
507         None => match odir {
508             Some(val) => val.join("dxr"),
509             None => PathBuf::from("dxr-temp"),
510         },
511     };
512
513     match fs::create_dir_all(&root_path) {
514         Err(e) => sess.err(&format!("Could not create directory {}: {}",
515                            root_path.display(), e)),
516         _ => (),
517     }
518
519     {
520         let disp = root_path.display();
521         info!("Writing output to {}", disp);
522     }
523
524     // Create output file.
525     let mut out_name = cratename.clone();
526     out_name.push_str(".csv");
527     root_path.push(&out_name);
528     let output_file = match File::create(&root_path) {
529         Ok(f) => box f,
530         Err(e) => {
531             let disp = root_path.display();
532             sess.fatal(&format!("Could not open {}: {}", disp, e));
533         }
534     };
535     root_path.pop();
536
537     let mut visitor = dump_csv::DumpCsvVisitor::new(sess, analysis, output_file);
538
539     visitor.dump_crate_info(&cratename, krate);
540     visit::walk_crate(&mut visitor, krate);
541 }
542
543 // Utility functions for the module.
544
545 // Helper function to escape quotes in a string
546 fn escape(s: String) -> String {
547     s.replace("\"", "\"\"")
548 }
549
550 // If the expression is a macro expansion or other generated code, run screaming
551 // and don't index.
552 fn generated_code(span: Span) -> bool {
553     span.expn_id != NO_EXPANSION || span  == DUMMY_SP
554 }