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, Data};
36 use middle::ty::{self, Ty};
41 use syntax::ast::{self, NodeId, DefId};
42 use syntax::codemap::*;
43 use syntax::parse::token::{self, keywords};
44 use syntax::owned_slice::OwnedSlice;
45 use syntax::visit::{self, Visitor};
46 use syntax::print::pprust::{path_to_string, ty_to_string};
49 use super::span_utils::SpanUtils;
50 use super::recorder::{Recorder, FmtStrs};
52 macro_rules! down_cast_data {
53 ($id:ident, $kind:ident, $this:ident, $sp:expr) => {
54 let $id = if let super::Data::$kind(data) = $id {
57 $this.sess.span_bug($sp, &format!("unexpected data kind: {:?}", $id));
62 pub struct DumpCsvVisitor<'l, 'tcx: 'l> {
63 save_ctxt: SaveContext<'l, 'tcx>,
65 tcx: &'l ty::ctxt<'tcx>,
66 analysis: &'l ty::CrateAnalysis,
74 impl <'l, 'tcx> DumpCsvVisitor<'l, 'tcx> {
75 pub fn new(tcx: &'l ty::ctxt<'tcx>,
76 analysis: &'l ty::CrateAnalysis,
77 output_file: Box<File>) -> DumpCsvVisitor<'l, 'tcx> {
78 let span_utils = SpanUtils::new(&tcx.sess);
82 save_ctxt: SaveContext::from_span_utils(tcx, span_utils.clone()),
84 span: span_utils.clone(),
85 fmt: FmtStrs::new(box Recorder {
93 fn nest<F>(&mut self, scope_id: NodeId, f: F) where
94 F: FnOnce(&mut DumpCsvVisitor<'l, 'tcx>),
96 let parent_scope = self.cur_scope;
97 self.cur_scope = scope_id;
99 self.cur_scope = parent_scope;
102 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
103 // The current crate.
104 self.fmt.crate_str(krate.span, name);
106 // Dump info about all the external crates referenced from this crate.
107 for c in &self.save_ctxt.get_external_crates() {
108 self.fmt.external_crate_str(krate.span, &c.name, c.number);
110 self.fmt.recorder.record("end_external_crates\n");
113 // Return all non-empty prefixes of a path.
114 // For each prefix, we return the span for the last segment in the prefix and
115 // a str representation of the entire prefix.
116 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
117 let spans = self.span.spans_for_path_segments(path);
119 // Paths to enums seem to not match their spans - the span includes all the
120 // variants too. But they seem to always be at the end, so I hope we can cope with
121 // always using the first ones. So, only error out if we don't have enough spans.
122 // What could go wrong...?
123 if spans.len() < path.segments.len() {
124 error!("Mis-calculated spans for path '{}'. \
125 Found {} spans, expected {}. Found spans:",
126 path_to_string(path), spans.len(), path.segments.len());
128 let loc = self.sess.codemap().lookup_char_pos(s.lo);
129 error!(" '{}' in {}, line {}",
130 self.span.snippet(*s), loc.file.name, loc.line);
135 let mut result: Vec<(Span, String)> = vec!();
137 let mut segs = vec!();
138 for (i, (seg, span)) in path.segments.iter().zip(&spans).enumerate() {
139 segs.push(seg.clone());
140 let sub_path = ast::Path{span: *span, // span for the last segment
143 let qualname = if i == 0 && path.global {
144 format!("::{}", path_to_string(&sub_path))
146 path_to_string(&sub_path)
148 result.push((*span, qualname));
149 segs = sub_path.segments;
155 // The global arg allows us to override the global-ness of the path (which
156 // actually means 'does the path start with `::`', rather than 'is the path
157 // semantically global). We use the override for `use` imports (etc.) where
158 // the syntax is non-global, but the semantics are global.
159 fn write_sub_paths(&mut self, path: &ast::Path, global: bool) {
160 let sub_paths = self.process_path_prefixes(path);
161 for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
162 let qualname = if i == 0 && global && !path.global {
163 format!("::{}", qualname)
167 self.fmt.sub_mod_ref_str(path.span,
174 // As write_sub_paths, but does not process the last ident in the path (assuming it
175 // will be processed elsewhere). See note on write_sub_paths about global.
176 fn write_sub_paths_truncated(&mut self, path: &ast::Path, global: bool) {
177 let sub_paths = self.process_path_prefixes(path);
178 let len = sub_paths.len();
183 let sub_paths = &sub_paths[..len-1];
184 for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
185 let qualname = if i == 0 && global && !path.global {
186 format!("::{}", qualname)
190 self.fmt.sub_mod_ref_str(path.span,
197 // As write_sub_paths, but expects a path of the form module_path::trait::method
198 // Where trait could actually be a struct too.
199 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
200 let sub_paths = self.process_path_prefixes(path);
201 let len = sub_paths.len();
205 let sub_paths = &sub_paths[.. (len-1)];
207 // write the trait part of the sub-path
208 let (ref span, ref qualname) = sub_paths[len-2];
209 self.fmt.sub_type_ref_str(path.span,
213 // write the other sub-paths
217 let sub_paths = &sub_paths[..len-2];
218 for &(ref span, ref qualname) in sub_paths {
219 self.fmt.sub_mod_ref_str(path.span,
226 // looks up anything, not just a type
227 fn lookup_type_ref(&self, ref_id: NodeId) -> Option<DefId> {
228 if !self.tcx.def_map.borrow().contains_key(&ref_id) {
229 self.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
232 let def = self.tcx.def_map.borrow().get(&ref_id).unwrap().full_def();
234 def::DefPrimTy(_) => None,
235 _ => Some(def.def_id()),
239 fn lookup_def_kind(&self, ref_id: NodeId, span: Span) -> Option<recorder::Row> {
240 let def_map = self.tcx.def_map.borrow();
241 if !def_map.contains_key(&ref_id) {
242 self.sess.span_bug(span, &format!("def_map has no key for {} in lookup_def_kind",
245 let def = def_map.get(&ref_id).unwrap().full_def();
248 def::DefForeignMod(_) => Some(recorder::ModRef),
249 def::DefStruct(_) => Some(recorder::TypeRef),
251 def::DefAssociatedTy(..) |
252 def::DefTrait(_) => Some(recorder::TypeRef),
253 def::DefStatic(_, _) |
255 def::DefAssociatedConst(..) |
257 def::DefVariant(_, _, _) |
258 def::DefUpvar(..) => Some(recorder::VarRef),
260 def::DefFn(..) => Some(recorder::FnRef),
265 def::DefTyParam(..) |
268 def::DefPrimTy(_) => {
269 self.sess.span_bug(span, &format!("lookup_def_kind for unexpected item: {:?}",
275 fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str) {
277 self.visit_pat(&arg.pat);
278 let mut collector = PathCollector::new();
279 collector.visit_pat(&arg.pat);
280 let span_utils = self.span.clone();
281 for &(id, ref p, _, _) in &collector.collected_paths {
282 let typ = self.tcx.node_types().get(&id).unwrap().to_string();
283 // get the span only for the name of the variable (I hope the path is only ever a
284 // variable name, but who knows?)
285 self.fmt.formal_str(p.span,
286 span_utils.span_for_last_ident(p.span),
295 fn process_method(&mut self,
296 sig: &ast::MethodSig,
297 body: Option<&ast::Block>,
301 if generated_code(span) {
305 debug!("process_method: {}:{}", id, name);
307 let method_data = self.save_ctxt.get_method_data(id, name, span);
310 self.fmt.method_str(span,
311 Some(method_data.span),
313 &method_data.qualname,
314 method_data.declaration,
316 self.process_formals(&sig.decl.inputs, &method_data.qualname);
318 self.fmt.method_decl_str(span,
319 Some(method_data.span),
321 &method_data.qualname,
325 // walk arg and return types
326 for arg in &sig.decl.inputs {
327 self.visit_ty(&arg.ty);
330 if let ast::Return(ref ret_ty) = sig.decl.output {
331 self.visit_ty(ret_ty);
335 if let Some(body) = body {
336 self.nest(id, |v| v.visit_block(body));
339 self.process_generic_params(&sig.generics,
341 &method_data.qualname,
345 fn process_trait_ref(&mut self, trait_ref: &ast::TraitRef) {
346 let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref, self.cur_scope);
347 if let Some(trait_ref_data) = trait_ref_data {
348 self.fmt.ref_str(recorder::TypeRef,
350 Some(trait_ref_data.span),
351 trait_ref_data.ref_id,
352 trait_ref_data.scope);
353 visit::walk_path(self, &trait_ref.path);
357 fn process_struct_field_def(&mut self,
358 field: &ast::StructField,
360 let field_data = self.save_ctxt.get_field_data(field, parent_id);
361 if let Some(field_data) = field_data {
362 self.fmt.field_str(field.span,
363 Some(field_data.span),
366 &field_data.qualname,
367 &field_data.type_value,
372 // Dump generic params bindings, then visit_generics
373 fn process_generic_params(&mut self,
374 generics:&ast::Generics,
378 // We can't only use visit_generics since we don't have spans for param
379 // bindings, so we reparse the full_span to get those sub spans.
380 // However full span is the entire enum/fn/struct block, so we only want
381 // the first few to match the number of generics we're looking for.
382 let param_sub_spans = self.span.spans_for_ty_params(full_span,
383 (generics.ty_params.len() as isize));
384 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
385 // Append $id to name to make sure each one is unique
386 let name = format!("{}::{}${}",
388 escape(self.span.snippet(param_ss)),
390 self.fmt.typedef_str(full_span,
396 self.visit_generics(generics);
399 fn process_fn(&mut self,
402 ty_params: &ast::Generics,
404 let fn_data = self.save_ctxt.get_item_data(item);
405 down_cast_data!(fn_data, FunctionData, self, item.span);
406 self.fmt.fn_str(item.span,
413 self.process_formals(&decl.inputs, &fn_data.qualname);
414 self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
416 for arg in &decl.inputs {
417 self.visit_ty(&arg.ty);
420 if let ast::Return(ref ret_ty) = decl.output {
421 self.visit_ty(&ret_ty);
424 self.nest(item.id, |v| v.visit_block(&body));
427 fn process_static_or_const_item(&mut self,
432 let var_data = self.save_ctxt.get_item_data(item);
433 down_cast_data!(var_data, VariableData, self, item.span);
434 self.fmt.static_str(item.span,
440 &var_data.type_value,
444 self.visit_expr(expr);
447 fn process_const(&mut self,
454 let qualname = format!("::{}", self.tcx.map.path_to_string(id));
456 let sub_span = self.span.sub_span_after_keyword(span,
459 self.fmt.static_str(span,
462 &ident.name.as_str(),
464 &self.span.snippet(expr.span),
465 &ty_to_string(&*typ),
468 // walk type and init value
470 self.visit_expr(expr);
473 fn process_struct(&mut self,
475 def: &ast::StructDef,
476 ty_params: &ast::Generics) {
477 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
479 let ctor_id = match def.ctor_id {
480 Some(node_id) => node_id,
481 None => ast::DUMMY_NODE_ID,
483 let val = self.span.snippet(item.span);
484 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
485 self.fmt.struct_str(item.span,
494 for field in &def.fields {
495 self.process_struct_field_def(field, item.id);
496 self.visit_ty(&field.node.ty);
499 self.process_generic_params(ty_params, item.span, &qualname, item.id);
502 fn process_enum(&mut self,
504 enum_definition: &ast::EnumDef,
505 ty_params: &ast::Generics) {
506 let enum_data = self.save_ctxt.get_item_data(item);
507 down_cast_data!(enum_data, EnumData, self, item.span);
508 self.fmt.enum_str(item.span,
509 Some(enum_data.span),
515 for variant in &enum_definition.variants {
516 let name = &variant.node.name.name.as_str();
517 let mut qualname = enum_data.qualname.clone();
518 qualname.push_str("::");
519 qualname.push_str(name);
520 let val = self.span.snippet(variant.span);
521 match variant.node.kind {
522 ast::TupleVariantKind(ref args) => {
523 // first ident in span is the variant's name
524 self.fmt.tuple_variant_str(variant.span,
525 self.span.span_for_first_ident(variant.span),
533 self.visit_ty(&*arg.ty);
536 ast::StructVariantKind(ref struct_def) => {
537 let ctor_id = match struct_def.ctor_id {
538 Some(node_id) => node_id,
539 None => ast::DUMMY_NODE_ID,
541 self.fmt.struct_variant_str(variant.span,
542 self.span.span_for_first_ident(variant.span),
550 for field in &struct_def.fields {
551 self.process_struct_field_def(field, variant.node.id);
552 self.visit_ty(&*field.node.ty);
557 self.process_generic_params(ty_params, item.span, &enum_data.qualname, enum_data.id);
560 fn process_impl(&mut self,
562 type_parameters: &ast::Generics,
563 trait_ref: &Option<ast::TraitRef>,
565 impl_items: &[P<ast::ImplItem>]) {
566 let impl_data = self.save_ctxt.get_item_data(item);
567 down_cast_data!(impl_data, ImplData, self, item.span);
568 match impl_data.self_ref {
569 Some(ref self_ref) => {
570 self.fmt.ref_str(recorder::TypeRef,
580 if let Some(ref trait_ref_data) = impl_data.trait_ref {
581 self.fmt.ref_str(recorder::TypeRef,
583 Some(trait_ref_data.span),
584 trait_ref_data.ref_id,
585 trait_ref_data.scope);
586 visit::walk_path(self, &trait_ref.as_ref().unwrap().path);
589 self.fmt.impl_str(item.span,
590 Some(impl_data.span),
592 impl_data.self_ref.map(|data| data.ref_id),
593 impl_data.trait_ref.map(|data| data.ref_id),
596 self.process_generic_params(type_parameters, item.span, "", item.id);
597 for impl_item in impl_items {
598 self.visit_impl_item(impl_item);
602 fn process_trait(&mut self,
604 generics: &ast::Generics,
605 trait_refs: &OwnedSlice<ast::TyParamBound>,
606 methods: &[P<ast::TraitItem>]) {
607 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
608 let val = self.span.snippet(item.span);
609 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
610 self.fmt.trait_str(item.span,
618 for super_bound in trait_refs.iter() {
619 let trait_ref = match *super_bound {
620 ast::TraitTyParamBound(ref trait_ref, _) => {
623 ast::RegionTyParamBound(..) => {
628 let trait_ref = &trait_ref.trait_ref;
629 match self.lookup_type_ref(trait_ref.ref_id) {
631 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
632 self.fmt.ref_str(recorder::TypeRef,
637 self.fmt.inherit_str(trait_ref.path.span,
646 // walk generics and methods
647 self.process_generic_params(generics, item.span, &qualname, item.id);
648 for method in methods {
649 self.visit_trait_item(method)
653 fn process_mod(&mut self,
654 item: &ast::Item) { // The module in question, represented as an item.
655 let mod_data = self.save_ctxt.get_item_data(item);
656 down_cast_data!(mod_data, ModData, self, item.span);
657 self.fmt.mod_str(item.span,
665 fn process_path(&mut self,
668 ref_kind: Option<recorder::Row>) {
669 if generated_code(path.span) {
673 let path_data = self.save_ctxt.get_path_data(id, path);
675 Data::VariableRefData(ref vrd) => {
676 self.fmt.ref_str(ref_kind.unwrap_or(recorder::VarRef),
683 Data::TypeRefData(ref trd) => {
684 self.fmt.ref_str(recorder::TypeRef,
690 Data::MethodCallData(ref mcd) => {
691 self.fmt.meth_call_str(path.span,
697 Data::FunctionCallData(fcd) => {
698 self.fmt.fn_call_str(path.span,
704 self.sess.span_bug(path.span,
705 &format!("Unexpected data: {:?}", path_data));
709 // Modules or types in the path prefix.
710 let def_map = self.tcx.def_map.borrow();
711 let def = def_map.get(&id).unwrap().full_def();
713 def::DefMethod(did, _) => {
714 let ti = self.tcx.impl_or_trait_item(did);
715 if let ty::MethodTraitItem(m) = ti {
716 if m.explicit_self == ty::StaticExplicitSelfCategory {
717 self.write_sub_path_trait_truncated(path);
722 def::DefStatic(_,_) |
724 def::DefAssociatedConst(..) |
726 def::DefVariant(..) |
727 def::DefFn(..) => self.write_sub_paths_truncated(path, false),
732 fn process_struct_lit(&mut self,
735 fields: &Vec<ast::Field>,
736 base: &Option<P<ast::Expr>>) {
737 if generated_code(path.span) {
741 self.write_sub_paths_truncated(path, false);
743 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
744 down_cast_data!(struct_lit_data, TypeRefData, self, ex.span);
745 self.fmt.ref_str(recorder::TypeRef,
747 Some(struct_lit_data.span),
748 struct_lit_data.ref_id,
749 struct_lit_data.scope);
750 let struct_def = struct_lit_data.ref_id;
751 let scope = self.save_ctxt.enclosing_scope(ex.id);
753 for field in fields {
754 if generated_code(field.ident.span) {
758 let field_data = self.save_ctxt.get_field_ref_data(field,
761 self.fmt.ref_str(recorder::VarRef,
763 Some(field_data.span),
767 self.visit_expr(&field.expr)
771 visit::walk_expr_opt(self, base)
774 fn process_method_call(&mut self,
776 args: &Vec<P<ast::Expr>>) {
777 if let Some(call_data) = self.save_ctxt.get_expr_data(ex) {
778 down_cast_data!(call_data, MethodCallData, self, ex.span);
779 self.fmt.meth_call_str(ex.span,
780 Some(call_data.span),
786 // walk receiver and args
787 visit::walk_exprs(self, &args);
790 fn process_pat(&mut self, p:&ast::Pat) {
791 if generated_code(p.span) {
796 ast::PatStruct(ref path, ref fields, _) => {
797 visit::walk_path(self, path);
799 let def = self.tcx.def_map.borrow().get(&p.id).unwrap().full_def();
800 let struct_def = match def {
801 def::DefConst(..) | def::DefAssociatedConst(..) => None,
802 def::DefVariant(_, variant_id, _) => Some(variant_id),
804 match self.tcx.node_id_to_type(p.id).ty_to_def_id() {
806 self.sess.span_bug(p.span,
807 &format!("Could not find struct_def for `{}`",
808 self.span.snippet(p.span)));
810 Some(def_id) => Some(def_id),
815 if let Some(struct_def) = struct_def {
816 let struct_fields = self.tcx.lookup_struct_fields(struct_def);
817 for &Spanned { node: ref field, span } in fields {
818 if generated_code(span) {
822 let sub_span = self.span.span_for_first_ident(span);
823 for f in &struct_fields {
824 if f.name == field.ident.name {
825 self.fmt.ref_str(recorder::VarRef,
833 self.visit_pat(&field.pat);
837 _ => visit::walk_pat(self, p)
842 impl<'l, 'tcx, 'v> Visitor<'v> for DumpCsvVisitor<'l, 'tcx> {
843 fn visit_item(&mut self, item: &ast::Item) {
844 if generated_code(item.span) {
849 ast::ItemUse(ref use_item) => {
850 match use_item.node {
851 ast::ViewPathSimple(ident, ref path) => {
852 let sub_span = self.span.span_for_last_ident(path.span);
853 let mod_id = match self.lookup_type_ref(item.id) {
855 match self.lookup_def_kind(item.id, path.span) {
856 Some(kind) => self.fmt.ref_str(kind,
868 // 'use' always introduces an alias, if there is not an explicit
869 // one, there is an implicit one.
871 match self.span.sub_span_after_keyword(use_item.span, keywords::As) {
872 Some(sub_span) => Some(sub_span),
876 self.fmt.use_alias_str(path.span,
880 &ident.name.as_str(),
882 self.write_sub_paths_truncated(path, true);
884 ast::ViewPathGlob(ref path) => {
885 // Make a comma-separated list of names of imported modules.
886 let mut name_string = String::new();
887 let glob_map = &self.analysis.glob_map;
888 let glob_map = glob_map.as_ref().unwrap();
889 if glob_map.contains_key(&item.id) {
890 for n in glob_map.get(&item.id).unwrap() {
891 if !name_string.is_empty() {
892 name_string.push_str(", ");
894 name_string.push_str(&n.as_str());
898 let sub_span = self.span.sub_span_of_token(path.span,
899 token::BinOp(token::Star));
900 self.fmt.use_glob_str(path.span,
905 self.write_sub_paths(path, true);
907 ast::ViewPathList(ref path, ref list) => {
910 ast::PathListIdent { id, .. } => {
911 match self.lookup_type_ref(id) {
913 match self.lookup_def_kind(id, plid.span) {
918 def_id, self.cur_scope);
925 ast::PathListMod { .. } => ()
929 self.write_sub_paths(path, true);
933 ast::ItemExternCrate(ref s) => {
934 let location = match *s {
935 Some(s) => s.to_string(),
936 None => item.ident.to_string(),
938 let alias_span = self.span.span_for_last_ident(item.span);
939 let cnum = match self.sess.cstore.find_extern_mod_stmt_cnum(item.id) {
943 self.fmt.extern_crate_str(item.span,
947 &item.ident.name.as_str(),
951 ast::ItemFn(ref decl, _, _, _, ref ty_params, ref body) =>
952 self.process_fn(item, &**decl, ty_params, &**body),
953 ast::ItemStatic(ref typ, _, ref expr) =>
954 self.process_static_or_const_item(item, typ, expr),
955 ast::ItemConst(ref typ, ref expr) =>
956 self.process_static_or_const_item(item, &typ, &expr),
957 ast::ItemStruct(ref def, ref ty_params) => self.process_struct(item, &**def, ty_params),
958 ast::ItemEnum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
964 self.process_impl(item,
970 ast::ItemTrait(_, ref generics, ref trait_refs, ref methods) =>
971 self.process_trait(item, generics, trait_refs, methods),
972 ast::ItemMod(ref m) => {
973 self.process_mod(item);
974 self.nest(item.id, |v| visit::walk_mod(v, m));
976 ast::ItemTy(ref ty, ref ty_params) => {
977 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
978 let value = ty_to_string(&**ty);
979 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
980 self.fmt.typedef_str(item.span,
986 self.visit_ty(&**ty);
987 self.process_generic_params(ty_params, item.span, &qualname, item.id);
989 ast::ItemMac(_) => (),
990 _ => visit::walk_item(self, item),
994 fn visit_generics(&mut self, generics: &ast::Generics) {
995 for param in generics.ty_params.iter() {
996 for bound in param.bounds.iter() {
997 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
998 self.process_trait_ref(&trait_ref.trait_ref);
1001 if let Some(ref ty) = param.default {
1002 self.visit_ty(&**ty);
1007 fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
1008 match trait_item.node {
1009 ast::ConstTraitItem(ref ty, Some(ref expr)) => {
1010 self.process_const(trait_item.id, &trait_item.ident,
1011 trait_item.span, &*ty, &*expr);
1013 ast::MethodTraitItem(ref sig, ref body) => {
1014 self.process_method(sig,
1015 body.as_ref().map(|x| &**x),
1017 trait_item.ident.name,
1020 ast::ConstTraitItem(_, None) |
1021 ast::TypeTraitItem(..) => {}
1025 fn visit_impl_item(&mut self, impl_item: &ast::ImplItem) {
1026 match impl_item.node {
1027 ast::ConstImplItem(ref ty, ref expr) => {
1028 self.process_const(impl_item.id, &impl_item.ident,
1029 impl_item.span, &ty, &expr);
1031 ast::MethodImplItem(ref sig, ref body) => {
1032 self.process_method(sig,
1035 impl_item.ident.name,
1038 ast::TypeImplItem(_) |
1039 ast::MacImplItem(_) => {}
1043 fn visit_ty(&mut self, t: &ast::Ty) {
1044 if generated_code(t.span) {
1049 ast::TyPath(_, ref path) => {
1050 match self.lookup_type_ref(t.id) {
1052 let sub_span = self.span.sub_span_for_type_name(t.span);
1053 self.fmt.ref_str(recorder::TypeRef,
1062 self.write_sub_paths_truncated(path, false);
1064 visit::walk_path(self, path);
1066 _ => visit::walk_ty(self, t),
1070 fn visit_expr(&mut self, ex: &ast::Expr) {
1071 if generated_code(ex.span) {
1076 ast::ExprCall(ref _f, ref _args) => {
1077 // Don't need to do anything for function calls,
1078 // because just walking the callee path does what we want.
1079 visit::walk_expr(self, ex);
1081 ast::ExprPath(_, ref path) => {
1082 self.process_path(ex.id, path, None);
1083 visit::walk_expr(self, ex);
1085 ast::ExprStruct(ref path, ref fields, ref base) =>
1086 self.process_struct_lit(ex, path, fields, base),
1087 ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, args),
1088 ast::ExprField(ref sub_ex, _) => {
1089 if generated_code(sub_ex.span) {
1093 self.visit_expr(&sub_ex);
1095 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1096 down_cast_data!(field_data, VariableRefData, self, ex.span);
1097 self.fmt.ref_str(recorder::VarRef,
1099 Some(field_data.span),
1104 ast::ExprTupField(ref sub_ex, idx) => {
1105 if generated_code(sub_ex.span) {
1109 self.visit_expr(&**sub_ex);
1111 let ty = &self.tcx.expr_ty_adjusted(&**sub_ex).sty;
1113 ty::TyStruct(def_id, _) => {
1114 let fields = self.tcx.lookup_struct_fields(def_id);
1115 for (i, f) in fields.iter().enumerate() {
1117 let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1118 self.fmt.ref_str(recorder::VarRef,
1127 ty::TyTuple(_) => {}
1128 _ => self.sess.span_bug(ex.span,
1129 &format!("Expected struct or tuple \
1130 type, found {:?}", ty)),
1133 ast::ExprClosure(_, ref decl, ref body) => {
1134 if generated_code(body.span) {
1138 let mut id = String::from("$");
1139 id.push_str(&ex.id.to_string());
1140 self.process_formals(&decl.inputs, &id);
1142 // walk arg and return types
1143 for arg in &decl.inputs {
1144 self.visit_ty(&*arg.ty);
1147 if let ast::Return(ref ret_ty) = decl.output {
1148 self.visit_ty(&**ret_ty);
1152 self.nest(ex.id, |v| v.visit_block(&**body));
1155 visit::walk_expr(self, ex)
1160 fn visit_mac(&mut self, _: &ast::Mac) {
1161 // Just stop, macros are poison to us.
1164 fn visit_pat(&mut self, p: &ast::Pat) {
1165 self.process_pat(p);
1168 fn visit_arm(&mut self, arm: &ast::Arm) {
1169 let mut collector = PathCollector::new();
1170 for pattern in &arm.pats {
1171 // collect paths from the arm's patterns
1172 collector.visit_pat(&pattern);
1173 self.visit_pat(&pattern);
1176 // This is to get around borrow checking, because we need mut self to call process_path.
1177 let mut paths_to_process = vec![];
1179 // process collected paths
1180 for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1181 let def_map = self.tcx.def_map.borrow();
1182 if !def_map.contains_key(&id) {
1183 self.sess.span_bug(p.span,
1184 &format!("def_map has no key for {} in visit_arm",
1187 let def = def_map.get(&id).unwrap().full_def();
1189 def::DefLocal(id) => {
1190 let value = if immut == ast::MutImmutable {
1191 self.span.snippet(p.span).to_string()
1193 "<mutable>".to_string()
1196 assert!(p.segments.len() == 1, "qualified path for local variable def in arm");
1197 self.fmt.variable_str(p.span,
1204 def::DefVariant(..) | def::DefTy(..) | def::DefStruct(..) => {
1205 paths_to_process.push((id, p.clone(), Some(ref_kind)))
1207 // FIXME(nrc) what are these doing here?
1208 def::DefStatic(_, _) |
1210 def::DefAssociatedConst(..) => {}
1211 _ => error!("unexpected definition kind when processing collected paths: {:?}",
1216 for &(id, ref path, ref_kind) in &paths_to_process {
1217 self.process_path(id, path, ref_kind);
1219 visit::walk_expr_opt(self, &arm.guard);
1220 self.visit_expr(&arm.body);
1223 fn visit_stmt(&mut self, s: &ast::Stmt) {
1224 if generated_code(s.span) {
1228 visit::walk_stmt(self, s)
1231 fn visit_local(&mut self, l: &ast::Local) {
1232 if generated_code(l.span) {
1236 // The local could declare multiple new vars, we must walk the
1237 // pattern and collect them all.
1238 let mut collector = PathCollector::new();
1239 collector.visit_pat(&l.pat);
1240 self.visit_pat(&l.pat);
1242 let value = self.span.snippet(l.span);
1244 for &(id, ref p, immut, _) in &collector.collected_paths {
1245 let value = if immut == ast::MutImmutable {
1248 "<mutable>".to_string()
1250 let types = self.tcx.node_types();
1251 let typ = types.get(&id).unwrap().to_string();
1252 // Get the span only for the name of the variable (I hope the path
1253 // is only ever a variable name, but who knows?).
1254 let sub_span = self.span.span_for_last_ident(p.span);
1255 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1256 self.fmt.variable_str(p.span,
1264 // Just walk the initialiser and type (don't want to walk the pattern again).
1265 visit::walk_ty_opt(self, &l.ty);
1266 visit::walk_expr_opt(self, &l.init);