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.
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.
16 use std::fs::{self, File};
17 use std::path::{Path, PathBuf};
20 use syntax::ast::{self, NodeId, DefId};
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;
29 use self::span_utils::SpanUtils;
37 pub struct SaveContext<'l, 'tcx: 'l> {
39 analysis: &'l ty::CrateAnalysis<'tcx>,
40 span_utils: SpanUtils<'l>,
43 pub struct CrateData {
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.
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),
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),
70 /// Data for all kinds of functions and methods.
72 pub struct FunctionData {
76 pub declaration: Option<DefId>,
81 /// Data for local and global variables (consts and statics).
83 pub struct VariableData {
90 pub type_value: String,
101 pub filename: String,
104 /// Data for enum declarations.
106 pub struct EnumData {
109 pub qualname: String,
115 pub struct ImplData {
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
122 pub trait_ref: Option<TypeRefData>,
123 pub self_ref: Option<TypeRefData>,
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)).
129 pub struct VariableRefData {
136 /// Data for a reference to a type or trait.
138 pub struct TypeRefData {
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> {
153 span_utils: span_utils,
157 // List external crates used by the current crate.
158 pub fn get_external_crates(&self) -> Vec<CrateData> {
159 let mut result = Vec::new();
161 self.sess.cstore.iter_crate_data(|n, cmd| {
162 result.push(CrateData { name: cmd.name.clone(), number: n });
168 pub fn get_item_data(&self, item: &ast::Item) -> Data {
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);
175 Data::FunctionData(FunctionData {
180 span: sub_span.unwrap(),
181 scope: self.analysis.ty_cx.map.get_parent(item.id),
184 ast::ItemStatic(ref typ, mt, ref expr) => {
185 let qualname = format!("::{}", self.analysis.ty_cx.map.path_to_string(item.id));
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),
193 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
195 Data::VariableData(VariableData {
197 name: get_ident(item.ident).to_string(),
199 span: sub_span.unwrap(),
200 scope: self.analysis.ty_cx.map.get_parent(item.id),
202 type_value: ty_to_string(&typ),
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);
209 Data::VariableData(VariableData {
211 name: get_ident(item.ident).to_string(),
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),
219 ast::ItemMod(ref m) => {
220 let qualname = format!("::{}", self.analysis.ty_cx.map.path_to_string(item.id));
222 let cm = self.sess.codemap();
223 let filename = cm.span_to_filename(m.inner);
225 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
227 Data::ModData(ModData {
229 name: get_ident(item.ident).to_string(),
231 span: sub_span.unwrap(),
232 scope: self.analysis.ty_cx.map.get_parent(item.id),
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);
241 Data::EnumData(EnumData {
244 span: sub_span.unwrap(),
246 scope: self.analysis.ty_cx.map.get_parent(item.id),
249 ast::ItemImpl(_, _, _, ref trait_ref, ref typ, _) => {
250 let mut type_data = None;
253 let parent = self.analysis.ty_cx.map.get_parent(item.id);
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(),
266 // Less useful case, impl for a compound type.
267 sub_span = self.span_utils.sub_span_for_type_name(typ.span);
272 trait_ref.as_ref().and_then(|tr| self.get_trait_ref_data(tr, parent));
274 Data::ImplData(ImplData {
276 span: sub_span.unwrap(),
278 trait_ref: trait_data,
289 // FIXME: we ought to be able to get the parent id ourselves, but we can't
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),
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 {
304 name: get_ident(ident).to_string(),
306 span: sub_span.unwrap(),
308 value: "".to_owned(),
316 // FIXME: we ought to be able to get the parent id ourselves, but we can't
318 pub fn get_trait_ref_data(&self,
319 trait_ref: &ast::TraitRef,
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);
325 span: sub_span.unwrap(),
332 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
334 ast::ExprField(ref sub_ex, ident) => {
335 let ty = &ty::expr_ty_adjusted(&self.analysis.ty_cx, &sub_ex).sty;
337 ty::TyStruct(def_id, _) => {
338 let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, def_id);
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),
351 self.sess.span_bug(expr.span,
352 &format!("Couldn't find field {} on {:?}",
353 &get_ident(ident.node),
357 debug!("Expected struct type, found {:?}", ty);
362 ast::ExprStruct(ref path, _, _) => {
363 let ty = &ty::expr_ty_adjusted(&self.analysis.ty_cx, expr).sty;
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),
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);
388 pub fn get_field_ref_data(&self,
389 field_ref: &ast::Field,
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();
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 {
401 span: sub_span.unwrap(),
408 self.sess.span_bug(field_ref.span,
409 &format!("Couldn't find field {}", field_name));
412 pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
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",
422 let def = self.analysis.ty_cx.def_map.borrow().get(&ref_id).unwrap().full_def();
424 def::DefPrimTy(_) => None,
425 _ => Some(def.def_id()),
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)>,
438 fn new() -> PathCollector {
440 collected_paths: vec![],
445 impl<'v> Visitor<'v> for PathCollector {
446 fn visit_pat(&mut self, p: &ast::Pat) {
447 if generated_code(p.span) {
452 ast::PatStruct(ref path, _, _) => {
453 self.collected_paths.push((p.id,
458 ast::PatEnum(ref path, _) |
459 ast::PatQPath(_, ref path) => {
460 self.collected_paths.push((p.id, path.clone(), ast::MutMutable, recorder::VarRef));
462 ast::PatIdent(bm, ref path1, _) => {
463 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
464 token::get_ident(path1.node),
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,
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));
480 visit::walk_pat(self, p);
485 pub fn process_crate(sess: &Session,
487 analysis: &ty::CrateAnalysis,
488 odir: Option<&Path>) {
489 if generated_code(krate.span) {
493 assert!(analysis.glob_map.is_some());
494 let cratename = match attr::find_crate_name(&krate.attrs) {
495 Some(name) => name.to_string(),
497 info!("Could not find crate name, using 'unknown_crate'");
498 String::from("unknown_crate")
502 info!("Dumping crate {}", cratename);
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),
508 Some(val) => val.join("dxr"),
509 None => PathBuf::from("dxr-temp"),
513 match fs::create_dir_all(&root_path) {
514 Err(e) => sess.err(&format!("Could not create directory {}: {}",
515 root_path.display(), e)),
520 let disp = root_path.display();
521 info!("Writing output to {}", disp);
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) {
531 let disp = root_path.display();
532 sess.fatal(&format!("Could not open {}: {}", disp, e));
537 let mut visitor = dump_csv::DumpCsvVisitor::new(sess, analysis, output_file);
539 visitor.dump_crate_info(&cratename, krate);
540 visit::walk_crate(&mut visitor, krate);
543 // Utility functions for the module.
545 // Helper function to escape quotes in a string
546 fn escape(s: String) -> String {
547 s.replace("\"", "\"\"")
550 // If the expression is a macro expansion or other generated code, run screaming
552 fn generated_code(span: Span) -> bool {
553 span.expn_id != NO_EXPANSION || span == DUMMY_SP