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.
13 use middle::def_id::DefId;
16 use std::fs::{self, File};
17 use std::path::{Path, PathBuf};
20 use rustc_front::{hir, lowering};
21 use rustc::front::map::NodeItem;
22 use rustc::session::config::CrateType::CrateTypeExecutable;
24 use syntax::ast::{self, NodeId};
26 use syntax::codemap::*;
27 use syntax::parse::token::{self, keywords};
28 use syntax::visit::{self, Visitor};
29 use syntax::print::pprust::ty_to_string;
31 use self::span_utils::SpanUtils;
39 pub struct SaveContext<'l, 'tcx: 'l> {
40 tcx: &'l ty::ctxt<'tcx>,
41 lcx: &'l lowering::LoweringContext<'l>,
42 span_utils: SpanUtils<'l>,
45 pub struct CrateData {
50 /// Data for any entity in the Rust language. The actual data contained varied
51 /// with the kind of entity being queried. See the nested structs for details.
54 /// Data for all kinds of functions and methods.
55 FunctionData(FunctionData),
56 /// Data for local and global variables (consts and statics), and fields.
57 VariableData(VariableData),
65 /// Data for the use of some variable (e.g., the use of a local variable, which
66 /// will refere to that variables declaration).
67 VariableRefData(VariableRefData),
68 /// Data for a reference to a type or trait.
69 TypeRefData(TypeRefData),
70 /// Data for a reference to a module.
71 ModRefData(ModRefData),
72 /// Data about a function call.
73 FunctionCallData(FunctionCallData),
74 /// Data about a method call.
75 MethodCallData(MethodCallData),
78 /// Data for all kinds of functions and methods.
80 pub struct FunctionData {
84 pub declaration: Option<DefId>,
89 /// Data for local and global variables (consts and statics).
91 pub struct VariableData {
98 pub type_value: String,
101 /// Data for modules.
106 pub qualname: String,
109 pub filename: String,
112 /// Data for enum declarations.
114 pub struct EnumData {
117 pub qualname: String,
123 pub struct ImplData {
127 // FIXME: I'm not really sure inline data is the best way to do this. Seems
128 // OK in this case, but generalising leads to returning chunks of AST, which
130 pub trait_ref: Option<TypeRefData>,
131 pub self_ref: Option<TypeRefData>,
134 /// Data for the use of some item (e.g., the use of a local variable, which
135 /// will refer to that variables declaration (by ref_id)).
137 pub struct VariableRefData {
144 /// Data for a reference to a type or trait.
146 pub struct TypeRefData {
152 /// Data for a reference to a module.
154 pub struct ModRefData {
160 /// Data about a function call.
162 pub struct FunctionCallData {
168 /// Data about a method call.
170 pub struct MethodCallData {
173 pub ref_id: Option<DefId>,
174 pub decl_id: Option<DefId>,
179 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
180 pub fn new(tcx: &'l ty::ctxt<'tcx>,
181 lcx: &'l lowering::LoweringContext<'l>)
182 -> SaveContext<'l, 'tcx> {
183 let span_utils = SpanUtils::new(&tcx.sess);
184 SaveContext::from_span_utils(tcx, lcx, span_utils)
187 pub fn from_span_utils(tcx: &'l ty::ctxt<'tcx>,
188 lcx: &'l lowering::LoweringContext<'l>,
189 span_utils: SpanUtils<'l>)
190 -> SaveContext<'l, 'tcx> {
194 span_utils: span_utils,
198 // List external crates used by the current crate.
199 pub fn get_external_crates(&self) -> Vec<CrateData> {
200 let mut result = Vec::new();
202 for n in self.tcx.sess.cstore.crates() {
203 result.push(CrateData {
204 name: self.tcx.sess.cstore.crate_name(n),
212 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
215 let name = self.tcx.map.path_to_string(item.id);
216 let qualname = format!("::{}", name);
217 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
218 filter!(self.span_utils, sub_span, item.span, None);
219 Some(Data::FunctionData(FunctionData {
224 span: sub_span.unwrap(),
225 scope: self.enclosing_scope(item.id),
228 ast::ItemStatic(ref typ, mt, ref expr) => {
229 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
231 // If the variable is immutable, save the initialising expression.
232 let (value, keyword) = match mt {
233 ast::MutMutable => (String::from("<mutable>"), keywords::Mut),
234 ast::MutImmutable => (self.span_utils.snippet(expr.span), keywords::Static),
237 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
238 filter!(self.span_utils, sub_span, item.span, None);
239 Some(Data::VariableData(VariableData {
241 name: item.ident.to_string(),
243 span: sub_span.unwrap(),
244 scope: self.enclosing_scope(item.id),
246 type_value: ty_to_string(&typ),
249 ast::ItemConst(ref typ, ref expr) => {
250 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
251 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
252 filter!(self.span_utils, sub_span, item.span, None);
253 Some(Data::VariableData(VariableData {
255 name: item.ident.to_string(),
257 span: sub_span.unwrap(),
258 scope: self.enclosing_scope(item.id),
259 value: self.span_utils.snippet(expr.span),
260 type_value: ty_to_string(&typ),
263 ast::ItemMod(ref m) => {
264 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
266 let cm = self.tcx.sess.codemap();
267 let filename = cm.span_to_filename(m.inner);
269 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
270 filter!(self.span_utils, sub_span, item.span, None);
271 Some(Data::ModData(ModData {
273 name: item.ident.to_string(),
275 span: sub_span.unwrap(),
276 scope: self.enclosing_scope(item.id),
280 ast::ItemEnum(..) => {
281 let enum_name = format!("::{}", self.tcx.map.path_to_string(item.id));
282 let val = self.span_utils.snippet(item.span);
283 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
284 filter!(self.span_utils, sub_span, item.span, None);
285 Some(Data::EnumData(EnumData {
288 span: sub_span.unwrap(),
290 scope: self.enclosing_scope(item.id),
293 ast::ItemImpl(_, _, _, ref trait_ref, ref typ, _) => {
294 let mut type_data = None;
297 let parent = self.enclosing_scope(item.id);
300 // Common case impl for a struct or something basic.
301 ast::TyPath(None, ref path) => {
302 sub_span = self.span_utils.sub_span_for_type_name(path.span);
303 filter!(self.span_utils, sub_span, path.span, None);
304 type_data = self.lookup_ref_id(typ.id).map(|id| {
306 span: sub_span.unwrap(),
313 // Less useful case, impl for a compound type.
315 sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
319 let trait_data = trait_ref.as_ref()
320 .and_then(|tr| self.get_trait_ref_data(tr, parent));
322 filter!(self.span_utils, sub_span, typ.span, None);
323 Some(Data::ImplData(ImplData {
325 span: sub_span.unwrap(),
327 trait_ref: trait_data,
338 pub fn get_field_data(&self, field: &ast::StructField,
339 scope: NodeId) -> Option<VariableData> {
340 match field.node.kind {
341 ast::NamedField(ident, _) => {
342 let qualname = format!("::{}::{}", self.tcx.map.path_to_string(scope), ident);
343 let typ = self.tcx.node_types().get(&field.node.id).unwrap().to_string();
344 let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
345 filter!(self.span_utils, sub_span, field.span, None);
348 name: ident.to_string(),
350 span: sub_span.unwrap(),
352 value: "".to_owned(),
360 // FIXME would be nice to take a MethodItem here, but the ast provides both
361 // trait and impl flavours, so the caller must do the disassembly.
362 pub fn get_method_data(&self, id: ast::NodeId,
363 name: ast::Name, span: Span) -> Option<FunctionData> {
364 // The qualname for a method is the trait name or name of the struct in an impl in
365 // which the method is declared in, followed by the method's name.
366 let qualname = match self.tcx.impl_of_method(self.tcx.map.local_def_id(id)) {
367 Some(impl_id) => match self.tcx.map.get_if_local(impl_id) {
368 Some(NodeItem(item)) => {
370 hir::ItemImpl(_, _, _, _, ref ty, _) => {
371 let mut result = String::from("<");
372 result.push_str(&rustc_front::print::pprust::ty_to_string(&**ty));
374 match self.tcx.trait_of_item(self.tcx.map.local_def_id(id)) {
376 result.push_str(" as ");
377 result.push_str(&self.tcx.item_path_str(def_id));
381 result.push_str(">");
385 self.tcx.sess.span_bug(span,
386 &format!("Container {:?} for method {} not \
394 self.tcx.sess.span_bug(span,
395 &format!("Container {:?} for method {} is not a node \
402 None => match self.tcx.trait_of_item(self.tcx.map.local_def_id(id)) {
404 match self.tcx.map.get_if_local(def_id) {
405 Some(NodeItem(_)) => {
406 format!("::{}", self.tcx.item_path_str(def_id))
409 self.tcx.sess.span_bug(span,
410 &format!("Could not find container {:?} for \
411 method {}, got {:?}",
419 self.tcx.sess.span_bug(span,
420 &format!("Could not find container for method {}", id));
425 let qualname = format!("{}::{}", qualname, name);
427 let def_id = self.tcx.map.local_def_id(id);
428 let decl_id = self.tcx.trait_item_of_item(def_id).and_then(|new_id| {
429 let new_def_id = new_id.def_id();
430 if new_def_id != def_id {
437 let sub_span = self.span_utils.sub_span_after_keyword(span, keywords::Fn);
438 filter!(self.span_utils, sub_span, span, None);
441 name: name.to_string(),
443 declaration: decl_id,
444 span: sub_span.unwrap(),
445 scope: self.enclosing_scope(id),
449 pub fn get_trait_ref_data(&self,
450 trait_ref: &ast::TraitRef,
452 -> Option<TypeRefData> {
453 self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
454 let span = trait_ref.path.span;
455 let sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
456 filter!(self.span_utils, sub_span, span, None);
458 span: sub_span.unwrap(),
465 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
467 ast::ExprField(ref sub_ex, ident) => {
468 let hir_node = lowering::lower_expr(self.lcx, sub_ex);
469 let ty = &self.tcx.expr_ty_adjusted(&hir_node).sty;
471 ty::TyStruct(def, _) => {
472 let f = def.struct_variant().field_named(ident.node.name);
473 let sub_span = self.span_utils.span_for_last_ident(expr.span);
474 filter!(self.span_utils, sub_span, expr.span, None);
475 return Some(Data::VariableRefData(VariableRefData {
476 name: ident.node.to_string(),
477 span: sub_span.unwrap(),
478 scope: self.enclosing_scope(expr.id),
483 debug!("Expected struct type, found {:?}", ty);
488 ast::ExprStruct(ref path, _, _) => {
489 let hir_node = lowering::lower_expr(self.lcx, expr);
490 let ty = &self.tcx.expr_ty_adjusted(&hir_node).sty;
492 ty::TyStruct(def, _) => {
493 let sub_span = self.span_utils.span_for_last_ident(path.span);
494 filter!(self.span_utils, sub_span, path.span, None);
495 Some(Data::TypeRefData(TypeRefData {
496 span: sub_span.unwrap(),
497 scope: self.enclosing_scope(expr.id),
502 // FIXME ty could legitimately be a TyEnum, but then we will fail
503 // later if we try to look up the fields.
504 debug!("expected TyStruct, found {:?}", ty);
509 ast::ExprMethodCall(..) => {
510 let method_call = ty::MethodCall::expr(expr.id);
511 let method_id = self.tcx.tables.borrow().method_map[&method_call].def_id;
512 let (def_id, decl_id) = match self.tcx.impl_or_trait_item(method_id).container() {
513 ty::ImplContainer(_) => (Some(method_id), None),
514 ty::TraitContainer(_) => (None, Some(method_id)),
516 let sub_span = self.span_utils.sub_span_for_meth_name(expr.span);
517 filter!(self.span_utils, sub_span, expr.span, None);
518 let parent = self.enclosing_scope(expr.id);
519 Some(Data::MethodCallData(MethodCallData {
520 span: sub_span.unwrap(),
526 ast::ExprPath(_, ref path) => {
527 self.get_path_data(expr.id, path)
536 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Data> {
537 let def_map = self.tcx.def_map.borrow();
538 if !def_map.contains_key(&id) {
539 self.tcx.sess.span_bug(path.span,
540 &format!("def_map has no key for {} in visit_expr", id));
542 let def = def_map.get(&id).unwrap().full_def();
543 let sub_span = self.span_utils.span_for_last_ident(path.span);
544 filter!(self.span_utils, sub_span, path.span, None);
550 Def::AssociatedConst(..) |
551 Def::Variant(..) => {
552 Some(Data::VariableRefData(VariableRefData {
553 name: self.span_utils.snippet(sub_span.unwrap()),
554 span: sub_span.unwrap(),
555 scope: self.enclosing_scope(id),
556 ref_id: def.def_id(),
559 Def::Struct(def_id) |
561 Def::TyAlias(def_id) |
563 Def::TyParam(_, _, def_id, _) => {
564 Some(Data::TypeRefData(TypeRefData {
565 span: sub_span.unwrap(),
567 scope: self.enclosing_scope(id),
570 Def::Method(decl_id) => {
571 let sub_span = self.span_utils.sub_span_for_meth_name(path.span);
572 filter!(self.span_utils, sub_span, path.span, None);
573 let def_id = if decl_id.is_local() {
574 let ti = self.tcx.impl_or_trait_item(decl_id);
575 match ti.container() {
576 ty::TraitContainer(def_id) => {
580 .find(|mr| mr.name() == ti.name() && self.trait_method_has_body(mr))
581 .map(|mr| mr.def_id())
583 ty::ImplContainer(def_id) => {
584 let impl_items = self.tcx.impl_items.borrow();
585 Some(impl_items.get(&def_id)
589 self.tcx.impl_or_trait_item(mr.def_id()).name() ==
599 Some(Data::MethodCallData(MethodCallData {
600 span: sub_span.unwrap(),
601 scope: self.enclosing_scope(id),
603 decl_id: Some(decl_id),
607 Some(Data::FunctionCallData(FunctionCallData {
609 span: sub_span.unwrap(),
610 scope: self.enclosing_scope(id),
613 Def::Mod(def_id) => {
614 Some(Data::ModRefData(ModRefData {
616 span: sub_span.unwrap(),
617 scope: self.enclosing_scope(id),
624 fn trait_method_has_body(&self, mr: &ty::ImplOrTraitItem) -> bool {
625 let def_id = mr.def_id();
626 if let Some(node_id) = self.tcx.map.as_local_node_id(def_id) {
627 let trait_item = self.tcx.map.expect_trait_item(node_id);
628 if let hir::TraitItem_::MethodTraitItem(_, Some(_)) = trait_item.node {
638 pub fn get_field_ref_data(&self,
639 field_ref: &ast::Field,
640 variant: ty::VariantDef,
642 -> Option<VariableRefData> {
643 let f = variant.field_named(field_ref.ident.node.name);
644 // We don't really need a sub-span here, but no harm done
645 let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
646 filter!(self.span_utils, sub_span, field_ref.ident.span, None);
647 Some(VariableRefData {
648 name: field_ref.ident.node.to_string(),
649 span: sub_span.unwrap(),
655 pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
660 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
661 if !self.tcx.def_map.borrow().contains_key(&ref_id) {
662 self.tcx.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
665 let def = self.tcx.def_map.borrow().get(&ref_id).unwrap().full_def();
667 Def::PrimTy(_) | Def::SelfTy(..) => None,
668 _ => Some(def.def_id()),
673 pub fn enclosing_scope(&self, id: NodeId) -> NodeId {
674 self.tcx.map.get_enclosing_scope(id).unwrap_or(0)
678 // An AST visitor for collecting paths from patterns.
679 struct PathCollector {
680 // The Row field identifies the kind of pattern.
681 collected_paths: Vec<(NodeId, ast::Path, ast::Mutability, recorder::Row)>,
685 fn new() -> PathCollector {
686 PathCollector { collected_paths: vec![] }
690 impl<'v> Visitor<'v> for PathCollector {
691 fn visit_pat(&mut self, p: &ast::Pat) {
693 ast::PatStruct(ref path, _, _) => {
694 self.collected_paths.push((p.id, path.clone(),
695 ast::MutMutable, recorder::TypeRef));
697 ast::PatEnum(ref path, _) |
698 ast::PatQPath(_, ref path) => {
699 self.collected_paths.push((p.id, path.clone(),
700 ast::MutMutable, recorder::VarRef));
702 ast::PatIdent(bm, ref path1, _) => {
703 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
707 let immut = match bm {
708 // Even if the ref is mut, you can't change the ref, only
709 // the data pointed at, so showing the initialising expression
710 // is still worthwhile.
711 ast::BindingMode::ByRef(_) => ast::MutImmutable,
712 ast::BindingMode::ByValue(mt) => mt,
714 // collect path for either visit_local or visit_arm
715 let path = ast_util::ident_to_path(path1.span, path1.node);
716 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
720 visit::walk_pat(self, p);
724 pub fn process_crate<'l, 'tcx>(tcx: &'l ty::ctxt<'tcx>,
725 lcx: &'l lowering::LoweringContext<'l>,
727 analysis: &ty::CrateAnalysis,
729 odir: Option<&Path>) {
730 let _ignore = tcx.dep_graph.in_ignore();
732 assert!(analysis.glob_map.is_some());
734 info!("Dumping crate {}", cratename);
736 // find a path to dump our data to
737 let mut root_path = match env::var_os("DXR_RUST_TEMP_FOLDER") {
738 Some(val) => PathBuf::from(val),
740 Some(val) => val.join("dxr"),
741 None => PathBuf::from("dxr-temp"),
745 if let Err(e) = fs::create_dir_all(&root_path) {
746 tcx.sess.err(&format!("Could not create directory {}: {}",
752 let disp = root_path.display();
753 info!("Writing output to {}", disp);
756 // Create output file.
757 let executable = tcx.sess.crate_types.borrow().iter().any(|ct| *ct == CrateTypeExecutable);
758 let mut out_name = if executable {
763 out_name.push_str(&cratename);
764 out_name.push_str(&tcx.sess.opts.cg.extra_filename);
765 out_name.push_str(".csv");
766 root_path.push(&out_name);
767 let output_file = match File::create(&root_path) {
770 let disp = root_path.display();
771 tcx.sess.fatal(&format!("Could not open {}: {}", disp, e));
776 let mut visitor = dump_csv::DumpCsvVisitor::new(tcx, lcx, analysis, output_file);
778 visitor.dump_crate_info(cratename, krate);
779 visit::walk_crate(&mut visitor, krate);
782 // Utility functions for the module.
784 // Helper function to escape quotes in a string
785 fn escape(s: String) -> String {
786 s.replace("\"", "\"\"")
789 // Helper function to determine if a span came from a
790 // macro expansion or syntax extension.
791 pub fn generated_code(span: Span) -> bool {
792 span.expn_id != NO_EXPANSION || span == DUMMY_SP