]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/save/mod.rs
98672a546cb117eab34426c75026e3cf31616bdf
[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
14 use std::env;
15 use std::fs::{self, File};
16 use std::path::{Path, PathBuf};
17
18 use syntax::{attr, visit};
19 use syntax::ast::{self, NodeId, DefId};
20 use syntax::parse::token::keywords;
21 use syntax::codemap::*;
22
23 use self::span_utils::SpanUtils;
24
25 mod span_utils;
26 mod recorder;
27
28 mod dump_csv;
29
30 pub struct SaveContext<'l, 'tcx: 'l> {
31     sess: &'l Session,
32     analysis: &'l ty::CrateAnalysis<'tcx>,
33     span_utils: SpanUtils<'l>,
34 }
35
36 pub struct CrateData {
37     pub name: String,
38     pub number: u32,
39 }
40
41 pub enum Data {
42     FunctionData(FunctionData),
43 }
44
45 pub struct FunctionData {
46     pub id: NodeId,
47     pub qualname: String,
48     pub declaration: Option<DefId>,
49     pub span: Span,
50     pub scope: NodeId,
51 }
52
53 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
54     pub fn new(sess: &'l Session,
55                analysis: &'l ty::CrateAnalysis<'tcx>,
56                span_utils: SpanUtils<'l>)
57                -> SaveContext<'l, 'tcx> {
58         SaveContext {
59             sess: sess,
60             analysis: analysis,
61             span_utils: span_utils,
62         }
63     }
64
65     // List external crates used by the current crate.
66     pub fn get_external_crates(&self) -> Vec<CrateData> {
67         let mut result = Vec::new();
68
69         self.sess.cstore.iter_crate_data(|n, cmd| {
70             result.push(CrateData { name: cmd.name.clone(), number: n });
71         });
72
73         result
74     }
75
76     pub fn get_item_data(&self, item: &ast::Item) -> Data {
77         match item.node {
78             ast::Item_::ItemFn(..) => {
79                 let qualname = format!("::{}", self.analysis.ty_cx.map.path_to_string(item.id));
80                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
81
82                 Data::FunctionData(FunctionData {
83                     id: item.id,
84                     qualname: qualname,
85                     declaration: None,
86                     span: sub_span.unwrap(),
87                     scope: self.analysis.ty_cx.map.get_parent(item.id),
88                 })
89             }
90             _ => {
91                 unimplemented!();
92             }
93         }
94     }
95
96     pub fn get_data_for_id(&self, id: &NodeId) -> Data {
97         unimplemented!();        
98     }
99 }
100
101 #[allow(deprecated)]
102 pub fn process_crate(sess: &Session,
103                      krate: &ast::Crate,
104                      analysis: &ty::CrateAnalysis,
105                      odir: Option<&Path>) {
106     if generated_code(krate.span) {
107         return;
108     }
109
110     assert!(analysis.glob_map.is_some());
111     let cratename = match attr::find_crate_name(&krate.attrs) {
112         Some(name) => name.to_string(),
113         None => {
114             info!("Could not find crate name, using 'unknown_crate'");
115             String::from_str("unknown_crate")
116         },
117     };
118
119     info!("Dumping crate {}", cratename);
120
121     // find a path to dump our data to
122     let mut root_path = match env::var_os("DXR_RUST_TEMP_FOLDER") {
123         Some(val) => PathBuf::from(val),
124         None => match odir {
125             Some(val) => val.join("dxr"),
126             None => PathBuf::from("dxr-temp"),
127         },
128     };
129
130     match fs::create_dir_all(&root_path) {
131         Err(e) => sess.err(&format!("Could not create directory {}: {}",
132                            root_path.display(), e)),
133         _ => (),
134     }
135
136     {
137         let disp = root_path.display();
138         info!("Writing output to {}", disp);
139     }
140
141     // Create output file.
142     let mut out_name = cratename.clone();
143     out_name.push_str(".csv");
144     root_path.push(&out_name);
145     let output_file = match File::create(&root_path) {
146         Ok(f) => box f,
147         Err(e) => {
148             let disp = root_path.display();
149             sess.fatal(&format!("Could not open {}: {}", disp, e));
150         }
151     };
152     root_path.pop();
153
154     let mut visitor = dump_csv::DumpCsvVisitor::new(sess, analysis, output_file);
155
156     visitor.dump_crate_info(&cratename[..], krate);
157     visit::walk_crate(&mut visitor, krate);
158 }
159
160 // Utility functions for the module.
161
162 // Helper function to escape quotes in a string
163 fn escape(s: String) -> String {
164     s.replace("\"", "\"\"")
165 }
166
167 // If the expression is a macro expansion or other generated code, run screaming
168 // and don't index.
169 fn generated_code(span: Span) -> bool {
170     span.expn_id != NO_EXPANSION || span  == DUMMY_SP
171 }