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