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;
46 use syntax::ast_util::PostExpansionMethod;
47 use syntax::ast::{NodeId,DefId};
48 use syntax::ast_map::NodeItem;
50 use syntax::codemap::*;
51 use syntax::parse::token;
52 use syntax::parse::token::{get_ident,keywords};
53 use syntax::owned_slice::OwnedSlice;
55 use syntax::visit::Visitor;
56 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_info.is_some() || span == DUMMY_SP
77 struct DxrVisitor<'l, 'tcx: 'l> {
79 analysis: &'l CrateAnalysis<'tcx>,
81 collected_paths: Vec<(NodeId, ast::Path, bool, recorder::Row)>,
88 impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
89 fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
91 self.fmt.crate_str(krate.span, name);
93 // dump info about all the external crates referenced from this crate
94 self.sess.cstore.iter_crate_data(|n, cmd| {
95 self.fmt.external_crate_str(krate.span, cmd.name.as_slice(), n);
97 self.fmt.recorder.record("end_external_crates\n");
100 // Return all non-empty prefixes of a path.
101 // For each prefix, we return the span for the last segment in the prefix and
102 // a str representation of the entire prefix.
103 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
104 let spans = self.span.spans_for_path_segments(path);
106 // Paths to enums seem to not match their spans - the span includes all the
107 // variants too. But they seem to always be at the end, so I hope we can cope with
108 // always using the first ones. So, only error out if we don't have enough spans.
109 // What could go wrong...?
110 if spans.len() < path.segments.len() {
111 error!("Mis-calculated spans for path '{}'. \
112 Found {} spans, expected {}. Found spans:",
113 path_to_string(path), spans.len(), path.segments.len());
114 for s in spans.iter() {
115 let loc = self.sess.codemap().lookup_char_pos(s.lo);
116 error!(" '{}' in {}, line {}",
117 self.span.snippet(*s), loc.file.name, loc.line);
122 let mut result: Vec<(Span, String)> = vec!();
125 let mut segs = vec!();
126 for (seg, span) in path.segments.iter().zip(spans.iter()) {
127 segs.push(seg.clone());
128 let sub_path = ast::Path{span: *span, // span for the last segment
131 let qualname = path_to_string(&sub_path);
132 result.push((*span, qualname));
133 segs = sub_path.segments;
139 fn write_sub_paths(&mut self, path: &ast::Path, scope_id: NodeId) {
140 let sub_paths = self.process_path_prefixes(path);
141 for &(ref span, ref qualname) in sub_paths.iter() {
142 self.fmt.sub_mod_ref_str(path.span,
149 // As write_sub_paths, but does not process the last ident in the path (assuming it
150 // will be processed elsewhere).
151 fn write_sub_paths_truncated(&mut self, path: &ast::Path, scope_id: NodeId) {
152 let sub_paths = self.process_path_prefixes(path);
153 let len = sub_paths.len();
158 let sub_paths = sub_paths.slice(0, len-1);
159 for &(ref span, ref qualname) in sub_paths.iter() {
160 self.fmt.sub_mod_ref_str(path.span,
167 // As write_sub_paths, but expects a path of the form module_path::trait::method
168 // Where trait could actually be a struct too.
169 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path, scope_id: NodeId) {
170 let sub_paths = self.process_path_prefixes(path);
171 let len = sub_paths.len();
175 let sub_paths = sub_paths.slice_to(len-1);
177 // write the trait part of the sub-path
178 let (ref span, ref qualname) = sub_paths[len-2];
179 self.fmt.sub_type_ref_str(path.span,
181 qualname.as_slice());
183 // write the other sub-paths
187 let sub_paths = sub_paths.slice(0, len-2);
188 for &(ref span, ref qualname) in sub_paths.iter() {
189 self.fmt.sub_mod_ref_str(path.span,
196 // looks up anything, not just a type
197 fn lookup_type_ref(&self, ref_id: NodeId) -> Option<DefId> {
198 if !self.analysis.ty_cx.def_map.borrow().contains_key(&ref_id) {
199 self.sess.bug(format!("def_map has no key for {} in lookup_type_ref",
202 let def = *self.analysis.ty_cx.def_map.borrow().get(&ref_id);
204 def::DefPrimTy(_) => None,
205 _ => Some(def.def_id()),
209 fn lookup_def_kind(&self, ref_id: NodeId, span: Span) -> Option<recorder::Row> {
210 let def_map = self.analysis.ty_cx.def_map.borrow();
211 if !def_map.contains_key(&ref_id) {
212 self.sess.span_bug(span, format!("def_map has no key for {} in lookup_def_kind",
215 let def = *def_map.get(&ref_id);
218 def::DefForeignMod(_) => Some(recorder::ModRef),
219 def::DefStruct(_) => Some(recorder::StructRef),
221 def::DefTrait(_) => Some(recorder::TypeRef),
222 def::DefStatic(_, _) |
223 def::DefBinding(_, _) |
225 def::DefLocal(_, _) |
226 def::DefVariant(_, _, _) |
227 def::DefUpvar(_, _, _, _) => Some(recorder::VarRef),
229 def::DefFn(_, _) => Some(recorder::FnRef),
233 def::DefTyParamBinder(_) |
235 def::DefStaticMethod(_, _, _) |
236 def::DefTyParam(..) |
238 def::DefMethod(_, _) |
239 def::DefPrimTy(_) => {
240 self.sess.span_bug(span, format!("lookup_def_kind for unexpected item: {:?}",
246 fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str, e:DxrVisitorEnv) {
247 for arg in formals.iter() {
248 assert!(self.collected_paths.len() == 0 && !self.collecting);
249 self.collecting = true;
250 self.visit_pat(&*arg.pat, e);
251 self.collecting = false;
252 let span_utils = self.span;
253 for &(id, ref p, _, _) in self.collected_paths.iter() {
254 let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
255 *self.analysis.ty_cx.node_types.borrow().get(&(id as uint)));
256 // get the span only for the name of the variable (I hope the path is only ever a
257 // variable name, but who knows?)
258 self.fmt.formal_str(p.span,
259 span_utils.span_for_last_ident(p.span),
262 path_to_string(p).as_slice(),
265 self.collected_paths.clear();
269 fn process_method(&mut self, method: &ast::Method, e:DxrVisitorEnv) {
270 if generated_code(method.span) {
275 // The qualname for a method is the trait name or name of the struct in an impl in
276 // which the method is declared in followed by the method's name.
277 let mut qualname = match ty::impl_of_method(&self.analysis.ty_cx,
278 ast_util::local_def(method.id)) {
279 Some(impl_id) => match self.analysis.ty_cx.map.get(impl_id.node) {
283 ast::ItemImpl(_, _, ty, _) => {
284 let mut result = String::from_str("<");
285 result.push_str(ty_to_string(&*ty).as_slice());
287 match ty::trait_of_item(&self.analysis.ty_cx,
288 ast_util::local_def(method.id)) {
290 result.push_str(" as ");
292 ty::item_path_str(&self.analysis.ty_cx, def_id).as_slice());
299 self.sess.span_bug(method.span,
300 format!("Container {} for method {} not an impl?",
301 impl_id.node, method.id).as_slice());
306 self.sess.span_bug(method.span,
307 format!("Container {} for method {} is not a node item {:?}",
310 self.analysis.ty_cx.map.get(impl_id.node)
314 None => match ty::trait_of_item(&self.analysis.ty_cx,
315 ast_util::local_def(method.id)) {
317 scope_id = def_id.node;
318 match self.analysis.ty_cx.map.get(def_id.node) {
320 let result = ty::item_path_str(&self.analysis.ty_cx, def_id);
324 self.sess.span_bug(method.span,
325 format!("Could not find container {} for method {}",
326 def_id.node, method.id).as_slice());
331 self.sess.span_bug(method.span,
332 format!("Could not find container for method {}",
333 method.id).as_slice());
338 qualname.push_str(get_ident(method.pe_ident()).get());
339 let qualname = qualname.as_slice();
341 // record the decl for this def (if it has one)
342 let decl_id = ty::trait_item_of_item(&self.analysis.ty_cx,
343 ast_util::local_def(method.id))
346 ty::MethodTraitItemId(def_id) => {
347 method.id != 0 && def_id.node == 0
351 let decl_id = match decl_id {
353 Some(ty::MethodTraitItemId(def_id)) => Some(def_id),
356 let sub_span = self.span.sub_span_after_keyword(method.span, keywords::Fn);
357 self.fmt.method_str(method.span,
364 self.process_formals(&method.pe_fn_decl().inputs, qualname, e);
366 // walk arg and return types
367 for arg in method.pe_fn_decl().inputs.iter() {
368 self.visit_ty(&*arg.ty, e);
370 self.visit_ty(&*method.pe_fn_decl().output, e);
372 self.visit_block(&*method.pe_body(),
373 DxrVisitorEnv::new_nested(method.id));
375 self.process_generic_params(method.pe_generics(),
382 fn process_trait_ref(&mut self,
383 trait_ref: &ast::TraitRef,
385 impl_id: Option<NodeId>) {
386 match self.lookup_type_ref(trait_ref.ref_id) {
388 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
389 self.fmt.ref_str(recorder::TypeRef,
395 Some(impl_id) => self.fmt.impl_str(trait_ref.path.span,
402 visit::walk_path(self, &trait_ref.path, e);
408 fn process_struct_field_def(&mut self,
409 field: &ast::StructField,
412 match field.node.kind {
413 ast::NamedField(ident, _) => {
414 let name = get_ident(ident);
415 let qualname = format!("{}::{}", qualname, name);
416 let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
417 *self.analysis.ty_cx.node_types.borrow().get(&(field.node.id as uint)));
418 match self.span.sub_span_before_token(field.span, token::COLON) {
419 Some(sub_span) => self.fmt.field_str(field.span,
422 name.get().as_slice(),
426 None => self.sess.span_bug(field.span,
427 format!("Could not find sub-span for field {}",
428 qualname).as_slice()),
435 // Dump generic params bindings, then visit_generics
436 fn process_generic_params(&mut self, generics:&ast::Generics,
441 // We can't only use visit_generics since we don't have spans for param
442 // bindings, so we reparse the full_span to get those sub spans.
443 // However full span is the entire enum/fn/struct block, so we only want
444 // the first few to match the number of generics we're looking for.
445 let param_sub_spans = self.span.spans_for_ty_params(full_span,
446 (generics.ty_params.len() as int));
447 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans.iter()) {
448 // Append $id to name to make sure each one is unique
449 let name = format!("{}::{}${}",
451 escape(self.span.snippet(*param_ss)),
453 self.fmt.typedef_str(full_span,
459 self.visit_generics(generics, e);
462 fn process_fn(&mut self,
465 decl: ast::P<ast::FnDecl>,
466 ty_params: &ast::Generics,
467 body: ast::P<ast::Block>) {
468 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
470 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Fn);
471 self.fmt.fn_str(item.span,
477 self.process_formals(&decl.inputs, qualname.as_slice(), e);
479 // walk arg and return types
480 for arg in decl.inputs.iter() {
481 self.visit_ty(&*arg.ty, e);
483 self.visit_ty(&*decl.output, e);
486 self.visit_block(&*body, DxrVisitorEnv::new_nested(item.id));
488 self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id, e);
491 fn process_static(&mut self,
494 typ: ast::P<ast::Ty>,
498 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
500 // If the variable is immutable, save the initialising expression.
501 let value = match mt {
502 ast::MutMutable => String::from_str("<mutable>"),
503 ast::MutImmutable => self.span.snippet(expr.span),
506 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Static);
507 self.fmt.static_str(item.span,
510 get_ident(item.ident).get(),
513 ty_to_string(&*typ).as_slice(),
516 // walk type and init value
517 self.visit_ty(&*typ, e);
518 self.visit_expr(expr, e);
521 fn process_struct(&mut self,
524 def: &ast::StructDef,
525 ty_params: &ast::Generics) {
526 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
528 let ctor_id = match def.ctor_id {
529 Some(node_id) => node_id,
532 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
533 self.fmt.struct_str(item.span,
541 for field in def.fields.iter() {
542 self.process_struct_field_def(field, qualname.as_slice(), item.id);
543 self.visit_ty(&*field.node.ty, e);
546 self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id, e);
549 fn process_enum(&mut self,
552 enum_definition: &ast::EnumDef,
553 ty_params: &ast::Generics) {
554 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
555 match self.span.sub_span_after_keyword(item.span, keywords::Enum) {
556 Some(sub_span) => self.fmt.enum_str(item.span,
561 None => self.sess.span_bug(item.span,
562 format!("Could not find subspan for enum {}",
563 qualname).as_slice()),
565 for variant in enum_definition.variants.iter() {
566 let name = get_ident(variant.node.name);
567 let name = name.get();
568 let qualname = qualname.clone().append("::").append(name);
569 let val = self.span.snippet(variant.span);
570 match variant.node.kind {
571 ast::TupleVariantKind(ref args) => {
572 // first ident in span is the variant's name
573 self.fmt.tuple_variant_str(variant.span,
574 self.span.span_for_first_ident(variant.span),
580 for arg in args.iter() {
581 self.visit_ty(&*arg.ty, e);
584 ast::StructVariantKind(ref struct_def) => {
585 let ctor_id = match struct_def.ctor_id {
586 Some(node_id) => node_id,
589 self.fmt.struct_variant_str(
591 self.span.span_for_first_ident(variant.span),
598 for field in struct_def.fields.iter() {
599 self.process_struct_field_def(field, qualname.as_slice(), variant.node.id);
600 self.visit_ty(&*field.node.ty, e);
606 self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id, e);
609 fn process_impl(&mut self,
612 type_parameters: &ast::Generics,
613 trait_ref: &Option<ast::TraitRef>,
614 typ: ast::P<ast::Ty>,
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, e),
639 Some(ref trait_ref) => self.process_trait_ref(trait_ref, e, Some(item.id)),
643 self.process_generic_params(type_parameters, item.span, "", item.id, e);
644 for impl_item in impl_items.iter() {
646 ast::MethodImplItem(method) => {
647 visit::walk_method_helper(self, &*method, e)
653 fn process_trait(&mut self,
656 generics: &ast::Generics,
657 trait_refs: &OwnedSlice<ast::TyParamBound>,
658 methods: &Vec<ast::TraitItem>) {
659 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
661 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
662 self.fmt.trait_str(item.span,
669 for super_bound in trait_refs.iter() {
670 let trait_ref = match *super_bound {
671 ast::TraitTyParamBound(ref trait_ref) => {
674 ast::UnboxedFnTyParamBound(..) | ast::RegionTyParamBound(..) => {
679 match self.lookup_type_ref(trait_ref.ref_id) {
681 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
682 self.fmt.ref_str(recorder::TypeRef,
687 self.fmt.inherit_str(trait_ref.path.span,
696 // walk generics and methods
697 self.process_generic_params(generics, item.span, qualname.as_slice(), item.id, e);
698 for method in methods.iter() {
699 self.visit_trait_item(method, e)
703 fn process_mod(&mut self,
704 item: &ast::Item, // The module in question, represented as an item.
707 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
709 let cm = self.sess.codemap();
710 let filename = cm.span_to_filename(m.inner);
712 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Mod);
713 self.fmt.mod_str(item.span,
718 filename.as_slice());
720 visit::walk_mod(self, m, DxrVisitorEnv::new_nested(item.id));
723 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);
740 def::DefLocal(id, _) |
742 def::DefUpvar(id, _, _, _) |
743 def::DefBinding(id, _) => self.fmt.ref_str(recorder::VarRef,
746 ast_util::local_def(id),
748 def::DefStatic(def_id,_) |
749 def::DefVariant(_, def_id, _) => self.fmt.ref_str(recorder::VarRef,
754 def::DefStruct(def_id) => self.fmt.ref_str(recorder::StructRef,
759 def::DefStaticMethod(declid, provenence, _) => {
760 let sub_span = self.span.sub_span_for_meth_name(ex.span);
761 let defid = if declid.krate == ast::LOCAL_CRATE {
762 let ti = ty::impl_or_trait_item(&self.analysis.ty_cx,
765 def::FromTrait(def_id) => {
766 Some(ty::trait_items(&self.analysis.ty_cx,
771 ty::MethodTraitItem(ref mr) => {
772 mr.ident.name == ti.ident()
780 def::FromImpl(def_id) => {
781 let impl_items = self.analysis
785 Some(impl_items.get(&def_id)
789 ty::MethodTraitItemId(mr) => {
790 ty::impl_or_trait_item(
805 self.fmt.meth_call_str(ex.span,
811 def::DefFn(def_id, _) => self.fmt.fn_call_str(ex.span,
815 _ => self.sess.span_bug(ex.span,
816 format!("Unexpected def kind while looking up path in '{}'",
817 self.span.snippet(ex.span)).as_slice()),
819 // modules or types in the path prefix
821 def::DefStaticMethod(_, _, _) => {
822 self.write_sub_path_trait_truncated(path, e.cur_scope);
824 def::DefLocal(_, _) |
826 def::DefStatic(_,_) |
828 def::DefFn(_, _) => self.write_sub_paths_truncated(path, e.cur_scope),
832 visit::walk_path(self, path, e);
835 fn process_struct_lit(&mut self,
839 fields: &Vec<ast::Field>,
840 base: Option<Gc<ast::Expr>>) {
841 if generated_code(path.span) {
845 let mut struct_def: Option<DefId> = None;
846 match self.lookup_type_ref(ex.id) {
848 struct_def = Some(id);
849 let sub_span = self.span.span_for_last_ident(path.span);
850 self.fmt.ref_str(recorder::StructRef,
859 self.write_sub_paths_truncated(path, e.cur_scope);
861 for field in fields.iter() {
863 Some(struct_def) => {
864 let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def);
865 for f in fields.iter() {
866 if generated_code(field.ident.span) {
869 if f.name == field.ident.node.name {
870 // We don't really need a sub-span here, but no harm done
871 let sub_span = self.span.span_for_last_ident(field.ident.span);
872 self.fmt.ref_str(recorder::VarRef,
883 self.visit_expr(&*field.expr, e)
885 visit::walk_expr_opt(self, base, e)
888 fn process_method_call(&mut self,
891 args: &Vec<Gc<ast::Expr>>) {
892 let method_map = self.analysis.ty_cx.method_map.borrow();
893 let method_callee = method_map.get(&typeck::MethodCall::expr(ex.id));
894 let (def_id, decl_id) = match method_callee.origin {
895 typeck::MethodStatic(def_id) |
896 typeck::MethodStaticUnboxedClosure(def_id) => {
897 // method invoked on an object with a concrete type (not a static method)
899 match ty::trait_item_of_item(&self.analysis.ty_cx,
902 Some(ty::MethodTraitItemId(decl_id)) => Some(decl_id),
905 // This incantation is required if the method referenced is a
906 // trait's default implementation.
907 let def_id = match ty::impl_or_trait_item(&self.analysis
910 ty::MethodTraitItem(method) => {
911 method.provided_source.unwrap_or(def_id)
914 (Some(def_id), decl_id)
916 typeck::MethodParam(mp) => {
917 // method invoked on a type parameter
918 let trait_item = ty::trait_item(&self.analysis.ty_cx,
922 ty::MethodTraitItem(method) => {
923 (None, Some(method.def_id))
927 typeck::MethodObject(mo) => {
928 // method invoked on a trait instance
929 let trait_item = ty::trait_item(&self.analysis.ty_cx,
933 ty::MethodTraitItem(method) => {
934 (None, Some(method.def_id))
939 let sub_span = self.span.sub_span_for_meth_name(ex.span);
940 self.fmt.meth_call_str(ex.span,
946 // walk receiver and args
947 visit::walk_exprs(self, args.as_slice(), e);
950 fn process_pat(&mut self, p:&ast::Pat, e: DxrVisitorEnv) {
951 if generated_code(p.span) {
956 ast::PatStruct(ref path, ref fields, _) => {
957 self.collected_paths.push((p.id, path.clone(), false, recorder::StructRef));
958 visit::walk_path(self, path, e);
959 let struct_def = match self.lookup_type_ref(p.id) {
962 self.sess.span_bug(p.span,
963 format!("Could not find struct_def for `{}`",
964 self.span.snippet(p.span)).as_slice());
967 // The AST doesn't give us a span for the struct field, so we have
968 // to figure out where it is by assuming it's the token before each colon.
969 let field_spans = self.span.sub_spans_before_tokens(p.span,
972 if fields.len() != field_spans.len() {
973 self.sess.span_bug(p.span,
974 format!("Mismatched field count in '{}', found {}, expected {}",
975 self.span.snippet(p.span), field_spans.len(), fields.len()
978 for (field, &span) in fields.iter().zip(field_spans.iter()) {
979 self.visit_pat(&*field.pat, e);
983 let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def);
984 for f in fields.iter() {
985 if f.name == field.ident.name {
986 self.fmt.ref_str(recorder::VarRef,
996 ast::PatEnum(ref path, _) => {
997 self.collected_paths.push((p.id, path.clone(), false, recorder::VarRef));
998 visit::walk_pat(self, p, e);
1000 ast::PatIdent(bm, ref path1, ref optional_subpattern) => {
1001 let immut = match bm {
1002 // Even if the ref is mut, you can't change the ref, only
1003 // the data pointed at, so showing the initialising expression
1004 // is still worthwhile.
1005 ast::BindByRef(_) => true,
1006 ast::BindByValue(mt) => {
1008 ast::MutMutable => false,
1009 ast::MutImmutable => true,
1013 // collect path for either visit_local or visit_arm
1014 let path = ast_util::ident_to_path(path1.span,path1.node);
1015 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
1016 match *optional_subpattern {
1018 Some(subpattern) => self.visit_pat(&*subpattern, e),
1021 _ => visit::walk_pat(self, p, e)
1026 impl<'l, 'tcx> Visitor<DxrVisitorEnv> for DxrVisitor<'l, 'tcx> {
1027 fn visit_item(&mut self, item:&ast::Item, e: DxrVisitorEnv) {
1028 if generated_code(item.span) {
1033 ast::ItemFn(decl, _, _, ref ty_params, body) =>
1034 self.process_fn(item, e, decl, ty_params, body),
1035 ast::ItemStatic(typ, mt, expr) =>
1036 self.process_static(item, e, typ, mt, &*expr),
1037 ast::ItemStruct(def, ref ty_params) => self.process_struct(item, e, &*def, ty_params),
1038 ast::ItemEnum(ref def, ref ty_params) => self.process_enum(item, e, def, ty_params),
1039 ast::ItemImpl(ref ty_params,
1042 ref impl_items) => {
1043 self.process_impl(item,
1050 ast::ItemTrait(ref generics, _, ref trait_refs, ref methods) =>
1051 self.process_trait(item, e, generics, trait_refs, methods),
1052 ast::ItemMod(ref m) => self.process_mod(item, e, m),
1053 ast::ItemTy(ty, ref ty_params) => {
1054 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
1055 let value = ty_to_string(&*ty);
1056 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1057 self.fmt.typedef_str(item.span,
1060 qualname.as_slice(),
1063 self.visit_ty(&*ty, e);
1064 self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id, e);
1066 ast::ItemMac(_) => (),
1067 _ => visit::walk_item(self, item, e),
1071 fn visit_generics(&mut self, generics: &ast::Generics, e: DxrVisitorEnv) {
1072 for param in generics.ty_params.iter() {
1073 for bound in param.bounds.iter() {
1075 ast::TraitTyParamBound(ref trait_ref) => {
1076 self.process_trait_ref(trait_ref, e, None);
1081 match param.default {
1082 Some(ty) => self.visit_ty(&*ty, e),
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,
1097 if generated_code(s) {
1102 visit::FkMethod(_, _, method) => self.process_method(method, e),
1103 _ => visit::walk_fn(self, fk, fd, b, s, e),
1107 fn visit_trait_item(&mut self, tm: &ast::TraitItem, e: DxrVisitorEnv) {
1109 ast::RequiredMethod(ref method_type) => {
1110 if generated_code(method_type.span) {
1115 let mut qualname = match ty::trait_of_item(&self.analysis.ty_cx,
1116 ast_util::local_def(method_type.id)) {
1118 scope_id = def_id.node;
1119 ty::item_path_str(&self.analysis.ty_cx, def_id).append("::")
1122 self.sess.span_bug(method_type.span,
1123 format!("Could not find trait for method {}",
1124 method_type.id).as_slice());
1128 qualname.push_str(get_ident(method_type.ident).get());
1129 let qualname = qualname.as_slice();
1131 let sub_span = self.span.sub_span_after_keyword(method_type.span, keywords::Fn);
1132 self.fmt.method_decl_str(method_type.span,
1138 // walk arg and return types
1139 for arg in method_type.decl.inputs.iter() {
1140 self.visit_ty(&*arg.ty, e);
1142 self.visit_ty(&*method_type.decl.output, e);
1144 self.process_generic_params(&method_type.generics,
1150 ast::ProvidedMethod(method) => self.process_method(&*method, e),
1154 fn visit_view_item(&mut self, i:&ast::ViewItem, e:DxrVisitorEnv) {
1155 if generated_code(i.span) {
1160 ast::ViewItemUse(ref path) => {
1162 ast::ViewPathSimple(ident, ref path, id) => {
1163 let sub_span = self.span.span_for_last_ident(path.span);
1164 let mod_id = match self.lookup_type_ref(id) {
1166 match self.lookup_def_kind(id, path.span) {
1167 Some(kind) => self.fmt.ref_str(kind,
1179 // 'use' always introduces an alias, if there is not an explicit
1180 // one, there is an implicit one.
1182 match self.span.sub_span_before_token(path.span, token::EQ) {
1183 Some(sub_span) => Some(sub_span),
1187 self.fmt.use_alias_str(path.span,
1191 get_ident(ident).get(),
1193 self.write_sub_paths_truncated(path, e.cur_scope);
1195 ast::ViewPathGlob(ref path, _) => {
1196 self.write_sub_paths(path, e.cur_scope);
1198 ast::ViewPathList(ref path, ref list, _) => {
1199 for plid in list.iter() {
1201 ast::PathListIdent { id, .. } => {
1202 match self.lookup_type_ref(id) {
1204 match self.lookup_def_kind(id, plid.span) {
1209 def_id, e.cur_scope);
1216 ast::PathListMod { .. } => ()
1220 self.write_sub_paths(path, e.cur_scope);
1224 ast::ViewItemExternCrate(ident, ref s, id) => {
1225 let name = get_ident(ident);
1226 let name = name.get();
1228 Some((ref s, _)) => s.get().to_string(),
1229 None => name.to_string(),
1231 let sub_span = self.span.sub_span_after_keyword(i.span, keywords::Crate);
1232 let cnum = match self.sess.cstore.find_extern_mod_stmt_cnum(id) {
1236 self.fmt.extern_crate_str(i.span,
1247 fn visit_ty(&mut self, t: &ast::Ty, e: DxrVisitorEnv) {
1248 if generated_code(t.span) {
1253 ast::TyPath(ref path, _, id) => {
1254 match self.lookup_type_ref(id) {
1256 let sub_span = self.span.sub_span_for_type_name(t.span);
1257 self.fmt.ref_str(recorder::TypeRef,
1266 self.write_sub_paths_truncated(path, e.cur_scope);
1268 visit::walk_path(self, path, e);
1270 _ => visit::walk_ty(self, t, e),
1274 fn visit_expr(&mut self, ex: &ast::Expr, e: DxrVisitorEnv) {
1275 if generated_code(ex.span) {
1280 ast::ExprCall(_f, ref _args) => {
1281 // Don't need to do anything for function calls,
1282 // because just walking the callee path does what we want.
1283 visit::walk_expr(self, ex, e);
1285 ast::ExprPath(ref path) => self.process_path(ex, e, path),
1286 ast::ExprStruct(ref path, ref fields, base) =>
1287 self.process_struct_lit(ex, e, path, fields, base),
1288 ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, e, args),
1289 ast::ExprField(sub_ex, ident, _) => {
1290 if generated_code(sub_ex.span) {
1294 self.visit_expr(&*sub_ex, e);
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 f in fields.iter() {
1302 if f.name == ident.node.name {
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::ExprTupField(sub_ex, idx, _) => {
1318 if generated_code(sub_ex.span) {
1322 self.visit_expr(&*sub_ex, e);
1324 let t = ty::expr_ty_adjusted(&self.analysis.ty_cx, &*sub_ex);
1325 let t_box = ty::get(t);
1327 ty::ty_struct(def_id, _) => {
1328 let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, def_id);
1329 for (i, f) in fields.iter().enumerate() {
1331 let sub_span = self.span.span_for_last_ident(ex.span);
1332 self.fmt.ref_str(recorder::VarRef,
1341 _ => self.sess.span_bug(ex.span,
1342 "Expected struct type, but not ty_struct"),
1345 ast::ExprFnBlock(_, decl, body) => {
1346 if generated_code(body.span) {
1350 let id = String::from_str("$").append(ex.id.to_string().as_slice());
1351 self.process_formals(&decl.inputs, id.as_slice(), e);
1353 // walk arg and return types
1354 for arg in decl.inputs.iter() {
1355 self.visit_ty(&*arg.ty, e);
1357 self.visit_ty(&*decl.output, e);
1360 self.visit_block(&*body, DxrVisitorEnv::new_nested(ex.id));
1363 visit::walk_expr(self, ex, e)
1368 fn visit_mac(&mut self, _: &ast::Mac, _: DxrVisitorEnv) {
1369 // Just stop, macros are poison to us.
1372 fn visit_pat(&mut self, p: &ast::Pat, e: DxrVisitorEnv) {
1373 self.process_pat(p, e);
1374 if !self.collecting {
1375 self.collected_paths.clear();
1379 fn visit_arm(&mut self, arm: &ast::Arm, e: DxrVisitorEnv) {
1380 assert!(self.collected_paths.len() == 0 && !self.collecting);
1381 self.collecting = true;
1383 for pattern in arm.pats.iter() {
1384 // collect paths from the arm's patterns
1385 self.visit_pat(&**pattern, e);
1387 self.collecting = false;
1388 // process collected paths
1389 for &(id, ref p, ref immut, ref_kind) in self.collected_paths.iter() {
1390 let value = if *immut {
1391 self.span.snippet(p.span).into_string()
1393 "<mutable>".to_string()
1395 let sub_span = self.span.span_for_first_ident(p.span);
1396 let def_map = self.analysis.ty_cx.def_map.borrow();
1397 if !def_map.contains_key(&id) {
1398 self.sess.span_bug(p.span,
1399 format!("def_map has no key for {} in visit_arm",
1402 let def = def_map.get(&id);
1404 def::DefBinding(id, _) => self.fmt.variable_str(p.span,
1407 path_to_string(p).as_slice(),
1410 def::DefVariant(_,id,_) => self.fmt.ref_str(ref_kind,
1415 // FIXME(nrc) what is this doing here?
1416 def::DefStatic(_, _) => {}
1417 _ => error!("unexpected defintion kind when processing collected paths: {:?}", *def)
1420 self.collected_paths.clear();
1421 visit::walk_expr_opt(self, arm.guard, e);
1422 self.visit_expr(&*arm.body, e);
1425 fn visit_stmt(&mut self, s:&ast::Stmt, e:DxrVisitorEnv) {
1426 if generated_code(s.span) {
1430 visit::walk_stmt(self, s, e)
1433 fn visit_local(&mut self, l:&ast::Local, e: DxrVisitorEnv) {
1434 if generated_code(l.span) {
1438 // The local could declare multiple new vars, we must walk the
1439 // pattern and collect them all.
1440 assert!(self.collected_paths.len() == 0 && !self.collecting);
1441 self.collecting = true;
1442 self.visit_pat(&*l.pat, e);
1443 self.collecting = false;
1445 let value = self.span.snippet(l.span);
1447 for &(id, ref p, ref immut, _) in self.collected_paths.iter() {
1448 let value = if *immut { value.to_string() } else { "<mutable>".to_string() };
1449 let types = self.analysis.ty_cx.node_types.borrow();
1450 let typ = ppaux::ty_to_string(&self.analysis.ty_cx, *types.get(&(id as uint)));
1451 // Get the span only for the name of the variable (I hope the path
1452 // is only ever a variable name, but who knows?).
1453 let sub_span = self.span.span_for_last_ident(p.span);
1454 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1455 self.fmt.variable_str(p.span,
1458 path_to_string(p).as_slice(),
1462 self.collected_paths.clear();
1464 // Just walk the initialiser and type (don't want to walk the pattern again).
1465 self.visit_ty(&*l.ty, e);
1466 visit::walk_expr_opt(self, l.init, e);
1471 struct DxrVisitorEnv {
1475 impl DxrVisitorEnv {
1476 fn new() -> DxrVisitorEnv {
1477 DxrVisitorEnv{cur_scope: 0}
1479 fn new_nested(new_mod: NodeId) -> DxrVisitorEnv {
1480 DxrVisitorEnv{cur_scope: new_mod}
1484 pub fn process_crate(sess: &Session,
1486 analysis: &CrateAnalysis,
1487 odir: &Option<Path>) {
1488 if generated_code(krate.span) {
1492 let cratename = match attr::find_crate_name(krate.attrs.as_slice()) {
1493 Some(name) => name.get().to_string(),
1495 info!("Could not find crate name, using 'unknown_crate'");
1496 String::from_str("unknown_crate")
1500 info!("Dumping crate {}", cratename);
1502 // find a path to dump our data to
1503 let mut root_path = match os::getenv("DXR_RUST_TEMP_FOLDER") {
1504 Some(val) => Path::new(val),
1505 None => match *odir {
1506 Some(ref val) => val.join("dxr"),
1507 None => Path::new("dxr-temp"),
1511 match fs::mkdir_recursive(&root_path, io::UserRWX) {
1512 Err(e) => sess.err(format!("Could not create directory {}: {}",
1513 root_path.display(), e).as_slice()),
1518 let disp = root_path.display();
1519 info!("Writing output to {}", disp);
1522 // Create output file.
1523 let mut out_name = cratename.clone();
1524 out_name.push_str(".csv");
1525 root_path.push(out_name);
1526 let output_file = match File::create(&root_path) {
1529 let disp = root_path.display();
1530 sess.fatal(format!("Could not open {}: {}", disp, e).as_slice());
1535 let mut visitor = DxrVisitor{ sess: sess,
1537 collected_paths: vec!(),
1539 fmt: FmtStrs::new(box Recorder {
1540 out: output_file as Box<Writer+'static>,
1545 err_count: Cell::new(0)
1550 err_count: Cell::new(0)
1553 visitor.dump_crate_info(cratename.as_slice(), krate);
1555 visit::walk_crate(&mut visitor, krate, DxrVisitorEnv::new());