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 method call.
65 MethodCallData(MethodCallData),
68 /// Data for all kinds of functions and methods.
70 pub struct FunctionData {
74 pub declaration: Option<DefId>,
79 /// Data for local and global variables (consts and statics).
81 pub struct VariableData {
88 pub type_value: String,
102 /// Data for enum declarations.
104 pub struct EnumData {
107 pub qualname: String,
113 pub struct ImplData {
117 // FIXME: I'm not really sure inline data is the best way to do this. Seems
118 // OK in this case, but generalising leads to returning chunks of AST, which
120 pub trait_ref: Option<TypeRefData>,
121 pub self_ref: Option<TypeRefData>,
124 /// Data for the use of some item (e.g., the use of a local variable, which
125 /// will refere to that variables declaration (by ref_id)).
127 pub struct VariableRefData {
134 /// Data for a reference to a type or trait.
136 pub struct TypeRefData {
142 /// Data about a method call.
144 pub struct MethodCallData {
147 pub ref_id: Option<DefId>,
148 pub decl_id: Option<DefId>,
153 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
154 pub fn new(tcx: &'l ty::ctxt<'tcx>,
155 span_utils: SpanUtils<'l>)
156 -> SaveContext<'l, 'tcx> {
159 span_utils: span_utils,
163 // List external crates used by the current crate.
164 pub fn get_external_crates(&self) -> Vec<CrateData> {
165 let mut result = Vec::new();
167 self.tcx.sess.cstore.iter_crate_data(|n, cmd| {
168 result.push(CrateData { name: cmd.name.clone(), number: n });
174 pub fn get_item_data(&self, item: &ast::Item) -> Data {
177 let name = self.tcx.map.path_to_string(item.id);
178 let qualname = format!("::{}", name);
179 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
181 Data::FunctionData(FunctionData {
186 span: sub_span.unwrap(),
187 scope: self.tcx.map.get_enclosing_scope(item.id).unwrap_or(0),
190 ast::ItemStatic(ref typ, mt, ref expr) => {
191 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
193 // If the variable is immutable, save the initialising expression.
194 let (value, keyword) = match mt {
195 ast::MutMutable => (String::from("<mutable>"), keywords::Mut),
196 ast::MutImmutable => (self.span_utils.snippet(expr.span), keywords::Static),
199 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
201 Data::VariableData(VariableData {
203 name: get_ident(item.ident).to_string(),
205 span: sub_span.unwrap(),
206 scope: self.tcx.map.get_enclosing_scope(item.id).unwrap_or(0),
208 type_value: ty_to_string(&typ),
211 ast::ItemConst(ref typ, ref expr) => {
212 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
213 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
215 Data::VariableData(VariableData {
217 name: get_ident(item.ident).to_string(),
219 span: sub_span.unwrap(),
220 scope: self.tcx.map.get_enclosing_scope(item.id).unwrap_or(0),
221 value: self.span_utils.snippet(expr.span),
222 type_value: ty_to_string(&typ),
225 ast::ItemMod(ref m) => {
226 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
228 let cm = self.tcx.sess.codemap();
229 let filename = cm.span_to_filename(m.inner);
231 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
233 Data::ModData(ModData {
235 name: get_ident(item.ident).to_string(),
237 span: sub_span.unwrap(),
238 scope: self.tcx.map.get_enclosing_scope(item.id).unwrap_or(0),
242 ast::ItemEnum(..) => {
243 let enum_name = format!("::{}", self.tcx.map.path_to_string(item.id));
244 let val = self.span_utils.snippet(item.span);
245 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
247 Data::EnumData(EnumData {
250 span: sub_span.unwrap(),
252 scope: self.tcx.map.get_enclosing_scope(item.id).unwrap_or(0),
255 ast::ItemImpl(_, _, _, ref trait_ref, ref typ, _) => {
256 let mut type_data = None;
259 let parent = self.tcx.map.get_enclosing_scope(item.id).unwrap_or(0);
262 // Common case impl for a struct or something basic.
263 ast::TyPath(None, ref path) => {
264 sub_span = self.span_utils.sub_span_for_type_name(path.span).unwrap();
265 type_data = self.lookup_ref_id(typ.id).map(|id| TypeRefData {
272 // Less useful case, impl for a compound type.
274 sub_span = self.span_utils.sub_span_for_type_name(span).unwrap_or(span);
279 trait_ref.as_ref().and_then(|tr| self.get_trait_ref_data(tr, parent));
281 Data::ImplData(ImplData {
285 trait_ref: trait_data,
296 // FIXME: we ought to be able to get the parent id ourselves, but we can't
298 pub fn get_field_data(&self, field: &ast::StructField, parent: NodeId) -> Option<Data> {
299 match field.node.kind {
300 ast::NamedField(ident, _) => {
301 let name = get_ident(ident);
302 let qualname = format!("::{}::{}",
303 self.tcx.map.path_to_string(parent),
305 let typ = self.tcx.node_types().get(&field.node.id).unwrap()
307 let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
308 Some(Data::VariableData(VariableData {
310 name: get_ident(ident).to_string(),
312 span: sub_span.unwrap(),
314 value: "".to_owned(),
322 // FIXME: we ought to be able to get the parent id ourselves, but we can't
324 pub fn get_trait_ref_data(&self,
325 trait_ref: &ast::TraitRef,
327 -> Option<TypeRefData> {
328 self.lookup_ref_id(trait_ref.ref_id).map(|def_id| {
329 let span = trait_ref.path.span;
330 let sub_span = self.span_utils.sub_span_for_type_name(span).unwrap_or(span);
339 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
341 ast::ExprField(ref sub_ex, ident) => {
342 let ty = &self.tcx.expr_ty_adjusted(&sub_ex).sty;
344 ty::TyStruct(def_id, _) => {
345 let fields = self.tcx.lookup_struct_fields(def_id);
347 if f.name == ident.node.name {
348 let sub_span = self.span_utils.span_for_last_ident(expr.span);
349 return Some(Data::VariableRefData(VariableRefData {
350 name: get_ident(ident.node).to_string(),
351 span: sub_span.unwrap(),
352 scope: self.tcx.map.get_enclosing_scope(expr.id).unwrap_or(0),
358 self.tcx.sess.span_bug(expr.span,
359 &format!("Couldn't find field {} on {:?}",
360 &get_ident(ident.node), ty))
363 debug!("Expected struct type, found {:?}", ty);
368 ast::ExprStruct(ref path, _, _) => {
369 let ty = &self.tcx.expr_ty_adjusted(expr).sty;
371 ty::TyStruct(def_id, _) => {
372 let sub_span = self.span_utils.span_for_last_ident(path.span);
373 Some(Data::TypeRefData(TypeRefData {
374 span: sub_span.unwrap(),
375 scope: self.tcx.map.get_enclosing_scope(expr.id).unwrap_or(0),
380 // FIXME ty could legitimately be a TyEnum, but then we will fail
381 // later if we try to look up the fields.
382 debug!("expected TyStruct, found {:?}", ty);
387 ast::ExprMethodCall(..) => {
388 let method_call = ty::MethodCall::expr(expr.id);
389 let method_id = self.tcx.tables.borrow().method_map[&method_call].def_id;
390 let (def_id, decl_id) = match self.tcx.impl_or_trait_item(method_id).container() {
391 ty::ImplContainer(_) => (Some(method_id), None),
392 ty::TraitContainer(_) => (None, Some(method_id))
394 let sub_span = self.span_utils.sub_span_for_meth_name(expr.span);
395 Some(Data::MethodCallData(MethodCallData {
396 span: sub_span.unwrap(),
397 scope: self.tcx.map.get_enclosing_scope(expr.id).unwrap_or(0),
409 pub fn get_field_ref_data(&self,
410 field_ref: &ast::Field,
414 let fields = self.tcx.lookup_struct_fields(struct_id);
415 let field_name = get_ident(field_ref.ident.node).to_string();
417 if f.name == field_ref.ident.node.name {
418 // We don't really need a sub-span here, but no harm done
419 let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
420 return VariableRefData {
422 span: sub_span.unwrap(),
429 self.tcx.sess.span_bug(field_ref.span,
430 &format!("Couldn't find field {}", field_name));
433 pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
438 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
439 if !self.tcx.def_map.borrow().contains_key(&ref_id) {
440 self.tcx.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
443 let def = self.tcx.def_map.borrow().get(&ref_id).unwrap().full_def();
445 def::DefPrimTy(_) => None,
446 _ => Some(def.def_id()),
452 // An AST visitor for collecting paths from patterns.
453 struct PathCollector {
454 // The Row field identifies the kind of pattern.
455 collected_paths: Vec<(NodeId, ast::Path, ast::Mutability, recorder::Row)>,
459 fn new() -> PathCollector {
461 collected_paths: vec![],
466 impl<'v> Visitor<'v> for PathCollector {
467 fn visit_pat(&mut self, p: &ast::Pat) {
468 if generated_code(p.span) {
473 ast::PatStruct(ref path, _, _) => {
474 self.collected_paths.push((p.id,
479 ast::PatEnum(ref path, _) |
480 ast::PatQPath(_, ref path) => {
481 self.collected_paths.push((p.id, path.clone(), ast::MutMutable, recorder::VarRef));
483 ast::PatIdent(bm, ref path1, _) => {
484 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
485 token::get_ident(path1.node),
488 let immut = match bm {
489 // Even if the ref is mut, you can't change the ref, only
490 // the data pointed at, so showing the initialising expression
491 // is still worthwhile.
492 ast::BindByRef(_) => ast::MutImmutable,
493 ast::BindByValue(mt) => mt,
495 // collect path for either visit_local or visit_arm
496 let path = ast_util::ident_to_path(path1.span, path1.node);
497 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
501 visit::walk_pat(self, p);
506 pub fn process_crate(tcx: &ty::ctxt,
507 analysis: &ty::CrateAnalysis,
508 odir: Option<&Path>) {
509 let krate = tcx.map.krate();
510 if generated_code(krate.span) {
514 assert!(analysis.glob_map.is_some());
515 let cratename = match attr::find_crate_name(&krate.attrs) {
516 Some(name) => name.to_string(),
518 info!("Could not find crate name, using 'unknown_crate'");
519 String::from("unknown_crate")
523 info!("Dumping crate {}", cratename);
525 // find a path to dump our data to
526 let mut root_path = match env::var_os("DXR_RUST_TEMP_FOLDER") {
527 Some(val) => PathBuf::from(val),
529 Some(val) => val.join("dxr"),
530 None => PathBuf::from("dxr-temp"),
534 if let Err(e) = fs::create_dir_all(&root_path) {
535 tcx.sess.err(&format!("Could not create directory {}: {}",
536 root_path.display(), e));
540 let disp = root_path.display();
541 info!("Writing output to {}", disp);
544 // Create output file.
545 let mut out_name = cratename.clone();
546 out_name.push_str(".csv");
547 root_path.push(&out_name);
548 let output_file = match File::create(&root_path) {
551 let disp = root_path.display();
552 tcx.sess.fatal(&format!("Could not open {}: {}", disp, e));
557 let mut visitor = dump_csv::DumpCsvVisitor::new(tcx, analysis, output_file);
559 visitor.dump_crate_info(&cratename, krate);
560 visit::walk_crate(&mut visitor, krate);
563 // Utility functions for the module.
565 // Helper function to escape quotes in a string
566 fn escape(s: String) -> String {
567 s.replace("\"", "\"\"")
570 // If the expression is a macro expansion or other generated code, run screaming
572 fn generated_code(span: Span) -> bool {
573 span.expn_id != NO_EXPANSION || span == DUMMY_SP