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 //! Write the output of rustc's analysis to an implementor of Dump. 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 //! DumpVisitor walks the AST and processes it, and an implementor of Dump
27 //! is used for recording the output in a format-agnostic way (see CsvDumper
31 use rustc::hir::def::Def;
32 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
33 use rustc::hir::map::{Node, NodeItem};
34 use rustc::session::Session;
35 use rustc::ty::{self, TyCtxt, AssociatedItemContainer};
37 use std::collections::HashSet;
38 use std::collections::hash_map::DefaultHasher;
41 use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID};
42 use syntax::parse::token;
43 use syntax::symbol::keywords;
44 use syntax::visit::{self, Visitor};
45 use syntax::print::pprust::{path_to_string, ty_to_string, bounds_to_string, generics_to_string};
47 use syntax::codemap::Spanned;
50 use super::{escape, generated_code, SaveContext, PathCollector, docs_for_attrs};
52 use super::dump::Dump;
53 use super::external_data::{Lower, make_def_id};
54 use super::span_utils::SpanUtils;
57 macro_rules! down_cast_data {
58 ($id:ident, $kind:ident, $sp:expr) => {
59 let $id = if let super::Data::$kind(data) = $id {
62 span_bug!($sp, "unexpected data kind: {:?}", $id);
67 pub struct DumpVisitor<'l, 'tcx: 'l, 'll, D: 'll> {
68 save_ctxt: SaveContext<'l, 'tcx>,
70 tcx: TyCtxt<'l, 'tcx, 'tcx>,
77 // Set of macro definition (callee) spans, and the set
78 // of macro use (callsite) spans. We store these to ensure
79 // we only write one macro def per unique macro definition, and
80 // one macro use per unique callsite span.
81 mac_defs: HashSet<Span>,
82 mac_uses: HashSet<Span>,
85 impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> {
86 pub fn new(save_ctxt: SaveContext<'l, 'tcx>,
88 -> DumpVisitor<'l, 'tcx, 'll, D> {
89 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
91 sess: &save_ctxt.tcx.sess,
95 span: span_utils.clone(),
96 cur_scope: CRATE_NODE_ID,
97 mac_defs: HashSet::new(),
98 mac_uses: HashSet::new(),
102 fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
103 where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, D>)
105 let parent_scope = self.cur_scope;
106 self.cur_scope = scope_id;
108 self.cur_scope = parent_scope;
111 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
112 where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, D>)
114 let item_def_id = self.tcx.hir.local_def_id(item_id);
115 match self.tcx.tables.borrow().get(&item_def_id) {
117 let old_tables = self.save_ctxt.tables;
118 self.save_ctxt.tables = tables;
120 self.save_ctxt.tables = old_tables;
126 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
127 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
128 let crate_root = source_file.map(|source_file| {
129 match source_file.file_name() {
130 Some(_) => source_file.parent().unwrap().display().to_string(),
131 None => source_file.display().to_string(),
135 // Info about all the external crates referenced from this crate.
136 let external_crates = self.save_ctxt.get_external_crates().into_iter().map(|c| {
137 let lo_loc = self.span.sess.codemap().lookup_char_pos(c.span.lo);
140 num: CrateNum::from_u32(c.number),
141 file_name: SpanUtils::make_path_string(&lo_loc.file.name),
145 // The current crate.
146 let data = CratePreludeData {
147 crate_name: name.into(),
148 crate_root: crate_root.unwrap_or("<no source>".to_owned()),
149 external_crates: external_crates,
153 self.dumper.crate_prelude(data.lower(self.tcx));
156 // Return all non-empty prefixes of a path.
157 // For each prefix, we return the span for the last segment in the prefix and
158 // a str representation of the entire prefix.
159 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
160 let spans = self.span.spans_for_path_segments(path);
161 let segments = &path.segments[if path.is_global() { 1 } else { 0 }..];
163 // Paths to enums seem to not match their spans - the span includes all the
164 // variants too. But they seem to always be at the end, so I hope we can cope with
165 // always using the first ones. So, only error out if we don't have enough spans.
166 // What could go wrong...?
167 if spans.len() < segments.len() {
168 if generated_code(path.span) {
171 error!("Mis-calculated spans for path '{}'. Found {} spans, expected {}. Found spans:",
172 path_to_string(path),
176 let loc = self.sess.codemap().lookup_char_pos(s.lo);
177 error!(" '{}' in {}, line {}",
178 self.span.snippet(*s),
182 error!(" master span: {:?}: `{}`", path.span, self.span.snippet(path.span));
186 let mut result: Vec<(Span, String)> = vec![];
188 let mut segs = vec![];
189 for (i, (seg, span)) in segments.iter().zip(&spans).enumerate() {
190 segs.push(seg.clone());
191 let sub_path = ast::Path {
192 span: *span, // span for the last segment
195 let qualname = if i == 0 && path.is_global() {
196 format!("::{}", path_to_string(&sub_path))
198 path_to_string(&sub_path)
200 result.push((*span, qualname));
201 segs = sub_path.segments;
207 fn write_sub_paths(&mut self, path: &ast::Path) {
208 let sub_paths = self.process_path_prefixes(path);
209 for (span, qualname) in sub_paths {
210 self.dumper.mod_ref(ModRefData {
213 scope: self.cur_scope,
219 // As write_sub_paths, but does not process the last ident in the path (assuming it
220 // will be processed elsewhere). See note on write_sub_paths about global.
221 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
222 let sub_paths = self.process_path_prefixes(path);
223 let len = sub_paths.len();
228 for (span, qualname) in sub_paths.into_iter().take(len - 1) {
229 self.dumper.mod_ref(ModRefData {
232 scope: self.cur_scope,
238 // As write_sub_paths, but expects a path of the form module_path::trait::method
239 // Where trait could actually be a struct too.
240 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
241 let sub_paths = self.process_path_prefixes(path);
242 let len = sub_paths.len();
246 let sub_paths = &sub_paths[.. (len-1)];
248 // write the trait part of the sub-path
249 let (ref span, ref qualname) = sub_paths[len-2];
250 self.dumper.type_ref(TypeRefData {
253 qualname: qualname.to_owned(),
257 // write the other sub-paths
261 let sub_paths = &sub_paths[..len-2];
262 for &(ref span, ref qualname) in sub_paths {
263 self.dumper.mod_ref(ModRefData {
265 qualname: qualname.to_owned(),
266 scope: self.cur_scope,
272 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
273 match self.save_ctxt.get_path_def(ref_id) {
274 Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => None,
275 def => Some(def.def_id()),
279 fn process_def_kind(&mut self,
282 sub_span: Option<Span>,
285 if self.span.filter_generated(sub_span, span) {
289 let def = self.save_ctxt.get_path_def(ref_id);
292 self.dumper.mod_ref(ModRefData {
293 span: sub_span.expect("No span found for mod ref"),
294 ref_id: Some(def_id),
296 qualname: String::new()
305 self.dumper.type_ref(TypeRefData {
306 span: sub_span.expect("No span found for type ref"),
307 ref_id: Some(def_id),
309 qualname: String::new()
314 Def::StructCtor(..) |
315 Def::VariantCtor(..) => {
316 self.dumper.variable_ref(VariableRefData {
317 span: sub_span.expect("No span found for var ref"),
324 self.dumper.function_ref(FunctionRefData {
325 span: sub_span.expect("No span found for fn ref"),
336 Def::AssociatedTy(..) |
337 Def::AssociatedConst(..) |
342 "process_def_kind for unexpected item: {:?}",
348 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
350 self.visit_pat(&arg.pat);
351 let mut collector = PathCollector::new();
352 collector.visit_pat(&arg.pat);
353 let span_utils = self.span.clone();
354 for &(id, ref p, ..) in &collector.collected_paths {
355 let typ = match self.save_ctxt.tables.node_types.get(&id) {
356 Some(s) => s.to_string(),
359 // get the span only for the name of the variable (I hope the path is only ever a
360 // variable name, but who knows?)
361 let sub_span = span_utils.span_for_last_ident(p.span);
362 if !self.span.filter_generated(sub_span, p.span) {
363 self.dumper.variable(VariableData {
365 kind: VariableKind::Local,
366 span: sub_span.expect("No span found for variable"),
367 name: path_to_string(p),
368 qualname: format!("{}::{}", qualname, path_to_string(p)),
370 value: String::new(),
371 scope: CRATE_NODE_ID,
373 visibility: Visibility::Inherited,
382 fn process_method(&mut self,
383 sig: &'l ast::MethodSig,
384 body: Option<&'l ast::Block>,
388 attrs: &'l [Attribute],
390 debug!("process_method: {}:{}", id, name);
392 if let Some(method_data) = self.save_ctxt.get_method_data(id, name, span) {
394 let sig_str = ::make_signature(&sig.decl, &sig.generics);
396 self.nest_tables(id, |v| {
397 v.process_formals(&sig.decl.inputs, &method_data.qualname)
401 // If the method is defined in an impl, then try and find the corresponding
402 // method decl in a trait, and if there is one, make a decl_id for it. This
403 // requires looking up the impl, then the trait, then searching for a method
404 // with the right name.
405 if !self.span.filter_generated(Some(method_data.span), span) {
407 self.tcx.associated_item(self.tcx.hir.local_def_id(id)).container;
409 let mut decl_id = None;
411 AssociatedItemContainer::ImplContainer(id) => {
412 trait_id = self.tcx.trait_id_of_impl(id);
416 for item in self.tcx.associated_items(id) {
417 if item.kind == ty::AssociatedKind::Method {
418 if item.name == name {
419 decl_id = Some(item.def_id);
426 if let Some(NodeItem(item)) = self.tcx.hir.get_if_local(id) {
427 if let hir::ItemImpl(_, _, _, _, ref ty, _) = item.node {
428 trait_id = self.lookup_def_id(ty.id);
434 AssociatedItemContainer::TraitContainer(id) => {
439 self.dumper.method(MethodData {
441 name: method_data.name,
442 span: method_data.span,
443 scope: method_data.scope,
444 qualname: method_data.qualname.clone(),
449 docs: docs_for_attrs(attrs),
450 sig: method_data.sig,
454 self.process_generic_params(&sig.generics, span, &method_data.qualname, id);
457 // walk arg and return types
458 for arg in &sig.decl.inputs {
459 self.visit_ty(&arg.ty);
462 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
463 self.visit_ty(ret_ty);
467 if let Some(body) = body {
468 self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
472 fn process_trait_ref(&mut self, trait_ref: &'l ast::TraitRef) {
473 let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref, self.cur_scope);
474 if let Some(trait_ref_data) = trait_ref_data {
475 if !self.span.filter_generated(Some(trait_ref_data.span), trait_ref.path.span) {
476 self.dumper.type_ref(trait_ref_data.lower(self.tcx));
479 self.process_path(trait_ref.ref_id, &trait_ref.path, Some(recorder::TypeRef));
482 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
483 let field_data = self.save_ctxt.get_field_data(field, parent_id);
484 if let Some(mut field_data) = field_data {
485 if !self.span.filter_generated(Some(field_data.span), field.span) {
486 field_data.value = String::new();
487 self.dumper.variable(field_data.lower(self.tcx));
492 // Dump generic params bindings, then visit_generics
493 fn process_generic_params(&mut self,
494 generics: &'l ast::Generics,
498 // We can't only use visit_generics since we don't have spans for param
499 // bindings, so we reparse the full_span to get those sub spans.
500 // However full span is the entire enum/fn/struct block, so we only want
501 // the first few to match the number of generics we're looking for.
502 let param_sub_spans = self.span.spans_for_ty_params(full_span,
503 (generics.ty_params.len() as isize));
504 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
505 let name = escape(self.span.snippet(param_ss));
506 // Append $id to name to make sure each one is unique
507 let qualname = format!("{}::{}${}",
511 if !self.span.filter_generated(Some(param_ss), full_span) {
512 self.dumper.typedef(TypeDefData {
517 value: String::new(),
518 visibility: Visibility::Inherited,
525 self.visit_generics(generics);
528 fn process_fn(&mut self,
530 decl: &'l ast::FnDecl,
531 ty_params: &'l ast::Generics,
532 body: &'l ast::Block) {
533 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
534 down_cast_data!(fn_data, FunctionData, item.span);
535 if !self.span.filter_generated(Some(fn_data.span), item.span) {
536 self.dumper.function(fn_data.clone().lower(self.tcx));
539 self.nest_tables(item.id, |v| v.process_formals(&decl.inputs, &fn_data.qualname));
540 self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
543 for arg in &decl.inputs {
544 self.visit_ty(&arg.ty);
547 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
548 self.visit_ty(&ret_ty);
551 self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
554 fn process_static_or_const_item(&mut self,
557 expr: &'l ast::Expr) {
558 if let Some(var_data) = self.save_ctxt.get_item_data(item) {
559 down_cast_data!(var_data, VariableData, item.span);
560 if !self.span.filter_generated(Some(var_data.span), item.span) {
561 self.dumper.variable(var_data.lower(self.tcx));
565 self.visit_expr(expr);
568 fn process_assoc_const(&mut self,
576 attrs: &'l [Attribute]) {
577 let qualname = format!("::{}", self.tcx.node_path_str(id));
579 let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
581 if !self.span.filter_generated(sub_span, span) {
582 self.dumper.variable(VariableData {
583 span: sub_span.expect("No span found for variable"),
584 kind: VariableKind::Const,
586 name: name.to_string(),
588 value: self.span.snippet(expr.span),
589 type_value: ty_to_string(&typ),
590 scope: self.cur_scope,
591 parent: Some(parent_id),
593 docs: docs_for_attrs(attrs),
598 // walk type and init value
600 self.visit_expr(expr);
603 // FIXME tuple structs should generate tuple-specific data.
604 fn process_struct(&mut self,
606 def: &'l ast::VariantData,
607 ty_params: &'l ast::Generics) {
608 let name = item.ident.to_string();
609 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
611 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
613 if let ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, _), _) = item.node
615 let fields_str = fields.iter()
617 .map(|(i, f)| f.ident.map(|i| i.to_string())
618 .unwrap_or(i.to_string()))
621 (format!("{} {{ {} }}", name, fields_str), fields.iter().map(|f| f.id).collect())
623 (String::new(), vec![])
626 if !self.span.filter_generated(sub_span, item.span) {
627 self.dumper.struct_data(StructData {
628 span: sub_span.expect("No span found for struct"),
632 qualname: qualname.clone(),
633 scope: self.cur_scope,
636 visibility: From::from(&item.vis),
637 docs: docs_for_attrs(&item.attrs),
638 sig: self.save_ctxt.sig_base(item),
642 for field in def.fields() {
643 self.process_struct_field_def(field, item.id);
644 self.visit_ty(&field.ty);
647 self.process_generic_params(ty_params, item.span, &qualname, item.id);
650 fn process_enum(&mut self,
652 enum_definition: &'l ast::EnumDef,
653 ty_params: &'l ast::Generics) {
654 let enum_data = self.save_ctxt.get_item_data(item);
655 let enum_data = match enum_data {
659 down_cast_data!(enum_data, EnumData, item.span);
660 if !self.span.filter_generated(Some(enum_data.span), item.span) {
661 self.dumper.enum_data(enum_data.clone().lower(self.tcx));
664 for variant in &enum_definition.variants {
665 let name = variant.node.name.name.to_string();
666 let mut qualname = enum_data.qualname.clone();
667 qualname.push_str("::");
668 qualname.push_str(&name);
670 let text = self.span.signature_string_for_span(variant.span);
671 let ident_start = text.find(&name).unwrap();
672 let ident_end = ident_start + name.len();
673 let sig = Signature {
676 ident_start: ident_start,
677 ident_end: ident_end,
682 match variant.node.data {
683 ast::VariantData::Struct(ref fields, _) => {
684 let sub_span = self.span.span_for_first_ident(variant.span);
685 let fields_str = fields.iter()
687 .map(|(i, f)| f.ident.map(|i| i.to_string())
688 .unwrap_or(i.to_string()))
691 let val = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
692 if !self.span.filter_generated(sub_span, variant.span) {
693 self.dumper.struct_variant(StructVariantData {
694 span: sub_span.expect("No span found for struct variant"),
695 id: variant.node.data.id(),
698 type_value: enum_data.qualname.clone(),
700 scope: enum_data.scope,
701 parent: Some(make_def_id(item.id, &self.tcx.hir)),
702 docs: docs_for_attrs(&variant.node.attrs),
708 let sub_span = self.span.span_for_first_ident(variant.span);
709 let mut val = format!("{}::{}", enum_data.name, name);
710 if let &ast::VariantData::Tuple(ref fields, _) = v {
712 val.push_str(&fields.iter()
713 .map(|f| ty_to_string(&f.ty))
718 if !self.span.filter_generated(sub_span, variant.span) {
719 self.dumper.tuple_variant(TupleVariantData {
720 span: sub_span.expect("No span found for tuple variant"),
721 id: variant.node.data.id(),
724 type_value: enum_data.qualname.clone(),
726 scope: enum_data.scope,
727 parent: Some(make_def_id(item.id, &self.tcx.hir)),
728 docs: docs_for_attrs(&variant.node.attrs),
736 for field in variant.node.data.fields() {
737 self.process_struct_field_def(field, variant.node.data.id());
738 self.visit_ty(&field.ty);
741 self.process_generic_params(ty_params, item.span, &enum_data.qualname, enum_data.id);
744 fn process_impl(&mut self,
746 type_parameters: &'l ast::Generics,
747 trait_ref: &'l Option<ast::TraitRef>,
749 impl_items: &'l [ast::ImplItem]) {
750 let mut has_self_ref = false;
751 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
752 down_cast_data!(impl_data, ImplData, item.span);
753 if let Some(ref self_ref) = impl_data.self_ref {
755 if !self.span.filter_generated(Some(self_ref.span), item.span) {
756 self.dumper.type_ref(self_ref.clone().lower(self.tcx));
759 if let Some(ref trait_ref_data) = impl_data.trait_ref {
760 if !self.span.filter_generated(Some(trait_ref_data.span), item.span) {
761 self.dumper.type_ref(trait_ref_data.clone().lower(self.tcx));
765 if !self.span.filter_generated(Some(impl_data.span), item.span) {
766 self.dumper.impl_data(ImplData {
768 span: impl_data.span,
769 scope: impl_data.scope,
770 trait_ref: impl_data.trait_ref.map(|d| d.ref_id.unwrap()),
771 self_ref: impl_data.self_ref.map(|d| d.ref_id.unwrap())
778 if let &Some(ref trait_ref) = trait_ref {
779 self.process_path(trait_ref.ref_id, &trait_ref.path, Some(recorder::TypeRef));
781 self.process_generic_params(type_parameters, item.span, "", item.id);
782 for impl_item in impl_items {
783 let map = &self.tcx.hir;
784 self.process_impl_item(impl_item, make_def_id(item.id, map));
788 fn process_trait(&mut self,
790 generics: &'l ast::Generics,
791 trait_refs: &'l ast::TyParamBounds,
792 methods: &'l [ast::TraitItem]) {
793 let name = item.ident.to_string();
794 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
795 let mut val = name.clone();
796 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
797 val.push_str(&generics_to_string(generics));
799 if !trait_refs.is_empty() {
801 val.push_str(&bounds_to_string(trait_refs));
803 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
804 if !self.span.filter_generated(sub_span, item.span) {
805 self.dumper.trait_data(TraitData {
806 span: sub_span.expect("No span found for trait"),
809 qualname: qualname.clone(),
810 scope: self.cur_scope,
812 items: methods.iter().map(|i| i.id).collect(),
813 visibility: From::from(&item.vis),
814 docs: docs_for_attrs(&item.attrs),
815 sig: self.save_ctxt.sig_base(item),
820 for super_bound in trait_refs.iter() {
821 let trait_ref = match *super_bound {
822 ast::TraitTyParamBound(ref trait_ref, _) => {
825 ast::RegionTyParamBound(..) => {
830 let trait_ref = &trait_ref.trait_ref;
831 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
832 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
833 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
834 self.dumper.type_ref(TypeRefData {
835 span: sub_span.expect("No span found for trait ref"),
837 scope: self.cur_scope,
838 qualname: String::new()
842 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
843 let sub_span = sub_span.expect("No span for inheritance");
844 self.dumper.inheritance(InheritanceData {
853 // walk generics and methods
854 self.process_generic_params(generics, item.span, &qualname, item.id);
855 for method in methods {
856 let map = &self.tcx.hir;
857 self.process_trait_item(method, make_def_id(item.id, map))
861 // `item` is the module in question, represented as an item.
862 fn process_mod(&mut self, item: &ast::Item) {
863 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
864 down_cast_data!(mod_data, ModData, item.span);
865 if !self.span.filter_generated(Some(mod_data.span), item.span) {
866 self.dumper.mod_data(mod_data.lower(self.tcx));
871 fn process_path(&mut self, id: NodeId, path: &ast::Path, ref_kind: Option<recorder::Row>) {
872 let path_data = self.save_ctxt.get_path_data(id, path);
873 if generated_code(path.span) && path_data.is_none() {
877 let path_data = match path_data {
885 Data::VariableRefData(vrd) => {
886 // FIXME: this whole block duplicates the code in process_def_kind
887 if !self.span.filter_generated(Some(vrd.span), path.span) {
889 Some(recorder::TypeRef) => {
890 self.dumper.type_ref(TypeRefData {
892 ref_id: Some(vrd.ref_id),
894 qualname: String::new()
897 Some(recorder::FnRef) => {
898 self.dumper.function_ref(FunctionRefData {
904 Some(recorder::ModRef) => {
905 self.dumper.mod_ref( ModRefData {
907 ref_id: Some(vrd.ref_id),
909 qualname: String::new()
912 Some(recorder::VarRef) | None
913 => self.dumper.variable_ref(vrd.lower(self.tcx))
918 Data::TypeRefData(trd) => {
919 if !self.span.filter_generated(Some(trd.span), path.span) {
920 self.dumper.type_ref(trd.lower(self.tcx));
923 Data::MethodCallData(mcd) => {
924 if !self.span.filter_generated(Some(mcd.span), path.span) {
925 self.dumper.method_call(mcd.lower(self.tcx));
928 Data::FunctionCallData(fcd) => {
929 if !self.span.filter_generated(Some(fcd.span), path.span) {
930 self.dumper.function_call(fcd.lower(self.tcx));
934 span_bug!(path.span, "Unexpected data: {:?}", path_data);
938 // Modules or types in the path prefix.
939 match self.save_ctxt.get_path_def(id) {
940 Def::Method(did) => {
941 let ti = self.tcx.associated_item(did);
942 if ti.kind == ty::AssociatedKind::Method && ti.method_has_self_argument {
943 self.write_sub_path_trait_truncated(path);
949 Def::StructCtor(..) |
950 Def::VariantCtor(..) |
951 Def::AssociatedConst(..) |
958 Def::AssociatedTy(..) => self.write_sub_paths_truncated(path),
963 fn process_struct_lit(&mut self,
966 fields: &'l [ast::Field],
967 variant: &'l ty::VariantDef,
968 base: &'l Option<P<ast::Expr>>) {
969 self.write_sub_paths_truncated(path);
971 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
972 down_cast_data!(struct_lit_data, TypeRefData, ex.span);
973 if !self.span.filter_generated(Some(struct_lit_data.span), ex.span) {
974 self.dumper.type_ref(struct_lit_data.lower(self.tcx));
977 let scope = self.save_ctxt.enclosing_scope(ex.id);
979 for field in fields {
980 if let Some(field_data) = self.save_ctxt
981 .get_field_ref_data(field, variant, scope) {
983 if !self.span.filter_generated(Some(field_data.span), field.ident.span) {
984 self.dumper.variable_ref(field_data.lower(self.tcx));
988 self.visit_expr(&field.expr)
992 walk_list!(self, visit_expr, base);
995 fn process_method_call(&mut self, ex: &'l ast::Expr, args: &'l [P<ast::Expr>]) {
996 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
997 down_cast_data!(mcd, MethodCallData, ex.span);
998 if !self.span.filter_generated(Some(mcd.span), ex.span) {
999 self.dumper.method_call(mcd.lower(self.tcx));
1003 // walk receiver and args
1004 walk_list!(self, visit_expr, args);
1007 fn process_pat(&mut self, p: &'l ast::Pat) {
1009 PatKind::Struct(ref _path, ref fields, _) => {
1010 // FIXME do something with _path?
1011 let adt = match self.save_ctxt.tables.node_id_to_type_opt(p.id) {
1012 Some(ty) => ty.ty_adt_def().unwrap(),
1014 visit::walk_pat(self, p);
1018 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
1020 for &Spanned { node: ref field, span } in fields {
1021 let sub_span = self.span.span_for_first_ident(span);
1022 if let Some(f) = variant.find_field_named(field.ident.name) {
1023 if !self.span.filter_generated(sub_span, span) {
1024 self.dumper.variable_ref(VariableRefData {
1025 span: sub_span.expect("No span fund for var ref"),
1027 scope: self.cur_scope,
1032 self.visit_pat(&field.pat);
1035 _ => visit::walk_pat(self, p),
1040 fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
1041 // The local could declare multiple new vars, we must walk the
1042 // pattern and collect them all.
1043 let mut collector = PathCollector::new();
1044 collector.visit_pat(&p);
1047 for &(id, ref p, immut, _) in &collector.collected_paths {
1048 let mut value = match immut {
1049 ast::Mutability::Immutable => value.to_string(),
1052 let typ = match self.save_ctxt.tables.node_types.get(&id) {
1054 let typ = typ.to_string();
1055 if !value.is_empty() {
1056 value.push_str(": ");
1058 value.push_str(&typ);
1061 None => String::new(),
1064 // Get the span only for the name of the variable (I hope the path
1065 // is only ever a variable name, but who knows?).
1066 let sub_span = self.span.span_for_last_ident(p.span);
1067 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1068 if !self.span.filter_generated(sub_span, p.span) {
1069 self.dumper.variable(VariableData {
1070 span: sub_span.expect("No span found for variable"),
1071 kind: VariableKind::Local,
1073 name: path_to_string(p),
1074 qualname: format!("{}${}", path_to_string(p), id),
1077 scope: CRATE_NODE_ID,
1079 visibility: Visibility::Inherited,
1080 docs: String::new(),
1087 /// Extract macro use and definition information from the AST node defined
1088 /// by the given NodeId, using the expansion information from the node's
1091 /// If the span is not macro-generated, do nothing, else use callee and
1092 /// callsite spans to record macro definition and use data, using the
1093 /// mac_uses and mac_defs sets to prevent multiples.
1094 fn process_macro_use(&mut self, span: Span, id: NodeId) {
1095 let data = match self.save_ctxt.get_macro_use_data(span, id) {
1099 let mut hasher = DefaultHasher::new();
1100 data.callee_span.hash(&mut hasher);
1101 let hash = hasher.finish();
1102 let qualname = format!("{}::{}", data.name, hash);
1103 // Don't write macro definition for imported macros
1104 if !self.mac_defs.contains(&data.callee_span)
1106 self.mac_defs.insert(data.callee_span);
1107 if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1108 self.dumper.macro_data(MacroData {
1110 name: data.name.clone(),
1111 qualname: qualname.clone(),
1112 // FIXME where do macro docs come from?
1113 docs: String::new(),
1117 if !self.mac_uses.contains(&data.span) {
1118 self.mac_uses.insert(data.span);
1119 if let Some(sub_span) = self.span.span_for_macro_use_name(data.span) {
1120 self.dumper.macro_use(MacroUseData {
1125 callee_span: data.callee_span,
1126 imported: data.imported,
1132 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1133 self.process_macro_use(trait_item.span, trait_item.id);
1134 match trait_item.node {
1135 ast::TraitItemKind::Const(ref ty, Some(ref expr)) => {
1136 self.process_assoc_const(trait_item.id,
1137 trait_item.ident.name,
1145 ast::TraitItemKind::Method(ref sig, ref body) => {
1146 self.process_method(sig,
1147 body.as_ref().map(|x| &**x),
1149 trait_item.ident.name,
1154 ast::TraitItemKind::Const(_, None) |
1155 ast::TraitItemKind::Type(..) |
1156 ast::TraitItemKind::Macro(_) => {}
1160 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1161 self.process_macro_use(impl_item.span, impl_item.id);
1162 match impl_item.node {
1163 ast::ImplItemKind::Const(ref ty, ref expr) => {
1164 self.process_assoc_const(impl_item.id,
1165 impl_item.ident.name,
1170 From::from(&impl_item.vis),
1173 ast::ImplItemKind::Method(ref sig, ref body) => {
1174 self.process_method(sig,
1177 impl_item.ident.name,
1178 From::from(&impl_item.vis),
1182 ast::ImplItemKind::Type(_) |
1183 ast::ImplItemKind::Macro(_) => {}
1188 impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, D> {
1189 fn visit_item(&mut self, item: &'l ast::Item) {
1190 use syntax::ast::ItemKind::*;
1191 self.process_macro_use(item.span, item.id);
1193 Use(ref use_item) => {
1194 match use_item.node {
1195 ast::ViewPathSimple(ident, ref path) => {
1196 let sub_span = self.span.span_for_last_ident(path.span);
1197 let mod_id = match self.lookup_def_id(item.id) {
1199 let scope = self.cur_scope;
1200 self.process_def_kind(item.id, path.span, sub_span, def_id, scope);
1207 // 'use' always introduces an alias, if there is not an explicit
1208 // one, there is an implicit one.
1209 let sub_span = match self.span.sub_span_after_keyword(use_item.span,
1211 Some(sub_span) => Some(sub_span),
1215 if !self.span.filter_generated(sub_span, path.span) {
1216 self.dumper.use_data(UseData {
1217 span: sub_span.expect("No span found for use"),
1220 name: ident.to_string(),
1221 scope: self.cur_scope,
1222 visibility: From::from(&item.vis),
1225 self.write_sub_paths_truncated(path);
1227 ast::ViewPathGlob(ref path) => {
1228 // Make a comma-separated list of names of imported modules.
1229 let mut names = vec![];
1230 let glob_map = &self.save_ctxt.analysis.glob_map;
1231 let glob_map = glob_map.as_ref().unwrap();
1232 if glob_map.contains_key(&item.id) {
1233 for n in glob_map.get(&item.id).unwrap() {
1234 names.push(n.to_string());
1238 let sub_span = self.span
1239 .sub_span_of_token(item.span, token::BinOp(token::Star));
1240 if !self.span.filter_generated(sub_span, item.span) {
1241 self.dumper.use_glob(UseGlobData {
1242 span: sub_span.expect("No span found for use glob"),
1245 scope: self.cur_scope,
1246 visibility: From::from(&item.vis),
1249 self.write_sub_paths(path);
1251 ast::ViewPathList(ref path, ref list) => {
1253 let scope = self.cur_scope;
1254 let id = plid.node.id;
1255 if let Some(def_id) = self.lookup_def_id(id) {
1256 let span = plid.span;
1257 self.process_def_kind(id, span, Some(span), def_id, scope);
1261 self.write_sub_paths(path);
1265 ExternCrate(ref s) => {
1266 let location = match *s {
1267 Some(s) => s.to_string(),
1268 None => item.ident.to_string(),
1270 let alias_span = self.span.span_for_last_ident(item.span);
1271 let cnum = match self.sess.cstore.extern_mod_stmt_cnum(item.id) {
1273 None => LOCAL_CRATE,
1276 if !self.span.filter_generated(alias_span, item.span) {
1277 self.dumper.extern_crate(ExternCrateData {
1279 name: item.ident.to_string(),
1282 span: alias_span.expect("No span found for extern crate"),
1283 scope: self.cur_scope,
1287 Fn(ref decl, .., ref ty_params, ref body) =>
1288 self.process_fn(item, &decl, ty_params, &body),
1289 Static(ref typ, _, ref expr) =>
1290 self.process_static_or_const_item(item, typ, expr),
1291 Const(ref typ, ref expr) =>
1292 self.process_static_or_const_item(item, &typ, &expr),
1293 Struct(ref def, ref ty_params) => self.process_struct(item, def, ty_params),
1294 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1299 ref impl_items) => {
1300 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1302 Trait(_, ref generics, ref trait_refs, ref methods) =>
1303 self.process_trait(item, generics, trait_refs, methods),
1305 self.process_mod(item);
1306 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1308 Ty(ref ty, ref ty_params) => {
1309 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1310 let value = ty_to_string(&ty);
1311 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1312 if !self.span.filter_generated(sub_span, item.span) {
1313 self.dumper.typedef(TypeDefData {
1314 span: sub_span.expect("No span found for typedef"),
1315 name: item.ident.to_string(),
1317 qualname: qualname.clone(),
1319 visibility: From::from(&item.vis),
1321 docs: docs_for_attrs(&item.attrs),
1322 sig: Some(self.save_ctxt.sig_base(item)),
1327 self.process_generic_params(ty_params, item.span, &qualname, item.id);
1330 _ => visit::walk_item(self, item),
1334 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1335 for param in generics.ty_params.iter() {
1336 for bound in param.bounds.iter() {
1337 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
1338 self.process_trait_ref(&trait_ref.trait_ref);
1341 if let Some(ref ty) = param.default {
1347 fn visit_ty(&mut self, t: &'l ast::Ty) {
1348 self.process_macro_use(t.span, t.id);
1350 ast::TyKind::Path(_, ref path) => {
1351 if generated_code(t.span) {
1355 if let Some(id) = self.lookup_def_id(t.id) {
1356 if let Some(sub_span) = self.span.sub_span_for_type_name(t.span) {
1357 self.dumper.type_ref(TypeRefData {
1360 scope: self.cur_scope,
1361 qualname: String::new()
1366 self.write_sub_paths_truncated(path);
1367 visit::walk_path(self, path);
1369 ast::TyKind::Array(ref element, ref length) => {
1370 self.visit_ty(element);
1371 self.nest_tables(length.id, |v| v.visit_expr(length));
1373 _ => visit::walk_ty(self, t),
1377 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1378 debug!("visit_expr {:?}", ex.node);
1379 self.process_macro_use(ex.span, ex.id);
1381 ast::ExprKind::Call(ref _f, ref _args) => {
1382 // Don't need to do anything for function calls,
1383 // because just walking the callee path does what we want.
1384 visit::walk_expr(self, ex);
1386 ast::ExprKind::Path(_, ref path) => {
1387 self.process_path(ex.id, path, None);
1388 visit::walk_expr(self, ex);
1390 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1391 let hir_expr = self.save_ctxt.tcx.hir.expect_expr(ex.id);
1392 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1393 Some(ty) => ty.ty_adt_def().unwrap(),
1395 visit::walk_expr(self, ex);
1399 let def = self.save_ctxt.get_path_def(hir_expr.id);
1400 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1402 ast::ExprKind::MethodCall(.., ref args) => self.process_method_call(ex, args),
1403 ast::ExprKind::Field(ref sub_ex, _) => {
1404 self.visit_expr(&sub_ex);
1406 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1407 down_cast_data!(field_data, VariableRefData, ex.span);
1408 if !self.span.filter_generated(Some(field_data.span), ex.span) {
1409 self.dumper.variable_ref(field_data.lower(self.tcx));
1413 ast::ExprKind::TupField(ref sub_ex, idx) => {
1414 self.visit_expr(&sub_ex);
1416 let hir_node = match self.save_ctxt.tcx.hir.find(sub_ex.id) {
1417 Some(Node::NodeExpr(expr)) => expr,
1419 debug!("Missing or weird node for sub-expression {} in {:?}",
1424 let ty = match self.save_ctxt.tables.expr_ty_adjusted_opt(&hir_node) {
1425 Some(ty) => &ty.sty,
1427 visit::walk_expr(self, ex);
1432 ty::TyAdt(def, _) => {
1433 let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1434 if !self.span.filter_generated(sub_span, ex.span) {
1435 self.dumper.variable_ref(VariableRefData {
1436 span: sub_span.expect("No span found for var ref"),
1437 ref_id: def.struct_variant().fields[idx.node].did,
1438 scope: self.cur_scope,
1443 ty::TyTuple(..) => {}
1444 _ => span_bug!(ex.span,
1445 "Expected struct or tuple type, found {:?}",
1449 ast::ExprKind::Closure(_, ref decl, ref body, _fn_decl_span) => {
1450 let mut id = String::from("$");
1451 id.push_str(&ex.id.to_string());
1453 // walk arg and return types
1454 for arg in &decl.inputs {
1455 self.visit_ty(&arg.ty);
1458 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1459 self.visit_ty(&ret_ty);
1463 self.nest_tables(ex.id, |v| {
1464 v.process_formals(&decl.inputs, &id);
1465 v.nest_scope(ex.id, |v| v.visit_expr(body))
1468 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) |
1469 ast::ExprKind::WhileLet(ref pattern, ref subexpression, ref block, _) => {
1470 let value = self.span.snippet(subexpression.span);
1471 self.process_var_decl(pattern, value);
1472 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1473 visit::walk_expr(self, subexpression);
1474 visit::walk_block(self, block);
1476 ast::ExprKind::IfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
1477 let value = self.span.snippet(subexpression.span);
1478 self.process_var_decl(pattern, value);
1479 visit::walk_expr(self, subexpression);
1480 visit::walk_block(self, block);
1481 opt_else.as_ref().map(|el| visit::walk_expr(self, el));
1483 ast::ExprKind::Repeat(ref element, ref count) => {
1484 self.visit_expr(element);
1485 self.nest_tables(count.id, |v| v.visit_expr(count));
1488 visit::walk_expr(self, ex)
1493 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1494 // These shouldn't exist in the AST at this point, log a span bug.
1495 span_bug!(mac.span, "macro invocation should have been expanded out of AST");
1498 fn visit_pat(&mut self, p: &'l ast::Pat) {
1499 self.process_macro_use(p.span, p.id);
1500 self.process_pat(p);
1503 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1504 let mut collector = PathCollector::new();
1505 for pattern in &arm.pats {
1506 // collect paths from the arm's patterns
1507 collector.visit_pat(&pattern);
1508 self.visit_pat(&pattern);
1511 // This is to get around borrow checking, because we need mut self to call process_path.
1512 let mut paths_to_process = vec![];
1514 // process collected paths
1515 for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1516 match self.save_ctxt.get_path_def(id) {
1517 Def::Local(def_id) => {
1518 let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1519 let mut value = if immut == ast::Mutability::Immutable {
1520 self.span.snippet(p.span).to_string()
1522 "<mutable>".to_string()
1524 let typ = self.save_ctxt.tables.node_types
1525 .get(&id).map(|t| t.to_string()).unwrap_or(String::new());
1526 value.push_str(": ");
1527 value.push_str(&typ);
1529 assert!(p.segments.len() == 1,
1530 "qualified path for local variable def in arm");
1531 if !self.span.filter_generated(Some(p.span), p.span) {
1532 self.dumper.variable(VariableData {
1534 kind: VariableKind::Local,
1536 name: path_to_string(p),
1537 qualname: format!("{}${}", path_to_string(p), id),
1540 scope: CRATE_NODE_ID,
1542 visibility: Visibility::Inherited,
1543 docs: String::new(),
1548 Def::StructCtor(..) | Def::VariantCtor(..) |
1549 Def::Const(..) | Def::AssociatedConst(..) |
1550 Def::Struct(..) | Def::Variant(..) |
1551 Def::TyAlias(..) | Def::AssociatedTy(..) |
1552 Def::SelfTy(..) => {
1553 paths_to_process.push((id, p.clone(), Some(ref_kind)))
1555 def => error!("unexpected definition kind when processing collected paths: {:?}",
1560 for &(id, ref path, ref_kind) in &paths_to_process {
1561 self.process_path(id, path, ref_kind);
1563 walk_list!(self, visit_expr, &arm.guard);
1564 self.visit_expr(&arm.body);
1567 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1568 self.process_path(id, p, None);
1571 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1572 self.process_macro_use(s.span, s.id);
1573 visit::walk_stmt(self, s)
1576 fn visit_local(&mut self, l: &'l ast::Local) {
1577 self.process_macro_use(l.span, l.id);
1578 let value = l.init.as_ref().map(|i| self.span.snippet(i.span)).unwrap_or(String::new());
1579 self.process_var_decl(&l.pat, value);
1581 // Just walk the initialiser and type (don't want to walk the pattern again).
1582 walk_list!(self, visit_ty, &l.ty);
1583 walk_list!(self, visit_expr, &l.init);