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),
66 /// Data for all kinds of functions and methods.
68 pub struct FunctionData {
72 pub declaration: Option<DefId>,
77 /// Data for local and global variables (consts and statics).
79 pub struct VariableData {
86 pub type_value: String,
100 /// Data for enum declarations.
102 pub struct EnumData {
105 pub qualname: String,
111 pub struct ImplData {
115 // FIXME: I'm not really sure inline data is the best way to do this. Seems
116 // OK in this case, but generalising leads to returning chunks of AST, which
118 pub trait_ref: Option<TypeRefData>,
119 pub self_ref: Option<TypeRefData>,
122 /// Data for the use of some item (e.g., the use of a local variable, which
123 /// will refere to that variables declaration (by ref_id)).
125 pub struct VariableRefData {
132 /// Data for a reference to a type or trait.
134 pub struct TypeRefData {
141 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
142 pub fn new(tcx: &'l ty::ctxt<'tcx>,
143 span_utils: SpanUtils<'l>)
144 -> SaveContext<'l, 'tcx> {
147 span_utils: span_utils,
151 // List external crates used by the current crate.
152 pub fn get_external_crates(&self) -> Vec<CrateData> {
153 let mut result = Vec::new();
155 self.tcx.sess.cstore.iter_crate_data(|n, cmd| {
156 result.push(CrateData { name: cmd.name.clone(), number: n });
162 pub fn get_item_data(&self, item: &ast::Item) -> Data {
165 let name = self.tcx.map.path_to_string(item.id);
166 let qualname = format!("::{}", name);
167 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
169 Data::FunctionData(FunctionData {
174 span: sub_span.unwrap(),
175 scope: self.tcx.map.get_parent(item.id),
178 ast::ItemStatic(ref typ, mt, ref expr) => {
179 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
181 // If the variable is immutable, save the initialising expression.
182 let (value, keyword) = match mt {
183 ast::MutMutable => (String::from("<mutable>"), keywords::Mut),
184 ast::MutImmutable => (self.span_utils.snippet(expr.span), keywords::Static),
187 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
189 Data::VariableData(VariableData {
191 name: get_ident(item.ident).to_string(),
193 span: sub_span.unwrap(),
194 scope: self.tcx.map.get_parent(item.id),
196 type_value: ty_to_string(&typ),
199 ast::ItemConst(ref typ, ref expr) => {
200 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
201 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
203 Data::VariableData(VariableData {
205 name: get_ident(item.ident).to_string(),
207 span: sub_span.unwrap(),
208 scope: self.tcx.map.get_parent(item.id),
209 value: self.span_utils.snippet(expr.span),
210 type_value: ty_to_string(&typ),
213 ast::ItemMod(ref m) => {
214 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
216 let cm = self.tcx.sess.codemap();
217 let filename = cm.span_to_filename(m.inner);
219 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
221 Data::ModData(ModData {
223 name: get_ident(item.ident).to_string(),
225 span: sub_span.unwrap(),
226 scope: self.tcx.map.get_parent(item.id),
230 ast::ItemEnum(..) => {
231 let enum_name = format!("::{}", self.tcx.map.path_to_string(item.id));
232 let val = self.span_utils.snippet(item.span);
233 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
235 Data::EnumData(EnumData {
238 span: sub_span.unwrap(),
240 scope: self.tcx.map.get_parent(item.id),
243 ast::ItemImpl(_, _, _, ref trait_ref, ref typ, _) => {
244 let mut type_data = None;
247 let parent = self.tcx.map.get_parent(item.id);
250 // Common case impl for a struct or something basic.
251 ast::TyPath(None, ref path) => {
252 sub_span = self.span_utils.sub_span_for_type_name(path.span).unwrap();
253 type_data = self.lookup_ref_id(typ.id).map(|id| TypeRefData {
260 // Less useful case, impl for a compound type.
262 sub_span = self.span_utils.sub_span_for_type_name(span).unwrap_or(span);
267 trait_ref.as_ref().and_then(|tr| self.get_trait_ref_data(tr, parent));
269 Data::ImplData(ImplData {
273 trait_ref: trait_data,
284 // FIXME: we ought to be able to get the parent id ourselves, but we can't
286 pub fn get_field_data(&self, field: &ast::StructField, parent: NodeId) -> Option<Data> {
287 match field.node.kind {
288 ast::NamedField(ident, _) => {
289 let name = get_ident(ident);
290 let qualname = format!("::{}::{}",
291 self.tcx.map.path_to_string(parent),
293 let typ = self.tcx.node_types().get(&field.node.id).unwrap()
295 let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
296 Some(Data::VariableData(VariableData {
298 name: get_ident(ident).to_string(),
300 span: sub_span.unwrap(),
302 value: "".to_owned(),
310 // FIXME: we ought to be able to get the parent id ourselves, but we can't
312 pub fn get_trait_ref_data(&self,
313 trait_ref: &ast::TraitRef,
315 -> Option<TypeRefData> {
316 self.lookup_ref_id(trait_ref.ref_id).map(|def_id| {
317 let span = trait_ref.path.span;
318 let sub_span = self.span_utils.sub_span_for_type_name(span).unwrap_or(span);
327 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
329 ast::ExprField(ref sub_ex, ident) => {
330 let ty = &self.tcx.expr_ty_adjusted(&sub_ex).sty;
332 ty::TyStruct(def_id, _) => {
333 let fields = self.tcx.lookup_struct_fields(def_id);
335 if f.name == ident.node.name {
336 let sub_span = self.span_utils.span_for_last_ident(expr.span);
337 return Some(Data::VariableRefData(VariableRefData {
338 name: get_ident(ident.node).to_string(),
339 span: sub_span.unwrap(),
340 scope: self.tcx.map.get_parent(expr.id),
346 self.tcx.sess.span_bug(expr.span,
347 &format!("Couldn't find field {} on {:?}",
348 &get_ident(ident.node), ty))
351 debug!("Expected struct type, found {:?}", ty);
356 ast::ExprStruct(ref path, _, _) => {
357 let ty = &self.tcx.expr_ty_adjusted(expr).sty;
359 ty::TyStruct(def_id, _) => {
360 let sub_span = self.span_utils.span_for_last_ident(path.span);
361 Some(Data::TypeRefData(TypeRefData {
362 span: sub_span.unwrap(),
363 scope: self.tcx.map.get_parent(expr.id),
368 // FIXME ty could legitimately be a TyEnum, but then we will fail
369 // later if we try to look up the fields.
370 debug!("expected TyStruct, found {:?}", ty);
382 pub fn get_field_ref_data(&self,
383 field_ref: &ast::Field,
387 let fields = self.tcx.lookup_struct_fields(struct_id);
388 let field_name = get_ident(field_ref.ident.node).to_string();
390 if f.name == field_ref.ident.node.name {
391 // We don't really need a sub-span here, but no harm done
392 let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
393 return VariableRefData {
395 span: sub_span.unwrap(),
402 self.tcx.sess.span_bug(field_ref.span,
403 &format!("Couldn't find field {}", field_name));
406 pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
411 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
412 if !self.tcx.def_map.borrow().contains_key(&ref_id) {
413 self.tcx.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
416 let def = self.tcx.def_map.borrow().get(&ref_id).unwrap().full_def();
418 def::DefPrimTy(_) => None,
419 _ => Some(def.def_id()),
425 // An AST visitor for collecting paths from patterns.
426 struct PathCollector {
427 // The Row field identifies the kind of pattern.
428 collected_paths: Vec<(NodeId, ast::Path, ast::Mutability, recorder::Row)>,
432 fn new() -> PathCollector {
434 collected_paths: vec![],
439 impl<'v> Visitor<'v> for PathCollector {
440 fn visit_pat(&mut self, p: &ast::Pat) {
441 if generated_code(p.span) {
446 ast::PatStruct(ref path, _, _) => {
447 self.collected_paths.push((p.id,
452 ast::PatEnum(ref path, _) |
453 ast::PatQPath(_, ref path) => {
454 self.collected_paths.push((p.id, path.clone(), ast::MutMutable, recorder::VarRef));
456 ast::PatIdent(bm, ref path1, _) => {
457 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
458 token::get_ident(path1.node),
461 let immut = match bm {
462 // Even if the ref is mut, you can't change the ref, only
463 // the data pointed at, so showing the initialising expression
464 // is still worthwhile.
465 ast::BindByRef(_) => ast::MutImmutable,
466 ast::BindByValue(mt) => mt,
468 // collect path for either visit_local or visit_arm
469 let path = ast_util::ident_to_path(path1.span, path1.node);
470 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
474 visit::walk_pat(self, p);
479 pub fn process_crate(tcx: &ty::ctxt,
480 analysis: &ty::CrateAnalysis,
481 odir: Option<&Path>) {
482 let krate = tcx.map.krate();
483 if generated_code(krate.span) {
487 assert!(analysis.glob_map.is_some());
488 let cratename = match attr::find_crate_name(&krate.attrs) {
489 Some(name) => name.to_string(),
491 info!("Could not find crate name, using 'unknown_crate'");
492 String::from("unknown_crate")
496 info!("Dumping crate {}", cratename);
498 // find a path to dump our data to
499 let mut root_path = match env::var_os("DXR_RUST_TEMP_FOLDER") {
500 Some(val) => PathBuf::from(val),
502 Some(val) => val.join("dxr"),
503 None => PathBuf::from("dxr-temp"),
507 if let Err(e) = fs::create_dir_all(&root_path) {
508 tcx.sess.err(&format!("Could not create directory {}: {}",
509 root_path.display(), e));
513 let disp = root_path.display();
514 info!("Writing output to {}", disp);
517 // Create output file.
518 let mut out_name = cratename.clone();
519 out_name.push_str(".csv");
520 root_path.push(&out_name);
521 let output_file = match File::create(&root_path) {
524 let disp = root_path.display();
525 tcx.sess.fatal(&format!("Could not open {}: {}", disp, e));
530 let mut visitor = dump_csv::DumpCsvVisitor::new(tcx, analysis, output_file);
532 visitor.dump_crate_info(&cratename, krate);
533 visit::walk_crate(&mut visitor, krate);
536 // Utility functions for the module.
538 // Helper function to escape quotes in a string
539 fn escape(s: String) -> String {
540 s.replace("\"", "\"\"")
543 // If the expression is a macro expansion or other generated code, run screaming
545 fn generated_code(span: Span) -> bool {
546 span.expn_id != NO_EXPANSION || span == DUMMY_SP