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