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::visit::{self, Visitor};
45 use syntax::print::pprust::{path_to_string, ty_to_string};
48 use rustc_front::lowering::{lower_expr, LoweringContext};
50 use super::span_utils::SpanUtils;
51 use super::recorder::{Recorder, FmtStrs};
53 macro_rules! down_cast_data {
54 ($id:ident, $kind:ident, $this:ident, $sp:expr) => {
55 let $id = if let super::Data::$kind(data) = $id {
58 $this.sess.span_bug($sp, &format!("unexpected data kind: {:?}", $id));
63 pub struct DumpCsvVisitor<'l, 'tcx: 'l> {
64 save_ctxt: SaveContext<'l, 'tcx>,
66 tcx: &'l ty::ctxt<'tcx>,
67 analysis: &'l ty::CrateAnalysis<'l>,
70 fmt: FmtStrs<'l, 'tcx>,
75 impl <'l, 'tcx> DumpCsvVisitor<'l, 'tcx> {
76 pub fn new(tcx: &'l ty::ctxt<'tcx>,
77 lcx: &'l LoweringContext<'l>,
78 analysis: &'l ty::CrateAnalysis<'l>,
79 output_file: Box<File>)
80 -> DumpCsvVisitor<'l, 'tcx> {
81 let span_utils = SpanUtils::new(&tcx.sess);
85 save_ctxt: SaveContext::from_span_utils(tcx, lcx, span_utils.clone()),
87 span: span_utils.clone(),
88 fmt: FmtStrs::new(box Recorder {
98 fn nest<F>(&mut self, scope_id: NodeId, f: F)
99 where F: FnOnce(&mut DumpCsvVisitor<'l, 'tcx>)
101 let parent_scope = self.cur_scope;
102 self.cur_scope = scope_id;
104 self.cur_scope = parent_scope;
107 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
108 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
109 let crate_root = match source_file {
110 Some(source_file) => match source_file.file_name() {
111 Some(_) => source_file.parent().unwrap().display().to_string(),
112 None => source_file.display().to_string(),
114 None => "<no source>".to_owned(),
117 // The current crate.
118 self.fmt.crate_str(krate.span, name, &crate_root);
120 // Dump info about all the external crates referenced from this crate.
121 for c in &self.save_ctxt.get_external_crates() {
122 self.fmt.external_crate_str(krate.span, &c.name, c.number);
124 self.fmt.recorder.record("end_external_crates\n");
127 // Return all non-empty prefixes of a path.
128 // For each prefix, we return the span for the last segment in the prefix and
129 // a str representation of the entire prefix.
130 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
131 let spans = self.span.spans_for_path_segments(path);
133 // Paths to enums seem to not match their spans - the span includes all the
134 // variants too. But they seem to always be at the end, so I hope we can cope with
135 // always using the first ones. So, only error out if we don't have enough spans.
136 // What could go wrong...?
137 if spans.len() < path.segments.len() {
138 if generated_code(path.span) {
141 error!("Mis-calculated spans for path '{}'. Found {} spans, expected {}. Found spans:",
142 path_to_string(path),
144 path.segments.len());
146 let loc = self.sess.codemap().lookup_char_pos(s.lo);
147 error!(" '{}' in {}, line {}",
148 self.span.snippet(*s),
155 let mut result: Vec<(Span, String)> = vec!();
157 let mut segs = vec!();
158 for (i, (seg, span)) in path.segments.iter().zip(&spans).enumerate() {
159 segs.push(seg.clone());
160 let sub_path = ast::Path {
161 span: *span, // span for the last segment
165 let qualname = if i == 0 && path.global {
166 format!("::{}", path_to_string(&sub_path))
168 path_to_string(&sub_path)
170 result.push((*span, qualname));
171 segs = sub_path.segments;
177 // The global arg allows us to override the global-ness of the path (which
178 // actually means 'does the path start with `::`', rather than 'is the path
179 // semantically global). We use the override for `use` imports (etc.) where
180 // the syntax is non-global, but the semantics are global.
181 fn write_sub_paths(&mut self, path: &ast::Path, global: bool) {
182 let sub_paths = self.process_path_prefixes(path);
183 for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
184 let qualname = if i == 0 && global && !path.global {
185 format!("::{}", qualname)
189 self.fmt.sub_mod_ref_str(path.span, *span, &qualname, self.cur_scope);
193 // As write_sub_paths, but does not process the last ident in the path (assuming it
194 // will be processed elsewhere). See note on write_sub_paths about global.
195 fn write_sub_paths_truncated(&mut self, path: &ast::Path, global: bool) {
196 let sub_paths = self.process_path_prefixes(path);
197 let len = sub_paths.len();
202 let sub_paths = &sub_paths[..len-1];
203 for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
204 let qualname = if i == 0 && global && !path.global {
205 format!("::{}", qualname)
209 self.fmt.sub_mod_ref_str(path.span, *span, &qualname, self.cur_scope);
213 // As write_sub_paths, but expects a path of the form module_path::trait::method
214 // Where trait could actually be a struct too.
215 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
216 let sub_paths = self.process_path_prefixes(path);
217 let len = sub_paths.len();
221 let sub_paths = &sub_paths[.. (len-1)];
223 // write the trait part of the sub-path
224 let (ref span, ref qualname) = sub_paths[len-2];
225 self.fmt.sub_type_ref_str(path.span, *span, &qualname);
227 // write the other sub-paths
231 let sub_paths = &sub_paths[..len-2];
232 for &(ref span, ref qualname) in sub_paths {
233 self.fmt.sub_mod_ref_str(path.span, *span, &qualname, self.cur_scope);
237 // looks up anything, not just a type
238 fn lookup_type_ref(&self, ref_id: NodeId) -> Option<DefId> {
239 if !self.tcx.def_map.borrow().contains_key(&ref_id) {
240 self.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
243 let def = self.tcx.def_map.borrow().get(&ref_id).unwrap().full_def();
245 Def::PrimTy(..) => None,
246 Def::SelfTy(..) => None,
247 _ => Some(def.def_id()),
251 fn lookup_def_kind(&self, ref_id: NodeId, span: Span) -> Option<recorder::Row> {
252 let def_map = self.tcx.def_map.borrow();
253 if !def_map.contains_key(&ref_id) {
254 self.sess.span_bug(span,
255 &format!("def_map has no key for {} in lookup_def_kind",
258 let def = def_map.get(&ref_id).unwrap().full_def();
261 Def::ForeignMod(_) => Some(recorder::ModRef),
262 Def::Struct(..) => Some(recorder::TypeRef),
265 Def::AssociatedTy(..) |
266 Def::Trait(_) => Some(recorder::TypeRef),
269 Def::AssociatedConst(..) |
272 Def::Upvar(..) => Some(recorder::VarRef),
274 Def::Fn(..) => Some(recorder::FnRef),
282 self.sess.span_bug(span,
283 &format!("lookup_def_kind for unexpected item: {:?}", def));
288 fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str) {
290 self.visit_pat(&arg.pat);
291 let mut collector = PathCollector::new();
292 collector.visit_pat(&arg.pat);
293 let span_utils = self.span.clone();
294 for &(id, ref p, _, _) in &collector.collected_paths {
295 let typ = self.tcx.node_types().get(&id).unwrap().to_string();
296 // get the span only for the name of the variable (I hope the path is only ever a
297 // variable name, but who knows?)
298 self.fmt.formal_str(p.span,
299 span_utils.span_for_last_ident(p.span),
308 fn process_method(&mut self,
309 sig: &ast::MethodSig,
310 body: Option<&ast::Block>,
314 debug!("process_method: {}:{}", id, name);
316 if let Some(method_data) = self.save_ctxt.get_method_data(id, name, span) {
319 self.fmt.method_str(span,
320 Some(method_data.span),
322 &method_data.qualname,
323 method_data.declaration,
325 self.process_formals(&sig.decl.inputs, &method_data.qualname);
327 self.fmt.method_decl_str(span,
328 Some(method_data.span),
330 &method_data.qualname,
333 self.process_generic_params(&sig.generics, span, &method_data.qualname, id);
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));
351 fn process_trait_ref(&mut self, trait_ref: &ast::TraitRef) {
352 let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref, self.cur_scope);
353 if let Some(trait_ref_data) = trait_ref_data {
354 self.fmt.ref_str(recorder::TypeRef,
356 Some(trait_ref_data.span),
357 trait_ref_data.ref_id,
358 trait_ref_data.scope);
359 visit::walk_path(self, &trait_ref.path);
363 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
364 let field_data = self.save_ctxt.get_field_data(field, parent_id);
365 if let Some(field_data) = field_data {
366 self.fmt.field_str(field.span,
367 Some(field_data.span),
370 &field_data.qualname,
371 &field_data.type_value,
376 // Dump generic params bindings, then visit_generics
377 fn process_generic_params(&mut self,
378 generics: &ast::Generics,
382 // We can't only use visit_generics since we don't have spans for param
383 // bindings, so we reparse the full_span to get those sub spans.
384 // However full span is the entire enum/fn/struct block, so we only want
385 // the first few to match the number of generics we're looking for.
386 let param_sub_spans = self.span.spans_for_ty_params(full_span,
387 (generics.ty_params.len() as isize));
388 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
389 // Append $id to name to make sure each one is unique
390 let name = format!("{}::{}${}",
392 escape(self.span.snippet(param_ss)),
394 self.fmt.typedef_str(full_span, Some(param_ss), param.id, &name, "");
396 self.visit_generics(generics);
399 fn process_fn(&mut self,
402 ty_params: &ast::Generics,
404 if let Some(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,
412 self.process_formals(&decl.inputs, &fn_data.qualname);
413 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, item: &ast::Item, typ: &ast::Ty, expr: &ast::Expr) {
428 if let Some(var_data) = self.save_ctxt.get_item_data(item) {
429 down_cast_data!(var_data, VariableData, self, item.span);
430 self.fmt.static_str(item.span,
436 &var_data.type_value,
440 self.visit_expr(expr);
443 fn process_const(&mut self,
449 let qualname = format!("::{}", self.tcx.map.path_to_string(id));
451 let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
453 self.fmt.static_str(span,
458 &self.span.snippet(expr.span),
459 &ty_to_string(&*typ),
462 // walk type and init value
464 self.visit_expr(expr);
467 fn process_struct(&mut self,
469 def: &ast::VariantData,
470 ty_params: &ast::Generics) {
471 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
473 let val = self.span.snippet(item.span);
474 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
475 self.fmt.struct_str(item.span,
484 for field in def.fields() {
485 self.process_struct_field_def(field, item.id);
486 self.visit_ty(&field.node.ty);
489 self.process_generic_params(ty_params, item.span, &qualname, item.id);
492 fn process_enum(&mut self,
494 enum_definition: &ast::EnumDef,
495 ty_params: &ast::Generics) {
496 let enum_data = self.save_ctxt.get_item_data(item);
497 let enum_data = match enum_data {
501 down_cast_data!(enum_data, EnumData, self, item.span);
502 self.fmt.enum_str(item.span,
503 Some(enum_data.span),
509 for variant in &enum_definition.variants {
510 let name = &variant.node.name.name.as_str();
511 let mut qualname = enum_data.qualname.clone();
512 qualname.push_str("::");
513 qualname.push_str(name);
514 let val = self.span.snippet(variant.span);
516 match variant.node.data {
517 ast::VariantData::Struct(..) => {
518 self.fmt.struct_variant_str(variant.span,
519 self.span.span_for_first_ident(variant.span),
520 variant.node.data.id(),
527 self.fmt.tuple_variant_str(variant.span,
528 self.span.span_for_first_ident(variant.span),
529 variant.node.data.id(),
539 for field in variant.node.data.fields() {
540 self.process_struct_field_def(field, variant.node.data.id());
541 self.visit_ty(&*field.node.ty);
544 self.process_generic_params(ty_params, item.span, &enum_data.qualname, enum_data.id);
547 fn process_impl(&mut self,
549 type_parameters: &ast::Generics,
550 trait_ref: &Option<ast::TraitRef>,
552 impl_items: &[P<ast::ImplItem>]) {
553 let mut has_self_ref = false;
554 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
555 down_cast_data!(impl_data, ImplData, self, item.span);
556 if let Some(ref self_ref) = impl_data.self_ref {
558 self.fmt.ref_str(recorder::TypeRef,
564 if let Some(ref trait_ref_data) = impl_data.trait_ref {
565 self.fmt.ref_str(recorder::TypeRef,
567 Some(trait_ref_data.span),
568 trait_ref_data.ref_id,
569 trait_ref_data.scope);
570 visit::walk_path(self, &trait_ref.as_ref().unwrap().path);
573 self.fmt.impl_str(item.span,
574 Some(impl_data.span),
576 impl_data.self_ref.map(|data| data.ref_id),
577 impl_data.trait_ref.map(|data| data.ref_id),
583 self.process_generic_params(type_parameters, item.span, "", item.id);
584 for impl_item in impl_items {
585 self.visit_impl_item(impl_item);
589 fn process_trait(&mut self,
591 generics: &ast::Generics,
592 trait_refs: &ast::TyParamBounds,
593 methods: &[P<ast::TraitItem>]) {
594 let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
595 let val = self.span.snippet(item.span);
596 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
597 self.fmt.trait_str(item.span,
605 for super_bound in trait_refs.iter() {
606 let trait_ref = match *super_bound {
607 ast::TraitTyParamBound(ref trait_ref, _) => {
610 ast::RegionTyParamBound(..) => {
615 let trait_ref = &trait_ref.trait_ref;
616 match self.lookup_type_ref(trait_ref.ref_id) {
618 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
619 self.fmt.ref_str(recorder::TypeRef,
624 self.fmt.inherit_str(trait_ref.path.span, sub_span, id, item.id);
630 // walk generics and methods
631 self.process_generic_params(generics, item.span, &qualname, item.id);
632 for method in methods {
633 self.visit_trait_item(method)
637 // `item` is the module in question, represented as an item.
638 fn process_mod(&mut self, item: &ast::Item) {
639 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
640 down_cast_data!(mod_data, ModData, self, item.span);
641 self.fmt.mod_str(item.span,
650 fn process_path(&mut self, id: NodeId, path: &ast::Path, ref_kind: Option<recorder::Row>) {
651 let path_data = self.save_ctxt.get_path_data(id, path);
652 if generated_code(path.span) && path_data.is_none() {
656 let path_data = match path_data {
659 self.tcx.sess.span_bug(path.span,
660 &format!("Unexpected def kind while looking up path in \
662 self.span.snippet(path.span)))
666 Data::VariableRefData(ref vrd) => {
667 self.fmt.ref_str(ref_kind.unwrap_or(recorder::VarRef),
674 Data::TypeRefData(ref trd) => {
675 self.fmt.ref_str(recorder::TypeRef,
681 Data::MethodCallData(ref mcd) => {
682 self.fmt.meth_call_str(path.span,
688 Data::FunctionCallData(fcd) => {
689 self.fmt.fn_call_str(path.span, Some(fcd.span), fcd.ref_id, fcd.scope);
692 self.sess.span_bug(path.span,
693 &format!("Unexpected data: {:?}", path_data));
697 // Modules or types in the path prefix.
698 let def_map = self.tcx.def_map.borrow();
699 let def = def_map.get(&id).unwrap().full_def();
701 Def::Method(did) => {
702 let ti = self.tcx.impl_or_trait_item(did);
703 if let ty::MethodTraitItem(m) = ti {
704 if m.explicit_self == ty::ExplicitSelfCategory::Static {
705 self.write_sub_path_trait_truncated(path);
712 Def::AssociatedConst(..) |
715 Def::Fn(..) => self.write_sub_paths_truncated(path, false),
720 fn process_struct_lit(&mut self,
723 fields: &Vec<ast::Field>,
724 variant: ty::VariantDef,
725 base: &Option<P<ast::Expr>>) {
726 self.write_sub_paths_truncated(path, false);
728 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
729 down_cast_data!(struct_lit_data, TypeRefData, self, ex.span);
730 self.fmt.ref_str(recorder::TypeRef,
732 Some(struct_lit_data.span),
733 struct_lit_data.ref_id,
734 struct_lit_data.scope);
735 let scope = self.save_ctxt.enclosing_scope(ex.id);
737 for field in fields {
738 if let Some(field_data) = self.save_ctxt
739 .get_field_ref_data(field, variant, scope) {
741 self.fmt.ref_str(recorder::VarRef,
743 Some(field_data.span),
748 self.visit_expr(&field.expr)
752 walk_list!(self, visit_expr, base);
755 fn process_method_call(&mut self, ex: &ast::Expr, args: &Vec<P<ast::Expr>>) {
756 if let Some(call_data) = self.save_ctxt.get_expr_data(ex) {
757 down_cast_data!(call_data, MethodCallData, self, ex.span);
758 self.fmt.meth_call_str(ex.span,
759 Some(call_data.span),
765 // walk receiver and args
766 walk_list!(self, visit_expr, args);
769 fn process_pat(&mut self, p: &ast::Pat) {
771 ast::PatStruct(ref path, ref fields, _) => {
772 visit::walk_path(self, path);
773 let adt = self.tcx.node_id_to_type(p.id).ty_adt_def().unwrap();
774 let def = self.tcx.def_map.borrow()[&p.id].full_def();
775 let variant = adt.variant_of_def(def);
777 for &Spanned { node: ref field, span } in fields {
778 let sub_span = self.span.span_for_first_ident(span);
779 if let Some(f) = variant.find_field_named(field.ident.name) {
780 self.fmt.ref_str(recorder::VarRef, span, sub_span, f.did, self.cur_scope);
782 self.visit_pat(&field.pat);
785 _ => visit::walk_pat(self, p),
790 fn process_var_decl(&mut self, p: &ast::Pat, value: String) {
791 // The local could declare multiple new vars, we must walk the
792 // pattern and collect them all.
793 let mut collector = PathCollector::new();
794 collector.visit_pat(&p);
797 for &(id, ref p, immut, _) in &collector.collected_paths {
798 let value = if immut == ast::MutImmutable {
801 "<mutable>".to_string()
803 let types = self.tcx.node_types();
804 let typ = types.get(&id).unwrap().to_string();
805 // Get the span only for the name of the variable (I hope the path
806 // is only ever a variable name, but who knows?).
807 let sub_span = self.span.span_for_last_ident(p.span);
808 // Rust uses the id of the pattern for var lookups, so we'll use it too.
809 self.fmt.variable_str(p.span,
819 impl<'l, 'tcx, 'v> Visitor<'v> for DumpCsvVisitor<'l, 'tcx> {
820 fn visit_item(&mut self, item: &ast::Item) {
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) {
1016 ast::TyPath(_, ref path) => {
1017 match self.lookup_type_ref(t.id) {
1019 let sub_span = self.span.sub_span_for_type_name(t.span);
1020 self.fmt.ref_str(recorder::TypeRef, t.span, sub_span, id, self.cur_scope);
1025 self.write_sub_paths_truncated(path, false);
1027 visit::walk_path(self, path);
1029 _ => visit::walk_ty(self, t),
1033 fn visit_expr(&mut self, ex: &ast::Expr) {
1035 ast::ExprCall(ref _f, ref _args) => {
1036 // Don't need to do anything for function calls,
1037 // because just walking the callee path does what we want.
1038 visit::walk_expr(self, ex);
1040 ast::ExprPath(_, ref path) => {
1041 self.process_path(ex.id, path, None);
1042 visit::walk_expr(self, ex);
1044 ast::ExprStruct(ref path, ref fields, ref base) => {
1045 let hir_expr = lower_expr(self.save_ctxt.lcx, ex);
1046 let adt = self.tcx.expr_ty(&hir_expr).ty_adt_def().unwrap();
1047 let def = self.tcx.resolve_expr(&hir_expr);
1048 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1050 ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, args),
1051 ast::ExprField(ref sub_ex, _) => {
1052 self.visit_expr(&sub_ex);
1054 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1055 down_cast_data!(field_data, VariableRefData, self, ex.span);
1056 self.fmt.ref_str(recorder::VarRef,
1058 Some(field_data.span),
1063 ast::ExprTupField(ref sub_ex, idx) => {
1064 self.visit_expr(&**sub_ex);
1066 let hir_node = lower_expr(self.save_ctxt.lcx, sub_ex);
1067 let ty = &self.tcx.expr_ty_adjusted(&hir_node).sty;
1069 ty::TyStruct(def, _) => {
1070 let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1071 self.fmt.ref_str(recorder::VarRef,
1074 def.struct_variant().fields[idx.node].did,
1077 ty::TyTuple(_) => {}
1078 _ => self.sess.span_bug(ex.span,
1079 &format!("Expected struct or tuple type, found {:?}",
1083 ast::ExprClosure(_, ref decl, ref body) => {
1084 let mut id = String::from("$");
1085 id.push_str(&ex.id.to_string());
1086 self.process_formals(&decl.inputs, &id);
1088 // walk arg and return types
1089 for arg in &decl.inputs {
1090 self.visit_ty(&*arg.ty);
1093 if let ast::Return(ref ret_ty) = decl.output {
1094 self.visit_ty(&**ret_ty);
1098 self.nest(ex.id, |v| v.visit_block(&**body));
1100 ast::ExprForLoop(ref pattern, ref subexpression, ref block, _) |
1101 ast::ExprWhileLet(ref pattern, ref subexpression, ref block, _) => {
1102 let value = self.span.snippet(mk_sp(ex.span.lo, subexpression.span.hi));
1103 self.process_var_decl(pattern, value);
1104 visit::walk_expr(self, subexpression);
1105 visit::walk_block(self, block);
1107 ast::ExprIfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
1108 let value = self.span.snippet(mk_sp(ex.span.lo, subexpression.span.hi));
1109 self.process_var_decl(pattern, value);
1110 visit::walk_expr(self, subexpression);
1111 visit::walk_block(self, block);
1112 opt_else.as_ref().map(|el| visit::walk_expr(self, el));
1115 visit::walk_expr(self, ex)
1120 fn visit_mac(&mut self, _: &ast::Mac) {
1121 // Just stop, macros are poison to us.
1124 fn visit_pat(&mut self, p: &ast::Pat) {
1125 self.process_pat(p);
1128 fn visit_arm(&mut self, arm: &ast::Arm) {
1129 let mut collector = PathCollector::new();
1130 for pattern in &arm.pats {
1131 // collect paths from the arm's patterns
1132 collector.visit_pat(&pattern);
1133 self.visit_pat(&pattern);
1136 // This is to get around borrow checking, because we need mut self to call process_path.
1137 let mut paths_to_process = vec![];
1139 // process collected paths
1140 for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1141 let def_map = self.tcx.def_map.borrow();
1142 if !def_map.contains_key(&id) {
1143 self.sess.span_bug(p.span,
1144 &format!("def_map has no key for {} in visit_arm", id));
1146 let def = def_map.get(&id).unwrap().full_def();
1148 Def::Local(_, id) => {
1149 let value = if immut == ast::MutImmutable {
1150 self.span.snippet(p.span).to_string()
1152 "<mutable>".to_string()
1155 assert!(p.segments.len() == 1,
1156 "qualified path for local variable def in arm");
1157 self.fmt.variable_str(p.span, Some(p.span), id, &path_to_string(p), &value, "")
1159 Def::Variant(..) | Def::Enum(..) |
1160 Def::TyAlias(..) | Def::Struct(..) => {
1161 paths_to_process.push((id, p.clone(), Some(ref_kind)))
1163 // FIXME(nrc) what are these doing here?
1166 Def::AssociatedConst(..) => {}
1167 _ => error!("unexpected definition kind when processing collected paths: {:?}",
1172 for &(id, ref path, ref_kind) in &paths_to_process {
1173 self.process_path(id, path, ref_kind);
1175 walk_list!(self, visit_expr, &arm.guard);
1176 self.visit_expr(&arm.body);
1179 fn visit_stmt(&mut self, s: &ast::Stmt) {
1180 visit::walk_stmt(self, s)
1183 fn visit_local(&mut self, l: &ast::Local) {
1184 let value = self.span.snippet(l.span);
1185 self.process_var_decl(&l.pat, value);
1187 // Just walk the initialiser and type (don't want to walk the pattern again).
1188 walk_list!(self, visit_ty, &l.ty);
1189 walk_list!(self, visit_expr, &l.init);