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(..) |
346 "process_def_kind for unexpected item: {:?}",
352 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
354 self.visit_pat(&arg.pat);
355 let mut collector = PathCollector::new();
356 collector.visit_pat(&arg.pat);
357 let span_utils = self.span.clone();
358 for &(id, ref p, ..) in &collector.collected_paths {
359 let typ = match self.save_ctxt.tables.node_types.get(&id) {
360 Some(s) => s.to_string(),
363 // get the span only for the name of the variable (I hope the path is only ever a
364 // variable name, but who knows?)
365 let sub_span = span_utils.span_for_last_ident(p.span);
366 if !self.span.filter_generated(sub_span, p.span) {
367 self.dumper.variable(VariableData {
369 kind: VariableKind::Local,
370 span: sub_span.expect("No span found for variable"),
371 name: path_to_string(p),
372 qualname: format!("{}::{}", qualname, path_to_string(p)),
374 value: String::new(),
375 scope: CRATE_NODE_ID,
377 visibility: Visibility::Inherited,
387 fn process_method(&mut self,
388 sig: &'l ast::MethodSig,
389 body: Option<&'l ast::Block>,
393 attrs: &'l [Attribute],
395 debug!("process_method: {}:{}", id, name);
397 if let Some(method_data) = self.save_ctxt.get_method_data(id, name, span) {
399 let sig_str = ::make_signature(&sig.decl, &sig.generics);
401 self.nest_tables(id, |v| {
402 v.process_formals(&sig.decl.inputs, &method_data.qualname)
406 // If the method is defined in an impl, then try and find the corresponding
407 // method decl in a trait, and if there is one, make a decl_id for it. This
408 // requires looking up the impl, then the trait, then searching for a method
409 // with the right name.
410 if !self.span.filter_generated(Some(method_data.span), span) {
412 self.tcx.associated_item(self.tcx.hir.local_def_id(id)).container;
414 let mut decl_id = None;
416 AssociatedItemContainer::ImplContainer(id) => {
417 trait_id = self.tcx.trait_id_of_impl(id);
421 for item in self.tcx.associated_items(id) {
422 if item.kind == ty::AssociatedKind::Method {
423 if item.name == name {
424 decl_id = Some(item.def_id);
431 if let Some(NodeItem(item)) = self.tcx.hir.get_if_local(id) {
432 if let hir::ItemImpl(_, _, _, _, ref ty, _) = item.node {
433 trait_id = self.lookup_def_id(ty.id);
439 AssociatedItemContainer::TraitContainer(id) => {
444 self.dumper.method(MethodData {
446 name: method_data.name,
447 span: method_data.span,
448 scope: method_data.scope,
449 qualname: method_data.qualname.clone(),
454 docs: docs_for_attrs(attrs),
455 sig: method_data.sig,
456 attributes: attrs.to_vec(),
460 self.process_generic_params(&sig.generics, span, &method_data.qualname, id);
463 // walk arg and return types
464 for arg in &sig.decl.inputs {
465 self.visit_ty(&arg.ty);
468 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
469 self.visit_ty(ret_ty);
473 if let Some(body) = body {
474 self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
478 fn process_trait_ref(&mut self, trait_ref: &'l ast::TraitRef) {
479 let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref, self.cur_scope);
480 if let Some(trait_ref_data) = trait_ref_data {
481 if !self.span.filter_generated(Some(trait_ref_data.span), trait_ref.path.span) {
482 self.dumper.type_ref(trait_ref_data.lower(self.tcx));
485 self.process_path(trait_ref.ref_id, &trait_ref.path, Some(recorder::TypeRef));
488 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
489 let field_data = self.save_ctxt.get_field_data(field, parent_id);
490 if let Some(mut field_data) = field_data {
491 if !self.span.filter_generated(Some(field_data.span), field.span) {
492 field_data.value = String::new();
493 self.dumper.variable(field_data.lower(self.tcx));
498 // Dump generic params bindings, then visit_generics
499 fn process_generic_params(&mut self,
500 generics: &'l ast::Generics,
504 // We can't only use visit_generics since we don't have spans for param
505 // bindings, so we reparse the full_span to get those sub spans.
506 // However full span is the entire enum/fn/struct block, so we only want
507 // the first few to match the number of generics we're looking for.
508 let param_sub_spans = self.span.spans_for_ty_params(full_span,
509 (generics.ty_params.len() as isize));
510 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
511 let name = escape(self.span.snippet(param_ss));
512 // Append $id to name to make sure each one is unique
513 let qualname = format!("{}::{}${}",
517 if !self.span.filter_generated(Some(param_ss), full_span) {
518 self.dumper.typedef(TypeDefData {
523 value: String::new(),
524 visibility: Visibility::Inherited,
532 self.visit_generics(generics);
535 fn process_fn(&mut self,
537 decl: &'l ast::FnDecl,
538 ty_params: &'l ast::Generics,
539 body: &'l ast::Block) {
540 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
541 down_cast_data!(fn_data, FunctionData, item.span);
542 if !self.span.filter_generated(Some(fn_data.span), item.span) {
543 self.dumper.function(fn_data.clone().lower(self.tcx));
546 self.nest_tables(item.id, |v| v.process_formals(&decl.inputs, &fn_data.qualname));
547 self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
550 for arg in &decl.inputs {
551 self.visit_ty(&arg.ty);
554 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
555 self.visit_ty(&ret_ty);
558 self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
561 fn process_static_or_const_item(&mut self,
564 expr: &'l ast::Expr) {
565 if let Some(var_data) = self.save_ctxt.get_item_data(item) {
566 down_cast_data!(var_data, VariableData, item.span);
567 if !self.span.filter_generated(Some(var_data.span), item.span) {
568 self.dumper.variable(var_data.lower(self.tcx));
572 self.visit_expr(expr);
575 fn process_assoc_const(&mut self,
583 attrs: &'l [Attribute]) {
584 let qualname = format!("::{}", self.tcx.node_path_str(id));
586 let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
588 if !self.span.filter_generated(sub_span, span) {
589 self.dumper.variable(VariableData {
590 span: sub_span.expect("No span found for variable"),
591 kind: VariableKind::Const,
593 name: name.to_string(),
595 value: self.span.snippet(expr.span),
596 type_value: ty_to_string(&typ),
597 scope: self.cur_scope,
598 parent: Some(parent_id),
600 docs: docs_for_attrs(attrs),
602 attributes: attrs.to_vec(),
606 // walk type and init value
608 self.visit_expr(expr);
611 // FIXME tuple structs should generate tuple-specific data.
612 fn process_struct(&mut self,
614 def: &'l ast::VariantData,
615 ty_params: &'l ast::Generics) {
616 let name = item.ident.to_string();
617 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
619 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
621 if let ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, _), _) = item.node
623 let fields_str = fields.iter()
625 .map(|(i, f)| f.ident.map(|i| i.to_string())
626 .unwrap_or(i.to_string()))
629 (format!("{} {{ {} }}", name, fields_str), fields.iter().map(|f| f.id).collect())
631 (String::new(), vec![])
634 if !self.span.filter_generated(sub_span, item.span) {
635 self.dumper.struct_data(StructData {
636 span: sub_span.expect("No span found for struct"),
640 qualname: qualname.clone(),
641 scope: self.cur_scope,
644 visibility: From::from(&item.vis),
645 docs: docs_for_attrs(&item.attrs),
646 sig: self.save_ctxt.sig_base(item),
647 attributes: item.attrs.clone(),
651 for field in def.fields() {
652 self.process_struct_field_def(field, item.id);
653 self.visit_ty(&field.ty);
656 self.process_generic_params(ty_params, item.span, &qualname, item.id);
659 fn process_enum(&mut self,
661 enum_definition: &'l ast::EnumDef,
662 ty_params: &'l ast::Generics) {
663 let enum_data = self.save_ctxt.get_item_data(item);
664 let enum_data = match enum_data {
668 down_cast_data!(enum_data, EnumData, item.span);
669 if !self.span.filter_generated(Some(enum_data.span), item.span) {
670 self.dumper.enum_data(enum_data.clone().lower(self.tcx));
673 for variant in &enum_definition.variants {
674 let name = variant.node.name.name.to_string();
675 let mut qualname = enum_data.qualname.clone();
676 qualname.push_str("::");
677 qualname.push_str(&name);
679 let text = self.span.signature_string_for_span(variant.span);
680 let ident_start = text.find(&name).unwrap();
681 let ident_end = ident_start + name.len();
682 let sig = Signature {
685 ident_start: ident_start,
686 ident_end: ident_end,
691 match variant.node.data {
692 ast::VariantData::Struct(ref fields, _) => {
693 let sub_span = self.span.span_for_first_ident(variant.span);
694 let fields_str = fields.iter()
696 .map(|(i, f)| f.ident.map(|i| i.to_string())
697 .unwrap_or(i.to_string()))
700 let val = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
701 if !self.span.filter_generated(sub_span, variant.span) {
702 self.dumper.struct_variant(StructVariantData {
703 span: sub_span.expect("No span found for struct variant"),
704 id: variant.node.data.id(),
707 type_value: enum_data.qualname.clone(),
709 scope: enum_data.scope,
710 parent: Some(make_def_id(item.id, &self.tcx.hir)),
711 docs: docs_for_attrs(&variant.node.attrs),
713 attributes: variant.node.attrs.clone(),
718 let sub_span = self.span.span_for_first_ident(variant.span);
719 let mut val = format!("{}::{}", enum_data.name, name);
720 if let &ast::VariantData::Tuple(ref fields, _) = v {
722 val.push_str(&fields.iter()
723 .map(|f| ty_to_string(&f.ty))
728 if !self.span.filter_generated(sub_span, variant.span) {
729 self.dumper.tuple_variant(TupleVariantData {
730 span: sub_span.expect("No span found for tuple variant"),
731 id: variant.node.data.id(),
734 type_value: enum_data.qualname.clone(),
736 scope: enum_data.scope,
737 parent: Some(make_def_id(item.id, &self.tcx.hir)),
738 docs: docs_for_attrs(&variant.node.attrs),
740 attributes: variant.node.attrs.clone(),
747 for field in variant.node.data.fields() {
748 self.process_struct_field_def(field, variant.node.data.id());
749 self.visit_ty(&field.ty);
752 self.process_generic_params(ty_params, item.span, &enum_data.qualname, enum_data.id);
755 fn process_impl(&mut self,
757 type_parameters: &'l ast::Generics,
758 trait_ref: &'l Option<ast::TraitRef>,
760 impl_items: &'l [ast::ImplItem]) {
761 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
762 down_cast_data!(impl_data, ImplData, item.span);
763 if !self.span.filter_generated(Some(impl_data.span), item.span) {
764 self.dumper.impl_data(ImplData {
766 span: impl_data.span,
767 scope: impl_data.scope,
768 trait_ref: impl_data.trait_ref.map(|d| d.ref_id.unwrap()),
769 self_ref: impl_data.self_ref.map(|d| d.ref_id.unwrap())
774 if let &Some(ref trait_ref) = trait_ref {
775 self.process_path(trait_ref.ref_id, &trait_ref.path, Some(recorder::TypeRef));
777 self.process_generic_params(type_parameters, item.span, "", item.id);
778 for impl_item in impl_items {
779 let map = &self.tcx.hir;
780 self.process_impl_item(impl_item, make_def_id(item.id, map));
784 fn process_trait(&mut self,
786 generics: &'l ast::Generics,
787 trait_refs: &'l ast::TyParamBounds,
788 methods: &'l [ast::TraitItem]) {
789 let name = item.ident.to_string();
790 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
791 let mut val = name.clone();
792 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
793 val.push_str(&generics_to_string(generics));
795 if !trait_refs.is_empty() {
797 val.push_str(&bounds_to_string(trait_refs));
799 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
800 if !self.span.filter_generated(sub_span, item.span) {
801 self.dumper.trait_data(TraitData {
802 span: sub_span.expect("No span found for trait"),
805 qualname: qualname.clone(),
806 scope: self.cur_scope,
808 items: methods.iter().map(|i| i.id).collect(),
809 visibility: From::from(&item.vis),
810 docs: docs_for_attrs(&item.attrs),
811 sig: self.save_ctxt.sig_base(item),
812 attributes: item.attrs.clone(),
817 for super_bound in trait_refs.iter() {
818 let trait_ref = match *super_bound {
819 ast::TraitTyParamBound(ref trait_ref, _) => {
822 ast::RegionTyParamBound(..) => {
827 let trait_ref = &trait_ref.trait_ref;
828 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
829 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
830 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
831 self.dumper.type_ref(TypeRefData {
832 span: sub_span.expect("No span found for trait ref"),
834 scope: self.cur_scope,
835 qualname: String::new()
839 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
840 let sub_span = sub_span.expect("No span for inheritance");
841 self.dumper.inheritance(InheritanceData {
850 // walk generics and methods
851 self.process_generic_params(generics, item.span, &qualname, item.id);
852 for method in methods {
853 let map = &self.tcx.hir;
854 self.process_trait_item(method, make_def_id(item.id, map))
858 // `item` is the module in question, represented as an item.
859 fn process_mod(&mut self, item: &ast::Item) {
860 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
861 down_cast_data!(mod_data, ModData, item.span);
862 if !self.span.filter_generated(Some(mod_data.span), item.span) {
863 self.dumper.mod_data(mod_data.lower(self.tcx));
868 fn process_path(&mut self, id: NodeId, path: &ast::Path, ref_kind: Option<recorder::Row>) {
869 let path_data = self.save_ctxt.get_path_data(id, path);
870 if generated_code(path.span) && path_data.is_none() {
874 let path_data = match path_data {
882 Data::VariableRefData(vrd) => {
883 // FIXME: this whole block duplicates the code in process_def_kind
884 if !self.span.filter_generated(Some(vrd.span), path.span) {
886 Some(recorder::TypeRef) => {
887 self.dumper.type_ref(TypeRefData {
889 ref_id: Some(vrd.ref_id),
891 qualname: String::new()
894 Some(recorder::FnRef) => {
895 self.dumper.function_ref(FunctionRefData {
901 Some(recorder::ModRef) => {
902 self.dumper.mod_ref( ModRefData {
904 ref_id: Some(vrd.ref_id),
906 qualname: String::new()
909 Some(recorder::VarRef) | None
910 => self.dumper.variable_ref(vrd.lower(self.tcx))
915 Data::TypeRefData(trd) => {
916 if !self.span.filter_generated(Some(trd.span), path.span) {
917 self.dumper.type_ref(trd.lower(self.tcx));
920 Data::MethodCallData(mcd) => {
921 if !self.span.filter_generated(Some(mcd.span), path.span) {
922 self.dumper.method_call(mcd.lower(self.tcx));
925 Data::FunctionCallData(fcd) => {
926 if !self.span.filter_generated(Some(fcd.span), path.span) {
927 self.dumper.function_call(fcd.lower(self.tcx));
931 span_bug!(path.span, "Unexpected data: {:?}", path_data);
935 // Modules or types in the path prefix.
936 match self.save_ctxt.get_path_def(id) {
937 Def::Method(did) => {
938 let ti = self.tcx.associated_item(did);
939 if ti.kind == ty::AssociatedKind::Method && ti.method_has_self_argument {
940 self.write_sub_path_trait_truncated(path);
946 Def::StructCtor(..) |
947 Def::VariantCtor(..) |
948 Def::AssociatedConst(..) |
955 Def::AssociatedTy(..) => self.write_sub_paths_truncated(path),
960 fn process_struct_lit(&mut self,
963 fields: &'l [ast::Field],
964 variant: &'l ty::VariantDef,
965 base: &'l Option<P<ast::Expr>>) {
966 self.write_sub_paths_truncated(path);
968 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
969 down_cast_data!(struct_lit_data, TypeRefData, ex.span);
970 if !self.span.filter_generated(Some(struct_lit_data.span), ex.span) {
971 self.dumper.type_ref(struct_lit_data.lower(self.tcx));
974 let scope = self.save_ctxt.enclosing_scope(ex.id);
976 for field in fields {
977 if let Some(field_data) = self.save_ctxt
978 .get_field_ref_data(field, variant, scope) {
980 if !self.span.filter_generated(Some(field_data.span), field.ident.span) {
981 self.dumper.variable_ref(field_data.lower(self.tcx));
985 self.visit_expr(&field.expr)
989 walk_list!(self, visit_expr, base);
992 fn process_method_call(&mut self, ex: &'l ast::Expr, args: &'l [P<ast::Expr>]) {
993 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
994 down_cast_data!(mcd, MethodCallData, ex.span);
995 if !self.span.filter_generated(Some(mcd.span), ex.span) {
996 self.dumper.method_call(mcd.lower(self.tcx));
1000 // walk receiver and args
1001 walk_list!(self, visit_expr, args);
1004 fn process_pat(&mut self, p: &'l ast::Pat) {
1006 PatKind::Struct(ref _path, ref fields, _) => {
1007 // FIXME do something with _path?
1008 let adt = match self.save_ctxt.tables.node_id_to_type_opt(p.id) {
1009 Some(ty) => ty.ty_adt_def().unwrap(),
1011 visit::walk_pat(self, p);
1015 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
1017 for &Spanned { node: ref field, span } in fields {
1018 let sub_span = self.span.span_for_first_ident(span);
1019 if let Some(f) = variant.find_field_named(field.ident.name) {
1020 if !self.span.filter_generated(sub_span, span) {
1021 self.dumper.variable_ref(VariableRefData {
1022 span: sub_span.expect("No span fund for var ref"),
1024 scope: self.cur_scope,
1029 self.visit_pat(&field.pat);
1032 _ => visit::walk_pat(self, p),
1037 fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
1038 // The local could declare multiple new vars, we must walk the
1039 // pattern and collect them all.
1040 let mut collector = PathCollector::new();
1041 collector.visit_pat(&p);
1044 for &(id, ref p, immut, _) in &collector.collected_paths {
1045 let mut value = match immut {
1046 ast::Mutability::Immutable => value.to_string(),
1049 let typ = match self.save_ctxt.tables.node_types.get(&id) {
1051 let typ = typ.to_string();
1052 if !value.is_empty() {
1053 value.push_str(": ");
1055 value.push_str(&typ);
1058 None => String::new(),
1061 // Get the span only for the name of the variable (I hope the path
1062 // is only ever a variable name, but who knows?).
1063 let sub_span = self.span.span_for_last_ident(p.span);
1064 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1065 if !self.span.filter_generated(sub_span, p.span) {
1066 self.dumper.variable(VariableData {
1067 span: sub_span.expect("No span found for variable"),
1068 kind: VariableKind::Local,
1070 name: path_to_string(p),
1071 qualname: format!("{}${}", path_to_string(p), id),
1074 scope: CRATE_NODE_ID,
1076 visibility: Visibility::Inherited,
1077 docs: String::new(),
1085 /// Extract macro use and definition information from the AST node defined
1086 /// by the given NodeId, using the expansion information from the node's
1089 /// If the span is not macro-generated, do nothing, else use callee and
1090 /// callsite spans to record macro definition and use data, using the
1091 /// mac_uses and mac_defs sets to prevent multiples.
1092 fn process_macro_use(&mut self, span: Span, id: NodeId) {
1093 let data = match self.save_ctxt.get_macro_use_data(span, id) {
1097 let mut hasher = DefaultHasher::new();
1098 data.callee_span.hash(&mut hasher);
1099 let hash = hasher.finish();
1100 let qualname = format!("{}::{}", data.name, hash);
1101 // Don't write macro definition for imported macros
1102 if !self.mac_defs.contains(&data.callee_span)
1104 self.mac_defs.insert(data.callee_span);
1105 if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1106 self.dumper.macro_data(MacroData {
1108 name: data.name.clone(),
1109 qualname: qualname.clone(),
1110 // FIXME where do macro docs come from?
1111 docs: String::new(),
1115 if !self.mac_uses.contains(&data.span) {
1116 self.mac_uses.insert(data.span);
1117 if let Some(sub_span) = self.span.span_for_macro_use_name(data.span) {
1118 self.dumper.macro_use(MacroUseData {
1123 callee_span: data.callee_span,
1124 imported: data.imported,
1130 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1131 self.process_macro_use(trait_item.span, trait_item.id);
1132 match trait_item.node {
1133 ast::TraitItemKind::Const(ref ty, Some(ref expr)) => {
1134 self.process_assoc_const(trait_item.id,
1135 trait_item.ident.name,
1143 ast::TraitItemKind::Method(ref sig, ref body) => {
1144 self.process_method(sig,
1145 body.as_ref().map(|x| &**x),
1147 trait_item.ident.name,
1152 ast::TraitItemKind::Type(ref _bounds, ref default_ty) => {
1153 // FIXME do something with _bounds (for type refs)
1154 let name = trait_item.ident.name.to_string();
1155 let qualname = format!("::{}", self.tcx.node_path_str(trait_item.id));
1156 let sub_span = self.span.sub_span_after_keyword(trait_item.span, keywords::Type);
1158 if !self.span.filter_generated(sub_span, trait_item.span) {
1159 self.dumper.typedef(TypeDefData {
1160 span: sub_span.expect("No span found for assoc type"),
1164 value: self.span.snippet(trait_item.span),
1165 visibility: Visibility::Public,
1166 parent: Some(trait_id),
1167 docs: docs_for_attrs(&trait_item.attrs),
1169 attributes: trait_item.attrs.clone(),
1173 if let &Some(ref default_ty) = default_ty {
1174 self.visit_ty(default_ty)
1177 ast::TraitItemKind::Const(ref ty, None) => self.visit_ty(ty),
1178 ast::TraitItemKind::Macro(_) => {}
1182 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1183 self.process_macro_use(impl_item.span, impl_item.id);
1184 match impl_item.node {
1185 ast::ImplItemKind::Const(ref ty, ref expr) => {
1186 self.process_assoc_const(impl_item.id,
1187 impl_item.ident.name,
1192 From::from(&impl_item.vis),
1195 ast::ImplItemKind::Method(ref sig, ref body) => {
1196 self.process_method(sig,
1199 impl_item.ident.name,
1200 From::from(&impl_item.vis),
1204 ast::ImplItemKind::Type(ref ty) => self.visit_ty(ty),
1205 ast::ImplItemKind::Macro(_) => {}
1210 impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, D> {
1211 fn visit_item(&mut self, item: &'l ast::Item) {
1212 use syntax::ast::ItemKind::*;
1213 self.process_macro_use(item.span, item.id);
1215 Use(ref use_item) => {
1216 match use_item.node {
1217 ast::ViewPathSimple(ident, ref path) => {
1218 let sub_span = self.span.span_for_last_ident(path.span);
1219 let mod_id = match self.lookup_def_id(item.id) {
1221 let scope = self.cur_scope;
1222 self.process_def_kind(item.id, path.span, sub_span, def_id, scope);
1229 // 'use' always introduces an alias, if there is not an explicit
1230 // one, there is an implicit one.
1231 let sub_span = match self.span.sub_span_after_keyword(use_item.span,
1233 Some(sub_span) => Some(sub_span),
1237 if !self.span.filter_generated(sub_span, path.span) {
1238 self.dumper.use_data(UseData {
1239 span: sub_span.expect("No span found for use"),
1242 name: ident.to_string(),
1243 scope: self.cur_scope,
1244 visibility: From::from(&item.vis),
1247 self.write_sub_paths_truncated(path);
1249 ast::ViewPathGlob(ref path) => {
1250 // Make a comma-separated list of names of imported modules.
1251 let mut names = vec![];
1252 let glob_map = &self.save_ctxt.analysis.glob_map;
1253 let glob_map = glob_map.as_ref().unwrap();
1254 if glob_map.contains_key(&item.id) {
1255 for n in glob_map.get(&item.id).unwrap() {
1256 names.push(n.to_string());
1260 let sub_span = self.span
1261 .sub_span_of_token(item.span, token::BinOp(token::Star));
1262 if !self.span.filter_generated(sub_span, item.span) {
1263 self.dumper.use_glob(UseGlobData {
1264 span: sub_span.expect("No span found for use glob"),
1267 scope: self.cur_scope,
1268 visibility: From::from(&item.vis),
1271 self.write_sub_paths(path);
1273 ast::ViewPathList(ref path, ref list) => {
1275 let scope = self.cur_scope;
1276 let id = plid.node.id;
1277 if let Some(def_id) = self.lookup_def_id(id) {
1278 let span = plid.span;
1279 self.process_def_kind(id, span, Some(span), def_id, scope);
1283 self.write_sub_paths(path);
1287 ExternCrate(ref s) => {
1288 let location = match *s {
1289 Some(s) => s.to_string(),
1290 None => item.ident.to_string(),
1292 let alias_span = self.span.span_for_last_ident(item.span);
1293 let cnum = match self.sess.cstore.extern_mod_stmt_cnum(item.id) {
1295 None => LOCAL_CRATE,
1298 if !self.span.filter_generated(alias_span, item.span) {
1299 self.dumper.extern_crate(ExternCrateData {
1301 name: item.ident.to_string(),
1304 span: alias_span.expect("No span found for extern crate"),
1305 scope: self.cur_scope,
1309 Fn(ref decl, .., ref ty_params, ref body) =>
1310 self.process_fn(item, &decl, ty_params, &body),
1311 Static(ref typ, _, ref expr) =>
1312 self.process_static_or_const_item(item, typ, expr),
1313 Const(ref typ, ref expr) =>
1314 self.process_static_or_const_item(item, &typ, &expr),
1315 Struct(ref def, ref ty_params) => self.process_struct(item, def, ty_params),
1316 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1321 ref impl_items) => {
1322 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1324 Trait(_, ref generics, ref trait_refs, ref methods) =>
1325 self.process_trait(item, generics, trait_refs, methods),
1327 self.process_mod(item);
1328 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1330 Ty(ref ty, ref ty_params) => {
1331 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1332 let value = ty_to_string(&ty);
1333 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1334 if !self.span.filter_generated(sub_span, item.span) {
1335 self.dumper.typedef(TypeDefData {
1336 span: sub_span.expect("No span found for typedef"),
1337 name: item.ident.to_string(),
1339 qualname: qualname.clone(),
1341 visibility: From::from(&item.vis),
1343 docs: docs_for_attrs(&item.attrs),
1344 sig: Some(self.save_ctxt.sig_base(item)),
1345 attributes: item.attrs.clone(),
1350 self.process_generic_params(ty_params, item.span, &qualname, item.id);
1353 _ => visit::walk_item(self, item),
1357 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1358 for param in generics.ty_params.iter() {
1359 for bound in param.bounds.iter() {
1360 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
1361 self.process_trait_ref(&trait_ref.trait_ref);
1364 if let Some(ref ty) = param.default {
1370 fn visit_ty(&mut self, t: &'l ast::Ty) {
1371 self.process_macro_use(t.span, t.id);
1373 ast::TyKind::Path(_, ref path) => {
1374 if generated_code(t.span) {
1378 if let Some(id) = self.lookup_def_id(t.id) {
1379 if let Some(sub_span) = self.span.sub_span_for_type_name(t.span) {
1380 self.dumper.type_ref(TypeRefData {
1383 scope: self.cur_scope,
1384 qualname: String::new()
1389 self.write_sub_paths_truncated(path);
1390 visit::walk_path(self, path);
1392 ast::TyKind::Array(ref element, ref length) => {
1393 self.visit_ty(element);
1394 self.nest_tables(length.id, |v| v.visit_expr(length));
1396 _ => visit::walk_ty(self, t),
1400 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1401 debug!("visit_expr {:?}", ex.node);
1402 self.process_macro_use(ex.span, ex.id);
1404 ast::ExprKind::Call(ref _f, ref _args) => {
1405 // Don't need to do anything for function calls,
1406 // because just walking the callee path does what we want.
1407 visit::walk_expr(self, ex);
1409 ast::ExprKind::Path(_, ref path) => {
1410 self.process_path(ex.id, path, None);
1411 visit::walk_expr(self, ex);
1413 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1414 let hir_expr = self.save_ctxt.tcx.hir.expect_expr(ex.id);
1415 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1416 Some(ty) => ty.ty_adt_def().unwrap(),
1418 visit::walk_expr(self, ex);
1422 let def = self.save_ctxt.get_path_def(hir_expr.id);
1423 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1425 ast::ExprKind::MethodCall(.., ref args) => self.process_method_call(ex, args),
1426 ast::ExprKind::Field(ref sub_ex, _) => {
1427 self.visit_expr(&sub_ex);
1429 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1430 down_cast_data!(field_data, VariableRefData, ex.span);
1431 if !self.span.filter_generated(Some(field_data.span), ex.span) {
1432 self.dumper.variable_ref(field_data.lower(self.tcx));
1436 ast::ExprKind::TupField(ref sub_ex, idx) => {
1437 self.visit_expr(&sub_ex);
1439 let hir_node = match self.save_ctxt.tcx.hir.find(sub_ex.id) {
1440 Some(Node::NodeExpr(expr)) => expr,
1442 debug!("Missing or weird node for sub-expression {} in {:?}",
1447 let ty = match self.save_ctxt.tables.expr_ty_adjusted_opt(&hir_node) {
1448 Some(ty) => &ty.sty,
1450 visit::walk_expr(self, ex);
1455 ty::TyAdt(def, _) => {
1456 let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1457 if !self.span.filter_generated(sub_span, ex.span) {
1458 self.dumper.variable_ref(VariableRefData {
1459 span: sub_span.expect("No span found for var ref"),
1460 ref_id: def.struct_variant().fields[idx.node].did,
1461 scope: self.cur_scope,
1466 ty::TyTuple(..) => {}
1467 _ => span_bug!(ex.span,
1468 "Expected struct or tuple type, found {:?}",
1472 ast::ExprKind::Closure(_, ref decl, ref body, _fn_decl_span) => {
1473 let mut id = String::from("$");
1474 id.push_str(&ex.id.to_string());
1476 // walk arg and return types
1477 for arg in &decl.inputs {
1478 self.visit_ty(&arg.ty);
1481 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1482 self.visit_ty(&ret_ty);
1486 self.nest_tables(ex.id, |v| {
1487 v.process_formals(&decl.inputs, &id);
1488 v.nest_scope(ex.id, |v| v.visit_expr(body))
1491 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) |
1492 ast::ExprKind::WhileLet(ref pattern, ref subexpression, ref block, _) => {
1493 let value = self.span.snippet(subexpression.span);
1494 self.process_var_decl(pattern, value);
1495 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1496 visit::walk_expr(self, subexpression);
1497 visit::walk_block(self, block);
1499 ast::ExprKind::IfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
1500 let value = self.span.snippet(subexpression.span);
1501 self.process_var_decl(pattern, value);
1502 visit::walk_expr(self, subexpression);
1503 visit::walk_block(self, block);
1504 opt_else.as_ref().map(|el| visit::walk_expr(self, el));
1506 ast::ExprKind::Repeat(ref element, ref count) => {
1507 self.visit_expr(element);
1508 self.nest_tables(count.id, |v| v.visit_expr(count));
1511 visit::walk_expr(self, ex)
1516 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1517 // These shouldn't exist in the AST at this point, log a span bug.
1518 span_bug!(mac.span, "macro invocation should have been expanded out of AST");
1521 fn visit_pat(&mut self, p: &'l ast::Pat) {
1522 self.process_macro_use(p.span, p.id);
1523 self.process_pat(p);
1526 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1527 let mut collector = PathCollector::new();
1528 for pattern in &arm.pats {
1529 // collect paths from the arm's patterns
1530 collector.visit_pat(&pattern);
1531 self.visit_pat(&pattern);
1534 // This is to get around borrow checking, because we need mut self to call process_path.
1535 let mut paths_to_process = vec![];
1537 // process collected paths
1538 for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1539 match self.save_ctxt.get_path_def(id) {
1540 Def::Local(def_id) => {
1541 let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1542 let mut value = if immut == ast::Mutability::Immutable {
1543 self.span.snippet(p.span).to_string()
1545 "<mutable>".to_string()
1547 let typ = self.save_ctxt.tables.node_types
1548 .get(&id).map(|t| t.to_string()).unwrap_or(String::new());
1549 value.push_str(": ");
1550 value.push_str(&typ);
1552 assert!(p.segments.len() == 1,
1553 "qualified path for local variable def in arm");
1554 if !self.span.filter_generated(Some(p.span), p.span) {
1555 self.dumper.variable(VariableData {
1557 kind: VariableKind::Local,
1559 name: path_to_string(p),
1560 qualname: format!("{}${}", path_to_string(p), id),
1563 scope: CRATE_NODE_ID,
1565 visibility: Visibility::Inherited,
1566 docs: String::new(),
1572 Def::StructCtor(..) | Def::VariantCtor(..) |
1573 Def::Const(..) | Def::AssociatedConst(..) |
1574 Def::Struct(..) | Def::Variant(..) |
1575 Def::TyAlias(..) | Def::AssociatedTy(..) |
1576 Def::SelfTy(..) => {
1577 paths_to_process.push((id, p.clone(), Some(ref_kind)))
1579 def => error!("unexpected definition kind when processing collected paths: {:?}",
1584 for &(id, ref path, ref_kind) in &paths_to_process {
1585 self.process_path(id, path, ref_kind);
1587 walk_list!(self, visit_expr, &arm.guard);
1588 self.visit_expr(&arm.body);
1591 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1592 self.process_path(id, p, None);
1595 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1596 self.process_macro_use(s.span, s.id);
1597 visit::walk_stmt(self, s)
1600 fn visit_local(&mut self, l: &'l ast::Local) {
1601 self.process_macro_use(l.span, l.id);
1602 let value = l.init.as_ref().map(|i| self.span.snippet(i.span)).unwrap_or(String::new());
1603 self.process_var_decl(&l.pat, value);
1605 // Just walk the initialiser and type (don't want to walk the pattern again).
1606 walk_list!(self, visit_ty, &l.ty);
1607 walk_list!(self, visit_expr, &l.init);