1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
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 //! DumpCsvVisitor walks the AST and processes it.
31 use super::{escape, generated_code, recorder, SaveContext, PathCollector};
36 use middle::ty::{self, Ty};
37 use rustc::ast_map::NodeItem;
44 use syntax::ast::{self, NodeId, DefId};
45 use syntax::codemap::*;
46 use syntax::parse::token::{self, get_ident, keywords};
47 use syntax::owned_slice::OwnedSlice;
48 use syntax::visit::{self, Visitor};
49 use syntax::print::pprust::{path_to_string, ty_to_string};
52 use super::span_utils::SpanUtils;
53 use super::recorder::{Recorder, FmtStrs};
55 macro_rules! down_cast_data {
56 ($id:ident, $kind:ident, $this:ident, $sp:expr) => {
57 let $id = if let super::Data::$kind(data) = $id {
60 $this.sess.span_bug($sp, &format!("unexpected data kind: {:?}", $id));
65 pub struct DumpCsvVisitor<'l, 'tcx: 'l> {
66 save_ctxt: SaveContext<'l, 'tcx>,
68 tcx: &'l ty::ctxt<'tcx>,
69 analysis: &'l ty::CrateAnalysis,
77 impl <'l, 'tcx> DumpCsvVisitor<'l, 'tcx> {
78 pub fn new(tcx: &'l ty::ctxt<'tcx>,
79 analysis: &'l ty::CrateAnalysis,
80 output_file: Box<File>) -> DumpCsvVisitor<'l, 'tcx> {
81 let span_utils = SpanUtils {
83 err_count: Cell::new(0)
88 save_ctxt: SaveContext::new(tcx, span_utils.clone()),
90 span: span_utils.clone(),
91 fmt: FmtStrs::new(box Recorder {
99 fn nest<F>(&mut self, scope_id: NodeId, f: F) where
100 F: FnOnce(&mut DumpCsvVisitor<'l, 'tcx>),
102 let parent_scope = self.cur_scope;
103 self.cur_scope = scope_id;
105 self.cur_scope = parent_scope;
108 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
109 // The current crate.
110 self.fmt.crate_str(krate.span, name);
112 // Dump info about all the external crates referenced from this crate.
113 for c in &self.save_ctxt.get_external_crates() {
114 self.fmt.external_crate_str(krate.span, &c.name, c.number);
116 self.fmt.recorder.record("end_external_crates\n");
119 // Return all non-empty prefixes of a path.
120 // For each prefix, we return the span for the last segment in the prefix and
121 // a str representation of the entire prefix.
122 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
123 let spans = self.span.spans_for_path_segments(path);
125 // Paths to enums seem to not match their spans - the span includes all the
126 // variants too. But they seem to always be at the end, so I hope we can cope with
127 // always using the first ones. So, only error out if we don't have enough spans.
128 // What could go wrong...?
129 if spans.len() < path.segments.len() {
130 error!("Mis-calculated spans for path '{}'. \
131 Found {} spans, expected {}. Found spans:",
132 path_to_string(path), spans.len(), path.segments.len());
134 let loc = self.sess.codemap().lookup_char_pos(s.lo);
135 error!(" '{}' in {}, line {}",
136 self.span.snippet(*s), loc.file.name, loc.line);
141 let mut result: Vec<(Span, String)> = vec!();
143 let mut segs = vec!();
144 for (i, (seg, span)) in path.segments.iter().zip(&spans).enumerate() {
145 segs.push(seg.clone());
146 let sub_path = ast::Path{span: *span, // span for the last segment
149 let qualname = if i == 0 && path.global {
150 format!("::{}", path_to_string(&sub_path))
152 path_to_string(&sub_path)
154 result.push((*span, qualname));
155 segs = sub_path.segments;
161 // The global arg allows us to override the global-ness of the path (which
162 // actually means 'does the path start with `::`', rather than 'is the path
163 // semantically global). We use the override for `use` imports (etc.) where
164 // the syntax is non-global, but the semantics are global.
165 fn write_sub_paths(&mut self, path: &ast::Path, global: bool) {
166 let sub_paths = self.process_path_prefixes(path);
167 for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
168 let qualname = if i == 0 && global && !path.global {
169 format!("::{}", qualname)
173 self.fmt.sub_mod_ref_str(path.span,
180 // As write_sub_paths, but does not process the last ident in the path (assuming it
181 // will be processed elsewhere). See note on write_sub_paths about global.
182 fn write_sub_paths_truncated(&mut self, path: &ast::Path, global: bool) {
183 let sub_paths = self.process_path_prefixes(path);
184 let len = sub_paths.len();
189 let sub_paths = &sub_paths[..len-1];
190 for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
191 let qualname = if i == 0 && global && !path.global {
192 format!("::{}", qualname)
196 self.fmt.sub_mod_ref_str(path.span,
203 // As write_sub_paths, but expects a path of the form module_path::trait::method
204 // Where trait could actually be a struct too.
205 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
206 let sub_paths = self.process_path_prefixes(path);
207 let len = sub_paths.len();
211 let sub_paths = &sub_paths[.. (len-1)];
213 // write the trait part of the sub-path
214 let (ref span, ref qualname) = sub_paths[len-2];
215 self.fmt.sub_type_ref_str(path.span,
219 // write the other sub-paths
223 let sub_paths = &sub_paths[..len-2];
224 for &(ref span, ref qualname) in sub_paths {
225 self.fmt.sub_mod_ref_str(path.span,
232 // looks up anything, not just a type
233 fn lookup_type_ref(&self, ref_id: NodeId) -> Option<DefId> {
234 if !self.tcx.def_map.borrow().contains_key(&ref_id) {
235 self.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
238 let def = self.tcx.def_map.borrow().get(&ref_id).unwrap().full_def();
240 def::DefPrimTy(_) => None,
241 _ => Some(def.def_id()),
245 fn lookup_def_kind(&self, ref_id: NodeId, span: Span) -> Option<recorder::Row> {
246 let def_map = self.tcx.def_map.borrow();
247 if !def_map.contains_key(&ref_id) {
248 self.sess.span_bug(span, &format!("def_map has no key for {} in lookup_def_kind",
251 let def = def_map.get(&ref_id).unwrap().full_def();
254 def::DefForeignMod(_) => Some(recorder::ModRef),
255 def::DefStruct(_) => Some(recorder::TypeRef),
257 def::DefAssociatedTy(..) |
258 def::DefTrait(_) => Some(recorder::TypeRef),
259 def::DefStatic(_, _) |
261 def::DefAssociatedConst(..) |
263 def::DefVariant(_, _, _) |
264 def::DefUpvar(..) => Some(recorder::VarRef),
266 def::DefFn(..) => Some(recorder::FnRef),
271 def::DefTyParam(..) |
274 def::DefPrimTy(_) => {
275 self.sess.span_bug(span, &format!("lookup_def_kind for unexpected item: {:?}",
281 fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str) {
283 self.visit_pat(&arg.pat);
284 let mut collector = PathCollector::new();
285 collector.visit_pat(&arg.pat);
286 let span_utils = self.span.clone();
287 for &(id, ref p, _, _) in &collector.collected_paths {
288 let typ = self.tcx.node_types().get(&id).unwrap().to_string();
289 // get the span only for the name of the variable (I hope the path is only ever a
290 // variable name, but who knows?)
291 self.fmt.formal_str(p.span,
292 span_utils.span_for_last_ident(p.span),
301 fn process_method(&mut self, sig: &ast::MethodSig,
302 body: Option<&ast::Block>,
303 id: ast::NodeId, name: ast::Name,
305 if generated_code(span) {
309 debug!("process_method: {}:{}", id, token::get_name(name));
312 // The qualname for a method is the trait name or name of the struct in an impl in
313 // which the method is declared in, followed by the method's name.
314 let qualname = match self.tcx.impl_of_method(ast_util::local_def(id)) {
315 Some(impl_id) => match self.tcx.map.get(impl_id.node) {
319 ast::ItemImpl(_, _, _, _, ref ty, _) => {
320 let mut result = String::from("<");
321 result.push_str(&ty_to_string(&**ty));
323 match self.tcx.trait_of_item(ast_util::local_def(id)) {
325 result.push_str(" as ");
327 &self.tcx.item_path_str(def_id));
331 result.push_str(">");
335 self.sess.span_bug(span,
336 &format!("Container {} for method {} not an impl?",
342 self.sess.span_bug(span,
343 &format!("Container {} for method {} is not a node item {:?}",
344 impl_id.node, id, self.tcx.map.get(impl_id.node)));
347 None => match self.tcx.trait_of_item(ast_util::local_def(id)) {
349 scope_id = def_id.node;
350 match self.tcx.map.get(def_id.node) {
352 format!("::{}", self.tcx.item_path_str(def_id))
355 self.sess.span_bug(span,
356 &format!("Could not find container {} for method {}",
362 self.sess.span_bug(span,
363 &format!("Could not find container for method {}", id));
368 let qualname = &format!("{}::{}", qualname, &token::get_name(name));
370 // record the decl for this def (if it has one)
371 let decl_id = self.tcx.trait_item_of_item(ast_util::local_def(id))
373 let def_id = new_id.def_id();
374 if def_id.node != 0 && def_id != ast_util::local_def(id) {
381 let sub_span = self.span.sub_span_after_keyword(span, keywords::Fn);
383 self.fmt.method_str(span,
389 self.process_formals(&sig.decl.inputs, qualname);
391 self.fmt.method_decl_str(span,
398 // walk arg and return types
399 for arg in &sig.decl.inputs {
400 self.visit_ty(&arg.ty);
403 if let ast::Return(ref ret_ty) = sig.decl.output {
404 self.visit_ty(ret_ty);
408 if let Some(body) = body {
409 self.nest(id, |v| v.visit_block(body));
412 self.process_generic_params(&sig.generics,
418 fn process_trait_ref(&mut self, trait_ref: &ast::TraitRef) {
419 let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref, self.cur_scope);
420 if let Some(trait_ref_data) = trait_ref_data {
421 self.fmt.ref_str(recorder::TypeRef,
423 Some(trait_ref_data.span),
424 trait_ref_data.ref_id,
425 trait_ref_data.scope);
426 visit::walk_path(self, &trait_ref.path);
430 fn process_struct_field_def(&mut self,
431 field: &ast::StructField,
433 let field_data = self.save_ctxt.get_field_data(field, parent_id);
434 if let Some(field_data) = field_data {
435 down_cast_data!(field_data, VariableData, self, field.span);
436 self.fmt.field_str(field.span,
437 Some(field_data.span),
440 &field_data.qualname,
441 &field_data.type_value,
446 // Dump generic params bindings, then visit_generics
447 fn process_generic_params(&mut self,
448 generics:&ast::Generics,
452 // We can't only use visit_generics since we don't have spans for param
453 // bindings, so we reparse the full_span to get those sub spans.
454 // However full span is the entire enum/fn/struct block, so we only want
455 // the first few to match the number of generics we're looking for.
456 let param_sub_spans = self.span.spans_for_ty_params(full_span,
457 (generics.ty_params.len() as isize));
458 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
459 // Append $id to name to make sure each one is unique
460 let name = format!("{}::{}${}",
462 escape(self.span.snippet(param_ss)),
464 self.fmt.typedef_str(full_span,
470 self.visit_generics(generics);
473 fn process_fn(&mut self,
476 ty_params: &ast::Generics,
478 let fn_data = self.save_ctxt.get_item_data(item);
479 down_cast_data!(fn_data, FunctionData, self, item.span);
480 self.fmt.fn_str(item.span,
487 self.process_formals(&decl.inputs, &fn_data.qualname);
488 self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
490 for arg in &decl.inputs {
491 self.visit_ty(&arg.ty);
494 if let ast::Return(ref ret_ty) = decl.output {
495 self.visit_ty(&ret_ty);
498 self.nest(item.id, |v| v.visit_block(&body));
501 fn process_static_or_const_item(&mut self,
506 let var_data = self.save_ctxt.get_item_data(item);
507 down_cast_data!(var_data, VariableData, self, item.span);
508 self.fmt.static_str(item.span,
514 &var_data.type_value,
518 self.visit_expr(expr);
521 fn process_const(&mut self,
528 let qualname = format!("::{}", self.tcx.map.path_to_string(id));
530 let sub_span = self.span.sub_span_after_keyword(span,
533 self.fmt.static_str(span,
536 &get_ident((*ident).clone()),
538 &self.span.snippet(expr.span),
539 &ty_to_string(&*typ),
542 // walk type and init value
544 self.visit_expr(expr);
547 fn process_struct(&mut self,
549 def: &ast::StructDef,
550 ty_params: &ast::Generics) {
551 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
553 let ctor_id = match def.ctor_id {
554 Some(node_id) => node_id,
557 let val = self.span.snippet(item.span);
558 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
559 self.fmt.struct_str(item.span,
568 for field in &def.fields {
569 self.process_struct_field_def(field, item.id);
570 self.visit_ty(&field.node.ty);
573 self.process_generic_params(ty_params, item.span, &qualname, item.id);
576 fn process_enum(&mut self,
578 enum_definition: &ast::EnumDef,
579 ty_params: &ast::Generics) {
580 let enum_data = self.save_ctxt.get_item_data(item);
581 down_cast_data!(enum_data, EnumData, self, item.span);
582 self.fmt.enum_str(item.span,
583 Some(enum_data.span),
589 for variant in &enum_definition.variants {
590 let name = &get_ident(variant.node.name);
591 let mut qualname = enum_data.qualname.clone();
592 qualname.push_str("::");
593 qualname.push_str(name);
594 let val = self.span.snippet(variant.span);
595 match variant.node.kind {
596 ast::TupleVariantKind(ref args) => {
597 // first ident in span is the variant's name
598 self.fmt.tuple_variant_str(variant.span,
599 self.span.span_for_first_ident(variant.span),
607 self.visit_ty(&*arg.ty);
610 ast::StructVariantKind(ref struct_def) => {
611 let ctor_id = match struct_def.ctor_id {
612 Some(node_id) => node_id,
615 self.fmt.struct_variant_str(variant.span,
616 self.span.span_for_first_ident(variant.span),
624 for field in &struct_def.fields {
625 self.process_struct_field_def(field, variant.node.id);
626 self.visit_ty(&*field.node.ty);
631 self.process_generic_params(ty_params, item.span, &enum_data.qualname, enum_data.id);
634 fn process_impl(&mut self,
636 type_parameters: &ast::Generics,
637 trait_ref: &Option<ast::TraitRef>,
639 impl_items: &[P<ast::ImplItem>]) {
640 let impl_data = self.save_ctxt.get_item_data(item);
641 down_cast_data!(impl_data, ImplData, self, item.span);
642 match impl_data.self_ref {
643 Some(ref self_ref) => {
644 self.fmt.ref_str(recorder::TypeRef,
654 if let Some(ref trait_ref_data) = impl_data.trait_ref {
655 self.fmt.ref_str(recorder::TypeRef,
657 Some(trait_ref_data.span),
658 trait_ref_data.ref_id,
659 trait_ref_data.scope);
660 visit::walk_path(self, &trait_ref.as_ref().unwrap().path);
663 self.fmt.impl_str(item.span,
664 Some(impl_data.span),
666 impl_data.self_ref.map(|data| data.ref_id),
667 impl_data.trait_ref.map(|data| data.ref_id),
670 self.process_generic_params(type_parameters, item.span, "", item.id);
671 for impl_item in impl_items {
672 self.visit_impl_item(impl_item);
676 fn process_trait(&mut self,
678 generics: &ast::Generics,
679 trait_refs: &OwnedSlice<ast::TyParamBound>,
680 methods: &[P<ast::TraitItem>]) {
681 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
682 let val = self.span.snippet(item.span);
683 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
684 self.fmt.trait_str(item.span,
692 for super_bound in trait_refs.iter() {
693 let trait_ref = match *super_bound {
694 ast::TraitTyParamBound(ref trait_ref, _) => {
697 ast::RegionTyParamBound(..) => {
702 let trait_ref = &trait_ref.trait_ref;
703 match self.lookup_type_ref(trait_ref.ref_id) {
705 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
706 self.fmt.ref_str(recorder::TypeRef,
711 self.fmt.inherit_str(trait_ref.path.span,
720 // walk generics and methods
721 self.process_generic_params(generics, item.span, &qualname, item.id);
722 for method in methods {
723 self.visit_trait_item(method)
727 fn process_mod(&mut self,
728 item: &ast::Item) { // The module in question, represented as an item.
729 let mod_data = self.save_ctxt.get_item_data(item);
730 down_cast_data!(mod_data, ModData, self, item.span);
731 self.fmt.mod_str(item.span,
739 fn process_path(&mut self,
743 ref_kind: Option<recorder::Row>) {
744 if generated_code(span) {
748 let def_map = self.tcx.def_map.borrow();
749 if !def_map.contains_key(&id) {
750 self.sess.span_bug(span,
751 &format!("def_map has no key for {} in visit_expr", id));
753 let def = def_map.get(&id).unwrap().full_def();
754 let sub_span = self.span.span_for_last_ident(span);
760 def::DefAssociatedConst(..) |
761 def::DefVariant(..) => self.fmt.ref_str(ref_kind.unwrap_or(recorder::VarRef),
766 def::DefStruct(def_id) => self.fmt.ref_str(recorder::TypeRef,
771 def::DefTy(def_id, _) => self.fmt.ref_str(recorder::TypeRef,
776 def::DefMethod(declid, provenence) => {
777 let sub_span = self.span.sub_span_for_meth_name(span);
778 let defid = if declid.krate == ast::LOCAL_CRATE {
779 let ti = self.tcx.impl_or_trait_item(declid);
781 def::FromTrait(def_id) => {
782 Some(self.tcx.trait_items(def_id)
785 mr.name() == ti.name()
790 def::FromImpl(def_id) => {
791 let impl_items = self.tcx.impl_items.borrow();
792 Some(impl_items.get(&def_id)
796 self.tcx.impl_or_trait_item(mr.def_id()).name()
806 self.fmt.meth_call_str(span,
812 def::DefFn(def_id, _) => {
813 self.fmt.fn_call_str(span,
818 _ => self.sess.span_bug(span,
819 &format!("Unexpected def kind while looking \
820 up path in `{}`: `{:?}`",
821 self.span.snippet(span),
824 // modules or types in the path prefix
826 def::DefMethod(did, _) => {
827 let ti = self.tcx.impl_or_trait_item(did);
828 if let ty::MethodTraitItem(m) = ti {
829 if m.explicit_self == ty::StaticExplicitSelfCategory {
830 self.write_sub_path_trait_truncated(path);
835 def::DefStatic(_,_) |
837 def::DefAssociatedConst(..) |
839 def::DefVariant(..) |
840 def::DefFn(..) => self.write_sub_paths_truncated(path, false),
845 fn process_struct_lit(&mut self,
848 fields: &Vec<ast::Field>,
849 base: &Option<P<ast::Expr>>) {
850 if generated_code(path.span) {
854 self.write_sub_paths_truncated(path, false);
856 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
857 down_cast_data!(struct_lit_data, TypeRefData, self, ex.span);
858 self.fmt.ref_str(recorder::TypeRef,
860 Some(struct_lit_data.span),
861 struct_lit_data.ref_id,
862 struct_lit_data.scope);
863 let struct_def = struct_lit_data.ref_id;
865 for field in fields {
866 if generated_code(field.ident.span) {
870 let field_data = self.save_ctxt.get_field_ref_data(field,
873 self.fmt.ref_str(recorder::VarRef,
875 Some(field_data.span),
879 self.visit_expr(&field.expr)
883 visit::walk_expr_opt(self, base)
886 fn process_method_call(&mut self,
888 args: &Vec<P<ast::Expr>>) {
889 let method_map = &self.tcx.tables.borrow().method_map;
890 let method_callee = method_map.get(&ty::MethodCall::expr(ex.id)).unwrap();
891 let (def_id, decl_id) = match method_callee.origin {
892 ty::MethodStatic(def_id) |
893 ty::MethodStaticClosure(def_id) => {
894 // method invoked on an object with a concrete type (not a static method)
896 match self.tcx.trait_item_of_item(def_id) {
898 Some(decl_id) => Some(decl_id.def_id()),
901 // This incantation is required if the method referenced is a
902 // trait's default implementation.
903 let def_id = match self.tcx.impl_or_trait_item(def_id) {
904 ty::MethodTraitItem(method) => {
905 method.provided_source.unwrap_or(def_id)
909 "save::process_method_call: non-method \
910 DefId in MethodStatic or MethodStaticClosure"),
912 (Some(def_id), decl_id)
914 ty::MethodTypeParam(ref mp) => {
915 // method invoked on a type parameter
916 let trait_item = self.tcx.trait_item(mp.trait_ref.def_id,
918 (None, Some(trait_item.def_id()))
920 ty::MethodTraitObject(ref mo) => {
921 // method invoked on a trait instance
922 let trait_item = self.tcx.trait_item(mo.trait_ref.def_id,
924 (None, Some(trait_item.def_id()))
927 let sub_span = self.span.sub_span_for_meth_name(ex.span);
928 self.fmt.meth_call_str(ex.span,
934 // walk receiver and args
935 visit::walk_exprs(self, &args);
938 fn process_pat(&mut self, p:&ast::Pat) {
939 if generated_code(p.span) {
944 ast::PatStruct(ref path, ref fields, _) => {
945 visit::walk_path(self, path);
947 let def = self.tcx.def_map.borrow().get(&p.id).unwrap().full_def();
948 let struct_def = match def {
949 def::DefConst(..) | def::DefAssociatedConst(..) => None,
950 def::DefVariant(_, variant_id, _) => Some(variant_id),
952 match self.tcx.node_id_to_type(p.id).ty_to_def_id() {
954 self.sess.span_bug(p.span,
955 &format!("Could not find struct_def for `{}`",
956 self.span.snippet(p.span)));
958 Some(def_id) => Some(def_id),
963 if let Some(struct_def) = struct_def {
964 let struct_fields = self.tcx.lookup_struct_fields(struct_def);
965 for &Spanned { node: ref field, span } in fields {
966 if generated_code(span) {
970 let sub_span = self.span.span_for_first_ident(span);
971 for f in &struct_fields {
972 if f.name == field.ident.name {
973 self.fmt.ref_str(recorder::VarRef,
981 self.visit_pat(&field.pat);
985 _ => visit::walk_pat(self, p)
990 impl<'l, 'tcx, 'v> Visitor<'v> for DumpCsvVisitor<'l, 'tcx> {
991 fn visit_item(&mut self, item: &ast::Item) {
992 if generated_code(item.span) {
997 ast::ItemUse(ref use_item) => {
998 match use_item.node {
999 ast::ViewPathSimple(ident, ref path) => {
1000 let sub_span = self.span.span_for_last_ident(path.span);
1001 let mod_id = match self.lookup_type_ref(item.id) {
1003 match self.lookup_def_kind(item.id, path.span) {
1004 Some(kind) => self.fmt.ref_str(kind,
1016 // 'use' always introduces an alias, if there is not an explicit
1017 // one, there is an implicit one.
1019 match self.span.sub_span_after_keyword(use_item.span, keywords::As) {
1020 Some(sub_span) => Some(sub_span),
1024 self.fmt.use_alias_str(path.span,
1030 self.write_sub_paths_truncated(path, true);
1032 ast::ViewPathGlob(ref path) => {
1033 // Make a comma-separated list of names of imported modules.
1034 let mut name_string = String::new();
1035 let glob_map = &self.analysis.glob_map;
1036 let glob_map = glob_map.as_ref().unwrap();
1037 if glob_map.contains_key(&item.id) {
1038 for n in glob_map.get(&item.id).unwrap() {
1039 if !name_string.is_empty() {
1040 name_string.push_str(", ");
1042 name_string.push_str(n.as_str());
1046 let sub_span = self.span.sub_span_of_token(path.span,
1047 token::BinOp(token::Star));
1048 self.fmt.use_glob_str(path.span,
1053 self.write_sub_paths(path, true);
1055 ast::ViewPathList(ref path, ref list) => {
1058 ast::PathListIdent { id, .. } => {
1059 match self.lookup_type_ref(id) {
1061 match self.lookup_def_kind(id, plid.span) {
1066 def_id, self.cur_scope);
1073 ast::PathListMod { .. } => ()
1077 self.write_sub_paths(path, true);
1081 ast::ItemExternCrate(ref s) => {
1082 let name = get_ident(item.ident);
1084 let location = match *s {
1085 Some(s) => s.to_string(),
1086 None => name.to_string(),
1088 let alias_span = self.span.span_for_last_ident(item.span);
1089 let cnum = match self.sess.cstore.find_extern_mod_stmt_cnum(item.id) {
1093 self.fmt.extern_crate_str(item.span,
1101 ast::ItemFn(ref decl, _, _, _, ref ty_params, ref body) =>
1102 self.process_fn(item, &**decl, ty_params, &**body),
1103 ast::ItemStatic(ref typ, _, ref expr) =>
1104 self.process_static_or_const_item(item, typ, expr),
1105 ast::ItemConst(ref typ, ref expr) =>
1106 self.process_static_or_const_item(item, &typ, &expr),
1107 ast::ItemStruct(ref def, ref ty_params) => self.process_struct(item, &**def, ty_params),
1108 ast::ItemEnum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1113 ref impl_items) => {
1114 self.process_impl(item,
1120 ast::ItemTrait(_, ref generics, ref trait_refs, ref methods) =>
1121 self.process_trait(item, generics, trait_refs, methods),
1122 ast::ItemMod(ref m) => {
1123 self.process_mod(item);
1124 self.nest(item.id, |v| visit::walk_mod(v, m));
1126 ast::ItemTy(ref ty, ref ty_params) => {
1127 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
1128 let value = ty_to_string(&**ty);
1129 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1130 self.fmt.typedef_str(item.span,
1136 self.visit_ty(&**ty);
1137 self.process_generic_params(ty_params, item.span, &qualname, item.id);
1139 ast::ItemMac(_) => (),
1140 _ => visit::walk_item(self, item),
1144 fn visit_generics(&mut self, generics: &ast::Generics) {
1145 for param in generics.ty_params.iter() {
1146 for bound in param.bounds.iter() {
1147 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
1148 self.process_trait_ref(&trait_ref.trait_ref);
1151 if let Some(ref ty) = param.default {
1152 self.visit_ty(&**ty);
1157 fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
1158 match trait_item.node {
1159 ast::ConstTraitItem(ref ty, Some(ref expr)) => {
1160 self.process_const(trait_item.id, &trait_item.ident,
1161 trait_item.span, &*ty, &*expr);
1163 ast::MethodTraitItem(ref sig, ref body) => {
1164 self.process_method(sig, body.as_ref().map(|x| &**x),
1165 trait_item.id, trait_item.ident.name, trait_item.span);
1167 ast::ConstTraitItem(_, None) |
1168 ast::TypeTraitItem(..) => {}
1172 fn visit_impl_item(&mut self, impl_item: &ast::ImplItem) {
1173 match impl_item.node {
1174 ast::ConstImplItem(ref ty, ref expr) => {
1175 self.process_const(impl_item.id, &impl_item.ident,
1176 impl_item.span, &ty, &expr);
1178 ast::MethodImplItem(ref sig, ref body) => {
1179 self.process_method(sig, Some(body), impl_item.id,
1180 impl_item.ident.name, impl_item.span);
1182 ast::TypeImplItem(_) |
1183 ast::MacImplItem(_) => {}
1187 fn visit_ty(&mut self, t: &ast::Ty) {
1188 if generated_code(t.span) {
1193 ast::TyPath(_, ref path) => {
1194 match self.lookup_type_ref(t.id) {
1196 let sub_span = self.span.sub_span_for_type_name(t.span);
1197 self.fmt.ref_str(recorder::TypeRef,
1206 self.write_sub_paths_truncated(path, false);
1208 visit::walk_path(self, path);
1210 _ => visit::walk_ty(self, t),
1214 fn visit_expr(&mut self, ex: &ast::Expr) {
1215 if generated_code(ex.span) {
1220 ast::ExprCall(ref _f, ref _args) => {
1221 // Don't need to do anything for function calls,
1222 // because just walking the callee path does what we want.
1223 visit::walk_expr(self, ex);
1225 ast::ExprPath(_, ref path) => {
1226 self.process_path(ex.id, path.span, path, None);
1227 visit::walk_expr(self, ex);
1229 ast::ExprStruct(ref path, ref fields, ref base) =>
1230 self.process_struct_lit(ex, path, fields, base),
1231 ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, args),
1232 ast::ExprField(ref sub_ex, _) => {
1233 if generated_code(sub_ex.span) {
1237 self.visit_expr(&sub_ex);
1239 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1240 down_cast_data!(field_data, VariableRefData, self, ex.span);
1241 self.fmt.ref_str(recorder::VarRef,
1243 Some(field_data.span),
1248 ast::ExprTupField(ref sub_ex, idx) => {
1249 if generated_code(sub_ex.span) {
1253 self.visit_expr(&**sub_ex);
1255 let ty = &self.tcx.expr_ty_adjusted(&**sub_ex).sty;
1257 ty::TyStruct(def_id, _) => {
1258 let fields = self.tcx.lookup_struct_fields(def_id);
1259 for (i, f) in fields.iter().enumerate() {
1261 let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1262 self.fmt.ref_str(recorder::VarRef,
1271 ty::TyTuple(_) => {}
1272 _ => self.sess.span_bug(ex.span,
1273 &format!("Expected struct or tuple \
1274 type, found {:?}", ty)),
1277 ast::ExprClosure(_, ref decl, ref body) => {
1278 if generated_code(body.span) {
1282 let mut id = String::from("$");
1283 id.push_str(&ex.id.to_string());
1284 self.process_formals(&decl.inputs, &id);
1286 // walk arg and return types
1287 for arg in &decl.inputs {
1288 self.visit_ty(&*arg.ty);
1291 if let ast::Return(ref ret_ty) = decl.output {
1292 self.visit_ty(&**ret_ty);
1296 self.nest(ex.id, |v| v.visit_block(&**body));
1299 visit::walk_expr(self, ex)
1304 fn visit_mac(&mut self, _: &ast::Mac) {
1305 // Just stop, macros are poison to us.
1308 fn visit_pat(&mut self, p: &ast::Pat) {
1309 self.process_pat(p);
1312 fn visit_arm(&mut self, arm: &ast::Arm) {
1313 let mut collector = PathCollector::new();
1314 for pattern in &arm.pats {
1315 // collect paths from the arm's patterns
1316 collector.visit_pat(&pattern);
1317 self.visit_pat(&pattern);
1320 // This is to get around borrow checking, because we need mut self to call process_path.
1321 let mut paths_to_process = vec![];
1322 // process collected paths
1323 for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1324 let def_map = self.tcx.def_map.borrow();
1325 if !def_map.contains_key(&id) {
1326 self.sess.span_bug(p.span,
1327 &format!("def_map has no key for {} in visit_arm",
1330 let def = def_map.get(&id).unwrap().full_def();
1332 def::DefLocal(id) => {
1333 let value = if immut == ast::MutImmutable {
1334 self.span.snippet(p.span).to_string()
1336 "<mutable>".to_string()
1339 assert!(p.segments.len() == 1, "qualified path for local variable def in arm");
1340 self.fmt.variable_str(p.span,
1347 def::DefVariant(..) | def::DefTy(..) | def::DefStruct(..) => {
1348 paths_to_process.push((id, p.clone(), Some(ref_kind)))
1350 // FIXME(nrc) what are these doing here?
1351 def::DefStatic(_, _) |
1353 def::DefAssociatedConst(..) => {}
1354 _ => error!("unexpected definition kind when processing collected paths: {:?}",
1358 for &(id, ref path, ref_kind) in &paths_to_process {
1359 self.process_path(id, path.span, path, ref_kind);
1361 visit::walk_expr_opt(self, &arm.guard);
1362 self.visit_expr(&*arm.body);
1365 fn visit_stmt(&mut self, s: &ast::Stmt) {
1366 if generated_code(s.span) {
1370 visit::walk_stmt(self, s)
1373 fn visit_local(&mut self, l: &ast::Local) {
1374 if generated_code(l.span) {
1378 // The local could declare multiple new vars, we must walk the
1379 // pattern and collect them all.
1380 let mut collector = PathCollector::new();
1381 collector.visit_pat(&l.pat);
1382 self.visit_pat(&l.pat);
1384 let value = self.span.snippet(l.span);
1386 for &(id, ref p, immut, _) in &collector.collected_paths {
1387 let value = if immut == ast::MutImmutable {
1390 "<mutable>".to_string()
1392 let types = self.tcx.node_types();
1393 let typ = types.get(&id).unwrap().to_string();
1394 // Get the span only for the name of the variable (I hope the path
1395 // is only ever a variable name, but who knows?).
1396 let sub_span = self.span.span_for_last_ident(p.span);
1397 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1398 self.fmt.variable_str(p.span,
1406 // Just walk the initialiser and type (don't want to walk the pattern again).
1407 visit::walk_ty_opt(self, &l.ty);
1408 visit::walk_expr_opt(self, &l.init);