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.
30 use driver::driver::CrateAnalysis;
31 use driver::session::Session;
45 use syntax::ast_util::PostExpansionMethod;
46 use syntax::ast::{NodeId,DefId};
47 use syntax::ast_map::NodeItem;
49 use syntax::codemap::*;
50 use syntax::parse::token;
51 use syntax::parse::token::{get_ident,keywords};
52 use syntax::owned_slice::OwnedSlice;
54 use syntax::visit::Visitor;
55 use syntax::print::pprust::{path_to_string,ty_to_string};
58 use middle::save::span_utils::SpanUtils;
59 use middle::save::recorder::Recorder;
60 use middle::save::recorder::FmtStrs;
67 // Helper function to escape quotes in a string
68 fn escape(s: String) -> String {
69 s.replace("\"", "\"\"")
72 // If the expression is a macro expansion or other generated code, run screaming and don't index.
73 fn generated_code(span: Span) -> bool {
74 span.expn_id != NO_EXPANSION || span == DUMMY_SP
77 struct DxrVisitor<'l, 'tcx: 'l> {
79 analysis: &'l CrateAnalysis<'tcx>,
81 collected_paths: Vec<(NodeId, ast::Path, bool, recorder::Row)>,
90 impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
91 fn nest(&mut self, scope_id: NodeId, f: |&mut DxrVisitor<'l, 'tcx>|) {
92 let parent_scope = self.cur_scope;
93 self.cur_scope = scope_id;
95 self.cur_scope = parent_scope;
98 fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
100 self.fmt.crate_str(krate.span, name);
102 // dump info about all the external crates referenced from this crate
103 self.sess.cstore.iter_crate_data(|n, cmd| {
104 self.fmt.external_crate_str(krate.span, cmd.name.as_slice(), n);
106 self.fmt.recorder.record("end_external_crates\n");
109 // Return all non-empty prefixes of a path.
110 // For each prefix, we return the span for the last segment in the prefix and
111 // a str representation of the entire prefix.
112 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
113 let spans = self.span.spans_for_path_segments(path);
115 // Paths to enums seem to not match their spans - the span includes all the
116 // variants too. But they seem to always be at the end, so I hope we can cope with
117 // always using the first ones. So, only error out if we don't have enough spans.
118 // What could go wrong...?
119 if spans.len() < path.segments.len() {
120 error!("Mis-calculated spans for path '{}'. \
121 Found {} spans, expected {}. Found spans:",
122 path_to_string(path), spans.len(), path.segments.len());
123 for s in spans.iter() {
124 let loc = self.sess.codemap().lookup_char_pos(s.lo);
125 error!(" '{}' in {}, line {}",
126 self.span.snippet(*s), loc.file.name, loc.line);
131 let mut result: Vec<(Span, String)> = vec!();
134 let mut segs = vec!();
135 for (seg, span) in path.segments.iter().zip(spans.iter()) {
136 segs.push(seg.clone());
137 let sub_path = ast::Path{span: *span, // span for the last segment
140 let qualname = path_to_string(&sub_path);
141 result.push((*span, qualname));
142 segs = sub_path.segments;
148 fn write_sub_paths(&mut self, path: &ast::Path) {
149 let sub_paths = self.process_path_prefixes(path);
150 for &(ref span, ref qualname) in sub_paths.iter() {
151 self.fmt.sub_mod_ref_str(path.span,
158 // As write_sub_paths, but does not process the last ident in the path (assuming it
159 // will be processed elsewhere).
160 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
161 let sub_paths = self.process_path_prefixes(path);
162 let len = sub_paths.len();
167 let sub_paths = sub_paths.slice(0, len-1);
168 for &(ref span, ref qualname) in sub_paths.iter() {
169 self.fmt.sub_mod_ref_str(path.span,
176 // As write_sub_paths, but expects a path of the form module_path::trait::method
177 // Where trait could actually be a struct too.
178 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
179 let sub_paths = self.process_path_prefixes(path);
180 let len = sub_paths.len();
184 let sub_paths = sub_paths.slice_to(len-1);
186 // write the trait part of the sub-path
187 let (ref span, ref qualname) = sub_paths[len-2];
188 self.fmt.sub_type_ref_str(path.span,
190 qualname.as_slice());
192 // write the other sub-paths
196 let sub_paths = sub_paths.slice(0, len-2);
197 for &(ref span, ref qualname) in sub_paths.iter() {
198 self.fmt.sub_mod_ref_str(path.span,
205 // looks up anything, not just a type
206 fn lookup_type_ref(&self, ref_id: NodeId) -> Option<DefId> {
207 if !self.analysis.ty_cx.def_map.borrow().contains_key(&ref_id) {
208 self.sess.bug(format!("def_map has no key for {} in lookup_type_ref",
211 let def = *self.analysis.ty_cx.def_map.borrow().get(&ref_id);
213 def::DefPrimTy(_) => None,
214 _ => Some(def.def_id()),
218 fn lookup_def_kind(&self, ref_id: NodeId, span: Span) -> Option<recorder::Row> {
219 let def_map = self.analysis.ty_cx.def_map.borrow();
220 if !def_map.contains_key(&ref_id) {
221 self.sess.span_bug(span, format!("def_map has no key for {} in lookup_def_kind",
224 let def = *def_map.get(&ref_id);
227 def::DefForeignMod(_) => Some(recorder::ModRef),
228 def::DefStruct(_) => Some(recorder::StructRef),
230 def::DefAssociatedTy(..) |
231 def::DefTrait(_) => Some(recorder::TypeRef),
232 def::DefStatic(_, _) |
234 def::DefVariant(_, _, _) |
235 def::DefUpvar(..) => Some(recorder::VarRef),
237 def::DefFn(_, _) => Some(recorder::FnRef),
241 def::DefTyParamBinder(_) |
243 def::DefStaticMethod(_, _, _) |
244 def::DefTyParam(..) |
246 def::DefMethod(_, _) |
247 def::DefPrimTy(_) => {
248 self.sess.span_bug(span, format!("lookup_def_kind for unexpected item: {:?}",
254 fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str) {
255 for arg in formals.iter() {
256 assert!(self.collected_paths.len() == 0 && !self.collecting);
257 self.collecting = true;
258 self.visit_pat(&*arg.pat);
259 self.collecting = false;
260 let span_utils = self.span;
261 for &(id, ref p, _, _) in self.collected_paths.iter() {
262 let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
263 *self.analysis.ty_cx.node_types.borrow().get(&(id as uint)));
264 // get the span only for the name of the variable (I hope the path is only ever a
265 // variable name, but who knows?)
266 self.fmt.formal_str(p.span,
267 span_utils.span_for_last_ident(p.span),
270 path_to_string(p).as_slice(),
273 self.collected_paths.clear();
277 fn process_method(&mut self, method: &ast::Method) {
278 if generated_code(method.span) {
283 // The qualname for a method is the trait name or name of the struct in an impl in
284 // which the method is declared in followed by the method's name.
285 let mut qualname = match ty::impl_of_method(&self.analysis.ty_cx,
286 ast_util::local_def(method.id)) {
287 Some(impl_id) => match self.analysis.ty_cx.map.get(impl_id.node) {
291 ast::ItemImpl(_, _, ref ty, _) => {
292 let mut result = String::from_str("<");
293 result.push_str(ty_to_string(&**ty).as_slice());
295 match ty::trait_of_item(&self.analysis.ty_cx,
296 ast_util::local_def(method.id)) {
298 result.push_str(" as ");
300 ty::item_path_str(&self.analysis.ty_cx, def_id).as_slice());
307 self.sess.span_bug(method.span,
308 format!("Container {} for method {} not an impl?",
309 impl_id.node, method.id).as_slice());
314 self.sess.span_bug(method.span,
315 format!("Container {} for method {} is not a node item {:?}",
318 self.analysis.ty_cx.map.get(impl_id.node)
322 None => match ty::trait_of_item(&self.analysis.ty_cx,
323 ast_util::local_def(method.id)) {
325 scope_id = def_id.node;
326 match self.analysis.ty_cx.map.get(def_id.node) {
328 let result = ty::item_path_str(&self.analysis.ty_cx, def_id);
332 self.sess.span_bug(method.span,
333 format!("Could not find container {} for method {}",
334 def_id.node, method.id).as_slice());
339 self.sess.span_bug(method.span,
340 format!("Could not find container for method {}",
341 method.id).as_slice());
346 qualname.push_str(get_ident(method.pe_ident()).get());
347 let qualname = qualname.as_slice();
349 // record the decl for this def (if it has one)
350 let decl_id = ty::trait_item_of_item(&self.analysis.ty_cx,
351 ast_util::local_def(method.id))
354 ty::MethodTraitItemId(def_id) => {
355 method.id != 0 && def_id.node == 0
357 ty::TypeTraitItemId(_) => false,
360 let decl_id = match decl_id {
362 Some(id) => Some(id.def_id()),
365 let sub_span = self.span.sub_span_after_keyword(method.span, keywords::Fn);
366 self.fmt.method_str(method.span,
373 self.process_formals(&method.pe_fn_decl().inputs, qualname);
375 // walk arg and return types
376 for arg in method.pe_fn_decl().inputs.iter() {
377 self.visit_ty(&*arg.ty);
379 self.visit_ty(&*method.pe_fn_decl().output);
381 self.nest(method.id, |v| v.visit_block(&*method.pe_body()));
383 self.process_generic_params(method.pe_generics(),
389 fn process_trait_ref(&mut self,
390 trait_ref: &ast::TraitRef,
391 impl_id: Option<NodeId>) {
392 match self.lookup_type_ref(trait_ref.ref_id) {
394 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
395 self.fmt.ref_str(recorder::TypeRef,
401 Some(impl_id) => self.fmt.impl_str(trait_ref.path.span,
408 visit::walk_path(self, &trait_ref.path);
414 fn process_struct_field_def(&mut self,
415 field: &ast::StructField,
418 match field.node.kind {
419 ast::NamedField(ident, _) => {
420 let name = get_ident(ident);
421 let qualname = format!("{}::{}", qualname, name);
422 let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
423 *self.analysis.ty_cx.node_types.borrow().get(&(field.node.id as uint)));
424 match self.span.sub_span_before_token(field.span, token::COLON) {
425 Some(sub_span) => self.fmt.field_str(field.span,
428 name.get().as_slice(),
432 None => self.sess.span_bug(field.span,
433 format!("Could not find sub-span for field {}",
434 qualname).as_slice()),
441 // Dump generic params bindings, then visit_generics
442 fn process_generic_params(&mut self, generics:&ast::Generics,
446 // We can't only use visit_generics since we don't have spans for param
447 // bindings, so we reparse the full_span to get those sub spans.
448 // However full span is the entire enum/fn/struct block, so we only want
449 // the first few to match the number of generics we're looking for.
450 let param_sub_spans = self.span.spans_for_ty_params(full_span,
451 (generics.ty_params.len() as int));
452 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans.iter()) {
453 // Append $id to name to make sure each one is unique
454 let name = format!("{}::{}${}",
456 escape(self.span.snippet(*param_ss)),
458 self.fmt.typedef_str(full_span,
464 self.visit_generics(generics);
467 fn process_fn(&mut self,
470 ty_params: &ast::Generics,
472 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
474 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Fn);
475 self.fmt.fn_str(item.span,
481 self.process_formals(&decl.inputs, qualname.as_slice());
483 // walk arg and return types
484 for arg in decl.inputs.iter() {
485 self.visit_ty(&*arg.ty);
487 self.visit_ty(&*decl.output);
490 self.nest(item.id, |v| v.visit_block(&*body));
492 self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
495 fn process_static(&mut self,
501 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
503 // If the variable is immutable, save the initialising expression.
504 let value = match mt {
505 ast::MutMutable => String::from_str("<mutable>"),
506 ast::MutImmutable => self.span.snippet(expr.span),
509 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Static);
510 self.fmt.static_str(item.span,
513 get_ident(item.ident).get(),
516 ty_to_string(&*typ).as_slice(),
519 // walk type and init value
520 self.visit_ty(&*typ);
521 self.visit_expr(expr);
524 fn process_struct(&mut self,
526 def: &ast::StructDef,
527 ty_params: &ast::Generics) {
528 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
530 let ctor_id = match def.ctor_id {
531 Some(node_id) => node_id,
534 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
535 self.fmt.struct_str(item.span,
543 for field in def.fields.iter() {
544 self.process_struct_field_def(field, qualname.as_slice(), item.id);
545 self.visit_ty(&*field.node.ty);
548 self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
551 fn process_enum(&mut self,
553 enum_definition: &ast::EnumDef,
554 ty_params: &ast::Generics) {
555 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
556 match self.span.sub_span_after_keyword(item.span, keywords::Enum) {
557 Some(sub_span) => self.fmt.enum_str(item.span,
562 None => self.sess.span_bug(item.span,
563 format!("Could not find subspan for enum {}",
564 qualname).as_slice()),
566 for variant in enum_definition.variants.iter() {
567 let name = get_ident(variant.node.name);
568 let name = name.get();
569 let qualname = qualname.clone().append("::").append(name);
570 let val = self.span.snippet(variant.span);
571 match variant.node.kind {
572 ast::TupleVariantKind(ref args) => {
573 // first ident in span is the variant's name
574 self.fmt.tuple_variant_str(variant.span,
575 self.span.span_for_first_ident(variant.span),
581 for arg in args.iter() {
582 self.visit_ty(&*arg.ty);
585 ast::StructVariantKind(ref struct_def) => {
586 let ctor_id = match struct_def.ctor_id {
587 Some(node_id) => node_id,
590 self.fmt.struct_variant_str(
592 self.span.span_for_first_ident(variant.span),
599 for field in struct_def.fields.iter() {
600 self.process_struct_field_def(field, qualname.as_slice(), variant.node.id);
601 self.visit_ty(&*field.node.ty);
607 self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
610 fn process_impl(&mut self,
612 type_parameters: &ast::Generics,
613 trait_ref: &Option<ast::TraitRef>,
615 impl_items: &Vec<ast::ImplItem>) {
617 ast::TyPath(ref path, _, id) => {
618 match self.lookup_type_ref(id) {
620 let sub_span = self.span.sub_span_for_type_name(path.span);
621 self.fmt.ref_str(recorder::TypeRef,
626 self.fmt.impl_str(path.span,
635 _ => self.visit_ty(&*typ),
639 Some(ref trait_ref) => self.process_trait_ref(trait_ref, Some(item.id)),
643 self.process_generic_params(type_parameters, item.span, "", item.id);
644 for impl_item in impl_items.iter() {
646 ast::MethodImplItem(ref method) => {
647 visit::walk_method_helper(self, &**method)
649 ast::TypeImplItem(ref typedef) => {
650 visit::walk_ty(self, &*typedef.typ)
656 fn process_trait(&mut self,
658 generics: &ast::Generics,
659 trait_refs: &OwnedSlice<ast::TyParamBound>,
660 methods: &Vec<ast::TraitItem>) {
661 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
663 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
664 self.fmt.trait_str(item.span,
671 for super_bound in trait_refs.iter() {
672 let trait_ref = match *super_bound {
673 ast::TraitTyParamBound(ref trait_ref) => {
676 ast::UnboxedFnTyParamBound(..) | ast::RegionTyParamBound(..) => {
681 match self.lookup_type_ref(trait_ref.ref_id) {
683 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
684 self.fmt.ref_str(recorder::TypeRef,
689 self.fmt.inherit_str(trait_ref.path.span,
698 // walk generics and methods
699 self.process_generic_params(generics, item.span, qualname.as_slice(), item.id);
700 for method in methods.iter() {
701 self.visit_trait_item(method)
705 fn process_mod(&mut self,
706 item: &ast::Item, // The module in question, represented as an item.
708 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
710 let cm = self.sess.codemap();
711 let filename = cm.span_to_filename(m.inner);
713 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Mod);
714 self.fmt.mod_str(item.span,
719 filename.as_slice());
721 self.nest(item.id, |v| visit::walk_mod(v, m));
724 fn process_path(&mut self,
727 if generated_code(path.span) {
731 let def_map = self.analysis.ty_cx.def_map.borrow();
732 if !def_map.contains_key(&ex.id) {
733 self.sess.span_bug(ex.span,
734 format!("def_map has no key for {} in visit_expr",
737 let def = def_map.get(&ex.id);
738 let sub_span = self.span.span_for_last_ident(ex.span);
743 def::DefVariant(..) => self.fmt.ref_str(recorder::VarRef,
748 def::DefStruct(def_id) => self.fmt.ref_str(recorder::StructRef,
753 def::DefStaticMethod(declid, provenence, _) => {
754 let sub_span = self.span.sub_span_for_meth_name(ex.span);
755 let defid = if declid.krate == ast::LOCAL_CRATE {
756 let ti = ty::impl_or_trait_item(&self.analysis.ty_cx,
759 def::FromTrait(def_id) => {
760 Some(ty::trait_items(&self.analysis.ty_cx,
764 mr.ident().name == ti.ident().name
769 def::FromImpl(def_id) => {
770 let impl_items = self.analysis
774 Some(impl_items.get(&def_id)
777 ty::impl_or_trait_item(
778 &self.analysis.ty_cx,
779 mr.def_id()).ident().name ==
789 self.fmt.meth_call_str(ex.span,
795 def::DefFn(def_id, _) => self.fmt.fn_call_str(ex.span,
799 _ => self.sess.span_bug(ex.span,
800 format!("Unexpected def kind while looking up path in '{}'",
801 self.span.snippet(ex.span)).as_slice()),
803 // modules or types in the path prefix
805 def::DefStaticMethod(_, _, _) => {
806 self.write_sub_path_trait_truncated(path);
809 def::DefStatic(_,_) |
811 def::DefFn(_, _) => self.write_sub_paths_truncated(path),
815 visit::walk_path(self, path);
818 fn process_struct_lit(&mut self,
821 fields: &Vec<ast::Field>,
822 base: &Option<P<ast::Expr>>) {
823 if generated_code(path.span) {
827 let mut struct_def: Option<DefId> = None;
828 match self.lookup_type_ref(ex.id) {
830 struct_def = Some(id);
831 let sub_span = self.span.span_for_last_ident(path.span);
832 self.fmt.ref_str(recorder::StructRef,
841 self.write_sub_paths_truncated(path);
843 for field in fields.iter() {
845 Some(struct_def) => {
846 let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def);
847 for f in fields.iter() {
848 if generated_code(field.ident.span) {
851 if f.name == field.ident.node.name {
852 // We don't really need a sub-span here, but no harm done
853 let sub_span = self.span.span_for_last_ident(field.ident.span);
854 self.fmt.ref_str(recorder::VarRef,
865 self.visit_expr(&*field.expr)
867 visit::walk_expr_opt(self, base)
870 fn process_method_call(&mut self,
872 args: &Vec<P<ast::Expr>>) {
873 let method_map = self.analysis.ty_cx.method_map.borrow();
874 let method_callee = method_map.get(&typeck::MethodCall::expr(ex.id));
875 let (def_id, decl_id) = match method_callee.origin {
876 typeck::MethodStatic(def_id) |
877 typeck::MethodStaticUnboxedClosure(def_id) => {
878 // method invoked on an object with a concrete type (not a static method)
880 match ty::trait_item_of_item(&self.analysis.ty_cx,
883 Some(decl_id) => Some(decl_id.def_id()),
886 // This incantation is required if the method referenced is a
887 // trait's default implementation.
888 let def_id = match ty::impl_or_trait_item(&self.analysis
891 ty::MethodTraitItem(method) => {
892 method.provided_source.unwrap_or(def_id)
894 ty::TypeTraitItem(_) => def_id,
896 (Some(def_id), decl_id)
898 typeck::MethodTypeParam(ref mp) => {
899 // method invoked on a type parameter
900 let trait_item = ty::trait_item(&self.analysis.ty_cx,
903 (None, Some(trait_item.def_id()))
905 typeck::MethodTraitObject(ref mo) => {
906 // method invoked on a trait instance
907 let trait_item = ty::trait_item(&self.analysis.ty_cx,
910 (None, Some(trait_item.def_id()))
913 let sub_span = self.span.sub_span_for_meth_name(ex.span);
914 self.fmt.meth_call_str(ex.span,
920 // walk receiver and args
921 visit::walk_exprs(self, args.as_slice());
924 fn process_pat(&mut self, p:&ast::Pat) {
925 if generated_code(p.span) {
930 ast::PatStruct(ref path, ref fields, _) => {
931 self.collected_paths.push((p.id, path.clone(), false, recorder::StructRef));
932 visit::walk_path(self, path);
933 let struct_def = match self.lookup_type_ref(p.id) {
936 self.sess.span_bug(p.span,
937 format!("Could not find struct_def for `{}`",
938 self.span.snippet(p.span)).as_slice());
941 // The AST doesn't give us a span for the struct field, so we have
942 // to figure out where it is by assuming it's the token before each colon.
943 let field_spans = self.span.sub_spans_before_tokens(p.span,
946 if fields.len() != field_spans.len() {
947 self.sess.span_bug(p.span,
948 format!("Mismatched field count in '{}', found {}, expected {}",
949 self.span.snippet(p.span), field_spans.len(), fields.len()
952 for (field, &span) in fields.iter().zip(field_spans.iter()) {
953 self.visit_pat(&*field.pat);
957 let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def);
958 for f in fields.iter() {
959 if f.name == field.ident.name {
960 self.fmt.ref_str(recorder::VarRef,
970 ast::PatEnum(ref path, _) => {
971 self.collected_paths.push((p.id, path.clone(), false, recorder::VarRef));
972 visit::walk_pat(self, p);
974 ast::PatIdent(bm, ref path1, ref optional_subpattern) => {
975 let immut = match bm {
976 // Even if the ref is mut, you can't change the ref, only
977 // the data pointed at, so showing the initialising expression
978 // is still worthwhile.
979 ast::BindByRef(_) => true,
980 ast::BindByValue(mt) => {
982 ast::MutMutable => false,
983 ast::MutImmutable => true,
987 // collect path for either visit_local or visit_arm
988 let path = ast_util::ident_to_path(path1.span,path1.node);
989 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
990 match *optional_subpattern {
992 Some(ref subpattern) => self.visit_pat(&**subpattern)
995 _ => visit::walk_pat(self, p)
1000 impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> {
1001 fn visit_item(&mut self, item: &ast::Item) {
1002 if generated_code(item.span) {
1007 ast::ItemFn(ref decl, _, _, ref ty_params, ref body) =>
1008 self.process_fn(item, &**decl, ty_params, &**body),
1009 ast::ItemStatic(ref typ, mt, ref expr) =>
1010 self.process_static(item, &**typ, mt, &**expr),
1011 ast::ItemStruct(ref def, ref ty_params) => self.process_struct(item, &**def, ty_params),
1012 ast::ItemEnum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1013 ast::ItemImpl(ref ty_params,
1016 ref impl_items) => {
1017 self.process_impl(item,
1023 ast::ItemTrait(ref generics, _, ref trait_refs, ref methods) =>
1024 self.process_trait(item, generics, trait_refs, methods),
1025 ast::ItemMod(ref m) => self.process_mod(item, m),
1026 ast::ItemTy(ref ty, ref ty_params) => {
1027 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
1028 let value = ty_to_string(&**ty);
1029 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1030 self.fmt.typedef_str(item.span,
1033 qualname.as_slice(),
1036 self.visit_ty(&**ty);
1037 self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
1039 ast::ItemMac(_) => (),
1040 _ => visit::walk_item(self, item),
1044 fn visit_generics(&mut self, generics: &ast::Generics) {
1045 for param in generics.ty_params.iter() {
1046 for bound in param.bounds.iter() {
1048 ast::TraitTyParamBound(ref trait_ref) => {
1049 self.process_trait_ref(trait_ref, None);
1054 match param.default {
1055 Some(ref ty) => self.visit_ty(&**ty),
1061 // We don't actually index functions here, that is done in visit_item/ItemFn.
1062 // Here we just visit methods.
1063 fn visit_fn(&mut self,
1064 fk: visit::FnKind<'v>,
1065 fd: &'v ast::FnDecl,
1069 if generated_code(s) {
1074 visit::FkMethod(_, _, method) => self.process_method(method),
1075 _ => visit::walk_fn(self, fk, fd, b, s),
1079 fn visit_trait_item(&mut self, tm: &ast::TraitItem) {
1081 ast::RequiredMethod(ref method_type) => {
1082 if generated_code(method_type.span) {
1087 let mut qualname = match ty::trait_of_item(&self.analysis.ty_cx,
1088 ast_util::local_def(method_type.id)) {
1090 scope_id = def_id.node;
1091 ty::item_path_str(&self.analysis.ty_cx, def_id).append("::")
1094 self.sess.span_bug(method_type.span,
1095 format!("Could not find trait for method {}",
1096 method_type.id).as_slice());
1100 qualname.push_str(get_ident(method_type.ident).get());
1101 let qualname = qualname.as_slice();
1103 let sub_span = self.span.sub_span_after_keyword(method_type.span, keywords::Fn);
1104 self.fmt.method_decl_str(method_type.span,
1110 // walk arg and return types
1111 for arg in method_type.decl.inputs.iter() {
1112 self.visit_ty(&*arg.ty);
1114 self.visit_ty(&*method_type.decl.output);
1116 self.process_generic_params(&method_type.generics,
1121 ast::ProvidedMethod(ref method) => self.process_method(&**method),
1122 ast::TypeTraitItem(_) => {}
1126 fn visit_view_item(&mut self, i: &ast::ViewItem) {
1127 if generated_code(i.span) {
1132 ast::ViewItemUse(ref path) => {
1134 ast::ViewPathSimple(ident, ref path, id) => {
1135 let sub_span = self.span.span_for_last_ident(path.span);
1136 let mod_id = match self.lookup_type_ref(id) {
1138 match self.lookup_def_kind(id, path.span) {
1139 Some(kind) => self.fmt.ref_str(kind,
1151 // 'use' always introduces an alias, if there is not an explicit
1152 // one, there is an implicit one.
1154 match self.span.sub_span_before_token(path.span, token::EQ) {
1155 Some(sub_span) => Some(sub_span),
1159 self.fmt.use_alias_str(path.span,
1163 get_ident(ident).get(),
1165 self.write_sub_paths_truncated(path);
1167 ast::ViewPathGlob(ref path, _) => {
1168 self.write_sub_paths(path);
1170 ast::ViewPathList(ref path, ref list, _) => {
1171 for plid in list.iter() {
1173 ast::PathListIdent { id, .. } => {
1174 match self.lookup_type_ref(id) {
1176 match self.lookup_def_kind(id, plid.span) {
1181 def_id, self.cur_scope);
1188 ast::PathListMod { .. } => ()
1192 self.write_sub_paths(path);
1196 ast::ViewItemExternCrate(ident, ref s, id) => {
1197 let name = get_ident(ident);
1198 let name = name.get();
1200 Some((ref s, _)) => s.get().to_string(),
1201 None => name.to_string(),
1203 let sub_span = self.span.sub_span_after_keyword(i.span, keywords::Crate);
1204 let cnum = match self.sess.cstore.find_extern_mod_stmt_cnum(id) {
1208 self.fmt.extern_crate_str(i.span,
1219 fn visit_ty(&mut self, t: &ast::Ty) {
1220 if generated_code(t.span) {
1225 ast::TyPath(ref path, _, id) => {
1226 match self.lookup_type_ref(id) {
1228 let sub_span = self.span.sub_span_for_type_name(t.span);
1229 self.fmt.ref_str(recorder::TypeRef,
1238 self.write_sub_paths_truncated(path);
1240 visit::walk_path(self, path);
1242 _ => visit::walk_ty(self, t),
1246 fn visit_expr(&mut self, ex: &ast::Expr) {
1247 if generated_code(ex.span) {
1252 ast::ExprCall(ref _f, ref _args) => {
1253 // Don't need to do anything for function calls,
1254 // because just walking the callee path does what we want.
1255 visit::walk_expr(self, ex);
1257 ast::ExprPath(ref path) => self.process_path(ex, path),
1258 ast::ExprStruct(ref path, ref fields, ref base) =>
1259 self.process_struct_lit(ex, path, fields, base),
1260 ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, args),
1261 ast::ExprField(ref sub_ex, ident, _) => {
1262 if generated_code(sub_ex.span) {
1266 self.visit_expr(&**sub_ex);
1268 let t = ty::expr_ty_adjusted(&self.analysis.ty_cx, &**sub_ex);
1269 let t_box = ty::get(t);
1271 ty::ty_struct(def_id, _) => {
1272 let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, def_id);
1273 for f in fields.iter() {
1274 if f.name == ident.node.name {
1275 let sub_span = self.span.span_for_last_ident(ex.span);
1276 self.fmt.ref_str(recorder::VarRef,
1285 _ => self.sess.span_bug(ex.span,
1286 "Expected struct type, but not ty_struct"),
1289 ast::ExprTupField(ref sub_ex, idx, _) => {
1290 if generated_code(sub_ex.span) {
1294 self.visit_expr(&**sub_ex);
1296 let t = ty::expr_ty_adjusted(&self.analysis.ty_cx, &**sub_ex);
1297 let t_box = ty::get(t);
1299 ty::ty_struct(def_id, _) => {
1300 let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, def_id);
1301 for (i, f) in fields.iter().enumerate() {
1303 let sub_span = self.span.span_for_last_ident(ex.span);
1304 self.fmt.ref_str(recorder::VarRef,
1313 _ => self.sess.span_bug(ex.span,
1314 "Expected struct type, but not ty_struct"),
1317 ast::ExprFnBlock(_, ref decl, ref body) => {
1318 if generated_code(body.span) {
1322 let id = String::from_str("$").append(ex.id.to_string().as_slice());
1323 self.process_formals(&decl.inputs, id.as_slice());
1325 // walk arg and return types
1326 for arg in decl.inputs.iter() {
1327 self.visit_ty(&*arg.ty);
1329 self.visit_ty(&*decl.output);
1332 self.nest(ex.id, |v| v.visit_block(&**body));
1335 visit::walk_expr(self, ex)
1340 fn visit_mac(&mut self, _: &ast::Mac) {
1341 // Just stop, macros are poison to us.
1344 fn visit_pat(&mut self, p: &ast::Pat) {
1345 self.process_pat(p);
1346 if !self.collecting {
1347 self.collected_paths.clear();
1351 fn visit_arm(&mut self, arm: &ast::Arm) {
1352 assert!(self.collected_paths.len() == 0 && !self.collecting);
1353 self.collecting = true;
1355 for pattern in arm.pats.iter() {
1356 // collect paths from the arm's patterns
1357 self.visit_pat(&**pattern);
1359 self.collecting = false;
1360 // process collected paths
1361 for &(id, ref p, ref immut, ref_kind) in self.collected_paths.iter() {
1362 let value = if *immut {
1363 self.span.snippet(p.span).into_string()
1365 "<mutable>".to_string()
1367 let sub_span = self.span.span_for_first_ident(p.span);
1368 let def_map = self.analysis.ty_cx.def_map.borrow();
1369 if !def_map.contains_key(&id) {
1370 self.sess.span_bug(p.span,
1371 format!("def_map has no key for {} in visit_arm",
1374 let def = def_map.get(&id);
1376 def::DefLocal(id) => self.fmt.variable_str(p.span,
1379 path_to_string(p).as_slice(),
1382 def::DefVariant(_,id,_) => self.fmt.ref_str(ref_kind,
1387 // FIXME(nrc) what is this doing here?
1388 def::DefStatic(_, _) => {}
1389 _ => error!("unexpected definition kind when processing collected paths: {:?}",
1393 self.collected_paths.clear();
1394 visit::walk_expr_opt(self, &arm.guard);
1395 self.visit_expr(&*arm.body);
1398 fn visit_stmt(&mut self, s: &ast::Stmt) {
1399 if generated_code(s.span) {
1403 visit::walk_stmt(self, s)
1406 fn visit_local(&mut self, l: &ast::Local) {
1407 if generated_code(l.span) {
1411 // The local could declare multiple new vars, we must walk the
1412 // pattern and collect them all.
1413 assert!(self.collected_paths.len() == 0 && !self.collecting);
1414 self.collecting = true;
1415 self.visit_pat(&*l.pat);
1416 self.collecting = false;
1418 let value = self.span.snippet(l.span);
1420 for &(id, ref p, ref immut, _) in self.collected_paths.iter() {
1421 let value = if *immut { value.to_string() } else { "<mutable>".to_string() };
1422 let types = self.analysis.ty_cx.node_types.borrow();
1423 let typ = ppaux::ty_to_string(&self.analysis.ty_cx, *types.get(&(id as uint)));
1424 // Get the span only for the name of the variable (I hope the path
1425 // is only ever a variable name, but who knows?).
1426 let sub_span = self.span.span_for_last_ident(p.span);
1427 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1428 self.fmt.variable_str(p.span,
1431 path_to_string(p).as_slice(),
1435 self.collected_paths.clear();
1437 // Just walk the initialiser and type (don't want to walk the pattern again).
1438 self.visit_ty(&*l.ty);
1439 visit::walk_expr_opt(self, &l.init);
1443 pub fn process_crate(sess: &Session,
1445 analysis: &CrateAnalysis,
1446 odir: &Option<Path>) {
1447 if generated_code(krate.span) {
1451 let cratename = match attr::find_crate_name(krate.attrs.as_slice()) {
1452 Some(name) => name.get().to_string(),
1454 info!("Could not find crate name, using 'unknown_crate'");
1455 String::from_str("unknown_crate")
1459 info!("Dumping crate {}", cratename);
1461 // find a path to dump our data to
1462 let mut root_path = match os::getenv("DXR_RUST_TEMP_FOLDER") {
1463 Some(val) => Path::new(val),
1464 None => match *odir {
1465 Some(ref val) => val.join("dxr"),
1466 None => Path::new("dxr-temp"),
1470 match fs::mkdir_recursive(&root_path, io::UserRWX) {
1471 Err(e) => sess.err(format!("Could not create directory {}: {}",
1472 root_path.display(), e).as_slice()),
1477 let disp = root_path.display();
1478 info!("Writing output to {}", disp);
1481 // Create output file.
1482 let mut out_name = cratename.clone();
1483 out_name.push_str(".csv");
1484 root_path.push(out_name);
1485 let output_file = match File::create(&root_path) {
1488 let disp = root_path.display();
1489 sess.fatal(format!("Could not open {}: {}", disp, e).as_slice());
1494 let mut visitor = DxrVisitor {
1497 collected_paths: vec!(),
1499 fmt: FmtStrs::new(box Recorder {
1500 out: output_file as Box<Writer+'static>,
1505 err_count: Cell::new(0)
1510 err_count: Cell::new(0)
1515 visitor.dump_crate_info(cratename.as_slice(), krate);
1517 visit::walk_crate(&mut visitor, krate);