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::def_id::DefId;
41 use syntax::ast::{self, NodeId};
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 rustc_front::lowering::{lower_expr, LoweringContext};
51 use super::span_utils::SpanUtils;
52 use super::recorder::{Recorder, FmtStrs};
54 macro_rules! down_cast_data {
55 ($id:ident, $kind:ident, $this:ident, $sp:expr) => {
56 let $id = if let super::Data::$kind(data) = $id {
59 $this.sess.span_bug($sp, &format!("unexpected data kind: {:?}", $id));
64 pub struct DumpCsvVisitor<'l, 'tcx: 'l> {
65 save_ctxt: SaveContext<'l, 'tcx>,
67 tcx: &'l ty::ctxt<'tcx>,
68 analysis: &'l ty::CrateAnalysis<'l>,
71 fmt: FmtStrs<'l, 'tcx>,
76 impl <'l, 'tcx> DumpCsvVisitor<'l, 'tcx> {
77 pub fn new(tcx: &'l ty::ctxt<'tcx>,
78 lcx: &'l LoweringContext<'l>,
79 analysis: &'l ty::CrateAnalysis<'l>,
80 output_file: Box<File>)
81 -> DumpCsvVisitor<'l, 'tcx> {
82 let span_utils = SpanUtils::new(&tcx.sess);
86 save_ctxt: SaveContext::from_span_utils(tcx, lcx, span_utils.clone()),
88 span: span_utils.clone(),
89 fmt: FmtStrs::new(box Recorder {
99 fn nest<F>(&mut self, scope_id: NodeId, f: F)
100 where 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 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
110 let crate_root = match source_file {
111 Some(source_file) => match source_file.file_name() {
112 Some(_) => source_file.parent().unwrap().display().to_string(),
113 None => source_file.display().to_string(),
115 None => "<no source>".to_owned(),
118 // The current crate.
119 self.fmt.crate_str(krate.span, name, &crate_root);
121 // Dump info about all the external crates referenced from this crate.
122 for c in &self.save_ctxt.get_external_crates() {
123 self.fmt.external_crate_str(krate.span, &c.name, c.number);
125 self.fmt.recorder.record("end_external_crates\n");
128 // Return all non-empty prefixes of a path.
129 // For each prefix, we return the span for the last segment in the prefix and
130 // a str representation of the entire prefix.
131 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
132 let spans = self.span.spans_for_path_segments(path);
134 // Paths to enums seem to not match their spans - the span includes all the
135 // variants too. But they seem to always be at the end, so I hope we can cope with
136 // always using the first ones. So, only error out if we don't have enough spans.
137 // What could go wrong...?
138 if spans.len() < path.segments.len() {
139 error!("Mis-calculated spans for path '{}'. Found {} spans, expected {}. Found spans:",
140 path_to_string(path),
142 path.segments.len());
144 let loc = self.sess.codemap().lookup_char_pos(s.lo);
145 error!(" '{}' in {}, line {}",
146 self.span.snippet(*s),
153 let mut result: Vec<(Span, String)> = vec!();
155 let mut segs = vec!();
156 for (i, (seg, span)) in path.segments.iter().zip(&spans).enumerate() {
157 segs.push(seg.clone());
158 let sub_path = ast::Path {
159 span: *span, // span for the last segment
163 let qualname = if i == 0 && path.global {
164 format!("::{}", path_to_string(&sub_path))
166 path_to_string(&sub_path)
168 result.push((*span, qualname));
169 segs = sub_path.segments;
175 // The global arg allows us to override the global-ness of the path (which
176 // actually means 'does the path start with `::`', rather than 'is the path
177 // semantically global). We use the override for `use` imports (etc.) where
178 // the syntax is non-global, but the semantics are global.
179 fn write_sub_paths(&mut self, path: &ast::Path, global: bool) {
180 let sub_paths = self.process_path_prefixes(path);
181 for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
182 let qualname = if i == 0 && global && !path.global {
183 format!("::{}", qualname)
187 self.fmt.sub_mod_ref_str(path.span, *span, &qualname, self.cur_scope);
191 // As write_sub_paths, but does not process the last ident in the path (assuming it
192 // will be processed elsewhere). See note on write_sub_paths about global.
193 fn write_sub_paths_truncated(&mut self, path: &ast::Path, global: bool) {
194 let sub_paths = self.process_path_prefixes(path);
195 let len = sub_paths.len();
200 let sub_paths = &sub_paths[..len-1];
201 for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
202 let qualname = if i == 0 && global && !path.global {
203 format!("::{}", qualname)
207 self.fmt.sub_mod_ref_str(path.span, *span, &qualname, self.cur_scope);
211 // As write_sub_paths, but expects a path of the form module_path::trait::method
212 // Where trait could actually be a struct too.
213 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
214 let sub_paths = self.process_path_prefixes(path);
215 let len = sub_paths.len();
219 let sub_paths = &sub_paths[.. (len-1)];
221 // write the trait part of the sub-path
222 let (ref span, ref qualname) = sub_paths[len-2];
223 self.fmt.sub_type_ref_str(path.span, *span, &qualname);
225 // write the other sub-paths
229 let sub_paths = &sub_paths[..len-2];
230 for &(ref span, ref qualname) in sub_paths {
231 self.fmt.sub_mod_ref_str(path.span, *span, &qualname, self.cur_scope);
235 // looks up anything, not just a type
236 fn lookup_type_ref(&self, ref_id: NodeId) -> Option<DefId> {
237 if !self.tcx.def_map.borrow().contains_key(&ref_id) {
238 self.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
241 let def = self.tcx.def_map.borrow().get(&ref_id).unwrap().full_def();
243 def::DefPrimTy(..) => None,
244 def::DefSelfTy(..) => None,
245 _ => Some(def.def_id()),
249 fn lookup_def_kind(&self, ref_id: NodeId, span: Span) -> Option<recorder::Row> {
250 let def_map = self.tcx.def_map.borrow();
251 if !def_map.contains_key(&ref_id) {
252 self.sess.span_bug(span,
253 &format!("def_map has no key for {} in lookup_def_kind",
256 let def = def_map.get(&ref_id).unwrap().full_def();
259 def::DefForeignMod(_) => Some(recorder::ModRef),
260 def::DefStruct(_) => Some(recorder::TypeRef),
262 def::DefAssociatedTy(..) |
263 def::DefTrait(_) => Some(recorder::TypeRef),
264 def::DefStatic(_, _) |
266 def::DefAssociatedConst(..) |
268 def::DefVariant(_, _, _) |
269 def::DefUpvar(..) => Some(recorder::VarRef),
271 def::DefFn(..) => Some(recorder::FnRef),
275 def::DefTyParam(..) |
280 self.sess.span_bug(span,
281 &format!("lookup_def_kind for unexpected item: {:?}", def));
286 fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str) {
288 self.visit_pat(&arg.pat);
289 let mut collector = PathCollector::new();
290 collector.visit_pat(&arg.pat);
291 let span_utils = self.span.clone();
292 for &(id, ref p, _, _) in &collector.collected_paths {
293 let typ = self.tcx.node_types().get(&id).unwrap().to_string();
294 // get the span only for the name of the variable (I hope the path is only ever a
295 // variable name, but who knows?)
296 self.fmt.formal_str(p.span,
297 span_utils.span_for_last_ident(p.span),
306 fn process_method(&mut self,
307 sig: &ast::MethodSig,
308 body: Option<&ast::Block>,
312 if generated_code(span) {
316 debug!("process_method: {}:{}", id, name);
318 let method_data = self.save_ctxt.get_method_data(id, name, span);
321 self.fmt.method_str(span,
322 Some(method_data.span),
324 &method_data.qualname,
325 method_data.declaration,
327 self.process_formals(&sig.decl.inputs, &method_data.qualname);
329 self.fmt.method_decl_str(span,
330 Some(method_data.span),
332 &method_data.qualname,
336 // walk arg and return types
337 for arg in &sig.decl.inputs {
338 self.visit_ty(&arg.ty);
341 if let ast::Return(ref ret_ty) = sig.decl.output {
342 self.visit_ty(ret_ty);
346 if let Some(body) = body {
347 self.nest(id, |v| v.visit_block(body));
350 self.process_generic_params(&sig.generics, span, &method_data.qualname, id);
353 fn process_trait_ref(&mut self, trait_ref: &ast::TraitRef) {
354 let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref, self.cur_scope);
355 if let Some(trait_ref_data) = trait_ref_data {
356 self.fmt.ref_str(recorder::TypeRef,
358 Some(trait_ref_data.span),
359 trait_ref_data.ref_id,
360 trait_ref_data.scope);
361 visit::walk_path(self, &trait_ref.path);
365 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
366 let field_data = self.save_ctxt.get_field_data(field, parent_id);
367 if let Some(field_data) = field_data {
368 self.fmt.field_str(field.span,
369 Some(field_data.span),
372 &field_data.qualname,
373 &field_data.type_value,
378 // Dump generic params bindings, then visit_generics
379 fn process_generic_params(&mut self,
380 generics: &ast::Generics,
384 // We can't only use visit_generics since we don't have spans for param
385 // bindings, so we reparse the full_span to get those sub spans.
386 // However full span is the entire enum/fn/struct block, so we only want
387 // the first few to match the number of generics we're looking for.
388 let param_sub_spans = self.span.spans_for_ty_params(full_span,
389 (generics.ty_params.len() as isize));
390 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
391 // Append $id to name to make sure each one is unique
392 let name = format!("{}::{}${}",
394 escape(self.span.snippet(param_ss)),
396 self.fmt.typedef_str(full_span, Some(param_ss), param.id, &name, "");
398 self.visit_generics(generics);
401 fn process_fn(&mut self,
404 ty_params: &ast::Generics,
406 let fn_data = self.save_ctxt.get_item_data(item);
407 down_cast_data!(fn_data, FunctionData, self, item.span);
408 self.fmt.fn_str(item.span,
415 self.process_formals(&decl.inputs, &fn_data.qualname);
416 self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
418 for arg in &decl.inputs {
419 self.visit_ty(&arg.ty);
422 if let ast::Return(ref ret_ty) = decl.output {
423 self.visit_ty(&ret_ty);
426 self.nest(item.id, |v| v.visit_block(&body));
429 fn process_static_or_const_item(&mut self, item: &ast::Item, typ: &ast::Ty, expr: &ast::Expr) {
430 let var_data = self.save_ctxt.get_item_data(item);
431 down_cast_data!(var_data, VariableData, self, item.span);
432 self.fmt.static_str(item.span,
438 &var_data.type_value,
442 self.visit_expr(expr);
445 fn process_const(&mut self,
451 let qualname = format!("::{}", self.tcx.map.path_to_string(id));
453 let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
455 self.fmt.static_str(span,
460 &self.span.snippet(expr.span),
461 &ty_to_string(&*typ),
464 // walk type and init value
466 self.visit_expr(expr);
469 fn process_struct(&mut self,
471 def: &ast::VariantData,
472 ty_params: &ast::Generics) {
473 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
475 let val = self.span.snippet(item.span);
476 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
477 self.fmt.struct_str(item.span,
486 for field in def.fields() {
487 self.process_struct_field_def(field, item.id);
488 self.visit_ty(&field.node.ty);
491 self.process_generic_params(ty_params, item.span, &qualname, item.id);
494 fn process_enum(&mut self,
496 enum_definition: &ast::EnumDef,
497 ty_params: &ast::Generics) {
498 let enum_data = self.save_ctxt.get_item_data(item);
499 down_cast_data!(enum_data, EnumData, self, item.span);
500 self.fmt.enum_str(item.span,
501 Some(enum_data.span),
507 for variant in &enum_definition.variants {
508 let name = &variant.node.name.name.as_str();
509 let mut qualname = enum_data.qualname.clone();
510 qualname.push_str("::");
511 qualname.push_str(name);
512 let val = self.span.snippet(variant.span);
514 self.fmt.struct_variant_str(variant.span,
515 self.span.span_for_first_ident(variant.span),
516 variant.node.data.id(),
517 variant.node.data.id(),
523 for field in variant.node.data.fields() {
524 self.process_struct_field_def(field, variant.node.data.id());
525 self.visit_ty(&*field.node.ty);
528 self.process_generic_params(ty_params, item.span, &enum_data.qualname, enum_data.id);
531 fn process_impl(&mut self,
533 type_parameters: &ast::Generics,
534 trait_ref: &Option<ast::TraitRef>,
536 impl_items: &[P<ast::ImplItem>]) {
537 let impl_data = self.save_ctxt.get_item_data(item);
538 down_cast_data!(impl_data, ImplData, self, item.span);
539 match impl_data.self_ref {
540 Some(ref self_ref) => {
541 self.fmt.ref_str(recorder::TypeRef,
551 if let Some(ref trait_ref_data) = impl_data.trait_ref {
552 self.fmt.ref_str(recorder::TypeRef,
554 Some(trait_ref_data.span),
555 trait_ref_data.ref_id,
556 trait_ref_data.scope);
557 visit::walk_path(self, &trait_ref.as_ref().unwrap().path);
560 self.fmt.impl_str(item.span,
561 Some(impl_data.span),
563 impl_data.self_ref.map(|data| data.ref_id),
564 impl_data.trait_ref.map(|data| data.ref_id),
567 self.process_generic_params(type_parameters, item.span, "", item.id);
568 for impl_item in impl_items {
569 self.visit_impl_item(impl_item);
573 fn process_trait(&mut self,
575 generics: &ast::Generics,
576 trait_refs: &OwnedSlice<ast::TyParamBound>,
577 methods: &[P<ast::TraitItem>]) {
578 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
579 let val = self.span.snippet(item.span);
580 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
581 self.fmt.trait_str(item.span,
589 for super_bound in trait_refs.iter() {
590 let trait_ref = match *super_bound {
591 ast::TraitTyParamBound(ref trait_ref, _) => {
594 ast::RegionTyParamBound(..) => {
599 let trait_ref = &trait_ref.trait_ref;
600 match self.lookup_type_ref(trait_ref.ref_id) {
602 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
603 self.fmt.ref_str(recorder::TypeRef,
608 self.fmt.inherit_str(trait_ref.path.span, sub_span, id, item.id);
614 // walk generics and methods
615 self.process_generic_params(generics, item.span, &qualname, item.id);
616 for method in methods {
617 self.visit_trait_item(method)
621 // `item` is the module in question, represented as an item.
622 fn process_mod(&mut self, item: &ast::Item) {
623 let mod_data = self.save_ctxt.get_item_data(item);
624 down_cast_data!(mod_data, ModData, self, item.span);
625 self.fmt.mod_str(item.span,
633 fn process_path(&mut self, id: NodeId, path: &ast::Path, ref_kind: Option<recorder::Row>) {
634 if generated_code(path.span) {
638 let path_data = self.save_ctxt.get_path_data(id, path);
639 let path_data = match path_data {
642 self.tcx.sess.span_bug(path.span,
643 &format!("Unexpected def kind while looking up path in \
645 self.span.snippet(path.span)))
649 Data::VariableRefData(ref vrd) => {
650 self.fmt.ref_str(ref_kind.unwrap_or(recorder::VarRef),
657 Data::TypeRefData(ref trd) => {
658 self.fmt.ref_str(recorder::TypeRef,
664 Data::MethodCallData(ref mcd) => {
665 self.fmt.meth_call_str(path.span,
671 Data::FunctionCallData(fcd) => {
672 self.fmt.fn_call_str(path.span, Some(fcd.span), fcd.ref_id, fcd.scope);
675 self.sess.span_bug(path.span,
676 &format!("Unexpected data: {:?}", path_data));
680 // Modules or types in the path prefix.
681 let def_map = self.tcx.def_map.borrow();
682 let def = def_map.get(&id).unwrap().full_def();
684 def::DefMethod(did) => {
685 let ti = self.tcx.impl_or_trait_item(did);
686 if let ty::MethodTraitItem(m) = ti {
687 if m.explicit_self == ty::StaticExplicitSelfCategory {
688 self.write_sub_path_trait_truncated(path);
693 def::DefStatic(_,_) |
695 def::DefAssociatedConst(..) |
697 def::DefVariant(..) |
698 def::DefFn(..) => self.write_sub_paths_truncated(path, false),
703 fn process_struct_lit(&mut self,
706 fields: &Vec<ast::Field>,
707 variant: ty::VariantDef,
708 base: &Option<P<ast::Expr>>) {
709 if generated_code(path.span) {
713 self.write_sub_paths_truncated(path, false);
715 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
716 down_cast_data!(struct_lit_data, TypeRefData, self, ex.span);
717 self.fmt.ref_str(recorder::TypeRef,
719 Some(struct_lit_data.span),
720 struct_lit_data.ref_id,
721 struct_lit_data.scope);
722 let scope = self.save_ctxt.enclosing_scope(ex.id);
724 for field in fields {
725 if generated_code(field.ident.span) {
729 let field_data = self.save_ctxt.get_field_ref_data(field, variant, scope);
730 self.fmt.ref_str(recorder::VarRef,
732 Some(field_data.span),
736 self.visit_expr(&field.expr)
740 walk_list!(self, visit_expr, base);
743 fn process_method_call(&mut self, ex: &ast::Expr, args: &Vec<P<ast::Expr>>) {
744 if let Some(call_data) = self.save_ctxt.get_expr_data(ex) {
745 down_cast_data!(call_data, MethodCallData, self, ex.span);
746 self.fmt.meth_call_str(ex.span,
747 Some(call_data.span),
753 // walk receiver and args
754 walk_list!(self, visit_expr, args);
757 fn process_pat(&mut self, p: &ast::Pat) {
758 if generated_code(p.span) {
763 ast::PatStruct(ref path, ref fields, _) => {
764 visit::walk_path(self, path);
765 let adt = self.tcx.node_id_to_type(p.id).ty_adt_def().unwrap();
766 let def = self.tcx.def_map.borrow()[&p.id].full_def();
767 let variant = adt.variant_of_def(def);
769 for &Spanned { node: ref field, span } in fields {
770 if generated_code(span) {
774 let sub_span = self.span.span_for_first_ident(span);
775 if let Some(f) = variant.find_field_named(field.ident.name) {
776 self.fmt.ref_str(recorder::VarRef, span, sub_span, f.did, self.cur_scope);
778 self.visit_pat(&field.pat);
781 _ => visit::walk_pat(self, p),
786 fn process_var_decl(&mut self, p: &ast::Pat, value: String) {
787 // The local could declare multiple new vars, we must walk the
788 // pattern and collect them all.
789 let mut collector = PathCollector::new();
790 collector.visit_pat(&p);
793 for &(id, ref p, immut, _) in &collector.collected_paths {
794 let value = if immut == ast::MutImmutable {
797 "<mutable>".to_string()
799 let types = self.tcx.node_types();
800 let typ = types.get(&id).unwrap().to_string();
801 // Get the span only for the name of the variable (I hope the path
802 // is only ever a variable name, but who knows?).
803 let sub_span = self.span.span_for_last_ident(p.span);
804 // Rust uses the id of the pattern for var lookups, so we'll use it too.
805 self.fmt.variable_str(p.span,
815 impl<'l, 'tcx, 'v> Visitor<'v> for DumpCsvVisitor<'l, 'tcx> {
816 fn visit_item(&mut self, item: &ast::Item) {
817 if generated_code(item.span) {
822 ast::ItemUse(ref use_item) => {
823 match use_item.node {
824 ast::ViewPathSimple(ident, ref path) => {
825 let sub_span = self.span.span_for_last_ident(path.span);
826 let mod_id = match self.lookup_type_ref(item.id) {
828 match self.lookup_def_kind(item.id, path.span) {
829 Some(kind) => self.fmt.ref_str(kind,
841 // 'use' always introduces an alias, if there is not an explicit
842 // one, there is an implicit one.
843 let sub_span = match self.span.sub_span_after_keyword(use_item.span,
845 Some(sub_span) => Some(sub_span),
849 self.fmt.use_alias_str(path.span,
853 &ident.name.as_str(),
855 self.write_sub_paths_truncated(path, true);
857 ast::ViewPathGlob(ref path) => {
858 // Make a comma-separated list of names of imported modules.
859 let mut name_string = String::new();
860 let glob_map = &self.analysis.glob_map;
861 let glob_map = glob_map.as_ref().unwrap();
862 if glob_map.contains_key(&item.id) {
863 for n in glob_map.get(&item.id).unwrap() {
864 if !name_string.is_empty() {
865 name_string.push_str(", ");
867 name_string.push_str(&n.as_str());
871 let sub_span = self.span
872 .sub_span_of_token(path.span, token::BinOp(token::Star));
873 self.fmt.use_glob_str(path.span,
878 self.write_sub_paths(path, true);
880 ast::ViewPathList(ref path, ref list) => {
883 ast::PathListIdent { id, .. } => {
884 match self.lookup_type_ref(id) {
885 Some(def_id) => match self.lookup_def_kind(id, plid.span) {
887 self.fmt.ref_str(kind,
898 ast::PathListMod { .. } => (),
902 self.write_sub_paths(path, true);
906 ast::ItemExternCrate(ref s) => {
907 let location = match *s {
908 Some(s) => s.to_string(),
909 None => item.ident.to_string(),
911 let alias_span = self.span.span_for_last_ident(item.span);
912 let cnum = match self.sess.cstore.extern_mod_stmt_cnum(item.id) {
916 self.fmt.extern_crate_str(item.span,
920 &item.ident.name.as_str(),
924 ast::ItemFn(ref decl, _, _, _, ref ty_params, ref body) =>
925 self.process_fn(item, &**decl, ty_params, &**body),
926 ast::ItemStatic(ref typ, _, ref expr) =>
927 self.process_static_or_const_item(item, typ, expr),
928 ast::ItemConst(ref typ, ref expr) =>
929 self.process_static_or_const_item(item, &typ, &expr),
930 ast::ItemStruct(ref def, ref ty_params) => self.process_struct(item, def, ty_params),
931 ast::ItemEnum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
937 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
939 ast::ItemTrait(_, ref generics, ref trait_refs, ref methods) =>
940 self.process_trait(item, generics, trait_refs, methods),
941 ast::ItemMod(ref m) => {
942 self.process_mod(item);
943 self.nest(item.id, |v| visit::walk_mod(v, m));
945 ast::ItemTy(ref ty, ref ty_params) => {
946 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
947 let value = ty_to_string(&**ty);
948 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
949 self.fmt.typedef_str(item.span, sub_span, item.id, &qualname, &value);
951 self.visit_ty(&**ty);
952 self.process_generic_params(ty_params, item.span, &qualname, item.id);
954 ast::ItemMac(_) => (),
955 _ => visit::walk_item(self, item),
959 fn visit_generics(&mut self, generics: &ast::Generics) {
960 for param in generics.ty_params.iter() {
961 for bound in param.bounds.iter() {
962 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
963 self.process_trait_ref(&trait_ref.trait_ref);
966 if let Some(ref ty) = param.default {
967 self.visit_ty(&**ty);
972 fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
973 match trait_item.node {
974 ast::ConstTraitItem(ref ty, Some(ref expr)) => {
975 self.process_const(trait_item.id,
976 trait_item.ident.name,
981 ast::MethodTraitItem(ref sig, ref body) => {
982 self.process_method(sig,
983 body.as_ref().map(|x| &**x),
985 trait_item.ident.name,
988 ast::ConstTraitItem(_, None) |
989 ast::TypeTraitItem(..) => {}
993 fn visit_impl_item(&mut self, impl_item: &ast::ImplItem) {
994 match impl_item.node {
995 ast::ImplItemKind::Const(ref ty, ref expr) => {
996 self.process_const(impl_item.id,
997 impl_item.ident.name,
1002 ast::ImplItemKind::Method(ref sig, ref body) => {
1003 self.process_method(sig,
1006 impl_item.ident.name,
1009 ast::ImplItemKind::Type(_) |
1010 ast::ImplItemKind::Macro(_) => {}
1014 fn visit_ty(&mut self, t: &ast::Ty) {
1015 if generated_code(t.span) {
1020 ast::TyPath(_, ref path) => {
1021 match self.lookup_type_ref(t.id) {
1023 let sub_span = self.span.sub_span_for_type_name(t.span);
1024 self.fmt.ref_str(recorder::TypeRef, t.span, sub_span, id, self.cur_scope);
1029 self.write_sub_paths_truncated(path, false);
1031 visit::walk_path(self, path);
1033 _ => visit::walk_ty(self, t),
1037 fn visit_expr(&mut self, ex: &ast::Expr) {
1038 if generated_code(ex.span) {
1043 ast::ExprCall(ref _f, ref _args) => {
1044 // Don't need to do anything for function calls,
1045 // because just walking the callee path does what we want.
1046 visit::walk_expr(self, ex);
1048 ast::ExprPath(_, ref path) => {
1049 self.process_path(ex.id, path, None);
1050 visit::walk_expr(self, ex);
1052 ast::ExprStruct(ref path, ref fields, ref base) => {
1053 let hir_expr = lower_expr(self.save_ctxt.lcx, ex);
1054 let adt = self.tcx.expr_ty(&hir_expr).ty_adt_def().unwrap();
1055 let def = self.tcx.resolve_expr(&hir_expr);
1056 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1058 ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, args),
1059 ast::ExprField(ref sub_ex, _) => {
1060 if generated_code(sub_ex.span) {
1064 self.visit_expr(&sub_ex);
1066 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1067 down_cast_data!(field_data, VariableRefData, self, ex.span);
1068 self.fmt.ref_str(recorder::VarRef,
1070 Some(field_data.span),
1075 ast::ExprTupField(ref sub_ex, idx) => {
1076 if generated_code(sub_ex.span) {
1080 self.visit_expr(&**sub_ex);
1082 let hir_node = lower_expr(self.save_ctxt.lcx, sub_ex);
1083 let ty = &self.tcx.expr_ty_adjusted(&hir_node).sty;
1085 ty::TyStruct(def, _) => {
1086 let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1087 self.fmt.ref_str(recorder::VarRef,
1090 def.struct_variant().fields[idx.node].did,
1093 ty::TyTuple(_) => {}
1094 _ => self.sess.span_bug(ex.span,
1095 &format!("Expected struct or tuple type, found {:?}",
1099 ast::ExprClosure(_, ref decl, ref body) => {
1100 if generated_code(body.span) {
1104 let mut id = String::from("$");
1105 id.push_str(&ex.id.to_string());
1106 self.process_formals(&decl.inputs, &id);
1108 // walk arg and return types
1109 for arg in &decl.inputs {
1110 self.visit_ty(&*arg.ty);
1113 if let ast::Return(ref ret_ty) = decl.output {
1114 self.visit_ty(&**ret_ty);
1118 self.nest(ex.id, |v| v.visit_block(&**body));
1120 ast::ExprForLoop(ref pattern, ref subexpression, ref block, _) |
1121 ast::ExprWhileLet(ref pattern, ref subexpression, ref block, _) => {
1122 let value = self.span.snippet(mk_sp(ex.span.lo, subexpression.span.hi));
1123 self.process_var_decl(pattern, value);
1124 visit::walk_expr(self, subexpression);
1125 visit::walk_block(self, block);
1127 ast::ExprIfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
1128 let value = self.span.snippet(mk_sp(ex.span.lo, subexpression.span.hi));
1129 self.process_var_decl(pattern, value);
1130 visit::walk_expr(self, subexpression);
1131 visit::walk_block(self, block);
1132 opt_else.as_ref().map(|el| visit::walk_expr(self, el));
1135 visit::walk_expr(self, ex)
1140 fn visit_mac(&mut self, _: &ast::Mac) {
1141 // Just stop, macros are poison to us.
1144 fn visit_pat(&mut self, p: &ast::Pat) {
1145 self.process_pat(p);
1148 fn visit_arm(&mut self, arm: &ast::Arm) {
1149 let mut collector = PathCollector::new();
1150 for pattern in &arm.pats {
1151 // collect paths from the arm's patterns
1152 collector.visit_pat(&pattern);
1153 self.visit_pat(&pattern);
1156 // This is to get around borrow checking, because we need mut self to call process_path.
1157 let mut paths_to_process = vec![];
1159 // process collected paths
1160 for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1161 let def_map = self.tcx.def_map.borrow();
1162 if !def_map.contains_key(&id) {
1163 self.sess.span_bug(p.span,
1164 &format!("def_map has no key for {} in visit_arm", id));
1166 let def = def_map.get(&id).unwrap().full_def();
1168 def::DefLocal(_, id) => {
1169 let value = if immut == ast::MutImmutable {
1170 self.span.snippet(p.span).to_string()
1172 "<mutable>".to_string()
1175 assert!(p.segments.len() == 1,
1176 "qualified path for local variable def in arm");
1177 self.fmt.variable_str(p.span, Some(p.span), id, &path_to_string(p), &value, "")
1179 def::DefVariant(..) | def::DefTy(..) | def::DefStruct(..) => {
1180 paths_to_process.push((id, p.clone(), Some(ref_kind)))
1182 // FIXME(nrc) what are these doing here?
1183 def::DefStatic(_, _) |
1185 def::DefAssociatedConst(..) => {}
1186 _ => error!("unexpected definition kind when processing collected paths: {:?}",
1191 for &(id, ref path, ref_kind) in &paths_to_process {
1192 self.process_path(id, path, ref_kind);
1194 walk_list!(self, visit_expr, &arm.guard);
1195 self.visit_expr(&arm.body);
1198 fn visit_stmt(&mut self, s: &ast::Stmt) {
1199 if generated_code(s.span) {
1203 visit::walk_stmt(self, s)
1206 fn visit_local(&mut self, l: &ast::Local) {
1207 if generated_code(l.span) {
1211 let value = self.span.snippet(l.span);
1212 self.process_var_decl(&l.pat, value);
1214 // Just walk the initialiser and type (don't want to walk the pattern again).
1215 walk_list!(self, visit_ty, &l.ty);
1216 walk_list!(self, visit_expr, &l.init);