1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Write the output of rustc's analysis to an implementor of Dump. The data is
12 //! primarily designed to be used as input to the DXR tool, specifically its
13 //! Rust plugin. It could also be used by IDEs or other code browsing, search, or
14 //! cross-referencing tools.
16 //! Dumping the analysis is implemented by walking the AST and getting a bunch of
17 //! info out from all over the place. We use Def IDs to identify objects. The
18 //! tricky part is getting syntactic (span, source text) and semantic (reference
19 //! Def IDs) information for parts of expressions which the compiler has discarded.
20 //! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
21 //! path and a reference to `baz`, but we want spans and references for all three
24 //! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
25 //! from spans (e.g., the span for `bar` from the above example path).
26 //! DumpVisitor walks the AST and processes it, and an implementor of Dump
27 //! is used for recording the output in a format-agnostic way (see CsvDumper
31 use rustc::hir::def::Def;
32 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
33 use rustc::hir::map::{Node, NodeItem};
34 use rustc::session::Session;
35 use rustc::ty::{self, TyCtxt, AssociatedItemContainer};
37 use std::collections::HashSet;
38 use std::collections::hash_map::DefaultHasher;
41 use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID};
42 use syntax::parse::token;
43 use syntax::symbol::keywords;
44 use syntax::visit::{self, Visitor};
45 use syntax::print::pprust::{path_to_string, ty_to_string, bounds_to_string, generics_to_string};
47 use syntax::codemap::Spanned;
50 use super::{escape, generated_code, SaveContext, PathCollector, docs_for_attrs};
52 use super::dump::Dump;
53 use super::external_data::{Lower, make_def_id};
54 use super::span_utils::SpanUtils;
57 macro_rules! down_cast_data {
58 ($id:ident, $kind:ident, $sp:expr) => {
59 let $id = if let super::Data::$kind(data) = $id {
62 span_bug!($sp, "unexpected data kind: {:?}", $id);
67 pub struct DumpVisitor<'l, 'tcx: 'l, 'll, D: 'll> {
68 save_ctxt: SaveContext<'l, 'tcx>,
70 tcx: TyCtxt<'l, 'tcx, 'tcx>,
77 // Set of macro definition (callee) spans, and the set
78 // of macro use (callsite) spans. We store these to ensure
79 // we only write one macro def per unique macro definition, and
80 // one macro use per unique callsite span.
81 mac_defs: HashSet<Span>,
82 mac_uses: HashSet<Span>,
85 impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> {
86 pub fn new(save_ctxt: SaveContext<'l, 'tcx>,
88 -> DumpVisitor<'l, 'tcx, 'll, D> {
89 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
91 sess: &save_ctxt.tcx.sess,
95 span: span_utils.clone(),
96 cur_scope: CRATE_NODE_ID,
97 mac_defs: HashSet::new(),
98 mac_uses: HashSet::new(),
102 fn nest<F>(&mut self, scope_id: NodeId, f: F)
103 where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, D>)
105 let parent_scope = self.cur_scope;
106 self.cur_scope = scope_id;
108 self.cur_scope = parent_scope;
111 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
112 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
113 let crate_root = source_file.map(|source_file| {
114 match source_file.file_name() {
115 Some(_) => source_file.parent().unwrap().display().to_string(),
116 None => source_file.display().to_string(),
120 // Info about all the external crates referenced from this crate.
121 let external_crates = self.save_ctxt.get_external_crates().into_iter().map(|c| {
122 let lo_loc = self.span.sess.codemap().lookup_char_pos(c.span.lo);
125 num: CrateNum::from_u32(c.number),
126 file_name: SpanUtils::make_path_string(&lo_loc.file.name),
130 // The current crate.
131 let data = CratePreludeData {
132 crate_name: name.into(),
133 crate_root: crate_root.unwrap_or("<no source>".to_owned()),
134 external_crates: external_crates,
138 self.dumper.crate_prelude(data.lower(self.tcx));
141 // Return all non-empty prefixes of a path.
142 // For each prefix, we return the span for the last segment in the prefix and
143 // a str representation of the entire prefix.
144 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
145 let spans = self.span.spans_for_path_segments(path);
147 // Paths to enums seem to not match their spans - the span includes all the
148 // variants too. But they seem to always be at the end, so I hope we can cope with
149 // always using the first ones. So, only error out if we don't have enough spans.
150 // What could go wrong...?
151 if spans.len() < path.segments.len() {
152 if generated_code(path.span) {
155 error!("Mis-calculated spans for path '{}'. Found {} spans, expected {}. Found spans:",
156 path_to_string(path),
158 path.segments.len());
160 let loc = self.sess.codemap().lookup_char_pos(s.lo);
161 error!(" '{}' in {}, line {}",
162 self.span.snippet(*s),
166 error!(" master span: {:?}: `{}`", path.span, self.span.snippet(path.span));
170 let mut result: Vec<(Span, String)> = vec![];
172 let mut segs = vec![];
173 for (i, (seg, span)) in path.segments.iter().zip(&spans).enumerate() {
174 segs.push(seg.clone());
175 let sub_path = ast::Path {
176 span: *span, // span for the last segment
180 let qualname = if i == 0 && path.global {
181 format!("::{}", path_to_string(&sub_path))
183 path_to_string(&sub_path)
185 result.push((*span, qualname));
186 segs = sub_path.segments;
192 // The global arg allows us to override the global-ness of the path (which
193 // actually means 'does the path start with `::`', rather than 'is the path
194 // semantically global). We use the override for `use` imports (etc.) where
195 // the syntax is non-global, but the semantics are global.
196 fn write_sub_paths(&mut self, path: &ast::Path, global: bool) {
197 let sub_paths = self.process_path_prefixes(path);
198 for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
199 let qualname = if i == 0 && global && !path.global {
200 format!("::{}", qualname)
204 self.dumper.mod_ref(ModRefData {
207 scope: self.cur_scope,
213 // As write_sub_paths, but does not process the last ident in the path (assuming it
214 // will be processed elsewhere). See note on write_sub_paths about global.
215 fn write_sub_paths_truncated(&mut self, path: &ast::Path, global: bool) {
216 let sub_paths = self.process_path_prefixes(path);
217 let len = sub_paths.len();
222 let sub_paths = &sub_paths[..len-1];
223 for (i, &(ref span, ref qualname)) in sub_paths.iter().enumerate() {
224 let qualname = if i == 0 && global && !path.global {
225 format!("::{}", qualname)
229 self.dumper.mod_ref(ModRefData {
232 scope: self.cur_scope,
238 // As write_sub_paths, but expects a path of the form module_path::trait::method
239 // Where trait could actually be a struct too.
240 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
241 let sub_paths = self.process_path_prefixes(path);
242 let len = sub_paths.len();
246 let sub_paths = &sub_paths[.. (len-1)];
248 // write the trait part of the sub-path
249 let (ref span, ref qualname) = sub_paths[len-2];
250 self.dumper.type_ref(TypeRefData {
253 qualname: qualname.to_owned(),
257 // write the other sub-paths
261 let sub_paths = &sub_paths[..len-2];
262 for &(ref span, ref qualname) in sub_paths {
263 self.dumper.mod_ref(ModRefData {
265 qualname: qualname.to_owned(),
266 scope: self.cur_scope,
272 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
273 match self.save_ctxt.get_path_def(ref_id) {
274 Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => None,
275 def => Some(def.def_id()),
279 fn process_def_kind(&mut self,
282 sub_span: Option<Span>,
285 if self.span.filter_generated(sub_span, span) {
289 let def = self.save_ctxt.get_path_def(ref_id);
292 self.dumper.mod_ref(ModRefData {
293 span: sub_span.expect("No span found for mod ref"),
294 ref_id: Some(def_id),
296 qualname: String::new()
305 self.dumper.type_ref(TypeRefData {
306 span: sub_span.expect("No span found for type ref"),
307 ref_id: Some(def_id),
309 qualname: String::new()
314 Def::StructCtor(..) |
315 Def::VariantCtor(..) => {
316 self.dumper.variable_ref(VariableRefData {
317 span: sub_span.expect("No span found for var ref"),
324 self.dumper.function_ref(FunctionRefData {
325 span: sub_span.expect("No span found for fn ref"),
336 Def::AssociatedTy(..) |
337 Def::AssociatedConst(..) |
342 "process_def_kind for unexpected item: {:?}",
348 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
350 self.visit_pat(&arg.pat);
351 let mut collector = PathCollector::new();
352 collector.visit_pat(&arg.pat);
353 let span_utils = self.span.clone();
354 for &(id, ref p, ..) in &collector.collected_paths {
355 let typ = match self.tcx.tables().node_types.get(&id) {
356 Some(s) => s.to_string(),
359 // get the span only for the name of the variable (I hope the path is only ever a
360 // variable name, but who knows?)
361 let sub_span = span_utils.span_for_last_ident(p.span);
362 if !self.span.filter_generated(sub_span, p.span) {
363 self.dumper.variable(VariableData {
365 kind: VariableKind::Local,
366 span: sub_span.expect("No span found for variable"),
367 name: path_to_string(p),
368 qualname: format!("{}::{}", qualname, path_to_string(p)),
370 value: String::new(),
371 scope: CRATE_NODE_ID,
373 visibility: Visibility::Inherited,
381 fn process_method(&mut self,
382 sig: &'l ast::MethodSig,
383 body: Option<&'l ast::Block>,
387 attrs: &'l [Attribute],
389 debug!("process_method: {}:{}", id, name);
391 if let Some(method_data) = self.save_ctxt.get_method_data(id, name, span) {
393 let sig_str = ::make_signature(&sig.decl, &sig.generics);
395 self.process_formals(&sig.decl.inputs, &method_data.qualname);
398 // If the method is defined in an impl, then try and find the corresponding
399 // method decl in a trait, and if there is one, make a decl_id for it. This
400 // requires looking up the impl, then the trait, then searching for a method
401 // with the right name.
402 if !self.span.filter_generated(Some(method_data.span), span) {
404 self.tcx.associated_item(self.tcx.map.local_def_id(id)).container;
406 let mut decl_id = None;
408 AssociatedItemContainer::ImplContainer(id) => {
409 trait_id = self.tcx.trait_id_of_impl(id);
413 for item in self.tcx.associated_items(id) {
414 if item.kind == ty::AssociatedKind::Method {
415 if item.name == name {
416 decl_id = Some(item.def_id);
423 if let Some(NodeItem(item)) = self.tcx.map.get_if_local(id) {
424 if let hir::ItemImpl(_, _, _, _, ref ty, _) = item.node {
425 trait_id = self.lookup_def_id(ty.id);
431 AssociatedItemContainer::TraitContainer(id) => {
436 self.dumper.method(MethodData {
438 name: method_data.name,
439 span: method_data.span,
440 scope: method_data.scope,
441 qualname: method_data.qualname.clone(),
446 docs: docs_for_attrs(attrs),
450 self.process_generic_params(&sig.generics, span, &method_data.qualname, id);
453 // walk arg and return types
454 for arg in &sig.decl.inputs {
455 self.visit_ty(&arg.ty);
458 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
459 self.visit_ty(ret_ty);
463 if let Some(body) = body {
464 self.nest(id, |v| v.visit_block(body));
468 fn process_trait_ref(&mut self, trait_ref: &'l ast::TraitRef) {
469 let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref, self.cur_scope);
470 if let Some(trait_ref_data) = trait_ref_data {
471 if !self.span.filter_generated(Some(trait_ref_data.span), trait_ref.path.span) {
472 self.dumper.type_ref(trait_ref_data.lower(self.tcx));
475 visit::walk_path(self, &trait_ref.path);
479 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
480 let field_data = self.save_ctxt.get_field_data(field, parent_id);
481 if let Some(mut field_data) = field_data {
482 if !self.span.filter_generated(Some(field_data.span), field.span) {
483 field_data.value = String::new();
484 self.dumper.variable(field_data.lower(self.tcx));
489 // Dump generic params bindings, then visit_generics
490 fn process_generic_params(&mut self,
491 generics: &'l ast::Generics,
495 // We can't only use visit_generics since we don't have spans for param
496 // bindings, so we reparse the full_span to get those sub spans.
497 // However full span is the entire enum/fn/struct block, so we only want
498 // the first few to match the number of generics we're looking for.
499 let param_sub_spans = self.span.spans_for_ty_params(full_span,
500 (generics.ty_params.len() as isize));
501 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
502 let name = escape(self.span.snippet(param_ss));
503 // Append $id to name to make sure each one is unique
504 let qualname = format!("{}::{}${}",
508 if !self.span.filter_generated(Some(param_ss), full_span) {
509 self.dumper.typedef(TypeDefData {
514 value: String::new(),
515 visibility: Visibility::Inherited,
521 self.visit_generics(generics);
524 fn process_fn(&mut self,
526 decl: &'l ast::FnDecl,
527 ty_params: &'l ast::Generics,
528 body: &'l ast::Block) {
529 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
530 down_cast_data!(fn_data, FunctionData, item.span);
531 if !self.span.filter_generated(Some(fn_data.span), item.span) {
532 self.dumper.function(fn_data.clone().lower(self.tcx));
535 self.process_formals(&decl.inputs, &fn_data.qualname);
536 self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
539 for arg in &decl.inputs {
540 self.visit_ty(&arg.ty);
543 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
544 self.visit_ty(&ret_ty);
547 self.nest(item.id, |v| v.visit_block(&body));
550 fn process_static_or_const_item(&mut self,
553 expr: &'l ast::Expr) {
554 if let Some(var_data) = self.save_ctxt.get_item_data(item) {
555 down_cast_data!(var_data, VariableData, item.span);
556 if !self.span.filter_generated(Some(var_data.span), item.span) {
557 self.dumper.variable(var_data.lower(self.tcx));
561 self.visit_expr(expr);
564 fn process_assoc_const(&mut self,
572 attrs: &'l [Attribute]) {
573 let qualname = format!("::{}", self.tcx.node_path_str(id));
575 let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
577 if !self.span.filter_generated(sub_span, span) {
578 self.dumper.variable(VariableData {
579 span: sub_span.expect("No span found for variable"),
580 kind: VariableKind::Const,
582 name: name.to_string(),
584 value: self.span.snippet(expr.span),
585 type_value: ty_to_string(&typ),
586 scope: self.cur_scope,
587 parent: Some(parent_id),
589 docs: docs_for_attrs(attrs),
593 // walk type and init value
595 self.visit_expr(expr);
598 // FIXME tuple structs should generate tuple-specific data.
599 fn process_struct(&mut self,
601 def: &'l ast::VariantData,
602 ty_params: &'l ast::Generics) {
603 let name = item.ident.to_string();
604 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
606 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
608 if let ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, _), _) = item.node
610 let fields_str = fields.iter()
612 .map(|(i, f)| f.ident.map(|i| i.to_string())
613 .unwrap_or(i.to_string()))
616 (format!("{} {{ {} }}", name, fields_str), fields.iter().map(|f| f.id).collect())
618 (String::new(), vec![])
621 if !self.span.filter_generated(sub_span, item.span) {
622 let mut sig = self.sig_base(item);
623 sig.ident_start = sig.text.find(&name).expect("Name not in struct signature?");
624 sig.ident_end = sig.ident_start + name.len();
625 self.dumper.struct_data(StructData {
626 span: sub_span.expect("No span found for struct"),
630 qualname: qualname.clone(),
631 scope: self.cur_scope,
634 visibility: From::from(&item.vis),
635 docs: docs_for_attrs(&item.attrs),
640 for field in def.fields() {
641 self.process_struct_field_def(field, item.id);
642 self.visit_ty(&field.ty);
645 self.process_generic_params(ty_params, item.span, &qualname, item.id);
648 fn sig_base(&self, item: &ast::Item) -> Signature {
649 let text = self.span.signature_string_for_span(item.span).expect("Couldn't make signature");
651 span: mk_sp(item.span.lo, item.span.lo + BytePos(text.len() as u32)),
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 match variant.node.data {
681 ast::VariantData::Struct(ref fields, _) => {
682 let sub_span = self.span.span_for_first_ident(variant.span);
683 let fields_str = fields.iter()
685 .map(|(i, f)| f.ident.map(|i| i.to_string())
686 .unwrap_or(i.to_string()))
689 let val = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
690 if !self.span.filter_generated(sub_span, variant.span) {
691 self.dumper.struct_variant(StructVariantData {
692 span: sub_span.expect("No span found for struct variant"),
693 id: variant.node.data.id(),
696 type_value: enum_data.qualname.clone(),
698 scope: enum_data.scope,
699 parent: Some(make_def_id(item.id, &self.tcx.map)),
700 docs: docs_for_attrs(&variant.node.attrs),
705 let sub_span = self.span.span_for_first_ident(variant.span);
706 let mut val = format!("{}::{}", enum_data.name, name);
707 if let &ast::VariantData::Tuple(ref fields, _) = v {
709 val.push_str(&fields.iter()
710 .map(|f| ty_to_string(&f.ty))
715 if !self.span.filter_generated(sub_span, variant.span) {
716 self.dumper.tuple_variant(TupleVariantData {
717 span: sub_span.expect("No span found for tuple variant"),
718 id: variant.node.data.id(),
721 type_value: enum_data.qualname.clone(),
723 scope: enum_data.scope,
724 parent: Some(make_def_id(item.id, &self.tcx.map)),
725 docs: docs_for_attrs(&variant.node.attrs),
732 for field in variant.node.data.fields() {
733 self.process_struct_field_def(field, variant.node.data.id());
734 self.visit_ty(&field.ty);
737 self.process_generic_params(ty_params, item.span, &enum_data.qualname, enum_data.id);
740 fn process_impl(&mut self,
742 type_parameters: &'l ast::Generics,
743 trait_ref: &'l Option<ast::TraitRef>,
745 impl_items: &'l [ast::ImplItem]) {
746 let mut has_self_ref = false;
747 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
748 down_cast_data!(impl_data, ImplData, item.span);
749 if let Some(ref self_ref) = impl_data.self_ref {
751 if !self.span.filter_generated(Some(self_ref.span), item.span) {
752 self.dumper.type_ref(self_ref.clone().lower(self.tcx));
755 if let Some(ref trait_ref_data) = impl_data.trait_ref {
756 if !self.span.filter_generated(Some(trait_ref_data.span), item.span) {
757 self.dumper.type_ref(trait_ref_data.clone().lower(self.tcx));
760 visit::walk_path(self, &trait_ref.as_ref().unwrap().path);
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())
776 self.process_generic_params(type_parameters, item.span, "", item.id);
777 for impl_item in impl_items {
778 let map = &self.tcx.map;
779 self.process_impl_item(impl_item, make_def_id(item.id, map));
783 fn process_trait(&mut self,
785 generics: &'l ast::Generics,
786 trait_refs: &'l ast::TyParamBounds,
787 methods: &'l [ast::TraitItem]) {
788 let name = item.ident.to_string();
789 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
790 let mut val = name.clone();
791 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
792 val.push_str(&generics_to_string(generics));
794 if !trait_refs.is_empty() {
796 val.push_str(&bounds_to_string(trait_refs));
798 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
799 if !self.span.filter_generated(sub_span, item.span) {
800 self.dumper.trait_data(TraitData {
801 span: sub_span.expect("No span found for trait"),
804 qualname: qualname.clone(),
805 scope: self.cur_scope,
807 items: methods.iter().map(|i| i.id).collect(),
808 visibility: From::from(&item.vis),
809 docs: docs_for_attrs(&item.attrs),
814 for super_bound in trait_refs.iter() {
815 let trait_ref = match *super_bound {
816 ast::TraitTyParamBound(ref trait_ref, _) => {
819 ast::RegionTyParamBound(..) => {
824 let trait_ref = &trait_ref.trait_ref;
825 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
826 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
827 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
828 self.dumper.type_ref(TypeRefData {
829 span: sub_span.expect("No span found for trait ref"),
831 scope: self.cur_scope,
832 qualname: String::new()
836 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
837 let sub_span = sub_span.expect("No span for inheritance");
838 self.dumper.inheritance(InheritanceData {
847 // walk generics and methods
848 self.process_generic_params(generics, item.span, &qualname, item.id);
849 for method in methods {
850 let map = &self.tcx.map;
851 self.process_trait_item(method, make_def_id(item.id, map))
855 // `item` is the module in question, represented as an item.
856 fn process_mod(&mut self, item: &ast::Item) {
857 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
858 down_cast_data!(mod_data, ModData, item.span);
859 if !self.span.filter_generated(Some(mod_data.span), item.span) {
860 self.dumper.mod_data(mod_data.lower(self.tcx));
865 fn process_path(&mut self, id: NodeId, path: &ast::Path, ref_kind: Option<recorder::Row>) {
866 let path_data = self.save_ctxt.get_path_data(id, path);
867 if generated_code(path.span) && path_data.is_none() {
871 let path_data = match path_data {
879 Data::VariableRefData(vrd) => {
880 // FIXME: this whole block duplicates the code in process_def_kind
881 if !self.span.filter_generated(Some(vrd.span), path.span) {
883 Some(recorder::TypeRef) => {
884 self.dumper.type_ref(TypeRefData {
886 ref_id: Some(vrd.ref_id),
888 qualname: String::new()
891 Some(recorder::FnRef) => {
892 self.dumper.function_ref(FunctionRefData {
898 Some(recorder::ModRef) => {
899 self.dumper.mod_ref( ModRefData {
901 ref_id: Some(vrd.ref_id),
903 qualname: String::new()
906 Some(recorder::VarRef) | None
907 => self.dumper.variable_ref(vrd.lower(self.tcx))
912 Data::TypeRefData(trd) => {
913 if !self.span.filter_generated(Some(trd.span), path.span) {
914 self.dumper.type_ref(trd.lower(self.tcx));
917 Data::MethodCallData(mcd) => {
918 if !self.span.filter_generated(Some(mcd.span), path.span) {
919 self.dumper.method_call(mcd.lower(self.tcx));
922 Data::FunctionCallData(fcd) => {
923 if !self.span.filter_generated(Some(fcd.span), path.span) {
924 self.dumper.function_call(fcd.lower(self.tcx));
928 span_bug!(path.span, "Unexpected data: {:?}", path_data);
932 // Modules or types in the path prefix.
933 match self.save_ctxt.get_path_def(id) {
934 Def::Method(did) => {
935 let ti = self.tcx.associated_item(did);
936 if ti.kind == ty::AssociatedKind::Method && ti.method_has_self_argument {
937 self.write_sub_path_trait_truncated(path);
943 Def::StructCtor(..) |
944 Def::VariantCtor(..) |
945 Def::AssociatedConst(..) |
952 Def::AssociatedTy(..) => self.write_sub_paths_truncated(path, false),
957 fn process_struct_lit(&mut self,
960 fields: &'l [ast::Field],
961 variant: &'l ty::VariantDef,
962 base: &'l Option<P<ast::Expr>>) {
963 self.write_sub_paths_truncated(path, false);
965 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
966 down_cast_data!(struct_lit_data, TypeRefData, ex.span);
967 if !self.span.filter_generated(Some(struct_lit_data.span), ex.span) {
968 self.dumper.type_ref(struct_lit_data.lower(self.tcx));
971 let scope = self.save_ctxt.enclosing_scope(ex.id);
973 for field in fields {
974 if let Some(field_data) = self.save_ctxt
975 .get_field_ref_data(field, variant, scope) {
977 if !self.span.filter_generated(Some(field_data.span), field.ident.span) {
978 self.dumper.variable_ref(field_data.lower(self.tcx));
982 self.visit_expr(&field.expr)
986 walk_list!(self, visit_expr, base);
989 fn process_method_call(&mut self, ex: &'l ast::Expr, args: &'l [P<ast::Expr>]) {
990 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
991 down_cast_data!(mcd, MethodCallData, ex.span);
992 if !self.span.filter_generated(Some(mcd.span), ex.span) {
993 self.dumper.method_call(mcd.lower(self.tcx));
997 // walk receiver and args
998 walk_list!(self, visit_expr, args);
1001 fn process_pat(&mut self, p: &'l ast::Pat) {
1003 PatKind::Struct(ref path, ref fields, _) => {
1004 visit::walk_path(self, path);
1005 let adt = match self.tcx.tables().node_id_to_type_opt(p.id) {
1006 Some(ty) => ty.ty_adt_def().unwrap(),
1008 visit::walk_pat(self, p);
1012 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
1014 for &Spanned { node: ref field, span } in fields {
1015 let sub_span = self.span.span_for_first_ident(span);
1016 if let Some(f) = variant.find_field_named(field.ident.name) {
1017 if !self.span.filter_generated(sub_span, span) {
1018 self.dumper.variable_ref(VariableRefData {
1019 span: sub_span.expect("No span fund for var ref"),
1021 scope: self.cur_scope,
1026 self.visit_pat(&field.pat);
1029 _ => visit::walk_pat(self, p),
1034 fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
1035 // The local could declare multiple new vars, we must walk the
1036 // pattern and collect them all.
1037 let mut collector = PathCollector::new();
1038 collector.visit_pat(&p);
1041 for &(id, ref p, immut, _) in &collector.collected_paths {
1042 let mut value = match immut {
1043 ast::Mutability::Immutable => value.to_string(),
1046 let typ = match self.tcx.tables().node_types.get(&id) {
1048 let typ = typ.to_string();
1049 if !value.is_empty() {
1050 value.push_str(": ");
1052 value.push_str(&typ);
1055 None => String::new(),
1058 // Get the span only for the name of the variable (I hope the path
1059 // is only ever a variable name, but who knows?).
1060 let sub_span = self.span.span_for_last_ident(p.span);
1061 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1062 if !self.span.filter_generated(sub_span, p.span) {
1063 self.dumper.variable(VariableData {
1064 span: sub_span.expect("No span found for variable"),
1065 kind: VariableKind::Local,
1067 name: path_to_string(p),
1068 qualname: format!("{}${}", path_to_string(p), id),
1071 scope: CRATE_NODE_ID,
1073 visibility: Visibility::Inherited,
1074 docs: String::new(),
1080 /// Extract macro use and definition information from the AST node defined
1081 /// by the given NodeId, using the expansion information from the node's
1084 /// If the span is not macro-generated, do nothing, else use callee and
1085 /// callsite spans to record macro definition and use data, using the
1086 /// mac_uses and mac_defs sets to prevent multiples.
1087 fn process_macro_use(&mut self, span: Span, id: NodeId) {
1088 let data = match self.save_ctxt.get_macro_use_data(span, id) {
1092 let mut hasher = DefaultHasher::new();
1093 data.callee_span.hash(&mut hasher);
1094 let hash = hasher.finish();
1095 let qualname = format!("{}::{}", data.name, hash);
1096 // Don't write macro definition for imported macros
1097 if !self.mac_defs.contains(&data.callee_span)
1099 self.mac_defs.insert(data.callee_span);
1100 if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1101 self.dumper.macro_data(MacroData {
1103 name: data.name.clone(),
1104 qualname: qualname.clone(),
1105 // FIXME where do macro docs come from?
1106 docs: String::new(),
1110 if !self.mac_uses.contains(&data.span) {
1111 self.mac_uses.insert(data.span);
1112 if let Some(sub_span) = self.span.span_for_macro_use_name(data.span) {
1113 self.dumper.macro_use(MacroUseData {
1118 callee_span: data.callee_span,
1119 imported: data.imported,
1125 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1126 self.process_macro_use(trait_item.span, trait_item.id);
1127 match trait_item.node {
1128 ast::TraitItemKind::Const(ref ty, Some(ref expr)) => {
1129 self.process_assoc_const(trait_item.id,
1130 trait_item.ident.name,
1138 ast::TraitItemKind::Method(ref sig, ref body) => {
1139 self.process_method(sig,
1140 body.as_ref().map(|x| &**x),
1142 trait_item.ident.name,
1147 ast::TraitItemKind::Const(_, None) |
1148 ast::TraitItemKind::Type(..) |
1149 ast::TraitItemKind::Macro(_) => {}
1153 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1154 self.process_macro_use(impl_item.span, impl_item.id);
1155 match impl_item.node {
1156 ast::ImplItemKind::Const(ref ty, ref expr) => {
1157 self.process_assoc_const(impl_item.id,
1158 impl_item.ident.name,
1163 From::from(&impl_item.vis),
1166 ast::ImplItemKind::Method(ref sig, ref body) => {
1167 self.process_method(sig,
1170 impl_item.ident.name,
1171 From::from(&impl_item.vis),
1175 ast::ImplItemKind::Type(_) |
1176 ast::ImplItemKind::Macro(_) => {}
1181 impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, D> {
1182 fn visit_item(&mut self, item: &'l ast::Item) {
1183 use syntax::ast::ItemKind::*;
1184 self.process_macro_use(item.span, item.id);
1186 Use(ref use_item) => {
1187 match use_item.node {
1188 ast::ViewPathSimple(ident, ref path) => {
1189 let sub_span = self.span.span_for_last_ident(path.span);
1190 let mod_id = match self.lookup_def_id(item.id) {
1192 let scope = self.cur_scope;
1193 self.process_def_kind(item.id, path.span, sub_span, def_id, scope);
1200 // 'use' always introduces an alias, if there is not an explicit
1201 // one, there is an implicit one.
1202 let sub_span = match self.span.sub_span_after_keyword(use_item.span,
1204 Some(sub_span) => Some(sub_span),
1208 if !self.span.filter_generated(sub_span, path.span) {
1209 self.dumper.use_data(UseData {
1210 span: sub_span.expect("No span found for use"),
1213 name: ident.to_string(),
1214 scope: self.cur_scope,
1215 visibility: From::from(&item.vis),
1218 self.write_sub_paths_truncated(path, true);
1220 ast::ViewPathGlob(ref path) => {
1221 // Make a comma-separated list of names of imported modules.
1222 let mut names = vec![];
1223 let glob_map = &self.save_ctxt.analysis.glob_map;
1224 let glob_map = glob_map.as_ref().unwrap();
1225 if glob_map.contains_key(&item.id) {
1226 for n in glob_map.get(&item.id).unwrap() {
1227 names.push(n.to_string());
1231 let sub_span = self.span
1232 .sub_span_of_token(item.span, token::BinOp(token::Star));
1233 if !self.span.filter_generated(sub_span, item.span) {
1234 self.dumper.use_glob(UseGlobData {
1235 span: sub_span.expect("No span found for use glob"),
1238 scope: self.cur_scope,
1239 visibility: From::from(&item.vis),
1242 self.write_sub_paths(path, true);
1244 ast::ViewPathList(ref path, ref list) => {
1246 let scope = self.cur_scope;
1247 let id = plid.node.id;
1248 if let Some(def_id) = self.lookup_def_id(id) {
1249 let span = plid.span;
1250 self.process_def_kind(id, span, Some(span), def_id, scope);
1254 self.write_sub_paths(path, true);
1258 ExternCrate(ref s) => {
1259 let location = match *s {
1260 Some(s) => s.to_string(),
1261 None => item.ident.to_string(),
1263 let alias_span = self.span.span_for_last_ident(item.span);
1264 let cnum = match self.sess.cstore.extern_mod_stmt_cnum(item.id) {
1266 None => LOCAL_CRATE,
1269 if !self.span.filter_generated(alias_span, item.span) {
1270 self.dumper.extern_crate(ExternCrateData {
1272 name: item.ident.to_string(),
1275 span: alias_span.expect("No span found for extern crate"),
1276 scope: self.cur_scope,
1280 Fn(ref decl, .., ref ty_params, ref body) =>
1281 self.process_fn(item, &decl, ty_params, &body),
1282 Static(ref typ, _, ref expr) =>
1283 self.process_static_or_const_item(item, typ, expr),
1284 Const(ref typ, ref expr) =>
1285 self.process_static_or_const_item(item, &typ, &expr),
1286 Struct(ref def, ref ty_params) => self.process_struct(item, def, ty_params),
1287 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1292 ref impl_items) => {
1293 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1295 Trait(_, ref generics, ref trait_refs, ref methods) =>
1296 self.process_trait(item, generics, trait_refs, methods),
1298 self.process_mod(item);
1299 self.nest(item.id, |v| visit::walk_mod(v, m));
1301 Ty(ref ty, ref ty_params) => {
1302 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1303 let value = ty_to_string(&ty);
1304 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1305 if !self.span.filter_generated(sub_span, item.span) {
1306 self.dumper.typedef(TypeDefData {
1307 span: sub_span.expect("No span found for typedef"),
1308 name: item.ident.to_string(),
1310 qualname: qualname.clone(),
1312 visibility: From::from(&item.vis),
1314 docs: docs_for_attrs(&item.attrs),
1319 self.process_generic_params(ty_params, item.span, &qualname, item.id);
1322 _ => visit::walk_item(self, item),
1326 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1327 for param in generics.ty_params.iter() {
1328 for bound in param.bounds.iter() {
1329 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
1330 self.process_trait_ref(&trait_ref.trait_ref);
1333 if let Some(ref ty) = param.default {
1339 fn visit_ty(&mut self, t: &'l ast::Ty) {
1340 self.process_macro_use(t.span, t.id);
1342 ast::TyKind::Path(_, ref path) => {
1343 if self.span.filter_generated(None, t.span) {
1347 if let Some(id) = self.lookup_def_id(t.id) {
1348 let sub_span = self.span.sub_span_for_type_name(t.span);
1349 self.dumper.type_ref(TypeRefData {
1350 span: sub_span.expect("No span found for type ref"),
1352 scope: self.cur_scope,
1353 qualname: String::new()
1357 self.write_sub_paths_truncated(path, false);
1359 visit::walk_path(self, path);
1361 _ => visit::walk_ty(self, t),
1365 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1366 self.process_macro_use(ex.span, ex.id);
1368 ast::ExprKind::Call(ref _f, ref _args) => {
1369 // Don't need to do anything for function calls,
1370 // because just walking the callee path does what we want.
1371 visit::walk_expr(self, ex);
1373 ast::ExprKind::Path(_, ref path) => {
1374 self.process_path(ex.id, path, None);
1375 visit::walk_expr(self, ex);
1377 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1378 let hir_expr = self.save_ctxt.tcx.map.expect_expr(ex.id);
1379 let adt = match self.tcx.tables().expr_ty_opt(&hir_expr) {
1380 Some(ty) => ty.ty_adt_def().unwrap(),
1382 visit::walk_expr(self, ex);
1386 let def = self.save_ctxt.get_path_def(hir_expr.id);
1387 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1389 ast::ExprKind::MethodCall(.., ref args) => self.process_method_call(ex, args),
1390 ast::ExprKind::Field(ref sub_ex, _) => {
1391 self.visit_expr(&sub_ex);
1393 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1394 down_cast_data!(field_data, VariableRefData, ex.span);
1395 if !self.span.filter_generated(Some(field_data.span), ex.span) {
1396 self.dumper.variable_ref(field_data.lower(self.tcx));
1400 ast::ExprKind::TupField(ref sub_ex, idx) => {
1401 self.visit_expr(&sub_ex);
1403 let hir_node = match self.save_ctxt.tcx.map.find(sub_ex.id) {
1404 Some(Node::NodeExpr(expr)) => expr,
1406 debug!("Missing or weird node for sub-expression {} in {:?}",
1411 let ty = match self.tcx.tables().expr_ty_adjusted_opt(&hir_node) {
1412 Some(ty) => &ty.sty,
1414 visit::walk_expr(self, ex);
1419 ty::TyAdt(def, _) => {
1420 let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1421 if !self.span.filter_generated(sub_span, ex.span) {
1422 self.dumper.variable_ref(VariableRefData {
1423 span: sub_span.expect("No span found for var ref"),
1424 ref_id: def.struct_variant().fields[idx.node].did,
1425 scope: self.cur_scope,
1430 ty::TyTuple(_) => {}
1431 _ => span_bug!(ex.span,
1432 "Expected struct or tuple type, found {:?}",
1436 ast::ExprKind::Closure(_, ref decl, ref body, _fn_decl_span) => {
1437 let mut id = String::from("$");
1438 id.push_str(&ex.id.to_string());
1439 self.process_formals(&decl.inputs, &id);
1441 // walk arg and return types
1442 for arg in &decl.inputs {
1443 self.visit_ty(&arg.ty);
1446 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1447 self.visit_ty(&ret_ty);
1451 self.nest(ex.id, |v| v.visit_expr(body));
1453 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) |
1454 ast::ExprKind::WhileLet(ref pattern, ref subexpression, ref block, _) => {
1455 let value = self.span.snippet(subexpression.span);
1456 self.process_var_decl(pattern, value);
1457 visit::walk_expr(self, subexpression);
1458 visit::walk_block(self, block);
1460 ast::ExprKind::IfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
1461 let value = self.span.snippet(subexpression.span);
1462 self.process_var_decl(pattern, value);
1463 visit::walk_expr(self, subexpression);
1464 visit::walk_block(self, block);
1465 opt_else.as_ref().map(|el| visit::walk_expr(self, el));
1468 visit::walk_expr(self, ex)
1473 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1474 // These shouldn't exist in the AST at this point, log a span bug.
1475 span_bug!(mac.span, "macro invocation should have been expanded out of AST");
1478 fn visit_pat(&mut self, p: &'l ast::Pat) {
1479 self.process_macro_use(p.span, p.id);
1480 self.process_pat(p);
1483 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1484 let mut collector = PathCollector::new();
1485 for pattern in &arm.pats {
1486 // collect paths from the arm's patterns
1487 collector.visit_pat(&pattern);
1488 self.visit_pat(&pattern);
1491 // This is to get around borrow checking, because we need mut self to call process_path.
1492 let mut paths_to_process = vec![];
1494 // process collected paths
1495 for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1496 match self.save_ctxt.get_path_def(id) {
1497 Def::Local(def_id) => {
1498 let id = self.tcx.map.as_local_node_id(def_id).unwrap();
1499 let mut value = if immut == ast::Mutability::Immutable {
1500 self.span.snippet(p.span).to_string()
1502 "<mutable>".to_string()
1504 let typ = self.tcx.tables().node_types
1505 .get(&id).map(|t| t.to_string()).unwrap_or(String::new());
1506 value.push_str(": ");
1507 value.push_str(&typ);
1509 assert!(p.segments.len() == 1,
1510 "qualified path for local variable def in arm");
1511 if !self.span.filter_generated(Some(p.span), p.span) {
1512 self.dumper.variable(VariableData {
1514 kind: VariableKind::Local,
1516 name: path_to_string(p),
1517 qualname: format!("{}${}", path_to_string(p), id),
1520 scope: CRATE_NODE_ID,
1522 visibility: Visibility::Inherited,
1523 docs: String::new(),
1527 Def::StructCtor(..) | Def::VariantCtor(..) |
1528 Def::Const(..) | Def::AssociatedConst(..) |
1529 Def::Struct(..) | Def::Variant(..) |
1530 Def::TyAlias(..) | Def::AssociatedTy(..) |
1531 Def::SelfTy(..) => {
1532 paths_to_process.push((id, p.clone(), Some(ref_kind)))
1534 def => error!("unexpected definition kind when processing collected paths: {:?}",
1539 for &(id, ref path, ref_kind) in &paths_to_process {
1540 self.process_path(id, path, ref_kind);
1542 walk_list!(self, visit_expr, &arm.guard);
1543 self.visit_expr(&arm.body);
1546 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1547 self.process_macro_use(s.span, s.id);
1548 visit::walk_stmt(self, s)
1551 fn visit_local(&mut self, l: &'l ast::Local) {
1552 self.process_macro_use(l.span, l.id);
1553 let value = l.init.as_ref().map(|i| self.span.snippet(i.span)).unwrap_or(String::new());
1554 self.process_var_decl(&l.pat, value);
1556 // Just walk the initialiser and type (don't want to walk the pattern again).
1557 walk_list!(self, visit_ty, &l.ty);
1558 walk_list!(self, visit_expr, &l.init);