1 // Copyright 2012-2014 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.
11 //! Output a CSV file containing the output from rustc's analysis. The data is
12 //! primarily designed to be used as input to the DXR tool, specifically its
13 //! Rust plugin. It could also be used by IDEs or other code browsing, search, or
14 //! cross-referencing tools.
16 //! Dumping the analysis is implemented by walking the AST and getting a bunch of
17 //! info out from all over the place. We use Def IDs to identify objects. The
18 //! tricky part is getting syntactic (span, source text) and semantic (reference
19 //! Def IDs) information for parts of expressions which the compiler has discarded.
20 //! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
21 //! path and a reference to `baz`, but we want spans and references for all three
24 //! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
25 //! from spans (e.g., the span for `bar` from the above example path).
26 //! Recorder is used for recording the output in csv format. FmtStrs separates
27 //! the format of the output away from extracting it from the compiler.
28 //! DxrVisitor walks the AST and processes it.
33 use middle::ty::{self, Ty};
36 use std::io::{self, File, fs};
39 use syntax::ast_util::{self, PostExpansionMethod};
40 use syntax::ast::{self, NodeId, DefId};
41 use syntax::ast_map::NodeItem;
43 use syntax::codemap::*;
44 use syntax::parse::token::{self, get_ident, keywords};
45 use syntax::owned_slice::OwnedSlice;
46 use syntax::visit::{self, Visitor};
47 use syntax::print::pprust::{path_to_string,ty_to_string};
50 use self::span_utils::SpanUtils;
51 use self::recorder::{Recorder, FmtStrs};
58 // Helper function to escape quotes in a string
59 fn escape(s: String) -> String {
60 s.replace("\"", "\"\"")
63 // If the expression is a macro expansion or other generated code, run screaming and don't index.
64 fn generated_code(span: Span) -> bool {
65 span.expn_id != NO_EXPANSION || span == DUMMY_SP
68 struct DxrVisitor<'l, 'tcx: 'l> {
70 analysis: &'l ty::CrateAnalysis<'tcx>,
72 collected_paths: Vec<(NodeId, ast::Path, bool, recorder::Row)>,
81 impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
82 fn nest<F>(&mut self, scope_id: NodeId, f: F) where
83 F: FnOnce(&mut DxrVisitor<'l, 'tcx>),
85 let parent_scope = self.cur_scope;
86 self.cur_scope = scope_id;
88 self.cur_scope = parent_scope;
91 fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
93 self.fmt.crate_str(krate.span, name);
95 // dump info about all the external crates referenced from this crate
96 self.sess.cstore.iter_crate_data(|n, cmd| {
97 self.fmt.external_crate_str(krate.span, &cmd.name[], n);
99 self.fmt.recorder.record("end_external_crates\n");
102 // Return all non-empty prefixes of a path.
103 // For each prefix, we return the span for the last segment in the prefix and
104 // a str representation of the entire prefix.
105 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
106 let spans = self.span.spans_for_path_segments(path);
108 // Paths to enums seem to not match their spans - the span includes all the
109 // variants too. But they seem to always be at the end, so I hope we can cope with
110 // always using the first ones. So, only error out if we don't have enough spans.
111 // What could go wrong...?
112 if spans.len() < path.segments.len() {
113 error!("Mis-calculated spans for path '{}'. \
114 Found {} spans, expected {}. Found spans:",
115 path_to_string(path), spans.len(), path.segments.len());
116 for s in spans.iter() {
117 let loc = self.sess.codemap().lookup_char_pos(s.lo);
118 error!(" '{}' in {}, line {}",
119 self.span.snippet(*s), loc.file.name, loc.line);
124 let mut result: Vec<(Span, String)> = vec!();
127 let mut segs = vec!();
128 for (seg, span) in path.segments.iter().zip(spans.iter()) {
129 segs.push(seg.clone());
130 let sub_path = ast::Path{span: *span, // span for the last segment
133 let qualname = path_to_string(&sub_path);
134 result.push((*span, qualname));
135 segs = sub_path.segments;
141 fn write_sub_paths(&mut self, path: &ast::Path) {
142 let sub_paths = self.process_path_prefixes(path);
143 for &(ref span, ref qualname) in sub_paths.iter() {
144 self.fmt.sub_mod_ref_str(path.span,
151 // As write_sub_paths, but does not process the last ident in the path (assuming it
152 // will be processed elsewhere).
153 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
154 let sub_paths = self.process_path_prefixes(path);
155 let len = sub_paths.len();
160 let sub_paths = sub_paths.slice(0, len-1);
161 for &(ref span, ref qualname) in sub_paths.iter() {
162 self.fmt.sub_mod_ref_str(path.span,
169 // As write_sub_paths, but expects a path of the form module_path::trait::method
170 // Where trait could actually be a struct too.
171 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
172 let sub_paths = self.process_path_prefixes(path);
173 let len = sub_paths.len();
177 let sub_paths = sub_paths.slice_to(len-1);
179 // write the trait part of the sub-path
180 let (ref span, ref qualname) = sub_paths[len-2];
181 self.fmt.sub_type_ref_str(path.span,
185 // write the other sub-paths
189 let sub_paths = &sub_paths[..(len-2)];
190 for &(ref span, ref qualname) in sub_paths.iter() {
191 self.fmt.sub_mod_ref_str(path.span,
198 // looks up anything, not just a type
199 fn lookup_type_ref(&self, ref_id: NodeId) -> Option<DefId> {
200 if !self.analysis.ty_cx.def_map.borrow().contains_key(&ref_id) {
201 self.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
204 let def = (*self.analysis.ty_cx.def_map.borrow())[ref_id];
206 def::DefPrimTy(_) => None,
207 _ => Some(def.def_id()),
211 fn lookup_def_kind(&self, ref_id: NodeId, span: Span) -> Option<recorder::Row> {
212 let def_map = self.analysis.ty_cx.def_map.borrow();
213 if !def_map.contains_key(&ref_id) {
214 self.sess.span_bug(span, &format!("def_map has no key for {} in lookup_def_kind",
217 let def = (*def_map)[ref_id];
220 def::DefForeignMod(_) => Some(recorder::ModRef),
221 def::DefStruct(_) => Some(recorder::StructRef),
223 def::DefAssociatedTy(..) |
224 def::DefAssociatedPath(..) |
225 def::DefTrait(_) => Some(recorder::TypeRef),
226 def::DefStatic(_, _) |
229 def::DefVariant(_, _, _) |
230 def::DefUpvar(..) => Some(recorder::VarRef),
232 def::DefFn(..) => Some(recorder::FnRef),
236 def::DefTyParamBinder(_) |
238 def::DefStaticMethod(..) |
239 def::DefTyParam(..) |
242 def::DefPrimTy(_) => {
243 self.sess.span_bug(span, &format!("lookup_def_kind for unexpected item: {:?}",
249 fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str) {
250 for arg in formals.iter() {
251 assert!(self.collected_paths.len() == 0 && !self.collecting);
252 self.collecting = true;
253 self.visit_pat(&*arg.pat);
254 self.collecting = false;
255 let span_utils = self.span.clone();
256 for &(id, ref p, _, _) in self.collected_paths.iter() {
257 let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
258 (*self.analysis.ty_cx.node_types.borrow())[id]);
259 // get the span only for the name of the variable (I hope the path is only ever a
260 // variable name, but who knows?)
261 self.fmt.formal_str(p.span,
262 span_utils.span_for_last_ident(p.span),
265 &path_to_string(p)[],
268 self.collected_paths.clear();
272 fn process_method(&mut self, method: &ast::Method) {
273 if generated_code(method.span) {
278 // The qualname for a method is the trait name or name of the struct in an impl in
279 // which the method is declared in followed by the method's name.
280 let mut qualname = match ty::impl_of_method(&self.analysis.ty_cx,
281 ast_util::local_def(method.id)) {
282 Some(impl_id) => match self.analysis.ty_cx.map.get(impl_id.node) {
286 ast::ItemImpl(_, _, _, _, ref ty, _) => {
287 let mut result = String::from_str("<");
288 result.push_str(&ty_to_string(&**ty)[]);
290 match ty::trait_of_item(&self.analysis.ty_cx,
291 ast_util::local_def(method.id)) {
293 result.push_str(" as ");
295 ty::item_path_str(&self.analysis.ty_cx, def_id).as_slice());
299 result.push_str(">::");
303 self.sess.span_bug(method.span,
304 &format!("Container {} for method {} not an impl?",
305 impl_id.node, method.id)[]);
310 self.sess.span_bug(method.span,
312 "Container {} for method {} is not a node item {:?}",
315 self.analysis.ty_cx.map.get(impl_id.node))[]);
318 None => match ty::trait_of_item(&self.analysis.ty_cx,
319 ast_util::local_def(method.id)) {
321 scope_id = def_id.node;
322 match self.analysis.ty_cx.map.get(def_id.node) {
324 let mut result = ty::item_path_str(&self.analysis.ty_cx, def_id);
325 result.push_str("::");
329 self.sess.span_bug(method.span,
330 &format!("Could not find container {} for method {}",
331 def_id.node, method.id)[]);
336 self.sess.span_bug(method.span,
337 &format!("Could not find container for method {}",
343 qualname.push_str(get_ident(method.pe_ident()).get());
344 let qualname = &qualname[];
346 // record the decl for this def (if it has one)
347 let decl_id = ty::trait_item_of_item(&self.analysis.ty_cx,
348 ast_util::local_def(method.id))
351 ty::MethodTraitItemId(def_id) => {
352 method.id != 0 && def_id.node == 0
354 ty::TypeTraitItemId(_) => false,
361 let decl_id = match decl_id {
363 Some(id) => Some(id.def_id()),
366 let sub_span = self.span.sub_span_after_keyword(method.span, keywords::Fn);
367 self.fmt.method_str(method.span,
374 self.process_formals(&method.pe_fn_decl().inputs, qualname);
376 // walk arg and return types
377 for arg in method.pe_fn_decl().inputs.iter() {
378 self.visit_ty(&*arg.ty);
381 if let ast::Return(ref ret_ty) = method.pe_fn_decl().output {
382 self.visit_ty(&**ret_ty);
386 self.nest(method.id, |v| v.visit_block(&*method.pe_body()));
388 self.process_generic_params(method.pe_generics(),
394 fn process_trait_ref(&mut self,
395 trait_ref: &ast::TraitRef,
396 impl_id: Option<NodeId>) {
397 match self.lookup_type_ref(trait_ref.ref_id) {
399 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
400 self.fmt.ref_str(recorder::TypeRef,
406 Some(impl_id) => self.fmt.impl_str(trait_ref.path.span,
413 visit::walk_path(self, &trait_ref.path);
419 fn process_struct_field_def(&mut self,
420 field: &ast::StructField,
423 match field.node.kind {
424 ast::NamedField(ident, _) => {
425 let name = get_ident(ident);
426 let qualname = format!("{}::{}", qualname, name);
427 let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
428 (*self.analysis.ty_cx.node_types.borrow())[field.node.id]);
429 match self.span.sub_span_before_token(field.span, token::Colon) {
430 Some(sub_span) => self.fmt.field_str(field.span,
437 None => self.sess.span_bug(field.span,
438 &format!("Could not find sub-span for field {}",
446 // Dump generic params bindings, then visit_generics
447 fn process_generic_params(&mut self, generics:&ast::Generics,
451 // We can't only use visit_generics since we don't have spans for param
452 // bindings, so we reparse the full_span to get those sub spans.
453 // However full span is the entire enum/fn/struct block, so we only want
454 // the first few to match the number of generics we're looking for.
455 let param_sub_spans = self.span.spans_for_ty_params(full_span,
456 (generics.ty_params.len() as int));
457 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans.iter()) {
458 // Append $id to name to make sure each one is unique
459 let name = format!("{}::{}${}",
461 escape(self.span.snippet(*param_ss)),
463 self.fmt.typedef_str(full_span,
469 self.visit_generics(generics);
472 fn process_fn(&mut self,
475 ty_params: &ast::Generics,
477 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
479 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Fn);
480 self.fmt.fn_str(item.span,
486 self.process_formals(&decl.inputs, &qualname[]);
488 // walk arg and return types
489 for arg in decl.inputs.iter() {
490 self.visit_ty(&*arg.ty);
493 if let ast::Return(ref ret_ty) = decl.output {
494 self.visit_ty(&**ret_ty);
498 self.nest(item.id, |v| v.visit_block(&*body));
500 self.process_generic_params(ty_params, item.span, &qualname[], item.id);
503 fn process_static(&mut self,
509 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
511 // If the variable is immutable, save the initialising expression.
512 let value = match mt {
513 ast::MutMutable => String::from_str("<mutable>"),
514 ast::MutImmutable => self.span.snippet(expr.span),
517 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Static);
518 self.fmt.static_str(item.span,
521 get_ident(item.ident).get(),
524 &ty_to_string(&*typ)[],
527 // walk type and init value
528 self.visit_ty(&*typ);
529 self.visit_expr(expr);
532 fn process_const(&mut self,
537 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
539 let sub_span = self.span.sub_span_after_keyword(item.span,
541 self.fmt.static_str(item.span,
544 get_ident(item.ident).get(),
547 &ty_to_string(&*typ)[],
550 // walk type and init value
551 self.visit_ty(&*typ);
552 self.visit_expr(expr);
555 fn process_struct(&mut self,
557 def: &ast::StructDef,
558 ty_params: &ast::Generics) {
559 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
561 let ctor_id = match def.ctor_id {
562 Some(node_id) => node_id,
565 let val = self.span.snippet(item.span);
566 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
567 self.fmt.struct_str(item.span,
576 for field in def.fields.iter() {
577 self.process_struct_field_def(field, &qualname[], item.id);
578 self.visit_ty(&*field.node.ty);
581 self.process_generic_params(ty_params, item.span, &qualname[], item.id);
584 fn process_enum(&mut self,
586 enum_definition: &ast::EnumDef,
587 ty_params: &ast::Generics) {
588 let enum_name = self.analysis.ty_cx.map.path_to_string(item.id);
589 let val = self.span.snippet(item.span);
590 match self.span.sub_span_after_keyword(item.span, keywords::Enum) {
591 Some(sub_span) => self.fmt.enum_str(item.span,
597 None => self.sess.span_bug(item.span,
598 &format!("Could not find subspan for enum {}",
601 for variant in enum_definition.variants.iter() {
602 let name = get_ident(variant.node.name);
603 let name = name.get();
604 let mut qualname = enum_name.clone();
605 qualname.push_str("::");
606 qualname.push_str(name);
607 let val = self.span.snippet(variant.span);
608 match variant.node.kind {
609 ast::TupleVariantKind(ref args) => {
610 // first ident in span is the variant's name
611 self.fmt.tuple_variant_str(variant.span,
612 self.span.span_for_first_ident(variant.span),
619 for arg in args.iter() {
620 self.visit_ty(&*arg.ty);
623 ast::StructVariantKind(ref struct_def) => {
624 let ctor_id = match struct_def.ctor_id {
625 Some(node_id) => node_id,
628 self.fmt.struct_variant_str(
630 self.span.span_for_first_ident(variant.span),
638 for field in struct_def.fields.iter() {
639 self.process_struct_field_def(field, qualname.as_slice(), variant.node.id);
640 self.visit_ty(&*field.node.ty);
646 self.process_generic_params(ty_params, item.span, &enum_name[], item.id);
649 fn process_impl(&mut self,
651 type_parameters: &ast::Generics,
652 trait_ref: &Option<ast::TraitRef>,
654 impl_items: &Vec<ast::ImplItem>) {
656 ast::TyPath(ref path, id) => {
657 match self.lookup_type_ref(id) {
659 let sub_span = self.span.sub_span_for_type_name(path.span);
660 self.fmt.ref_str(recorder::TypeRef,
665 self.fmt.impl_str(path.span,
674 _ => self.visit_ty(&*typ),
678 Some(ref trait_ref) => self.process_trait_ref(trait_ref, Some(item.id)),
682 self.process_generic_params(type_parameters, item.span, "", item.id);
683 for impl_item in impl_items.iter() {
685 ast::MethodImplItem(ref method) => {
686 visit::walk_method_helper(self, &**method)
688 ast::TypeImplItem(ref typedef) => {
689 visit::walk_ty(self, &*typedef.typ)
695 fn process_trait(&mut self,
697 generics: &ast::Generics,
698 trait_refs: &OwnedSlice<ast::TyParamBound>,
699 methods: &Vec<ast::TraitItem>) {
700 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
701 let val = self.span.snippet(item.span);
702 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
703 self.fmt.trait_str(item.span,
711 for super_bound in trait_refs.iter() {
712 let trait_ref = match *super_bound {
713 ast::TraitTyParamBound(ref trait_ref, _) => {
716 ast::RegionTyParamBound(..) => {
721 let trait_ref = &trait_ref.trait_ref;
722 match self.lookup_type_ref(trait_ref.ref_id) {
724 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
725 self.fmt.ref_str(recorder::TypeRef,
730 self.fmt.inherit_str(trait_ref.path.span,
739 // walk generics and methods
740 self.process_generic_params(generics, item.span, &qualname[], item.id);
741 for method in methods.iter() {
742 self.visit_trait_item(method)
746 fn process_mod(&mut self,
747 item: &ast::Item, // The module in question, represented as an item.
749 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
751 let cm = self.sess.codemap();
752 let filename = cm.span_to_filename(m.inner);
754 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Mod);
755 self.fmt.mod_str(item.span,
762 self.nest(item.id, |v| visit::walk_mod(v, m));
765 fn process_path(&mut self,
769 ref_kind: Option<recorder::Row>) {
770 if generated_code(span) {
774 let def_map = self.analysis.ty_cx.def_map.borrow();
775 if !def_map.contains_key(&id) {
776 self.sess.span_bug(span,
777 format!("def_map has no key for {} in visit_expr", id).as_slice());
779 let def = &(*def_map)[id];
780 let sub_span = self.span.span_for_last_ident(span);
786 def::DefVariant(..) => self.fmt.ref_str(ref_kind.unwrap_or(recorder::VarRef),
791 def::DefStruct(def_id) => self.fmt.ref_str(recorder::StructRef,
796 def::DefStaticMethod(declid, provenence) => {
797 let sub_span = self.span.sub_span_for_meth_name(span);
798 let defid = if declid.krate == ast::LOCAL_CRATE {
799 let ti = ty::impl_or_trait_item(&self.analysis.ty_cx,
802 def::FromTrait(def_id) => {
803 Some(ty::trait_items(&self.analysis.ty_cx,
807 mr.name() == ti.name()
812 def::FromImpl(def_id) => {
813 let impl_items = self.analysis
817 Some((*impl_items)[def_id]
820 ty::impl_or_trait_item(
821 &self.analysis.ty_cx,
823 ).name() == ti.name()
832 self.fmt.meth_call_str(span,
838 def::DefFn(def_id, _) => self.fmt.fn_call_str(span,
842 _ => self.sess.span_bug(span,
843 &format!("Unexpected def kind while looking up path in '{}'",
844 self.span.snippet(span))[]),
846 // modules or types in the path prefix
848 def::DefStaticMethod(..) => self.write_sub_path_trait_truncated(path),
850 def::DefStatic(_,_) |
853 def::DefVariant(..) |
854 def::DefFn(..) => self.write_sub_paths_truncated(path),
859 fn process_struct_lit(&mut self,
862 fields: &Vec<ast::Field>,
863 base: &Option<P<ast::Expr>>) {
864 if generated_code(path.span) {
868 let mut struct_def: Option<DefId> = None;
869 match self.lookup_type_ref(ex.id) {
871 struct_def = Some(id);
872 let sub_span = self.span.span_for_last_ident(path.span);
873 self.fmt.ref_str(recorder::StructRef,
882 self.write_sub_paths_truncated(path);
884 for field in fields.iter() {
886 Some(struct_def) => {
887 let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def);
888 for f in fields.iter() {
889 if generated_code(field.ident.span) {
892 if f.name == field.ident.node.name {
893 // We don't really need a sub-span here, but no harm done
894 let sub_span = self.span.span_for_last_ident(field.ident.span);
895 self.fmt.ref_str(recorder::VarRef,
906 self.visit_expr(&*field.expr)
908 visit::walk_expr_opt(self, base)
911 fn process_method_call(&mut self,
913 args: &Vec<P<ast::Expr>>) {
914 let method_map = self.analysis.ty_cx.method_map.borrow();
915 let method_callee = &(*method_map)[ty::MethodCall::expr(ex.id)];
916 let (def_id, decl_id) = match method_callee.origin {
917 ty::MethodStatic(def_id) |
918 ty::MethodStaticUnboxedClosure(def_id) => {
919 // method invoked on an object with a concrete type (not a static method)
921 match ty::trait_item_of_item(&self.analysis.ty_cx,
924 Some(decl_id) => Some(decl_id.def_id()),
927 // This incantation is required if the method referenced is a
928 // trait's default implementation.
929 let def_id = match ty::impl_or_trait_item(&self.analysis
932 ty::MethodTraitItem(method) => {
933 method.provided_source.unwrap_or(def_id)
935 ty::TypeTraitItem(_) => def_id,
937 (Some(def_id), decl_id)
939 ty::MethodTypeParam(ref mp) => {
940 // method invoked on a type parameter
941 let trait_item = ty::trait_item(&self.analysis.ty_cx,
944 (None, Some(trait_item.def_id()))
946 ty::MethodTraitObject(ref mo) => {
947 // method invoked on a trait instance
948 let trait_item = ty::trait_item(&self.analysis.ty_cx,
951 (None, Some(trait_item.def_id()))
954 let sub_span = self.span.sub_span_for_meth_name(ex.span);
955 self.fmt.meth_call_str(ex.span,
961 // walk receiver and args
962 visit::walk_exprs(self, &args[]);
965 fn process_pat(&mut self, p:&ast::Pat) {
966 if generated_code(p.span) {
971 ast::PatStruct(ref path, ref fields, _) => {
972 self.collected_paths.push((p.id, path.clone(), false, recorder::StructRef));
973 visit::walk_path(self, path);
974 let struct_def = match self.lookup_type_ref(p.id) {
977 self.sess.span_bug(p.span,
978 &format!("Could not find struct_def for `{}`",
979 self.span.snippet(p.span))[]);
982 for &Spanned { node: ref field, span } in fields.iter() {
983 let sub_span = self.span.span_for_first_ident(span);
984 let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def);
985 for f in fields.iter() {
986 if f.name == field.ident.name {
987 self.fmt.ref_str(recorder::VarRef,
995 self.visit_pat(&*field.pat);
998 ast::PatEnum(ref path, _) => {
999 self.collected_paths.push((p.id, path.clone(), false, recorder::VarRef));
1000 visit::walk_pat(self, p);
1002 ast::PatIdent(bm, ref path1, ref optional_subpattern) => {
1003 let immut = match bm {
1004 // Even if the ref is mut, you can't change the ref, only
1005 // the data pointed at, so showing the initialising expression
1006 // is still worthwhile.
1007 ast::BindByRef(_) => true,
1008 ast::BindByValue(mt) => {
1010 ast::MutMutable => false,
1011 ast::MutImmutable => true,
1015 // collect path for either visit_local or visit_arm
1016 let path = ast_util::ident_to_path(path1.span,path1.node);
1017 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
1018 match *optional_subpattern {
1020 Some(ref subpattern) => self.visit_pat(&**subpattern)
1023 _ => visit::walk_pat(self, p)
1028 impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> {
1029 fn visit_item(&mut self, item: &ast::Item) {
1030 if generated_code(item.span) {
1035 ast::ItemFn(ref decl, _, _, ref ty_params, ref body) =>
1036 self.process_fn(item, &**decl, ty_params, &**body),
1037 ast::ItemStatic(ref typ, mt, ref expr) =>
1038 self.process_static(item, &**typ, mt, &**expr),
1039 ast::ItemConst(ref typ, ref expr) =>
1040 self.process_const(item, &**typ, &**expr),
1041 ast::ItemStruct(ref def, ref ty_params) => self.process_struct(item, &**def, ty_params),
1042 ast::ItemEnum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1047 ref impl_items) => {
1048 self.process_impl(item,
1054 ast::ItemTrait(_, ref generics, ref trait_refs, ref methods) =>
1055 self.process_trait(item, generics, trait_refs, methods),
1056 ast::ItemMod(ref m) => self.process_mod(item, m),
1057 ast::ItemTy(ref ty, ref ty_params) => {
1058 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
1059 let value = ty_to_string(&**ty);
1060 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1061 self.fmt.typedef_str(item.span,
1067 self.visit_ty(&**ty);
1068 self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
1070 ast::ItemMac(_) => (),
1071 _ => visit::walk_item(self, item),
1075 fn visit_generics(&mut self, generics: &ast::Generics) {
1076 for param in generics.ty_params.iter() {
1077 for bound in param.bounds.iter() {
1078 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
1079 self.process_trait_ref(&trait_ref.trait_ref, None);
1082 if let Some(ref ty) = param.default {
1083 self.visit_ty(&**ty);
1088 // We don't actually index functions here, that is done in visit_item/ItemFn.
1089 // Here we just visit methods.
1090 fn visit_fn(&mut self,
1091 fk: visit::FnKind<'v>,
1092 fd: &'v ast::FnDecl,
1096 if generated_code(s) {
1101 visit::FkMethod(_, _, method) => self.process_method(method),
1102 _ => visit::walk_fn(self, fk, fd, b, s),
1106 fn visit_trait_item(&mut self, tm: &ast::TraitItem) {
1108 ast::RequiredMethod(ref method_type) => {
1109 if generated_code(method_type.span) {
1114 let mut qualname = match ty::trait_of_item(&self.analysis.ty_cx,
1115 ast_util::local_def(method_type.id)) {
1117 scope_id = def_id.node;
1118 let mut s = ty::item_path_str(&self.analysis.ty_cx, def_id);
1123 self.sess.span_bug(method_type.span,
1124 &format!("Could not find trait for method {}",
1129 qualname.push_str(get_ident(method_type.ident).get());
1130 let qualname = &qualname[];
1132 let sub_span = self.span.sub_span_after_keyword(method_type.span, keywords::Fn);
1133 self.fmt.method_decl_str(method_type.span,
1139 // walk arg and return types
1140 for arg in method_type.decl.inputs.iter() {
1141 self.visit_ty(&*arg.ty);
1144 if let ast::Return(ref ret_ty) = method_type.decl.output {
1145 self.visit_ty(&**ret_ty);
1148 self.process_generic_params(&method_type.generics,
1153 ast::ProvidedMethod(ref method) => self.process_method(&**method),
1154 ast::TypeTraitItem(_) => {}
1158 fn visit_view_item(&mut self, i: &ast::ViewItem) {
1159 if generated_code(i.span) {
1164 ast::ViewItemUse(ref item) => {
1166 ast::ViewPathSimple(ident, ref path, id) => {
1167 let sub_span = self.span.span_for_last_ident(path.span);
1168 let mod_id = match self.lookup_type_ref(id) {
1170 match self.lookup_def_kind(id, path.span) {
1171 Some(kind) => self.fmt.ref_str(kind,
1183 // 'use' always introduces an alias, if there is not an explicit
1184 // one, there is an implicit one.
1186 match self.span.sub_span_after_keyword(item.span, keywords::As) {
1187 Some(sub_span) => Some(sub_span),
1191 self.fmt.use_alias_str(path.span,
1195 get_ident(ident).get(),
1197 self.write_sub_paths_truncated(path);
1199 ast::ViewPathGlob(ref path, id) => {
1200 // Make a comma-separated list of names of imported modules.
1201 let mut name_string = String::new();
1202 let glob_map = &self.analysis.glob_map;
1203 let glob_map = glob_map.as_ref().unwrap();
1204 if glob_map.contains_key(&id) {
1205 for n in glob_map[id].iter() {
1206 if name_string.len() > 0 {
1207 name_string.push_str(", ");
1209 name_string.push_str(n.as_str());
1213 let sub_span = self.span.sub_span_of_token(path.span,
1214 token::BinOp(token::Star));
1215 self.fmt.use_glob_str(path.span,
1218 name_string.as_slice(),
1220 self.write_sub_paths(path);
1222 ast::ViewPathList(ref path, ref list, _) => {
1223 for plid in list.iter() {
1225 ast::PathListIdent { id, .. } => {
1226 match self.lookup_type_ref(id) {
1228 match self.lookup_def_kind(id, plid.span) {
1233 def_id, self.cur_scope);
1240 ast::PathListMod { .. } => ()
1244 self.write_sub_paths(path);
1248 ast::ViewItemExternCrate(ident, ref s, id) => {
1249 let name = get_ident(ident);
1250 let name = name.get();
1252 Some((ref s, _)) => s.get().to_string(),
1253 None => name.to_string(),
1255 let sub_span = self.span.sub_span_after_keyword(i.span, keywords::Crate);
1256 let cnum = match self.sess.cstore.find_extern_mod_stmt_cnum(id) {
1260 self.fmt.extern_crate_str(i.span,
1271 fn visit_ty(&mut self, t: &ast::Ty) {
1272 if generated_code(t.span) {
1277 ast::TyPath(ref path, id) => {
1278 match self.lookup_type_ref(id) {
1280 let sub_span = self.span.sub_span_for_type_name(t.span);
1281 self.fmt.ref_str(recorder::TypeRef,
1290 self.write_sub_paths_truncated(path);
1292 visit::walk_path(self, path);
1294 _ => visit::walk_ty(self, t),
1298 fn visit_expr(&mut self, ex: &ast::Expr) {
1299 if generated_code(ex.span) {
1304 ast::ExprCall(ref _f, ref _args) => {
1305 // Don't need to do anything for function calls,
1306 // because just walking the callee path does what we want.
1307 visit::walk_expr(self, ex);
1309 ast::ExprPath(ref path) => {
1310 self.process_path(ex.id, path.span, path, None);
1311 visit::walk_path(self, path);
1313 ast::ExprQPath(ref qpath) => {
1314 let mut path = qpath.trait_ref.path.clone();
1315 path.segments.push(qpath.item_path.clone());
1316 self.process_path(ex.id, ex.span, &path, None);
1317 visit::walk_qpath(self, ex.span, &**qpath);
1319 ast::ExprStruct(ref path, ref fields, ref base) =>
1320 self.process_struct_lit(ex, path, fields, base),
1321 ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, args),
1322 ast::ExprField(ref sub_ex, ident) => {
1323 if generated_code(sub_ex.span) {
1327 self.visit_expr(&**sub_ex);
1329 match ty::expr_ty_adjusted(&self.analysis.ty_cx, &**sub_ex).sty {
1330 ty::ty_struct(def_id, _) => {
1331 let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, def_id);
1332 for f in fields.iter() {
1333 if f.name == ident.node.name {
1334 let sub_span = self.span.span_for_last_ident(ex.span);
1335 self.fmt.ref_str(recorder::VarRef,
1344 _ => self.sess.span_bug(ex.span,
1345 "Expected struct type, but not ty_struct"),
1348 ast::ExprTupField(ref sub_ex, idx) => {
1349 if generated_code(sub_ex.span) {
1353 self.visit_expr(&**sub_ex);
1355 match ty::expr_ty_adjusted(&self.analysis.ty_cx, &**sub_ex).sty {
1356 ty::ty_struct(def_id, _) => {
1357 let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, def_id);
1358 for (i, f) in fields.iter().enumerate() {
1360 let sub_span = self.span.span_for_last_ident(ex.span);
1361 self.fmt.ref_str(recorder::VarRef,
1370 _ => self.sess.span_bug(ex.span,
1371 "Expected struct type, but not ty_struct"),
1374 ast::ExprClosure(_, _, ref decl, ref body) => {
1375 if generated_code(body.span) {
1379 let mut id = String::from_str("$");
1380 id.push_str(&ex.id.to_string()[]);
1381 self.process_formals(&decl.inputs, &id[]);
1383 // walk arg and return types
1384 for arg in decl.inputs.iter() {
1385 self.visit_ty(&*arg.ty);
1388 if let ast::Return(ref ret_ty) = decl.output {
1389 self.visit_ty(&**ret_ty);
1393 self.nest(ex.id, |v| v.visit_block(&**body));
1396 visit::walk_expr(self, ex)
1401 fn visit_mac(&mut self, _: &ast::Mac) {
1402 // Just stop, macros are poison to us.
1405 fn visit_pat(&mut self, p: &ast::Pat) {
1406 self.process_pat(p);
1407 if !self.collecting {
1408 self.collected_paths.clear();
1412 fn visit_arm(&mut self, arm: &ast::Arm) {
1413 assert!(self.collected_paths.len() == 0 && !self.collecting);
1414 self.collecting = true;
1415 for pattern in arm.pats.iter() {
1416 // collect paths from the arm's patterns
1417 self.visit_pat(&**pattern);
1420 // This is to get around borrow checking, because we need mut self to call process_path.
1421 let mut paths_to_process = vec![];
1422 // process collected paths
1423 for &(id, ref p, ref immut, ref_kind) in self.collected_paths.iter() {
1424 let def_map = self.analysis.ty_cx.def_map.borrow();
1425 if !def_map.contains_key(&id) {
1426 self.sess.span_bug(p.span,
1427 &format!("def_map has no key for {} in visit_arm",
1430 let def = &(*def_map)[id];
1432 def::DefLocal(id) => {
1433 let value = if *immut {
1434 self.span.snippet(p.span).to_string()
1436 "<mutable>".to_string()
1439 assert!(p.segments.len() == 1, "qualified path for local variable def in arm");
1440 self.fmt.variable_str(p.span,
1443 &path_to_string(p)[],
1447 def::DefVariant(..) => {
1448 paths_to_process.push((id, p.clone(), Some(ref_kind)))
1450 // FIXME(nrc) what are these doing here?
1451 def::DefStatic(_, _) => {}
1452 def::DefConst(..) => {}
1453 _ => error!("unexpected definition kind when processing collected paths: {:?}",
1457 for &(id, ref path, ref_kind) in paths_to_process.iter() {
1458 self.process_path(id, path.span, path, ref_kind);
1460 self.collecting = false;
1461 self.collected_paths.clear();
1462 visit::walk_expr_opt(self, &arm.guard);
1463 self.visit_expr(&*arm.body);
1466 fn visit_stmt(&mut self, s: &ast::Stmt) {
1467 if generated_code(s.span) {
1471 visit::walk_stmt(self, s)
1474 fn visit_local(&mut self, l: &ast::Local) {
1475 if generated_code(l.span) {
1479 // The local could declare multiple new vars, we must walk the
1480 // pattern and collect them all.
1481 assert!(self.collected_paths.len() == 0 && !self.collecting);
1482 self.collecting = true;
1483 self.visit_pat(&*l.pat);
1484 self.collecting = false;
1486 let value = self.span.snippet(l.span);
1488 for &(id, ref p, ref immut, _) in self.collected_paths.iter() {
1489 let value = if *immut { value.to_string() } else { "<mutable>".to_string() };
1490 let types = self.analysis.ty_cx.node_types.borrow();
1491 let typ = ppaux::ty_to_string(&self.analysis.ty_cx, (*types)[id]);
1492 // Get the span only for the name of the variable (I hope the path
1493 // is only ever a variable name, but who knows?).
1494 let sub_span = self.span.span_for_last_ident(p.span);
1495 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1496 self.fmt.variable_str(p.span,
1499 &path_to_string(p)[],
1503 self.collected_paths.clear();
1505 // Just walk the initialiser and type (don't want to walk the pattern again).
1506 visit::walk_ty_opt(self, &l.ty);
1507 visit::walk_expr_opt(self, &l.init);
1511 pub fn process_crate(sess: &Session,
1513 analysis: &ty::CrateAnalysis,
1514 odir: Option<&Path>) {
1515 if generated_code(krate.span) {
1519 assert!(analysis.glob_map.is_some());
1520 let cratename = match attr::find_crate_name(&krate.attrs[]) {
1521 Some(name) => name.get().to_string(),
1523 info!("Could not find crate name, using 'unknown_crate'");
1524 String::from_str("unknown_crate")
1528 info!("Dumping crate {}", cratename);
1530 // find a path to dump our data to
1531 let mut root_path = match os::getenv("DXR_RUST_TEMP_FOLDER") {
1532 Some(val) => Path::new(val),
1533 None => match odir {
1534 Some(val) => val.join("dxr"),
1535 None => Path::new("dxr-temp"),
1539 match fs::mkdir_recursive(&root_path, io::USER_RWX) {
1540 Err(e) => sess.err(&format!("Could not create directory {}: {}",
1541 root_path.display(), e)[]),
1546 let disp = root_path.display();
1547 info!("Writing output to {}", disp);
1550 // Create output file.
1551 let mut out_name = cratename.clone();
1552 out_name.push_str(".csv");
1553 root_path.push(out_name);
1554 let output_file = match File::create(&root_path) {
1557 let disp = root_path.display();
1558 sess.fatal(&format!("Could not open {}: {}", disp, e)[]);
1563 let mut visitor = DxrVisitor {
1566 collected_paths: vec!(),
1568 fmt: FmtStrs::new(box Recorder {
1569 out: output_file as Box<Writer+'static>,
1574 err_count: Cell::new(0)
1579 err_count: Cell::new(0)
1584 visitor.dump_crate_info(&cratename[], krate);
1586 visit::walk_crate(&mut visitor, krate);