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;
42 use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID};
43 use syntax::parse::token;
44 use syntax::symbol::keywords;
45 use syntax::visit::{self, Visitor};
46 use syntax::print::pprust::{path_to_string, ty_to_string, bounds_to_string, generics_to_string};
48 use syntax::codemap::Spanned;
51 use super::{escape, generated_code, SaveContext, PathCollector, docs_for_attrs};
53 use super::dump::Dump;
54 use super::external_data::{Lower, make_def_id};
55 use super::span_utils::SpanUtils;
58 use rls_data::ExternalCrateData;
60 macro_rules! down_cast_data {
61 ($id:ident, $kind:ident, $sp:expr) => {
62 let $id = if let super::Data::$kind(data) = $id {
65 span_bug!($sp, "unexpected data kind: {:?}", $id);
70 pub struct DumpVisitor<'l, 'tcx: 'l, 'll, D: 'll> {
71 save_ctxt: SaveContext<'l, 'tcx>,
73 tcx: TyCtxt<'l, 'tcx, 'tcx>,
80 // Set of macro definition (callee) spans, and the set
81 // of macro use (callsite) spans. We store these to ensure
82 // we only write one macro def per unique macro definition, and
83 // one macro use per unique callsite span.
84 mac_defs: HashSet<Span>,
85 mac_uses: HashSet<Span>,
88 impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> {
89 pub fn new(save_ctxt: SaveContext<'l, 'tcx>,
91 -> DumpVisitor<'l, 'tcx, 'll, D> {
92 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
94 sess: &save_ctxt.tcx.sess,
98 span: span_utils.clone(),
99 cur_scope: CRATE_NODE_ID,
100 mac_defs: HashSet::new(),
101 mac_uses: HashSet::new(),
105 fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
106 where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, D>)
108 let parent_scope = self.cur_scope;
109 self.cur_scope = scope_id;
111 self.cur_scope = parent_scope;
114 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
115 where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, D>)
117 let item_def_id = self.tcx.hir.local_def_id(item_id);
118 if self.tcx.has_typeck_tables(item_def_id) {
119 let tables = self.tcx.typeck_tables_of(item_def_id);
120 let old_tables = self.save_ctxt.tables;
121 self.save_ctxt.tables = tables;
123 self.save_ctxt.tables = old_tables;
129 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
130 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
131 let crate_root = source_file.map(|source_file| {
132 let source_file = Path::new(source_file);
133 match source_file.file_name() {
134 Some(_) => source_file.parent().unwrap().display().to_string(),
135 None => source_file.display().to_string(),
139 // Info about all the external crates referenced from this crate.
140 let external_crates = self.save_ctxt.get_external_crates().into_iter().map(|c| {
141 let lo_loc = self.span.sess.codemap().lookup_char_pos(c.span.lo);
145 file_name: SpanUtils::make_path_string(&lo_loc.file.name),
149 // The current crate.
150 let data = CratePreludeData {
151 crate_name: name.into(),
152 crate_root: crate_root.unwrap_or("<no source>".to_owned()),
153 external_crates: external_crates,
157 self.dumper.crate_prelude(data.lower(self.tcx));
160 // Return all non-empty prefixes of a path.
161 // For each prefix, we return the span for the last segment in the prefix and
162 // a str representation of the entire prefix.
163 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
164 let spans = self.span.spans_for_path_segments(path);
165 let segments = &path.segments[if path.is_global() { 1 } else { 0 }..];
167 // Paths to enums seem to not match their spans - the span includes all the
168 // variants too. But they seem to always be at the end, so I hope we can cope with
169 // always using the first ones. So, only error out if we don't have enough spans.
170 // What could go wrong...?
171 if spans.len() < segments.len() {
172 if generated_code(path.span) {
175 error!("Mis-calculated spans for path '{}'. Found {} spans, expected {}. Found spans:",
176 path_to_string(path),
180 let loc = self.sess.codemap().lookup_char_pos(s.lo);
181 error!(" '{}' in {}, line {}",
182 self.span.snippet(*s),
186 error!(" master span: {:?}: `{}`", path.span, self.span.snippet(path.span));
190 let mut result: Vec<(Span, String)> = vec![];
192 let mut segs = vec![];
193 for (i, (seg, span)) in segments.iter().zip(&spans).enumerate() {
194 segs.push(seg.clone());
195 let sub_path = ast::Path {
196 span: *span, // span for the last segment
199 let qualname = if i == 0 && path.is_global() {
200 format!("::{}", path_to_string(&sub_path))
202 path_to_string(&sub_path)
204 result.push((*span, qualname));
205 segs = sub_path.segments;
211 fn write_sub_paths(&mut self, path: &ast::Path) {
212 let sub_paths = self.process_path_prefixes(path);
213 for (span, qualname) in sub_paths {
214 self.dumper.mod_ref(ModRefData {
217 scope: self.cur_scope,
223 // As write_sub_paths, but does not process the last ident in the path (assuming it
224 // will be processed elsewhere). See note on write_sub_paths about global.
225 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
226 let sub_paths = self.process_path_prefixes(path);
227 let len = sub_paths.len();
232 for (span, qualname) in sub_paths.into_iter().take(len - 1) {
233 self.dumper.mod_ref(ModRefData {
236 scope: self.cur_scope,
242 // As write_sub_paths, but expects a path of the form module_path::trait::method
243 // Where trait could actually be a struct too.
244 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
245 let sub_paths = self.process_path_prefixes(path);
246 let len = sub_paths.len();
250 let sub_paths = &sub_paths[.. (len-1)];
252 // write the trait part of the sub-path
253 let (ref span, ref qualname) = sub_paths[len-2];
254 self.dumper.type_ref(TypeRefData {
257 qualname: qualname.to_owned(),
261 // write the other sub-paths
265 let sub_paths = &sub_paths[..len-2];
266 for &(ref span, ref qualname) in sub_paths {
267 self.dumper.mod_ref(ModRefData {
269 qualname: qualname.to_owned(),
270 scope: self.cur_scope,
276 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
277 match self.save_ctxt.get_path_def(ref_id) {
278 Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => None,
279 def => Some(def.def_id()),
283 fn process_def_kind(&mut self,
286 sub_span: Option<Span>,
289 if self.span.filter_generated(sub_span, span) {
293 let def = self.save_ctxt.get_path_def(ref_id);
296 self.dumper.mod_ref(ModRefData {
297 span: sub_span.expect("No span found for mod ref"),
298 ref_id: Some(def_id),
300 qualname: String::new()
309 self.dumper.type_ref(TypeRefData {
310 span: sub_span.expect("No span found for type ref"),
311 ref_id: Some(def_id),
313 qualname: String::new()
318 Def::StructCtor(..) |
319 Def::VariantCtor(..) => {
320 self.dumper.variable_ref(VariableRefData {
321 span: sub_span.expect("No span found for var ref"),
328 self.dumper.function_ref(FunctionRefData {
329 span: sub_span.expect("No span found for fn ref"),
334 // With macros 2.0, we can legitimately get a ref to a macro, but
335 // we don't handle it properly for now (FIXME).
343 Def::AssociatedTy(..) |
344 Def::AssociatedConst(..) |
349 "process_def_kind for unexpected item: {:?}",
355 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
357 self.visit_pat(&arg.pat);
358 let mut collector = PathCollector::new();
359 collector.visit_pat(&arg.pat);
360 let span_utils = self.span.clone();
361 for &(id, ref p, ..) in &collector.collected_paths {
362 let typ = match self.save_ctxt.tables.node_types.get(&id) {
363 Some(s) => s.to_string(),
366 // get the span only for the name of the variable (I hope the path is only ever a
367 // variable name, but who knows?)
368 let sub_span = span_utils.span_for_last_ident(p.span);
369 if !self.span.filter_generated(sub_span, p.span) {
370 self.dumper.variable(VariableData {
372 kind: VariableKind::Local,
373 span: sub_span.expect("No span found for variable"),
374 name: path_to_string(p),
375 qualname: format!("{}::{}", qualname, path_to_string(p)),
377 value: String::new(),
378 scope: CRATE_NODE_ID,
380 visibility: Visibility::Inherited,
390 fn process_method(&mut self,
391 sig: &'l ast::MethodSig,
392 body: Option<&'l ast::Block>,
396 attrs: &'l [Attribute],
398 debug!("process_method: {}:{}", id, name);
400 if let Some(method_data) = self.save_ctxt.get_method_data(id, name, span) {
402 let sig_str = ::make_signature(&sig.decl, &sig.generics);
404 self.nest_tables(id, |v| {
405 v.process_formals(&sig.decl.inputs, &method_data.qualname)
409 // If the method is defined in an impl, then try and find the corresponding
410 // method decl in a trait, and if there is one, make a decl_id for it. This
411 // requires looking up the impl, then the trait, then searching for a method
412 // with the right name.
413 if !self.span.filter_generated(Some(method_data.span), span) {
415 self.tcx.associated_item(self.tcx.hir.local_def_id(id)).container;
417 let mut decl_id = None;
419 AssociatedItemContainer::ImplContainer(id) => {
420 trait_id = self.tcx.trait_id_of_impl(id);
424 for item in self.tcx.associated_items(id) {
425 if item.kind == ty::AssociatedKind::Method {
426 if item.name == name {
427 decl_id = Some(item.def_id);
434 if let Some(NodeItem(item)) = self.tcx.hir.get_if_local(id) {
435 if let hir::ItemImpl(_, _, _, _, _, ref ty, _) = item.node {
436 trait_id = self.lookup_def_id(ty.id);
442 AssociatedItemContainer::TraitContainer(id) => {
447 self.dumper.method(MethodData {
449 name: method_data.name,
450 span: method_data.span,
451 scope: method_data.scope,
452 qualname: method_data.qualname.clone(),
457 docs: docs_for_attrs(attrs),
458 sig: method_data.sig,
459 attributes: attrs.to_vec(),
463 self.process_generic_params(&sig.generics, span, &method_data.qualname, id);
466 // walk arg and return types
467 for arg in &sig.decl.inputs {
468 self.visit_ty(&arg.ty);
471 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
472 self.visit_ty(ret_ty);
476 if let Some(body) = body {
477 self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
481 fn process_trait_ref(&mut self, trait_ref: &'l ast::TraitRef) {
482 let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref, self.cur_scope);
483 if let Some(trait_ref_data) = trait_ref_data {
484 if !self.span.filter_generated(Some(trait_ref_data.span), trait_ref.path.span) {
485 self.dumper.type_ref(trait_ref_data.lower(self.tcx));
488 self.process_path(trait_ref.ref_id, &trait_ref.path, Some(recorder::TypeRef));
491 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
492 let field_data = self.save_ctxt.get_field_data(field, parent_id);
493 if let Some(mut field_data) = field_data {
494 if !self.span.filter_generated(Some(field_data.span), field.span) {
495 field_data.value = String::new();
496 self.dumper.variable(field_data.lower(self.tcx));
501 // Dump generic params bindings, then visit_generics
502 fn process_generic_params(&mut self,
503 generics: &'l ast::Generics,
507 // We can't only use visit_generics since we don't have spans for param
508 // bindings, so we reparse the full_span to get those sub spans.
509 // However full span is the entire enum/fn/struct block, so we only want
510 // the first few to match the number of generics we're looking for.
511 let param_sub_spans = self.span.spans_for_ty_params(full_span,
512 (generics.ty_params.len() as isize));
513 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
514 let name = escape(self.span.snippet(param_ss));
515 // Append $id to name to make sure each one is unique
516 let qualname = format!("{}::{}${}",
520 if !self.span.filter_generated(Some(param_ss), full_span) {
521 self.dumper.typedef(TypeDefData {
526 value: String::new(),
527 visibility: Visibility::Inherited,
535 self.visit_generics(generics);
538 fn process_fn(&mut self,
540 decl: &'l ast::FnDecl,
541 ty_params: &'l ast::Generics,
542 body: &'l ast::Block) {
543 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
544 down_cast_data!(fn_data, FunctionData, item.span);
545 if !self.span.filter_generated(Some(fn_data.span), item.span) {
546 self.dumper.function(fn_data.clone().lower(self.tcx));
549 self.nest_tables(item.id, |v| v.process_formals(&decl.inputs, &fn_data.qualname));
550 self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
553 for arg in &decl.inputs {
554 self.visit_ty(&arg.ty);
557 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
558 self.visit_ty(&ret_ty);
561 self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
564 fn process_static_or_const_item(&mut self,
567 expr: &'l ast::Expr) {
568 if let Some(var_data) = self.save_ctxt.get_item_data(item) {
569 down_cast_data!(var_data, VariableData, item.span);
570 if !self.span.filter_generated(Some(var_data.span), item.span) {
571 self.dumper.variable(var_data.lower(self.tcx));
575 self.visit_expr(expr);
578 fn process_assoc_const(&mut self,
586 attrs: &'l [Attribute]) {
587 let qualname = format!("::{}", self.tcx.node_path_str(id));
589 let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
591 if !self.span.filter_generated(sub_span, span) {
592 self.dumper.variable(VariableData {
593 span: sub_span.expect("No span found for variable"),
594 kind: VariableKind::Const,
596 name: name.to_string(),
598 value: self.span.snippet(expr.span),
599 type_value: ty_to_string(&typ),
600 scope: self.cur_scope,
601 parent: Some(parent_id),
603 docs: docs_for_attrs(attrs),
605 attributes: attrs.to_vec(),
609 // walk type and init value
611 self.visit_expr(expr);
614 // FIXME tuple structs should generate tuple-specific data.
615 fn process_struct(&mut self,
617 def: &'l ast::VariantData,
618 ty_params: &'l ast::Generics) {
619 let name = item.ident.to_string();
620 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
622 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
624 if let ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, _), _) = item.node
626 let fields_str = fields.iter()
628 .map(|(i, f)| f.ident.map(|i| i.to_string())
629 .unwrap_or(i.to_string()))
632 (format!("{} {{ {} }}", name, fields_str), fields.iter().map(|f| f.id).collect())
634 (String::new(), vec![])
637 if !self.span.filter_generated(sub_span, item.span) {
638 self.dumper.struct_data(StructData {
639 span: sub_span.expect("No span found for struct"),
643 qualname: qualname.clone(),
644 scope: self.cur_scope,
647 visibility: From::from(&item.vis),
648 docs: docs_for_attrs(&item.attrs),
649 sig: self.save_ctxt.sig_base(item),
650 attributes: item.attrs.clone(),
654 for field in def.fields() {
655 self.process_struct_field_def(field, item.id);
656 self.visit_ty(&field.ty);
659 self.process_generic_params(ty_params, item.span, &qualname, item.id);
662 fn process_enum(&mut self,
664 enum_definition: &'l ast::EnumDef,
665 ty_params: &'l ast::Generics) {
666 let enum_data = self.save_ctxt.get_item_data(item);
667 let enum_data = match enum_data {
671 down_cast_data!(enum_data, EnumData, item.span);
672 if !self.span.filter_generated(Some(enum_data.span), item.span) {
673 self.dumper.enum_data(enum_data.clone().lower(self.tcx));
676 for variant in &enum_definition.variants {
677 let name = variant.node.name.name.to_string();
678 let mut qualname = enum_data.qualname.clone();
679 qualname.push_str("::");
680 qualname.push_str(&name);
682 let text = self.span.signature_string_for_span(variant.span);
683 let ident_start = text.find(&name).unwrap();
684 let ident_end = ident_start + name.len();
685 let sig = Signature {
688 ident_start: ident_start,
689 ident_end: ident_end,
694 match variant.node.data {
695 ast::VariantData::Struct(ref fields, _) => {
696 let sub_span = self.span.span_for_first_ident(variant.span);
697 let fields_str = fields.iter()
699 .map(|(i, f)| f.ident.map(|i| i.to_string())
700 .unwrap_or(i.to_string()))
703 let val = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
704 if !self.span.filter_generated(sub_span, variant.span) {
705 self.dumper.struct_variant(StructVariantData {
706 span: sub_span.expect("No span found for struct variant"),
707 id: variant.node.data.id(),
710 type_value: enum_data.qualname.clone(),
712 scope: enum_data.scope,
713 parent: Some(make_def_id(item.id, &self.tcx.hir)),
714 docs: docs_for_attrs(&variant.node.attrs),
716 attributes: variant.node.attrs.clone(),
721 let sub_span = self.span.span_for_first_ident(variant.span);
722 let mut val = format!("{}::{}", enum_data.name, name);
723 if let &ast::VariantData::Tuple(ref fields, _) = v {
725 val.push_str(&fields.iter()
726 .map(|f| ty_to_string(&f.ty))
731 if !self.span.filter_generated(sub_span, variant.span) {
732 self.dumper.tuple_variant(TupleVariantData {
733 span: sub_span.expect("No span found for tuple variant"),
734 id: variant.node.data.id(),
737 type_value: enum_data.qualname.clone(),
739 scope: enum_data.scope,
740 parent: Some(make_def_id(item.id, &self.tcx.hir)),
741 docs: docs_for_attrs(&variant.node.attrs),
743 attributes: variant.node.attrs.clone(),
750 for field in variant.node.data.fields() {
751 self.process_struct_field_def(field, variant.node.data.id());
752 self.visit_ty(&field.ty);
755 self.process_generic_params(ty_params, item.span, &enum_data.qualname, enum_data.id);
758 fn process_impl(&mut self,
760 type_parameters: &'l ast::Generics,
761 trait_ref: &'l Option<ast::TraitRef>,
763 impl_items: &'l [ast::ImplItem]) {
764 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
765 down_cast_data!(impl_data, ImplData, item.span);
766 if !self.span.filter_generated(Some(impl_data.span), item.span) {
767 self.dumper.impl_data(ImplData {
769 span: impl_data.span,
770 scope: impl_data.scope,
771 trait_ref: impl_data.trait_ref.map(|d| d.ref_id.unwrap()),
772 self_ref: impl_data.self_ref.map(|d| d.ref_id.unwrap())
777 if let &Some(ref trait_ref) = trait_ref {
778 self.process_path(trait_ref.ref_id, &trait_ref.path, Some(recorder::TypeRef));
780 self.process_generic_params(type_parameters, item.span, "", item.id);
781 for impl_item in impl_items {
782 let map = &self.tcx.hir;
783 self.process_impl_item(impl_item, make_def_id(item.id, map));
787 fn process_trait(&mut self,
789 generics: &'l ast::Generics,
790 trait_refs: &'l ast::TyParamBounds,
791 methods: &'l [ast::TraitItem]) {
792 let name = item.ident.to_string();
793 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
794 let mut val = name.clone();
795 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
796 val.push_str(&generics_to_string(generics));
798 if !trait_refs.is_empty() {
800 val.push_str(&bounds_to_string(trait_refs));
802 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
803 if !self.span.filter_generated(sub_span, item.span) {
804 self.dumper.trait_data(TraitData {
805 span: sub_span.expect("No span found for trait"),
808 qualname: qualname.clone(),
809 scope: self.cur_scope,
811 items: methods.iter().map(|i| i.id).collect(),
812 visibility: From::from(&item.vis),
813 docs: docs_for_attrs(&item.attrs),
814 sig: self.save_ctxt.sig_base(item),
815 attributes: item.attrs.clone(),
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(),
1088 /// Extract macro use and definition information from the AST node defined
1089 /// by the given NodeId, using the expansion information from the node's
1092 /// If the span is not macro-generated, do nothing, else use callee and
1093 /// callsite spans to record macro definition and use data, using the
1094 /// mac_uses and mac_defs sets to prevent multiples.
1095 fn process_macro_use(&mut self, span: Span, id: NodeId) {
1096 let data = match self.save_ctxt.get_macro_use_data(span, id) {
1100 let mut hasher = DefaultHasher::new();
1101 data.callee_span.hash(&mut hasher);
1102 let hash = hasher.finish();
1103 let qualname = format!("{}::{}", data.name, hash);
1104 // Don't write macro definition for imported macros
1105 if !self.mac_defs.contains(&data.callee_span)
1107 self.mac_defs.insert(data.callee_span);
1108 if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1109 self.dumper.macro_data(MacroData {
1111 name: data.name.clone(),
1112 qualname: qualname.clone(),
1113 // FIXME where do macro docs come from?
1114 docs: String::new(),
1118 if !self.mac_uses.contains(&data.span) {
1119 self.mac_uses.insert(data.span);
1120 if let Some(sub_span) = self.span.span_for_macro_use_name(data.span) {
1121 self.dumper.macro_use(MacroUseData {
1126 callee_span: data.callee_span,
1127 imported: data.imported,
1133 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1134 self.process_macro_use(trait_item.span, trait_item.id);
1135 match trait_item.node {
1136 ast::TraitItemKind::Const(ref ty, Some(ref expr)) => {
1137 self.process_assoc_const(trait_item.id,
1138 trait_item.ident.name,
1146 ast::TraitItemKind::Method(ref sig, ref body) => {
1147 self.process_method(sig,
1148 body.as_ref().map(|x| &**x),
1150 trait_item.ident.name,
1155 ast::TraitItemKind::Type(ref _bounds, ref default_ty) => {
1156 // FIXME do something with _bounds (for type refs)
1157 let name = trait_item.ident.name.to_string();
1158 let qualname = format!("::{}", self.tcx.node_path_str(trait_item.id));
1159 let sub_span = self.span.sub_span_after_keyword(trait_item.span, keywords::Type);
1161 if !self.span.filter_generated(sub_span, trait_item.span) {
1162 self.dumper.typedef(TypeDefData {
1163 span: sub_span.expect("No span found for assoc type"),
1167 value: self.span.snippet(trait_item.span),
1168 visibility: Visibility::Public,
1169 parent: Some(trait_id),
1170 docs: docs_for_attrs(&trait_item.attrs),
1172 attributes: trait_item.attrs.clone(),
1176 if let &Some(ref default_ty) = default_ty {
1177 self.visit_ty(default_ty)
1180 ast::TraitItemKind::Const(ref ty, None) => self.visit_ty(ty),
1181 ast::TraitItemKind::Macro(_) => {}
1185 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1186 self.process_macro_use(impl_item.span, impl_item.id);
1187 match impl_item.node {
1188 ast::ImplItemKind::Const(ref ty, ref expr) => {
1189 self.process_assoc_const(impl_item.id,
1190 impl_item.ident.name,
1195 From::from(&impl_item.vis),
1198 ast::ImplItemKind::Method(ref sig, ref body) => {
1199 self.process_method(sig,
1202 impl_item.ident.name,
1203 From::from(&impl_item.vis),
1207 ast::ImplItemKind::Type(ref ty) => self.visit_ty(ty),
1208 ast::ImplItemKind::Macro(_) => {}
1213 impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, D> {
1214 fn visit_item(&mut self, item: &'l ast::Item) {
1215 use syntax::ast::ItemKind::*;
1216 self.process_macro_use(item.span, item.id);
1218 Use(ref use_item) => {
1219 match use_item.node {
1220 ast::ViewPathSimple(ident, ref path) => {
1221 let sub_span = self.span.span_for_last_ident(path.span);
1222 let mod_id = match self.lookup_def_id(item.id) {
1224 let scope = self.cur_scope;
1225 self.process_def_kind(item.id, path.span, sub_span, def_id, scope);
1232 // 'use' always introduces an alias, if there is not an explicit
1233 // one, there is an implicit one.
1234 let sub_span = match self.span.sub_span_after_keyword(use_item.span,
1236 Some(sub_span) => Some(sub_span),
1240 if !self.span.filter_generated(sub_span, path.span) {
1241 self.dumper.use_data(UseData {
1242 span: sub_span.expect("No span found for use"),
1245 name: ident.to_string(),
1246 scope: self.cur_scope,
1247 visibility: From::from(&item.vis),
1250 self.write_sub_paths_truncated(path);
1252 ast::ViewPathGlob(ref path) => {
1253 // Make a comma-separated list of names of imported modules.
1254 let mut names = vec![];
1255 let glob_map = &self.save_ctxt.analysis.glob_map;
1256 let glob_map = glob_map.as_ref().unwrap();
1257 if glob_map.contains_key(&item.id) {
1258 for n in glob_map.get(&item.id).unwrap() {
1259 names.push(n.to_string());
1263 let sub_span = self.span
1264 .sub_span_of_token(item.span, token::BinOp(token::Star));
1265 if !self.span.filter_generated(sub_span, item.span) {
1266 self.dumper.use_glob(UseGlobData {
1267 span: sub_span.expect("No span found for use glob"),
1270 scope: self.cur_scope,
1271 visibility: From::from(&item.vis),
1274 self.write_sub_paths(path);
1276 ast::ViewPathList(ref path, ref list) => {
1278 let scope = self.cur_scope;
1279 let id = plid.node.id;
1280 if let Some(def_id) = self.lookup_def_id(id) {
1281 let span = plid.span;
1282 self.process_def_kind(id, span, Some(span), def_id, scope);
1286 self.write_sub_paths(path);
1290 ExternCrate(ref s) => {
1291 let location = match *s {
1292 Some(s) => s.to_string(),
1293 None => item.ident.to_string(),
1295 let alias_span = self.span.span_for_last_ident(item.span);
1296 let cnum = match self.sess.cstore.extern_mod_stmt_cnum(item.id) {
1298 None => LOCAL_CRATE,
1301 if !self.span.filter_generated(alias_span, item.span) {
1302 self.dumper.extern_crate(ExternCrateData {
1304 name: item.ident.to_string(),
1307 span: alias_span.expect("No span found for extern crate"),
1308 scope: self.cur_scope,
1312 Fn(ref decl, .., ref ty_params, ref body) =>
1313 self.process_fn(item, &decl, ty_params, &body),
1314 Static(ref typ, _, ref expr) =>
1315 self.process_static_or_const_item(item, typ, expr),
1316 Const(ref typ, ref expr) =>
1317 self.process_static_or_const_item(item, &typ, &expr),
1318 Struct(ref def, ref ty_params) => self.process_struct(item, def, ty_params),
1319 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1324 ref impl_items) => {
1325 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1327 Trait(_, ref generics, ref trait_refs, ref methods) =>
1328 self.process_trait(item, generics, trait_refs, methods),
1330 self.process_mod(item);
1331 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1333 Ty(ref ty, ref ty_params) => {
1334 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1335 let value = ty_to_string(&ty);
1336 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1337 if !self.span.filter_generated(sub_span, item.span) {
1338 self.dumper.typedef(TypeDefData {
1339 span: sub_span.expect("No span found for typedef"),
1340 name: item.ident.to_string(),
1342 qualname: qualname.clone(),
1344 visibility: From::from(&item.vis),
1346 docs: docs_for_attrs(&item.attrs),
1347 sig: Some(self.save_ctxt.sig_base(item)),
1348 attributes: item.attrs.clone(),
1353 self.process_generic_params(ty_params, item.span, &qualname, item.id);
1356 _ => visit::walk_item(self, item),
1360 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1361 for param in generics.ty_params.iter() {
1362 for bound in param.bounds.iter() {
1363 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
1364 self.process_trait_ref(&trait_ref.trait_ref);
1367 if let Some(ref ty) = param.default {
1373 fn visit_ty(&mut self, t: &'l ast::Ty) {
1374 self.process_macro_use(t.span, t.id);
1376 ast::TyKind::Path(_, ref path) => {
1377 if generated_code(t.span) {
1381 if let Some(id) = self.lookup_def_id(t.id) {
1382 if let Some(sub_span) = self.span.sub_span_for_type_name(t.span) {
1383 self.dumper.type_ref(TypeRefData {
1386 scope: self.cur_scope,
1387 qualname: String::new()
1392 self.write_sub_paths_truncated(path);
1393 visit::walk_path(self, path);
1395 ast::TyKind::Array(ref element, ref length) => {
1396 self.visit_ty(element);
1397 self.nest_tables(length.id, |v| v.visit_expr(length));
1399 _ => visit::walk_ty(self, t),
1403 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1404 debug!("visit_expr {:?}", ex.node);
1405 self.process_macro_use(ex.span, ex.id);
1407 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1408 let hir_expr = self.save_ctxt.tcx.hir.expect_expr(ex.id);
1409 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1410 Some(ty) => ty.ty_adt_def().unwrap(),
1412 visit::walk_expr(self, ex);
1416 let def = self.save_ctxt.get_path_def(hir_expr.id);
1417 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1419 ast::ExprKind::MethodCall(.., ref args) => self.process_method_call(ex, args),
1420 ast::ExprKind::Field(ref sub_ex, _) => {
1421 self.visit_expr(&sub_ex);
1423 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1424 down_cast_data!(field_data, VariableRefData, ex.span);
1425 if !self.span.filter_generated(Some(field_data.span), ex.span) {
1426 self.dumper.variable_ref(field_data.lower(self.tcx));
1430 ast::ExprKind::TupField(ref sub_ex, idx) => {
1431 self.visit_expr(&sub_ex);
1433 let hir_node = match self.save_ctxt.tcx.hir.find(sub_ex.id) {
1434 Some(Node::NodeExpr(expr)) => expr,
1436 debug!("Missing or weird node for sub-expression {} in {:?}",
1441 let ty = match self.save_ctxt.tables.expr_ty_adjusted_opt(&hir_node) {
1442 Some(ty) => &ty.sty,
1444 visit::walk_expr(self, ex);
1449 ty::TyAdt(def, _) => {
1450 let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1451 if !self.span.filter_generated(sub_span, ex.span) {
1452 self.dumper.variable_ref(VariableRefData {
1453 span: sub_span.expect("No span found for var ref"),
1454 ref_id: def.struct_variant().fields[idx.node].did,
1455 scope: self.cur_scope,
1460 ty::TyTuple(..) => {}
1461 _ => span_bug!(ex.span,
1462 "Expected struct or tuple type, found {:?}",
1466 ast::ExprKind::Closure(_, ref decl, ref body, _fn_decl_span) => {
1467 let mut id = String::from("$");
1468 id.push_str(&ex.id.to_string());
1470 // walk arg and return types
1471 for arg in &decl.inputs {
1472 self.visit_ty(&arg.ty);
1475 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1476 self.visit_ty(&ret_ty);
1480 self.nest_tables(ex.id, |v| {
1481 v.process_formals(&decl.inputs, &id);
1482 v.nest_scope(ex.id, |v| v.visit_expr(body))
1485 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) |
1486 ast::ExprKind::WhileLet(ref pattern, ref subexpression, ref block, _) => {
1487 let value = self.span.snippet(subexpression.span);
1488 self.process_var_decl(pattern, value);
1489 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1490 visit::walk_expr(self, subexpression);
1491 visit::walk_block(self, block);
1493 ast::ExprKind::IfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
1494 let value = self.span.snippet(subexpression.span);
1495 self.process_var_decl(pattern, value);
1496 visit::walk_expr(self, subexpression);
1497 visit::walk_block(self, block);
1498 opt_else.as_ref().map(|el| visit::walk_expr(self, el));
1500 ast::ExprKind::Repeat(ref element, ref count) => {
1501 self.visit_expr(element);
1502 self.nest_tables(count.id, |v| v.visit_expr(count));
1504 // In particular, we take this branch for call and path expressions,
1505 // where we'll index the idents involved just by continuing to walk.
1507 visit::walk_expr(self, ex)
1512 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1513 // These shouldn't exist in the AST at this point, log a span bug.
1514 span_bug!(mac.span, "macro invocation should have been expanded out of AST");
1517 fn visit_pat(&mut self, p: &'l ast::Pat) {
1518 self.process_macro_use(p.span, p.id);
1519 self.process_pat(p);
1522 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1523 let mut collector = PathCollector::new();
1524 for pattern in &arm.pats {
1525 // collect paths from the arm's patterns
1526 collector.visit_pat(&pattern);
1527 self.visit_pat(&pattern);
1530 // This is to get around borrow checking, because we need mut self to call process_path.
1531 let mut paths_to_process = vec![];
1533 // process collected paths
1534 for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1535 match self.save_ctxt.get_path_def(id) {
1536 Def::Local(def_id) => {
1537 let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1538 let mut value = if immut == ast::Mutability::Immutable {
1539 self.span.snippet(p.span).to_string()
1541 "<mutable>".to_string()
1543 let typ = self.save_ctxt.tables.node_types
1544 .get(&id).map(|t| t.to_string()).unwrap_or(String::new());
1545 value.push_str(": ");
1546 value.push_str(&typ);
1548 assert!(p.segments.len() == 1,
1549 "qualified path for local variable def in arm");
1550 if !self.span.filter_generated(Some(p.span), p.span) {
1551 self.dumper.variable(VariableData {
1553 kind: VariableKind::Local,
1555 name: path_to_string(p),
1556 qualname: format!("{}${}", path_to_string(p), id),
1559 scope: CRATE_NODE_ID,
1561 visibility: Visibility::Inherited,
1562 docs: String::new(),
1568 Def::StructCtor(..) | Def::VariantCtor(..) |
1569 Def::Const(..) | Def::AssociatedConst(..) |
1570 Def::Struct(..) | Def::Variant(..) |
1571 Def::TyAlias(..) | Def::AssociatedTy(..) |
1572 Def::SelfTy(..) => {
1573 paths_to_process.push((id, p.clone(), Some(ref_kind)))
1575 def => error!("unexpected definition kind when processing collected paths: {:?}",
1580 for &(id, ref path, ref_kind) in &paths_to_process {
1581 self.process_path(id, path, ref_kind);
1583 walk_list!(self, visit_expr, &arm.guard);
1584 self.visit_expr(&arm.body);
1587 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1588 self.process_path(id, p, None);
1591 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1592 self.process_macro_use(s.span, s.id);
1593 visit::walk_stmt(self, s)
1596 fn visit_local(&mut self, l: &'l ast::Local) {
1597 self.process_macro_use(l.span, l.id);
1598 let value = l.init.as_ref().map(|i| self.span.snippet(i.span)).unwrap_or(String::new());
1599 self.process_var_decl(&l.pat, value);
1601 // Just walk the initialiser and type (don't want to walk the pattern again).
1602 walk_list!(self, visit_ty, &l.ty);
1603 walk_list!(self, visit_expr, &l.init);
1606 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1608 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1609 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1610 down_cast_data!(fn_data, FunctionData, item.span);
1611 if !self.span.filter_generated(Some(fn_data.span), item.span) {
1612 self.dumper.function(fn_data.clone().lower(self.tcx));
1615 self.nest_tables(item.id, |v| v.process_formals(&decl.inputs,
1616 &fn_data.qualname));
1617 self.process_generic_params(generics, item.span, &fn_data.qualname, item.id);
1620 for arg in &decl.inputs {
1621 self.visit_ty(&arg.ty);
1624 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1625 self.visit_ty(&ret_ty);
1628 ast::ForeignItemKind::Static(ref ty, _) => {
1629 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1630 down_cast_data!(var_data, VariableData, item.span);
1631 if !self.span.filter_generated(Some(var_data.span), item.span) {
1632 self.dumper.variable(var_data.lower(self.tcx));