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.
15 use std::fs::{self, File};
16 use std::path::{Path, PathBuf};
19 use syntax::ast::{self, NodeId, DefId};
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;
26 use self::span_utils::SpanUtils;
34 pub struct SaveContext<'l, 'tcx: 'l> {
35 tcx: &'l ty::ctxt<'tcx>,
36 span_utils: SpanUtils<'l>,
39 pub struct CrateData {
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.
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),
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),
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 refer 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 {
144 /// Data about a function call.
146 pub struct FunctionCallData {
152 /// Data about a method call.
154 pub struct MethodCallData {
157 pub ref_id: Option<DefId>,
158 pub decl_id: Option<DefId>,
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> {
169 span_utils: span_utils,
173 // List external crates used by the current crate.
174 pub fn get_external_crates(&self) -> Vec<CrateData> {
175 let mut result = Vec::new();
177 self.tcx.sess.cstore.iter_crate_data(|n, cmd| {
178 result.push(CrateData { name: cmd.name.clone(), number: n });
184 pub fn get_item_data(&self, item: &ast::Item) -> Data {
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);
191 Data::FunctionData(FunctionData {
196 span: sub_span.unwrap(),
197 scope: self.tcx.map.get_enclosing_scope(item.id).unwrap_or(0),
200 ast::ItemStatic(ref typ, mt, ref expr) => {
201 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
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),
209 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
211 Data::VariableData(VariableData {
213 name: get_ident(item.ident).to_string(),
215 span: sub_span.unwrap(),
216 scope: self.tcx.map.get_enclosing_scope(item.id).unwrap_or(0),
218 type_value: ty_to_string(&typ),
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);
225 Data::VariableData(VariableData {
227 name: get_ident(item.ident).to_string(),
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),
235 ast::ItemMod(ref m) => {
236 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
238 let cm = self.tcx.sess.codemap();
239 let filename = cm.span_to_filename(m.inner);
241 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
243 Data::ModData(ModData {
245 name: get_ident(item.ident).to_string(),
247 span: sub_span.unwrap(),
248 scope: self.tcx.map.get_enclosing_scope(item.id).unwrap_or(0),
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);
257 Data::EnumData(EnumData {
260 span: sub_span.unwrap(),
262 scope: self.tcx.map.get_enclosing_scope(item.id).unwrap_or(0),
265 ast::ItemImpl(_, _, _, ref trait_ref, ref typ, _) => {
266 let mut type_data = None;
269 let parent = self.tcx.map.get_enclosing_scope(item.id).unwrap_or(0);
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 {
282 // Less useful case, impl for a compound type.
284 sub_span = self.span_utils.sub_span_for_type_name(span).unwrap_or(span);
289 trait_ref.as_ref().and_then(|tr| self.get_trait_ref_data(tr, parent));
291 Data::ImplData(ImplData {
295 trait_ref: trait_data,
306 // FIXME: we ought to be able to get the parent id ourselves, but we can't
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),
315 let typ = self.tcx.node_types().get(&field.node.id).unwrap()
317 let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
318 Some(Data::VariableData(VariableData {
320 name: get_ident(ident).to_string(),
322 span: sub_span.unwrap(),
324 value: "".to_owned(),
332 // FIXME: we ought to be able to get the parent id ourselves, but we can't
334 pub fn get_trait_ref_data(&self,
335 trait_ref: &ast::TraitRef,
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);
349 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
351 ast::ExprField(ref sub_ex, ident) => {
352 let ty = &self.tcx.expr_ty_adjusted(&sub_ex).sty;
354 ty::TyStruct(def_id, _) => {
355 let fields = self.tcx.lookup_struct_fields(def_id);
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),
368 self.tcx.sess.span_bug(expr.span,
369 &format!("Couldn't find field {} on {:?}",
370 &get_ident(ident.node), ty))
373 debug!("Expected struct type, found {:?}", ty);
378 ast::ExprStruct(ref path, _, _) => {
379 let ty = &self.tcx.expr_ty_adjusted(expr).sty;
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),
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);
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))
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(),
413 ast::ExprPath(_, ref path) => {
414 Some(self.get_path_data(expr.id, path))
423 pub fn get_path_data(&self,
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));
432 let def = def_map.get(&id).unwrap().full_def();
433 let sub_span = self.span_utils.span_for_last_ident(path.span);
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(),
448 def::DefStruct(def_id) | def::DefTy(def_id, _) => {
449 Data::TypeRefData(TypeRefData {
450 span: sub_span.unwrap(),
452 scope: self.tcx.map.get_enclosing_scope(id).unwrap_or(0),
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);
460 def::FromTrait(def_id) => {
461 Some(self.tcx.trait_items(def_id)
464 mr.name() == ti.name()
469 def::FromImpl(def_id) => {
470 let impl_items = self.tcx.impl_items.borrow();
471 Some(impl_items.get(&def_id)
475 self.tcx.impl_or_trait_item(mr.def_id()).name()
485 Data::MethodCallData(MethodCallData {
486 span: sub_span.unwrap(),
487 scope: self.tcx.map.get_enclosing_scope(id).unwrap_or(0),
489 decl_id: Some(decl_id),
492 def::DefFn(def_id, _) => {
493 Data::FunctionCallData(FunctionCallData {
495 span: sub_span.unwrap(),
496 scope: self.tcx.map.get_enclosing_scope(id).unwrap_or(0),
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),
507 pub fn get_field_ref_data(&self,
508 field_ref: &ast::Field,
512 let fields = self.tcx.lookup_struct_fields(struct_id);
513 let field_name = get_ident(field_ref.ident.node).to_string();
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 {
520 span: sub_span.unwrap(),
527 self.tcx.sess.span_bug(field_ref.span,
528 &format!("Couldn't find field {}", field_name));
531 pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
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",
541 let def = self.tcx.def_map.borrow().get(&ref_id).unwrap().full_def();
543 def::DefPrimTy(_) => None,
544 _ => Some(def.def_id()),
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)>,
557 fn new() -> PathCollector {
559 collected_paths: vec![],
564 impl<'v> Visitor<'v> for PathCollector {
565 fn visit_pat(&mut self, p: &ast::Pat) {
566 if generated_code(p.span) {
571 ast::PatStruct(ref path, _, _) => {
572 self.collected_paths.push((p.id,
577 ast::PatEnum(ref path, _) |
578 ast::PatQPath(_, ref path) => {
579 self.collected_paths.push((p.id, path.clone(), ast::MutMutable, recorder::VarRef));
581 ast::PatIdent(bm, ref path1, _) => {
582 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
583 token::get_ident(path1.node),
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,
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));
599 visit::walk_pat(self, p);
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) {
612 assert!(analysis.glob_map.is_some());
613 let cratename = match attr::find_crate_name(&krate.attrs) {
614 Some(name) => name.to_string(),
616 info!("Could not find crate name, using 'unknown_crate'");
617 String::from("unknown_crate")
621 info!("Dumping crate {}", cratename);
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),
627 Some(val) => val.join("dxr"),
628 None => PathBuf::from("dxr-temp"),
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));
638 let disp = root_path.display();
639 info!("Writing output to {}", disp);
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) {
649 let disp = root_path.display();
650 tcx.sess.fatal(&format!("Could not open {}: {}", disp, e));
655 let mut visitor = dump_csv::DumpCsvVisitor::new(tcx, analysis, output_file);
657 visitor.dump_crate_info(&cratename, krate);
658 visit::walk_crate(&mut visitor, krate);
661 // Utility functions for the module.
663 // Helper function to escape quotes in a string
664 fn escape(s: String) -> String {
665 s.replace("\"", "\"\"")
668 // If the expression is a macro expansion or other generated code, run screaming
670 fn generated_code(span: Span) -> bool {
671 span.expn_id != NO_EXPANSION || span == DUMMY_SP