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