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::{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 use rls_data::ExternalCrateData;
59 macro_rules! down_cast_data {
60 ($id:ident, $kind:ident, $sp:expr) => {
61 let $id = if let super::Data::$kind(data) = $id {
64 span_bug!($sp, "unexpected data kind: {:?}", $id);
69 pub struct DumpVisitor<'l, 'tcx: 'l, 'll, D: 'll> {
70 save_ctxt: SaveContext<'l, 'tcx>,
72 tcx: TyCtxt<'l, 'tcx, 'tcx>,
79 // Set of macro definition (callee) spans, and the set
80 // of macro use (callsite) spans. We store these to ensure
81 // we only write one macro def per unique macro definition, and
82 // one macro use per unique callsite span.
83 mac_defs: HashSet<Span>,
84 mac_uses: HashSet<Span>,
87 impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> {
88 pub fn new(save_ctxt: SaveContext<'l, 'tcx>,
90 -> DumpVisitor<'l, 'tcx, 'll, D> {
91 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
93 sess: &save_ctxt.tcx.sess,
97 span: span_utils.clone(),
98 cur_scope: CRATE_NODE_ID,
99 mac_defs: HashSet::new(),
100 mac_uses: HashSet::new(),
104 fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
105 where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, D>)
107 let parent_scope = self.cur_scope;
108 self.cur_scope = scope_id;
110 self.cur_scope = parent_scope;
113 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
114 where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, D>)
116 let item_def_id = self.tcx.hir.local_def_id(item_id);
117 match self.tcx.maps.typeck_tables.borrow().get(&item_def_id) {
119 let old_tables = self.save_ctxt.tables;
120 self.save_ctxt.tables = tables;
122 self.save_ctxt.tables = old_tables;
128 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
129 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
130 let crate_root = source_file.map(|source_file| {
131 match source_file.file_name() {
132 Some(_) => source_file.parent().unwrap().display().to_string(),
133 None => source_file.display().to_string(),
137 // Info about all the external crates referenced from this crate.
138 let external_crates = self.save_ctxt.get_external_crates().into_iter().map(|c| {
139 let lo_loc = self.span.sess.codemap().lookup_char_pos(c.span.lo);
143 file_name: SpanUtils::make_path_string(&lo_loc.file.name),
147 // The current crate.
148 let data = CratePreludeData {
149 crate_name: name.into(),
150 crate_root: crate_root.unwrap_or("<no source>".to_owned()),
151 external_crates: external_crates,
155 self.dumper.crate_prelude(data.lower(self.tcx));
158 // Return all non-empty prefixes of a path.
159 // For each prefix, we return the span for the last segment in the prefix and
160 // a str representation of the entire prefix.
161 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
162 let spans = self.span.spans_for_path_segments(path);
163 let segments = &path.segments[if path.is_global() { 1 } else { 0 }..];
165 // Paths to enums seem to not match their spans - the span includes all the
166 // variants too. But they seem to always be at the end, so I hope we can cope with
167 // always using the first ones. So, only error out if we don't have enough spans.
168 // What could go wrong...?
169 if spans.len() < segments.len() {
170 if generated_code(path.span) {
173 error!("Mis-calculated spans for path '{}'. Found {} spans, expected {}. Found spans:",
174 path_to_string(path),
178 let loc = self.sess.codemap().lookup_char_pos(s.lo);
179 error!(" '{}' in {}, line {}",
180 self.span.snippet(*s),
184 error!(" master span: {:?}: `{}`", path.span, self.span.snippet(path.span));
188 let mut result: Vec<(Span, String)> = vec![];
190 let mut segs = vec![];
191 for (i, (seg, span)) in segments.iter().zip(&spans).enumerate() {
192 segs.push(seg.clone());
193 let sub_path = ast::Path {
194 span: *span, // span for the last segment
197 let qualname = if i == 0 && path.is_global() {
198 format!("::{}", path_to_string(&sub_path))
200 path_to_string(&sub_path)
202 result.push((*span, qualname));
203 segs = sub_path.segments;
209 fn write_sub_paths(&mut self, path: &ast::Path) {
210 let sub_paths = self.process_path_prefixes(path);
211 for (span, qualname) in sub_paths {
212 self.dumper.mod_ref(ModRefData {
215 scope: self.cur_scope,
221 // As write_sub_paths, but does not process the last ident in the path (assuming it
222 // will be processed elsewhere). See note on write_sub_paths about global.
223 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
224 let sub_paths = self.process_path_prefixes(path);
225 let len = sub_paths.len();
230 for (span, qualname) in sub_paths.into_iter().take(len - 1) {
231 self.dumper.mod_ref(ModRefData {
234 scope: self.cur_scope,
240 // As write_sub_paths, but expects a path of the form module_path::trait::method
241 // Where trait could actually be a struct too.
242 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
243 let sub_paths = self.process_path_prefixes(path);
244 let len = sub_paths.len();
248 let sub_paths = &sub_paths[.. (len-1)];
250 // write the trait part of the sub-path
251 let (ref span, ref qualname) = sub_paths[len-2];
252 self.dumper.type_ref(TypeRefData {
255 qualname: qualname.to_owned(),
259 // write the other sub-paths
263 let sub_paths = &sub_paths[..len-2];
264 for &(ref span, ref qualname) in sub_paths {
265 self.dumper.mod_ref(ModRefData {
267 qualname: qualname.to_owned(),
268 scope: self.cur_scope,
274 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
275 match self.save_ctxt.get_path_def(ref_id) {
276 Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => None,
277 def => Some(def.def_id()),
281 fn process_def_kind(&mut self,
284 sub_span: Option<Span>,
287 if self.span.filter_generated(sub_span, span) {
291 let def = self.save_ctxt.get_path_def(ref_id);
294 self.dumper.mod_ref(ModRefData {
295 span: sub_span.expect("No span found for mod ref"),
296 ref_id: Some(def_id),
298 qualname: String::new()
307 self.dumper.type_ref(TypeRefData {
308 span: sub_span.expect("No span found for type ref"),
309 ref_id: Some(def_id),
311 qualname: String::new()
316 Def::StructCtor(..) |
317 Def::VariantCtor(..) => {
318 self.dumper.variable_ref(VariableRefData {
319 span: sub_span.expect("No span found for var ref"),
326 self.dumper.function_ref(FunctionRefData {
327 span: sub_span.expect("No span found for fn ref"),
332 // With macros 2.0, we can legitimately get a ref to a macro, but
333 // we don't handle it properly for now (FIXME).
341 Def::AssociatedTy(..) |
342 Def::AssociatedConst(..) |
347 "process_def_kind for unexpected item: {:?}",
353 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
355 self.visit_pat(&arg.pat);
356 let mut collector = PathCollector::new();
357 collector.visit_pat(&arg.pat);
358 let span_utils = self.span.clone();
359 for &(id, ref p, ..) in &collector.collected_paths {
360 let typ = match self.save_ctxt.tables.node_types.get(&id) {
361 Some(s) => s.to_string(),
364 // get the span only for the name of the variable (I hope the path is only ever a
365 // variable name, but who knows?)
366 let sub_span = span_utils.span_for_last_ident(p.span);
367 if !self.span.filter_generated(sub_span, p.span) {
368 self.dumper.variable(VariableData {
370 kind: VariableKind::Local,
371 span: sub_span.expect("No span found for variable"),
372 name: path_to_string(p),
373 qualname: format!("{}::{}", qualname, path_to_string(p)),
375 value: String::new(),
376 scope: CRATE_NODE_ID,
378 visibility: Visibility::Inherited,
388 fn process_method(&mut self,
389 sig: &'l ast::MethodSig,
390 body: Option<&'l ast::Block>,
394 attrs: &'l [Attribute],
396 debug!("process_method: {}:{}", id, name);
398 if let Some(method_data) = self.save_ctxt.get_method_data(id, name, span) {
400 let sig_str = ::make_signature(&sig.decl, &sig.generics);
402 self.nest_tables(id, |v| {
403 v.process_formals(&sig.decl.inputs, &method_data.qualname)
407 // If the method is defined in an impl, then try and find the corresponding
408 // method decl in a trait, and if there is one, make a decl_id for it. This
409 // requires looking up the impl, then the trait, then searching for a method
410 // with the right name.
411 if !self.span.filter_generated(Some(method_data.span), span) {
413 self.tcx.associated_item(self.tcx.hir.local_def_id(id)).container;
415 let mut decl_id = None;
417 AssociatedItemContainer::ImplContainer(id) => {
418 trait_id = self.tcx.trait_id_of_impl(id);
422 for item in self.tcx.associated_items(id) {
423 if item.kind == ty::AssociatedKind::Method {
424 if item.name == name {
425 decl_id = Some(item.def_id);
432 if let Some(NodeItem(item)) = self.tcx.hir.get_if_local(id) {
433 if let hir::ItemImpl(_, _, _, _, ref ty, _) = item.node {
434 trait_id = self.lookup_def_id(ty.id);
440 AssociatedItemContainer::TraitContainer(id) => {
445 self.dumper.method(MethodData {
447 name: method_data.name,
448 span: method_data.span,
449 scope: method_data.scope,
450 qualname: method_data.qualname.clone(),
455 docs: docs_for_attrs(attrs),
456 sig: method_data.sig,
457 attributes: attrs.to_vec(),
461 self.process_generic_params(&sig.generics, span, &method_data.qualname, id);
464 // walk arg and return types
465 for arg in &sig.decl.inputs {
466 self.visit_ty(&arg.ty);
469 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
470 self.visit_ty(ret_ty);
474 if let Some(body) = body {
475 self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
479 fn process_trait_ref(&mut self, trait_ref: &'l ast::TraitRef) {
480 let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref, self.cur_scope);
481 if let Some(trait_ref_data) = trait_ref_data {
482 if !self.span.filter_generated(Some(trait_ref_data.span), trait_ref.path.span) {
483 self.dumper.type_ref(trait_ref_data.lower(self.tcx));
486 self.process_path(trait_ref.ref_id, &trait_ref.path, Some(recorder::TypeRef));
489 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
490 let field_data = self.save_ctxt.get_field_data(field, parent_id);
491 if let Some(mut field_data) = field_data {
492 if !self.span.filter_generated(Some(field_data.span), field.span) {
493 field_data.value = String::new();
494 self.dumper.variable(field_data.lower(self.tcx));
499 // Dump generic params bindings, then visit_generics
500 fn process_generic_params(&mut self,
501 generics: &'l ast::Generics,
505 // We can't only use visit_generics since we don't have spans for param
506 // bindings, so we reparse the full_span to get those sub spans.
507 // However full span is the entire enum/fn/struct block, so we only want
508 // the first few to match the number of generics we're looking for.
509 let param_sub_spans = self.span.spans_for_ty_params(full_span,
510 (generics.ty_params.len() as isize));
511 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
512 let name = escape(self.span.snippet(param_ss));
513 // Append $id to name to make sure each one is unique
514 let qualname = format!("{}::{}${}",
518 if !self.span.filter_generated(Some(param_ss), full_span) {
519 self.dumper.typedef(TypeDefData {
524 value: String::new(),
525 visibility: Visibility::Inherited,
533 self.visit_generics(generics);
536 fn process_fn(&mut self,
538 decl: &'l ast::FnDecl,
539 ty_params: &'l ast::Generics,
540 body: &'l ast::Block) {
541 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
542 down_cast_data!(fn_data, FunctionData, item.span);
543 if !self.span.filter_generated(Some(fn_data.span), item.span) {
544 self.dumper.function(fn_data.clone().lower(self.tcx));
547 self.nest_tables(item.id, |v| v.process_formals(&decl.inputs, &fn_data.qualname));
548 self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
551 for arg in &decl.inputs {
552 self.visit_ty(&arg.ty);
555 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
556 self.visit_ty(&ret_ty);
559 self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
562 fn process_static_or_const_item(&mut self,
565 expr: &'l ast::Expr) {
566 if let Some(var_data) = self.save_ctxt.get_item_data(item) {
567 down_cast_data!(var_data, VariableData, item.span);
568 if !self.span.filter_generated(Some(var_data.span), item.span) {
569 self.dumper.variable(var_data.lower(self.tcx));
573 self.visit_expr(expr);
576 fn process_assoc_const(&mut self,
584 attrs: &'l [Attribute]) {
585 let qualname = format!("::{}", self.tcx.node_path_str(id));
587 let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
589 if !self.span.filter_generated(sub_span, span) {
590 self.dumper.variable(VariableData {
591 span: sub_span.expect("No span found for variable"),
592 kind: VariableKind::Const,
594 name: name.to_string(),
596 value: self.span.snippet(expr.span),
597 type_value: ty_to_string(&typ),
598 scope: self.cur_scope,
599 parent: Some(parent_id),
601 docs: docs_for_attrs(attrs),
603 attributes: attrs.to_vec(),
607 // walk type and init value
609 self.visit_expr(expr);
612 // FIXME tuple structs should generate tuple-specific data.
613 fn process_struct(&mut self,
615 def: &'l ast::VariantData,
616 ty_params: &'l ast::Generics) {
617 let name = item.ident.to_string();
618 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
620 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
622 if let ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, _), _) = item.node
624 let fields_str = fields.iter()
626 .map(|(i, f)| f.ident.map(|i| i.to_string())
627 .unwrap_or(i.to_string()))
630 (format!("{} {{ {} }}", name, fields_str), fields.iter().map(|f| f.id).collect())
632 (String::new(), vec![])
635 if !self.span.filter_generated(sub_span, item.span) {
636 self.dumper.struct_data(StructData {
637 span: sub_span.expect("No span found for struct"),
641 qualname: qualname.clone(),
642 scope: self.cur_scope,
645 visibility: From::from(&item.vis),
646 docs: docs_for_attrs(&item.attrs),
647 sig: self.save_ctxt.sig_base(item),
648 attributes: item.attrs.clone(),
652 for field in def.fields() {
653 self.process_struct_field_def(field, item.id);
654 self.visit_ty(&field.ty);
657 self.process_generic_params(ty_params, item.span, &qualname, item.id);
660 fn process_enum(&mut self,
662 enum_definition: &'l ast::EnumDef,
663 ty_params: &'l ast::Generics) {
664 let enum_data = self.save_ctxt.get_item_data(item);
665 let enum_data = match enum_data {
669 down_cast_data!(enum_data, EnumData, item.span);
670 if !self.span.filter_generated(Some(enum_data.span), item.span) {
671 self.dumper.enum_data(enum_data.clone().lower(self.tcx));
674 for variant in &enum_definition.variants {
675 let name = variant.node.name.name.to_string();
676 let mut qualname = enum_data.qualname.clone();
677 qualname.push_str("::");
678 qualname.push_str(&name);
680 let text = self.span.signature_string_for_span(variant.span);
681 let ident_start = text.find(&name).unwrap();
682 let ident_end = ident_start + name.len();
683 let sig = Signature {
686 ident_start: ident_start,
687 ident_end: ident_end,
692 match variant.node.data {
693 ast::VariantData::Struct(ref fields, _) => {
694 let sub_span = self.span.span_for_first_ident(variant.span);
695 let fields_str = fields.iter()
697 .map(|(i, f)| f.ident.map(|i| i.to_string())
698 .unwrap_or(i.to_string()))
701 let val = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
702 if !self.span.filter_generated(sub_span, variant.span) {
703 self.dumper.struct_variant(StructVariantData {
704 span: sub_span.expect("No span found for struct variant"),
705 id: variant.node.data.id(),
708 type_value: enum_data.qualname.clone(),
710 scope: enum_data.scope,
711 parent: Some(make_def_id(item.id, &self.tcx.hir)),
712 docs: docs_for_attrs(&variant.node.attrs),
714 attributes: variant.node.attrs.clone(),
719 let sub_span = self.span.span_for_first_ident(variant.span);
720 let mut val = format!("{}::{}", enum_data.name, name);
721 if let &ast::VariantData::Tuple(ref fields, _) = v {
723 val.push_str(&fields.iter()
724 .map(|f| ty_to_string(&f.ty))
729 if !self.span.filter_generated(sub_span, variant.span) {
730 self.dumper.tuple_variant(TupleVariantData {
731 span: sub_span.expect("No span found for tuple variant"),
732 id: variant.node.data.id(),
735 type_value: enum_data.qualname.clone(),
737 scope: enum_data.scope,
738 parent: Some(make_def_id(item.id, &self.tcx.hir)),
739 docs: docs_for_attrs(&variant.node.attrs),
741 attributes: variant.node.attrs.clone(),
748 for field in variant.node.data.fields() {
749 self.process_struct_field_def(field, variant.node.data.id());
750 self.visit_ty(&field.ty);
753 self.process_generic_params(ty_params, item.span, &enum_data.qualname, enum_data.id);
756 fn process_impl(&mut self,
758 type_parameters: &'l ast::Generics,
759 trait_ref: &'l Option<ast::TraitRef>,
761 impl_items: &'l [ast::ImplItem]) {
762 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
763 down_cast_data!(impl_data, ImplData, item.span);
764 if !self.span.filter_generated(Some(impl_data.span), item.span) {
765 self.dumper.impl_data(ImplData {
767 span: impl_data.span,
768 scope: impl_data.scope,
769 trait_ref: impl_data.trait_ref.map(|d| d.ref_id.unwrap()),
770 self_ref: impl_data.self_ref.map(|d| d.ref_id.unwrap())
775 if let &Some(ref trait_ref) = trait_ref {
776 self.process_path(trait_ref.ref_id, &trait_ref.path, Some(recorder::TypeRef));
778 self.process_generic_params(type_parameters, item.span, "", item.id);
779 for impl_item in impl_items {
780 let map = &self.tcx.hir;
781 self.process_impl_item(impl_item, make_def_id(item.id, map));
785 fn process_trait(&mut self,
787 generics: &'l ast::Generics,
788 trait_refs: &'l ast::TyParamBounds,
789 methods: &'l [ast::TraitItem]) {
790 let name = item.ident.to_string();
791 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
792 let mut val = name.clone();
793 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
794 val.push_str(&generics_to_string(generics));
796 if !trait_refs.is_empty() {
798 val.push_str(&bounds_to_string(trait_refs));
800 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
801 if !self.span.filter_generated(sub_span, item.span) {
802 self.dumper.trait_data(TraitData {
803 span: sub_span.expect("No span found for trait"),
806 qualname: qualname.clone(),
807 scope: self.cur_scope,
809 items: methods.iter().map(|i| i.id).collect(),
810 visibility: From::from(&item.vis),
811 docs: docs_for_attrs(&item.attrs),
812 sig: self.save_ctxt.sig_base(item),
813 attributes: item.attrs.clone(),
818 for super_bound in trait_refs.iter() {
819 let trait_ref = match *super_bound {
820 ast::TraitTyParamBound(ref trait_ref, _) => {
823 ast::RegionTyParamBound(..) => {
828 let trait_ref = &trait_ref.trait_ref;
829 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
830 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
831 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
832 self.dumper.type_ref(TypeRefData {
833 span: sub_span.expect("No span found for trait ref"),
835 scope: self.cur_scope,
836 qualname: String::new()
840 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
841 let sub_span = sub_span.expect("No span for inheritance");
842 self.dumper.inheritance(InheritanceData {
851 // walk generics and methods
852 self.process_generic_params(generics, item.span, &qualname, item.id);
853 for method in methods {
854 let map = &self.tcx.hir;
855 self.process_trait_item(method, make_def_id(item.id, map))
859 // `item` is the module in question, represented as an item.
860 fn process_mod(&mut self, item: &ast::Item) {
861 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
862 down_cast_data!(mod_data, ModData, item.span);
863 if !self.span.filter_generated(Some(mod_data.span), item.span) {
864 self.dumper.mod_data(mod_data.lower(self.tcx));
869 fn process_path(&mut self, id: NodeId, path: &ast::Path, ref_kind: Option<recorder::Row>) {
870 let path_data = self.save_ctxt.get_path_data(id, path);
871 if generated_code(path.span) && path_data.is_none() {
875 let path_data = match path_data {
883 Data::VariableRefData(vrd) => {
884 // FIXME: this whole block duplicates the code in process_def_kind
885 if !self.span.filter_generated(Some(vrd.span), path.span) {
887 Some(recorder::TypeRef) => {
888 self.dumper.type_ref(TypeRefData {
890 ref_id: Some(vrd.ref_id),
892 qualname: String::new()
895 Some(recorder::FnRef) => {
896 self.dumper.function_ref(FunctionRefData {
902 Some(recorder::ModRef) => {
903 self.dumper.mod_ref( ModRefData {
905 ref_id: Some(vrd.ref_id),
907 qualname: String::new()
910 Some(recorder::VarRef) | None
911 => self.dumper.variable_ref(vrd.lower(self.tcx))
916 Data::TypeRefData(trd) => {
917 if !self.span.filter_generated(Some(trd.span), path.span) {
918 self.dumper.type_ref(trd.lower(self.tcx));
921 Data::MethodCallData(mcd) => {
922 if !self.span.filter_generated(Some(mcd.span), path.span) {
923 self.dumper.method_call(mcd.lower(self.tcx));
926 Data::FunctionCallData(fcd) => {
927 if !self.span.filter_generated(Some(fcd.span), path.span) {
928 self.dumper.function_call(fcd.lower(self.tcx));
932 span_bug!(path.span, "Unexpected data: {:?}", path_data);
936 // Modules or types in the path prefix.
937 match self.save_ctxt.get_path_def(id) {
938 Def::Method(did) => {
939 let ti = self.tcx.associated_item(did);
940 if ti.kind == ty::AssociatedKind::Method && ti.method_has_self_argument {
941 self.write_sub_path_trait_truncated(path);
947 Def::StructCtor(..) |
948 Def::VariantCtor(..) |
949 Def::AssociatedConst(..) |
956 Def::AssociatedTy(..) => self.write_sub_paths_truncated(path),
961 fn process_struct_lit(&mut self,
964 fields: &'l [ast::Field],
965 variant: &'l ty::VariantDef,
966 base: &'l Option<P<ast::Expr>>) {
967 self.write_sub_paths_truncated(path);
969 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
970 down_cast_data!(struct_lit_data, TypeRefData, ex.span);
971 if !self.span.filter_generated(Some(struct_lit_data.span), ex.span) {
972 self.dumper.type_ref(struct_lit_data.lower(self.tcx));
975 let scope = self.save_ctxt.enclosing_scope(ex.id);
977 for field in fields {
978 if let Some(field_data) = self.save_ctxt
979 .get_field_ref_data(field, variant, scope) {
981 if !self.span.filter_generated(Some(field_data.span), field.ident.span) {
982 self.dumper.variable_ref(field_data.lower(self.tcx));
986 self.visit_expr(&field.expr)
990 walk_list!(self, visit_expr, base);
993 fn process_method_call(&mut self, ex: &'l ast::Expr, args: &'l [P<ast::Expr>]) {
994 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
995 down_cast_data!(mcd, MethodCallData, ex.span);
996 if !self.span.filter_generated(Some(mcd.span), ex.span) {
997 self.dumper.method_call(mcd.lower(self.tcx));
1001 // walk receiver and args
1002 walk_list!(self, visit_expr, args);
1005 fn process_pat(&mut self, p: &'l ast::Pat) {
1007 PatKind::Struct(ref _path, ref fields, _) => {
1008 // FIXME do something with _path?
1009 let adt = match self.save_ctxt.tables.node_id_to_type_opt(p.id) {
1010 Some(ty) => ty.ty_adt_def().unwrap(),
1012 visit::walk_pat(self, p);
1016 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
1018 for &Spanned { node: ref field, span } in fields {
1019 let sub_span = self.span.span_for_first_ident(span);
1020 if let Some(f) = variant.find_field_named(field.ident.name) {
1021 if !self.span.filter_generated(sub_span, span) {
1022 self.dumper.variable_ref(VariableRefData {
1023 span: sub_span.expect("No span fund for var ref"),
1025 scope: self.cur_scope,
1030 self.visit_pat(&field.pat);
1033 _ => visit::walk_pat(self, p),
1038 fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
1039 // The local could declare multiple new vars, we must walk the
1040 // pattern and collect them all.
1041 let mut collector = PathCollector::new();
1042 collector.visit_pat(&p);
1045 for &(id, ref p, immut, _) in &collector.collected_paths {
1046 let mut value = match immut {
1047 ast::Mutability::Immutable => value.to_string(),
1050 let typ = match self.save_ctxt.tables.node_types.get(&id) {
1052 let typ = typ.to_string();
1053 if !value.is_empty() {
1054 value.push_str(": ");
1056 value.push_str(&typ);
1059 None => String::new(),
1062 // Get the span only for the name of the variable (I hope the path
1063 // is only ever a variable name, but who knows?).
1064 let sub_span = self.span.span_for_last_ident(p.span);
1065 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1066 if !self.span.filter_generated(sub_span, p.span) {
1067 self.dumper.variable(VariableData {
1068 span: sub_span.expect("No span found for variable"),
1069 kind: VariableKind::Local,
1071 name: path_to_string(p),
1072 qualname: format!("{}${}", path_to_string(p), id),
1075 scope: CRATE_NODE_ID,
1077 visibility: Visibility::Inherited,
1078 docs: String::new(),
1086 /// Extract macro use and definition information from the AST node defined
1087 /// by the given NodeId, using the expansion information from the node's
1090 /// If the span is not macro-generated, do nothing, else use callee and
1091 /// callsite spans to record macro definition and use data, using the
1092 /// mac_uses and mac_defs sets to prevent multiples.
1093 fn process_macro_use(&mut self, span: Span, id: NodeId) {
1094 let data = match self.save_ctxt.get_macro_use_data(span, id) {
1098 let mut hasher = DefaultHasher::new();
1099 data.callee_span.hash(&mut hasher);
1100 let hash = hasher.finish();
1101 let qualname = format!("{}::{}", data.name, hash);
1102 // Don't write macro definition for imported macros
1103 if !self.mac_defs.contains(&data.callee_span)
1105 self.mac_defs.insert(data.callee_span);
1106 if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1107 self.dumper.macro_data(MacroData {
1109 name: data.name.clone(),
1110 qualname: qualname.clone(),
1111 // FIXME where do macro docs come from?
1112 docs: String::new(),
1116 if !self.mac_uses.contains(&data.span) {
1117 self.mac_uses.insert(data.span);
1118 if let Some(sub_span) = self.span.span_for_macro_use_name(data.span) {
1119 self.dumper.macro_use(MacroUseData {
1124 callee_span: data.callee_span,
1125 imported: data.imported,
1131 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1132 self.process_macro_use(trait_item.span, trait_item.id);
1133 match trait_item.node {
1134 ast::TraitItemKind::Const(ref ty, Some(ref expr)) => {
1135 self.process_assoc_const(trait_item.id,
1136 trait_item.ident.name,
1144 ast::TraitItemKind::Method(ref sig, ref body) => {
1145 self.process_method(sig,
1146 body.as_ref().map(|x| &**x),
1148 trait_item.ident.name,
1153 ast::TraitItemKind::Type(ref _bounds, ref default_ty) => {
1154 // FIXME do something with _bounds (for type refs)
1155 let name = trait_item.ident.name.to_string();
1156 let qualname = format!("::{}", self.tcx.node_path_str(trait_item.id));
1157 let sub_span = self.span.sub_span_after_keyword(trait_item.span, keywords::Type);
1159 if !self.span.filter_generated(sub_span, trait_item.span) {
1160 self.dumper.typedef(TypeDefData {
1161 span: sub_span.expect("No span found for assoc type"),
1165 value: self.span.snippet(trait_item.span),
1166 visibility: Visibility::Public,
1167 parent: Some(trait_id),
1168 docs: docs_for_attrs(&trait_item.attrs),
1170 attributes: trait_item.attrs.clone(),
1174 if let &Some(ref default_ty) = default_ty {
1175 self.visit_ty(default_ty)
1178 ast::TraitItemKind::Const(ref ty, None) => self.visit_ty(ty),
1179 ast::TraitItemKind::Macro(_) => {}
1183 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1184 self.process_macro_use(impl_item.span, impl_item.id);
1185 match impl_item.node {
1186 ast::ImplItemKind::Const(ref ty, ref expr) => {
1187 self.process_assoc_const(impl_item.id,
1188 impl_item.ident.name,
1193 From::from(&impl_item.vis),
1196 ast::ImplItemKind::Method(ref sig, ref body) => {
1197 self.process_method(sig,
1200 impl_item.ident.name,
1201 From::from(&impl_item.vis),
1205 ast::ImplItemKind::Type(ref ty) => self.visit_ty(ty),
1206 ast::ImplItemKind::Macro(_) => {}
1211 impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, D> {
1212 fn visit_item(&mut self, item: &'l ast::Item) {
1213 use syntax::ast::ItemKind::*;
1214 self.process_macro_use(item.span, item.id);
1216 Use(ref use_item) => {
1217 match use_item.node {
1218 ast::ViewPathSimple(ident, ref path) => {
1219 let sub_span = self.span.span_for_last_ident(path.span);
1220 let mod_id = match self.lookup_def_id(item.id) {
1222 let scope = self.cur_scope;
1223 self.process_def_kind(item.id, path.span, sub_span, def_id, scope);
1230 // 'use' always introduces an alias, if there is not an explicit
1231 // one, there is an implicit one.
1232 let sub_span = match self.span.sub_span_after_keyword(use_item.span,
1234 Some(sub_span) => Some(sub_span),
1238 if !self.span.filter_generated(sub_span, path.span) {
1239 self.dumper.use_data(UseData {
1240 span: sub_span.expect("No span found for use"),
1243 name: ident.to_string(),
1244 scope: self.cur_scope,
1245 visibility: From::from(&item.vis),
1248 self.write_sub_paths_truncated(path);
1250 ast::ViewPathGlob(ref path) => {
1251 // Make a comma-separated list of names of imported modules.
1252 let mut names = vec![];
1253 let glob_map = &self.save_ctxt.analysis.glob_map;
1254 let glob_map = glob_map.as_ref().unwrap();
1255 if glob_map.contains_key(&item.id) {
1256 for n in glob_map.get(&item.id).unwrap() {
1257 names.push(n.to_string());
1261 let sub_span = self.span
1262 .sub_span_of_token(item.span, token::BinOp(token::Star));
1263 if !self.span.filter_generated(sub_span, item.span) {
1264 self.dumper.use_glob(UseGlobData {
1265 span: sub_span.expect("No span found for use glob"),
1268 scope: self.cur_scope,
1269 visibility: From::from(&item.vis),
1272 self.write_sub_paths(path);
1274 ast::ViewPathList(ref path, ref list) => {
1276 let scope = self.cur_scope;
1277 let id = plid.node.id;
1278 if let Some(def_id) = self.lookup_def_id(id) {
1279 let span = plid.span;
1280 self.process_def_kind(id, span, Some(span), def_id, scope);
1284 self.write_sub_paths(path);
1288 ExternCrate(ref s) => {
1289 let location = match *s {
1290 Some(s) => s.to_string(),
1291 None => item.ident.to_string(),
1293 let alias_span = self.span.span_for_last_ident(item.span);
1294 let cnum = match self.sess.cstore.extern_mod_stmt_cnum(item.id) {
1296 None => LOCAL_CRATE,
1299 if !self.span.filter_generated(alias_span, item.span) {
1300 self.dumper.extern_crate(ExternCrateData {
1302 name: item.ident.to_string(),
1305 span: alias_span.expect("No span found for extern crate"),
1306 scope: self.cur_scope,
1310 Fn(ref decl, .., ref ty_params, ref body) =>
1311 self.process_fn(item, &decl, ty_params, &body),
1312 Static(ref typ, _, ref expr) =>
1313 self.process_static_or_const_item(item, typ, expr),
1314 Const(ref typ, ref expr) =>
1315 self.process_static_or_const_item(item, &typ, &expr),
1316 Struct(ref def, ref ty_params) => self.process_struct(item, def, ty_params),
1317 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1322 ref impl_items) => {
1323 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1325 Trait(_, ref generics, ref trait_refs, ref methods) =>
1326 self.process_trait(item, generics, trait_refs, methods),
1328 self.process_mod(item);
1329 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1331 Ty(ref ty, ref ty_params) => {
1332 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1333 let value = ty_to_string(&ty);
1334 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1335 if !self.span.filter_generated(sub_span, item.span) {
1336 self.dumper.typedef(TypeDefData {
1337 span: sub_span.expect("No span found for typedef"),
1338 name: item.ident.to_string(),
1340 qualname: qualname.clone(),
1342 visibility: From::from(&item.vis),
1344 docs: docs_for_attrs(&item.attrs),
1345 sig: Some(self.save_ctxt.sig_base(item)),
1346 attributes: item.attrs.clone(),
1351 self.process_generic_params(ty_params, item.span, &qualname, item.id);
1354 _ => visit::walk_item(self, item),
1358 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1359 for param in generics.ty_params.iter() {
1360 for bound in param.bounds.iter() {
1361 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
1362 self.process_trait_ref(&trait_ref.trait_ref);
1365 if let Some(ref ty) = param.default {
1371 fn visit_ty(&mut self, t: &'l ast::Ty) {
1372 self.process_macro_use(t.span, t.id);
1374 ast::TyKind::Path(_, ref path) => {
1375 if generated_code(t.span) {
1379 if let Some(id) = self.lookup_def_id(t.id) {
1380 if let Some(sub_span) = self.span.sub_span_for_type_name(t.span) {
1381 self.dumper.type_ref(TypeRefData {
1384 scope: self.cur_scope,
1385 qualname: String::new()
1390 self.write_sub_paths_truncated(path);
1391 visit::walk_path(self, path);
1393 ast::TyKind::Array(ref element, ref length) => {
1394 self.visit_ty(element);
1395 self.nest_tables(length.id, |v| v.visit_expr(length));
1397 _ => visit::walk_ty(self, t),
1401 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1402 debug!("visit_expr {:?}", ex.node);
1403 self.process_macro_use(ex.span, ex.id);
1405 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1406 let hir_expr = self.save_ctxt.tcx.hir.expect_expr(ex.id);
1407 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1408 Some(ty) => ty.ty_adt_def().unwrap(),
1410 visit::walk_expr(self, ex);
1414 let def = self.save_ctxt.get_path_def(hir_expr.id);
1415 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1417 ast::ExprKind::MethodCall(.., ref args) => self.process_method_call(ex, args),
1418 ast::ExprKind::Field(ref sub_ex, _) => {
1419 self.visit_expr(&sub_ex);
1421 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1422 down_cast_data!(field_data, VariableRefData, ex.span);
1423 if !self.span.filter_generated(Some(field_data.span), ex.span) {
1424 self.dumper.variable_ref(field_data.lower(self.tcx));
1428 ast::ExprKind::TupField(ref sub_ex, idx) => {
1429 self.visit_expr(&sub_ex);
1431 let hir_node = match self.save_ctxt.tcx.hir.find(sub_ex.id) {
1432 Some(Node::NodeExpr(expr)) => expr,
1434 debug!("Missing or weird node for sub-expression {} in {:?}",
1439 let ty = match self.save_ctxt.tables.expr_ty_adjusted_opt(&hir_node) {
1440 Some(ty) => &ty.sty,
1442 visit::walk_expr(self, ex);
1447 ty::TyAdt(def, _) => {
1448 let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1449 if !self.span.filter_generated(sub_span, ex.span) {
1450 self.dumper.variable_ref(VariableRefData {
1451 span: sub_span.expect("No span found for var ref"),
1452 ref_id: def.struct_variant().fields[idx.node].did,
1453 scope: self.cur_scope,
1458 ty::TyTuple(..) => {}
1459 _ => span_bug!(ex.span,
1460 "Expected struct or tuple type, found {:?}",
1464 ast::ExprKind::Closure(_, ref decl, ref body, _fn_decl_span) => {
1465 let mut id = String::from("$");
1466 id.push_str(&ex.id.to_string());
1468 // walk arg and return types
1469 for arg in &decl.inputs {
1470 self.visit_ty(&arg.ty);
1473 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1474 self.visit_ty(&ret_ty);
1478 self.nest_tables(ex.id, |v| {
1479 v.process_formals(&decl.inputs, &id);
1480 v.nest_scope(ex.id, |v| v.visit_expr(body))
1483 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) |
1484 ast::ExprKind::WhileLet(ref pattern, ref subexpression, ref block, _) => {
1485 let value = self.span.snippet(subexpression.span);
1486 self.process_var_decl(pattern, value);
1487 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1488 visit::walk_expr(self, subexpression);
1489 visit::walk_block(self, block);
1491 ast::ExprKind::IfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
1492 let value = self.span.snippet(subexpression.span);
1493 self.process_var_decl(pattern, value);
1494 visit::walk_expr(self, subexpression);
1495 visit::walk_block(self, block);
1496 opt_else.as_ref().map(|el| visit::walk_expr(self, el));
1498 ast::ExprKind::Repeat(ref element, ref count) => {
1499 self.visit_expr(element);
1500 self.nest_tables(count.id, |v| v.visit_expr(count));
1502 // In particular, we take this branch for call and path expressions,
1503 // where we'll index the idents involved just by continuing to walk.
1505 visit::walk_expr(self, ex)
1510 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1511 // These shouldn't exist in the AST at this point, log a span bug.
1512 span_bug!(mac.span, "macro invocation should have been expanded out of AST");
1515 fn visit_pat(&mut self, p: &'l ast::Pat) {
1516 self.process_macro_use(p.span, p.id);
1517 self.process_pat(p);
1520 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1521 let mut collector = PathCollector::new();
1522 for pattern in &arm.pats {
1523 // collect paths from the arm's patterns
1524 collector.visit_pat(&pattern);
1525 self.visit_pat(&pattern);
1528 // This is to get around borrow checking, because we need mut self to call process_path.
1529 let mut paths_to_process = vec![];
1531 // process collected paths
1532 for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1533 match self.save_ctxt.get_path_def(id) {
1534 Def::Local(def_id) => {
1535 let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1536 let mut value = if immut == ast::Mutability::Immutable {
1537 self.span.snippet(p.span).to_string()
1539 "<mutable>".to_string()
1541 let typ = self.save_ctxt.tables.node_types
1542 .get(&id).map(|t| t.to_string()).unwrap_or(String::new());
1543 value.push_str(": ");
1544 value.push_str(&typ);
1546 assert!(p.segments.len() == 1,
1547 "qualified path for local variable def in arm");
1548 if !self.span.filter_generated(Some(p.span), p.span) {
1549 self.dumper.variable(VariableData {
1551 kind: VariableKind::Local,
1553 name: path_to_string(p),
1554 qualname: format!("{}${}", path_to_string(p), id),
1557 scope: CRATE_NODE_ID,
1559 visibility: Visibility::Inherited,
1560 docs: String::new(),
1566 Def::StructCtor(..) | Def::VariantCtor(..) |
1567 Def::Const(..) | Def::AssociatedConst(..) |
1568 Def::Struct(..) | Def::Variant(..) |
1569 Def::TyAlias(..) | Def::AssociatedTy(..) |
1570 Def::SelfTy(..) => {
1571 paths_to_process.push((id, p.clone(), Some(ref_kind)))
1573 def => error!("unexpected definition kind when processing collected paths: {:?}",
1578 for &(id, ref path, ref_kind) in &paths_to_process {
1579 self.process_path(id, path, ref_kind);
1581 walk_list!(self, visit_expr, &arm.guard);
1582 self.visit_expr(&arm.body);
1585 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1586 self.process_path(id, p, None);
1589 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1590 self.process_macro_use(s.span, s.id);
1591 visit::walk_stmt(self, s)
1594 fn visit_local(&mut self, l: &'l ast::Local) {
1595 self.process_macro_use(l.span, l.id);
1596 let value = l.init.as_ref().map(|i| self.span.snippet(i.span)).unwrap_or(String::new());
1597 self.process_var_decl(&l.pat, value);
1599 // Just walk the initialiser and type (don't want to walk the pattern again).
1600 walk_list!(self, visit_ty, &l.ty);
1601 walk_list!(self, visit_expr, &l.init);
1604 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1606 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1607 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1608 down_cast_data!(fn_data, FunctionData, item.span);
1609 if !self.span.filter_generated(Some(fn_data.span), item.span) {
1610 self.dumper.function(fn_data.clone().lower(self.tcx));
1613 self.nest_tables(item.id, |v| v.process_formals(&decl.inputs,
1614 &fn_data.qualname));
1615 self.process_generic_params(generics, item.span, &fn_data.qualname, item.id);
1618 for arg in &decl.inputs {
1619 self.visit_ty(&arg.ty);
1622 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1623 self.visit_ty(&ret_ty);
1626 ast::ForeignItemKind::Static(ref ty, _) => {
1627 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1628 down_cast_data!(var_data, VariableData, item.span);
1629 if !self.span.filter_generated(Some(var_data.span), item.span) {
1630 self.dumper.variable(var_data.lower(self.tcx));