1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Write the output of rustc's analysis to an implementor of Dump. The data is
12 //! primarily designed to be used as input to the DXR tool, specifically its
13 //! Rust plugin. It could also be used by IDEs or other code browsing, search, or
14 //! cross-referencing tools.
16 //! Dumping the analysis is implemented by walking the AST and getting a bunch of
17 //! info out from all over the place. We use Def IDs to identify objects. The
18 //! tricky part is getting syntactic (span, source text) and semantic (reference
19 //! Def IDs) information for parts of expressions which the compiler has discarded.
20 //! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
21 //! path and a reference to `baz`, but we want spans and references for all three
24 //! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
25 //! from spans (e.g., the span for `bar` from the above example path).
26 //! DumpVisitor walks the AST and processes it, and an implementor of Dump
27 //! is used for recording the output in a format-agnostic way (see CsvDumper
31 use rustc::hir::def::Def;
32 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
33 use rustc::hir::map::{Node, NodeItem};
34 use rustc::session::Session;
35 use rustc::ty::{self, TyCtxt, AssociatedItemContainer};
37 use std::collections::HashSet;
38 use std::collections::hash_map::DefaultHasher;
41 use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID};
42 use syntax::parse::token;
43 use syntax::symbol::keywords;
44 use syntax::visit::{self, Visitor};
45 use syntax::print::pprust::{path_to_string, ty_to_string, bounds_to_string, generics_to_string};
47 use syntax::codemap::Spanned;
50 use super::{escape, generated_code, SaveContext, PathCollector, docs_for_attrs};
52 use super::dump::Dump;
53 use super::external_data::{Lower, make_def_id};
54 use super::span_utils::SpanUtils;
57 macro_rules! down_cast_data {
58 ($id:ident, $kind:ident, $sp:expr) => {
59 let $id = if let super::Data::$kind(data) = $id {
62 span_bug!($sp, "unexpected data kind: {:?}", $id);
67 pub struct DumpVisitor<'l, 'tcx: 'l, 'll, D: 'll> {
68 save_ctxt: SaveContext<'l, 'tcx>,
70 tcx: TyCtxt<'l, 'tcx, 'tcx>,
77 // Set of macro definition (callee) spans, and the set
78 // of macro use (callsite) spans. We store these to ensure
79 // we only write one macro def per unique macro definition, and
80 // one macro use per unique callsite span.
81 mac_defs: HashSet<Span>,
82 mac_uses: HashSet<Span>,
85 impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> {
86 pub fn new(save_ctxt: SaveContext<'l, 'tcx>,
88 -> DumpVisitor<'l, 'tcx, 'll, D> {
89 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
91 sess: &save_ctxt.tcx.sess,
95 span: span_utils.clone(),
96 cur_scope: CRATE_NODE_ID,
97 mac_defs: HashSet::new(),
98 mac_uses: HashSet::new(),
102 fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
103 where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, D>)
105 let parent_scope = self.cur_scope;
106 self.cur_scope = scope_id;
108 self.cur_scope = parent_scope;
111 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
112 where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, D>)
114 let old_tables = self.save_ctxt.tables;
115 let item_def_id = self.tcx.hir.local_def_id(item_id);
116 self.save_ctxt.tables = self.tcx.item_tables(item_def_id);
118 self.save_ctxt.tables = old_tables;
121 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
122 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
123 let crate_root = source_file.map(|source_file| {
124 match source_file.file_name() {
125 Some(_) => source_file.parent().unwrap().display().to_string(),
126 None => source_file.display().to_string(),
130 // Info about all the external crates referenced from this crate.
131 let external_crates = self.save_ctxt.get_external_crates().into_iter().map(|c| {
132 let lo_loc = self.span.sess.codemap().lookup_char_pos(c.span.lo);
135 num: CrateNum::from_u32(c.number),
136 file_name: SpanUtils::make_path_string(&lo_loc.file.name),
140 // The current crate.
141 let data = CratePreludeData {
142 crate_name: name.into(),
143 crate_root: crate_root.unwrap_or("<no source>".to_owned()),
144 external_crates: external_crates,
148 self.dumper.crate_prelude(data.lower(self.tcx));
151 // Return all non-empty prefixes of a path.
152 // For each prefix, we return the span for the last segment in the prefix and
153 // a str representation of the entire prefix.
154 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
155 let spans = self.span.spans_for_path_segments(path);
156 let segments = &path.segments[if path.is_global() { 1 } else { 0 }..];
158 // Paths to enums seem to not match their spans - the span includes all the
159 // variants too. But they seem to always be at the end, so I hope we can cope with
160 // always using the first ones. So, only error out if we don't have enough spans.
161 // What could go wrong...?
162 if spans.len() < segments.len() {
163 if generated_code(path.span) {
166 error!("Mis-calculated spans for path '{}'. Found {} spans, expected {}. Found spans:",
167 path_to_string(path),
171 let loc = self.sess.codemap().lookup_char_pos(s.lo);
172 error!(" '{}' in {}, line {}",
173 self.span.snippet(*s),
177 error!(" master span: {:?}: `{}`", path.span, self.span.snippet(path.span));
181 let mut result: Vec<(Span, String)> = vec![];
183 let mut segs = vec![];
184 for (i, (seg, span)) in segments.iter().zip(&spans).enumerate() {
185 segs.push(seg.clone());
186 let sub_path = ast::Path {
187 span: *span, // span for the last segment
190 let qualname = if i == 0 && path.is_global() {
191 format!("::{}", path_to_string(&sub_path))
193 path_to_string(&sub_path)
195 result.push((*span, qualname));
196 segs = sub_path.segments;
202 fn write_sub_paths(&mut self, path: &ast::Path) {
203 let sub_paths = self.process_path_prefixes(path);
204 for (span, qualname) in sub_paths {
205 self.dumper.mod_ref(ModRefData {
208 scope: self.cur_scope,
214 // As write_sub_paths, but does not process the last ident in the path (assuming it
215 // will be processed elsewhere). See note on write_sub_paths about global.
216 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
217 let sub_paths = self.process_path_prefixes(path);
218 let len = sub_paths.len();
223 for (span, qualname) in sub_paths.into_iter().take(len - 1) {
224 self.dumper.mod_ref(ModRefData {
227 scope: self.cur_scope,
233 // As write_sub_paths, but expects a path of the form module_path::trait::method
234 // Where trait could actually be a struct too.
235 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
236 let sub_paths = self.process_path_prefixes(path);
237 let len = sub_paths.len();
241 let sub_paths = &sub_paths[.. (len-1)];
243 // write the trait part of the sub-path
244 let (ref span, ref qualname) = sub_paths[len-2];
245 self.dumper.type_ref(TypeRefData {
248 qualname: qualname.to_owned(),
252 // write the other sub-paths
256 let sub_paths = &sub_paths[..len-2];
257 for &(ref span, ref qualname) in sub_paths {
258 self.dumper.mod_ref(ModRefData {
260 qualname: qualname.to_owned(),
261 scope: self.cur_scope,
267 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
268 match self.save_ctxt.get_path_def(ref_id) {
269 Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => None,
270 def => Some(def.def_id()),
274 fn process_def_kind(&mut self,
277 sub_span: Option<Span>,
280 if self.span.filter_generated(sub_span, span) {
284 let def = self.save_ctxt.get_path_def(ref_id);
287 self.dumper.mod_ref(ModRefData {
288 span: sub_span.expect("No span found for mod ref"),
289 ref_id: Some(def_id),
291 qualname: String::new()
300 self.dumper.type_ref(TypeRefData {
301 span: sub_span.expect("No span found for type ref"),
302 ref_id: Some(def_id),
304 qualname: String::new()
309 Def::StructCtor(..) |
310 Def::VariantCtor(..) => {
311 self.dumper.variable_ref(VariableRefData {
312 span: sub_span.expect("No span found for var ref"),
319 self.dumper.function_ref(FunctionRefData {
320 span: sub_span.expect("No span found for fn ref"),
331 Def::AssociatedTy(..) |
332 Def::AssociatedConst(..) |
337 "process_def_kind for unexpected item: {:?}",
343 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
345 self.visit_pat(&arg.pat);
346 let mut collector = PathCollector::new();
347 collector.visit_pat(&arg.pat);
348 let span_utils = self.span.clone();
349 for &(id, ref p, ..) in &collector.collected_paths {
350 let typ = match self.save_ctxt.tables.node_types.get(&id) {
351 Some(s) => s.to_string(),
354 // get the span only for the name of the variable (I hope the path is only ever a
355 // variable name, but who knows?)
356 let sub_span = span_utils.span_for_last_ident(p.span);
357 if !self.span.filter_generated(sub_span, p.span) {
358 self.dumper.variable(VariableData {
360 kind: VariableKind::Local,
361 span: sub_span.expect("No span found for variable"),
362 name: path_to_string(p),
363 qualname: format!("{}::{}", qualname, path_to_string(p)),
365 value: String::new(),
366 scope: CRATE_NODE_ID,
368 visibility: Visibility::Inherited,
377 fn process_method(&mut self,
378 sig: &'l ast::MethodSig,
379 body: Option<&'l ast::Block>,
383 attrs: &'l [Attribute],
385 debug!("process_method: {}:{}", id, name);
387 if let Some(method_data) = self.save_ctxt.get_method_data(id, name, span) {
389 let sig_str = ::make_signature(&sig.decl, &sig.generics);
391 self.nest_tables(id, |v| {
392 v.process_formals(&sig.decl.inputs, &method_data.qualname)
396 // If the method is defined in an impl, then try and find the corresponding
397 // method decl in a trait, and if there is one, make a decl_id for it. This
398 // requires looking up the impl, then the trait, then searching for a method
399 // with the right name.
400 if !self.span.filter_generated(Some(method_data.span), span) {
402 self.tcx.associated_item(self.tcx.hir.local_def_id(id)).container;
404 let mut decl_id = None;
406 AssociatedItemContainer::ImplContainer(id) => {
407 trait_id = self.tcx.trait_id_of_impl(id);
411 for item in self.tcx.associated_items(id) {
412 if item.kind == ty::AssociatedKind::Method {
413 if item.name == name {
414 decl_id = Some(item.def_id);
421 if let Some(NodeItem(item)) = self.tcx.hir.get_if_local(id) {
422 if let hir::ItemImpl(_, _, _, _, ref ty, _) = item.node {
423 trait_id = self.lookup_def_id(ty.id);
429 AssociatedItemContainer::TraitContainer(id) => {
434 self.dumper.method(MethodData {
436 name: method_data.name,
437 span: method_data.span,
438 scope: method_data.scope,
439 qualname: method_data.qualname.clone(),
444 docs: docs_for_attrs(attrs),
445 sig: method_data.sig,
449 self.process_generic_params(&sig.generics, span, &method_data.qualname, id);
452 // walk arg and return types
453 for arg in &sig.decl.inputs {
454 self.visit_ty(&arg.ty);
457 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
458 self.visit_ty(ret_ty);
462 if let Some(body) = body {
463 self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
467 fn process_trait_ref(&mut self, trait_ref: &'l ast::TraitRef) {
468 let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref, self.cur_scope);
469 if let Some(trait_ref_data) = trait_ref_data {
470 if !self.span.filter_generated(Some(trait_ref_data.span), trait_ref.path.span) {
471 self.dumper.type_ref(trait_ref_data.lower(self.tcx));
474 self.process_path(trait_ref.ref_id, &trait_ref.path, Some(recorder::TypeRef));
477 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
478 let field_data = self.save_ctxt.get_field_data(field, parent_id);
479 if let Some(mut field_data) = field_data {
480 if !self.span.filter_generated(Some(field_data.span), field.span) {
481 field_data.value = String::new();
482 self.dumper.variable(field_data.lower(self.tcx));
487 // Dump generic params bindings, then visit_generics
488 fn process_generic_params(&mut self,
489 generics: &'l ast::Generics,
493 // We can't only use visit_generics since we don't have spans for param
494 // bindings, so we reparse the full_span to get those sub spans.
495 // However full span is the entire enum/fn/struct block, so we only want
496 // the first few to match the number of generics we're looking for.
497 let param_sub_spans = self.span.spans_for_ty_params(full_span,
498 (generics.ty_params.len() as isize));
499 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
500 let name = escape(self.span.snippet(param_ss));
501 // Append $id to name to make sure each one is unique
502 let qualname = format!("{}::{}${}",
506 if !self.span.filter_generated(Some(param_ss), full_span) {
507 self.dumper.typedef(TypeDefData {
512 value: String::new(),
513 visibility: Visibility::Inherited,
520 self.visit_generics(generics);
523 fn process_fn(&mut self,
525 decl: &'l ast::FnDecl,
526 ty_params: &'l ast::Generics,
527 body: &'l ast::Block) {
528 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
529 down_cast_data!(fn_data, FunctionData, item.span);
530 if !self.span.filter_generated(Some(fn_data.span), item.span) {
531 self.dumper.function(fn_data.clone().lower(self.tcx));
534 self.nest_tables(item.id, |v| v.process_formals(&decl.inputs, &fn_data.qualname));
535 self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
538 for arg in &decl.inputs {
539 self.visit_ty(&arg.ty);
542 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
543 self.visit_ty(&ret_ty);
546 self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
549 fn process_static_or_const_item(&mut self,
552 expr: &'l ast::Expr) {
553 if let Some(var_data) = self.save_ctxt.get_item_data(item) {
554 down_cast_data!(var_data, VariableData, item.span);
555 if !self.span.filter_generated(Some(var_data.span), item.span) {
556 self.dumper.variable(var_data.lower(self.tcx));
560 self.visit_expr(expr);
563 fn process_assoc_const(&mut self,
571 attrs: &'l [Attribute]) {
572 let qualname = format!("::{}", self.tcx.node_path_str(id));
574 let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
576 if !self.span.filter_generated(sub_span, span) {
577 self.dumper.variable(VariableData {
578 span: sub_span.expect("No span found for variable"),
579 kind: VariableKind::Const,
581 name: name.to_string(),
583 value: self.span.snippet(expr.span),
584 type_value: ty_to_string(&typ),
585 scope: self.cur_scope,
586 parent: Some(parent_id),
588 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 self.dumper.struct_data(StructData {
623 span: sub_span.expect("No span found for struct"),
627 qualname: qualname.clone(),
628 scope: self.cur_scope,
631 visibility: From::from(&item.vis),
632 docs: docs_for_attrs(&item.attrs),
633 sig: self.save_ctxt.sig_base(item),
637 for field in def.fields() {
638 self.process_struct_field_def(field, item.id);
639 self.visit_ty(&field.ty);
642 self.process_generic_params(ty_params, item.span, &qualname, item.id);
645 fn process_enum(&mut self,
647 enum_definition: &'l ast::EnumDef,
648 ty_params: &'l ast::Generics) {
649 let enum_data = self.save_ctxt.get_item_data(item);
650 let enum_data = match enum_data {
654 down_cast_data!(enum_data, EnumData, item.span);
655 if !self.span.filter_generated(Some(enum_data.span), item.span) {
656 self.dumper.enum_data(enum_data.clone().lower(self.tcx));
659 for variant in &enum_definition.variants {
660 let name = variant.node.name.name.to_string();
661 let mut qualname = enum_data.qualname.clone();
662 qualname.push_str("::");
663 qualname.push_str(&name);
665 let text = self.span.signature_string_for_span(variant.span);
666 let ident_start = text.find(&name).unwrap();
667 let ident_end = ident_start + name.len();
668 let sig = Signature {
671 ident_start: ident_start,
672 ident_end: ident_end,
677 match variant.node.data {
678 ast::VariantData::Struct(ref fields, _) => {
679 let sub_span = self.span.span_for_first_ident(variant.span);
680 let fields_str = fields.iter()
682 .map(|(i, f)| f.ident.map(|i| i.to_string())
683 .unwrap_or(i.to_string()))
686 let val = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
687 if !self.span.filter_generated(sub_span, variant.span) {
688 self.dumper.struct_variant(StructVariantData {
689 span: sub_span.expect("No span found for struct variant"),
690 id: variant.node.data.id(),
693 type_value: enum_data.qualname.clone(),
695 scope: enum_data.scope,
696 parent: Some(make_def_id(item.id, &self.tcx.hir)),
697 docs: docs_for_attrs(&variant.node.attrs),
703 let sub_span = self.span.span_for_first_ident(variant.span);
704 let mut val = format!("{}::{}", enum_data.name, name);
705 if let &ast::VariantData::Tuple(ref fields, _) = v {
707 val.push_str(&fields.iter()
708 .map(|f| ty_to_string(&f.ty))
713 if !self.span.filter_generated(sub_span, variant.span) {
714 self.dumper.tuple_variant(TupleVariantData {
715 span: sub_span.expect("No span found for tuple variant"),
716 id: variant.node.data.id(),
719 type_value: enum_data.qualname.clone(),
721 scope: enum_data.scope,
722 parent: Some(make_def_id(item.id, &self.tcx.hir)),
723 docs: docs_for_attrs(&variant.node.attrs),
731 for field in variant.node.data.fields() {
732 self.process_struct_field_def(field, variant.node.data.id());
733 self.visit_ty(&field.ty);
736 self.process_generic_params(ty_params, item.span, &enum_data.qualname, enum_data.id);
739 fn process_impl(&mut self,
741 type_parameters: &'l ast::Generics,
742 trait_ref: &'l Option<ast::TraitRef>,
744 impl_items: &'l [ast::ImplItem]) {
745 let mut has_self_ref = false;
746 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
747 down_cast_data!(impl_data, ImplData, item.span);
748 if let Some(ref self_ref) = impl_data.self_ref {
750 if !self.span.filter_generated(Some(self_ref.span), item.span) {
751 self.dumper.type_ref(self_ref.clone().lower(self.tcx));
754 if let Some(ref trait_ref_data) = impl_data.trait_ref {
755 if !self.span.filter_generated(Some(trait_ref_data.span), item.span) {
756 self.dumper.type_ref(trait_ref_data.clone().lower(self.tcx));
760 if !self.span.filter_generated(Some(impl_data.span), item.span) {
761 self.dumper.impl_data(ImplData {
763 span: impl_data.span,
764 scope: impl_data.scope,
765 trait_ref: impl_data.trait_ref.map(|d| d.ref_id.unwrap()),
766 self_ref: impl_data.self_ref.map(|d| d.ref_id.unwrap())
773 if let &Some(ref trait_ref) = trait_ref {
774 self.process_path(trait_ref.ref_id, &trait_ref.path, Some(recorder::TypeRef));
776 self.process_generic_params(type_parameters, item.span, "", item.id);
777 for impl_item in impl_items {
778 let map = &self.tcx.hir;
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),
810 sig: self.save_ctxt.sig_base(item),
815 for super_bound in trait_refs.iter() {
816 let trait_ref = match *super_bound {
817 ast::TraitTyParamBound(ref trait_ref, _) => {
820 ast::RegionTyParamBound(..) => {
825 let trait_ref = &trait_ref.trait_ref;
826 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
827 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
828 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
829 self.dumper.type_ref(TypeRefData {
830 span: sub_span.expect("No span found for trait ref"),
832 scope: self.cur_scope,
833 qualname: String::new()
837 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
838 let sub_span = sub_span.expect("No span for inheritance");
839 self.dumper.inheritance(InheritanceData {
848 // walk generics and methods
849 self.process_generic_params(generics, item.span, &qualname, item.id);
850 for method in methods {
851 let map = &self.tcx.hir;
852 self.process_trait_item(method, make_def_id(item.id, map))
856 // `item` is the module in question, represented as an item.
857 fn process_mod(&mut self, item: &ast::Item) {
858 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
859 down_cast_data!(mod_data, ModData, item.span);
860 if !self.span.filter_generated(Some(mod_data.span), item.span) {
861 self.dumper.mod_data(mod_data.lower(self.tcx));
866 fn process_path(&mut self, id: NodeId, path: &ast::Path, ref_kind: Option<recorder::Row>) {
867 let path_data = self.save_ctxt.get_path_data(id, path);
868 if generated_code(path.span) && path_data.is_none() {
872 let path_data = match path_data {
880 Data::VariableRefData(vrd) => {
881 // FIXME: this whole block duplicates the code in process_def_kind
882 if !self.span.filter_generated(Some(vrd.span), path.span) {
884 Some(recorder::TypeRef) => {
885 self.dumper.type_ref(TypeRefData {
887 ref_id: Some(vrd.ref_id),
889 qualname: String::new()
892 Some(recorder::FnRef) => {
893 self.dumper.function_ref(FunctionRefData {
899 Some(recorder::ModRef) => {
900 self.dumper.mod_ref( ModRefData {
902 ref_id: Some(vrd.ref_id),
904 qualname: String::new()
907 Some(recorder::VarRef) | None
908 => self.dumper.variable_ref(vrd.lower(self.tcx))
913 Data::TypeRefData(trd) => {
914 if !self.span.filter_generated(Some(trd.span), path.span) {
915 self.dumper.type_ref(trd.lower(self.tcx));
918 Data::MethodCallData(mcd) => {
919 if !self.span.filter_generated(Some(mcd.span), path.span) {
920 self.dumper.method_call(mcd.lower(self.tcx));
923 Data::FunctionCallData(fcd) => {
924 if !self.span.filter_generated(Some(fcd.span), path.span) {
925 self.dumper.function_call(fcd.lower(self.tcx));
929 span_bug!(path.span, "Unexpected data: {:?}", path_data);
933 // Modules or types in the path prefix.
934 match self.save_ctxt.get_path_def(id) {
935 Def::Method(did) => {
936 let ti = self.tcx.associated_item(did);
937 if ti.kind == ty::AssociatedKind::Method && ti.method_has_self_argument {
938 self.write_sub_path_trait_truncated(path);
944 Def::StructCtor(..) |
945 Def::VariantCtor(..) |
946 Def::AssociatedConst(..) |
953 Def::AssociatedTy(..) => self.write_sub_paths_truncated(path),
958 fn process_struct_lit(&mut self,
961 fields: &'l [ast::Field],
962 variant: &'l ty::VariantDef,
963 base: &'l Option<P<ast::Expr>>) {
964 self.write_sub_paths_truncated(path);
966 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
967 down_cast_data!(struct_lit_data, TypeRefData, ex.span);
968 if !self.span.filter_generated(Some(struct_lit_data.span), ex.span) {
969 self.dumper.type_ref(struct_lit_data.lower(self.tcx));
972 let scope = self.save_ctxt.enclosing_scope(ex.id);
974 for field in fields {
975 if let Some(field_data) = self.save_ctxt
976 .get_field_ref_data(field, variant, scope) {
978 if !self.span.filter_generated(Some(field_data.span), field.ident.span) {
979 self.dumper.variable_ref(field_data.lower(self.tcx));
983 self.visit_expr(&field.expr)
987 walk_list!(self, visit_expr, base);
990 fn process_method_call(&mut self, ex: &'l ast::Expr, args: &'l [P<ast::Expr>]) {
991 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
992 down_cast_data!(mcd, MethodCallData, ex.span);
993 if !self.span.filter_generated(Some(mcd.span), ex.span) {
994 self.dumper.method_call(mcd.lower(self.tcx));
998 // walk receiver and args
999 walk_list!(self, visit_expr, args);
1002 fn process_pat(&mut self, p: &'l ast::Pat) {
1004 PatKind::Struct(ref _path, ref fields, _) => {
1005 // FIXME do something with _path?
1006 let adt = match self.save_ctxt.tables.node_id_to_type_opt(p.id) {
1007 Some(ty) => ty.ty_adt_def().unwrap(),
1009 visit::walk_pat(self, p);
1013 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
1015 for &Spanned { node: ref field, span } in fields {
1016 let sub_span = self.span.span_for_first_ident(span);
1017 if let Some(f) = variant.find_field_named(field.ident.name) {
1018 if !self.span.filter_generated(sub_span, span) {
1019 self.dumper.variable_ref(VariableRefData {
1020 span: sub_span.expect("No span fund for var ref"),
1022 scope: self.cur_scope,
1027 self.visit_pat(&field.pat);
1030 _ => visit::walk_pat(self, p),
1035 fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
1036 // The local could declare multiple new vars, we must walk the
1037 // pattern and collect them all.
1038 let mut collector = PathCollector::new();
1039 collector.visit_pat(&p);
1042 for &(id, ref p, immut, _) in &collector.collected_paths {
1043 let mut value = match immut {
1044 ast::Mutability::Immutable => value.to_string(),
1047 let typ = match self.save_ctxt.tables.node_types.get(&id) {
1049 let typ = typ.to_string();
1050 if !value.is_empty() {
1051 value.push_str(": ");
1053 value.push_str(&typ);
1056 None => String::new(),
1059 // Get the span only for the name of the variable (I hope the path
1060 // is only ever a variable name, but who knows?).
1061 let sub_span = self.span.span_for_last_ident(p.span);
1062 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1063 if !self.span.filter_generated(sub_span, p.span) {
1064 self.dumper.variable(VariableData {
1065 span: sub_span.expect("No span found for variable"),
1066 kind: VariableKind::Local,
1068 name: path_to_string(p),
1069 qualname: format!("{}${}", path_to_string(p), id),
1072 scope: CRATE_NODE_ID,
1074 visibility: Visibility::Inherited,
1075 docs: String::new(),
1082 /// Extract macro use and definition information from the AST node defined
1083 /// by the given NodeId, using the expansion information from the node's
1086 /// If the span is not macro-generated, do nothing, else use callee and
1087 /// callsite spans to record macro definition and use data, using the
1088 /// mac_uses and mac_defs sets to prevent multiples.
1089 fn process_macro_use(&mut self, span: Span, id: NodeId) {
1090 let data = match self.save_ctxt.get_macro_use_data(span, id) {
1094 let mut hasher = DefaultHasher::new();
1095 data.callee_span.hash(&mut hasher);
1096 let hash = hasher.finish();
1097 let qualname = format!("{}::{}", data.name, hash);
1098 // Don't write macro definition for imported macros
1099 if !self.mac_defs.contains(&data.callee_span)
1101 self.mac_defs.insert(data.callee_span);
1102 if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1103 self.dumper.macro_data(MacroData {
1105 name: data.name.clone(),
1106 qualname: qualname.clone(),
1107 // FIXME where do macro docs come from?
1108 docs: String::new(),
1112 if !self.mac_uses.contains(&data.span) {
1113 self.mac_uses.insert(data.span);
1114 if let Some(sub_span) = self.span.span_for_macro_use_name(data.span) {
1115 self.dumper.macro_use(MacroUseData {
1120 callee_span: data.callee_span,
1121 imported: data.imported,
1127 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1128 self.process_macro_use(trait_item.span, trait_item.id);
1129 match trait_item.node {
1130 ast::TraitItemKind::Const(ref ty, Some(ref expr)) => {
1131 self.process_assoc_const(trait_item.id,
1132 trait_item.ident.name,
1140 ast::TraitItemKind::Method(ref sig, ref body) => {
1141 self.process_method(sig,
1142 body.as_ref().map(|x| &**x),
1144 trait_item.ident.name,
1149 ast::TraitItemKind::Const(_, None) |
1150 ast::TraitItemKind::Type(..) |
1151 ast::TraitItemKind::Macro(_) => {}
1155 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1156 self.process_macro_use(impl_item.span, impl_item.id);
1157 match impl_item.node {
1158 ast::ImplItemKind::Const(ref ty, ref expr) => {
1159 self.process_assoc_const(impl_item.id,
1160 impl_item.ident.name,
1165 From::from(&impl_item.vis),
1168 ast::ImplItemKind::Method(ref sig, ref body) => {
1169 self.process_method(sig,
1172 impl_item.ident.name,
1173 From::from(&impl_item.vis),
1177 ast::ImplItemKind::Type(_) |
1178 ast::ImplItemKind::Macro(_) => {}
1183 impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, D> {
1184 fn visit_item(&mut self, item: &'l ast::Item) {
1185 use syntax::ast::ItemKind::*;
1186 self.process_macro_use(item.span, item.id);
1188 Use(ref use_item) => {
1189 match use_item.node {
1190 ast::ViewPathSimple(ident, ref path) => {
1191 let sub_span = self.span.span_for_last_ident(path.span);
1192 let mod_id = match self.lookup_def_id(item.id) {
1194 let scope = self.cur_scope;
1195 self.process_def_kind(item.id, path.span, sub_span, def_id, scope);
1202 // 'use' always introduces an alias, if there is not an explicit
1203 // one, there is an implicit one.
1204 let sub_span = match self.span.sub_span_after_keyword(use_item.span,
1206 Some(sub_span) => Some(sub_span),
1210 if !self.span.filter_generated(sub_span, path.span) {
1211 self.dumper.use_data(UseData {
1212 span: sub_span.expect("No span found for use"),
1215 name: ident.to_string(),
1216 scope: self.cur_scope,
1217 visibility: From::from(&item.vis),
1220 self.write_sub_paths_truncated(path);
1222 ast::ViewPathGlob(ref path) => {
1223 // Make a comma-separated list of names of imported modules.
1224 let mut names = vec![];
1225 let glob_map = &self.save_ctxt.analysis.glob_map;
1226 let glob_map = glob_map.as_ref().unwrap();
1227 if glob_map.contains_key(&item.id) {
1228 for n in glob_map.get(&item.id).unwrap() {
1229 names.push(n.to_string());
1233 let sub_span = self.span
1234 .sub_span_of_token(item.span, token::BinOp(token::Star));
1235 if !self.span.filter_generated(sub_span, item.span) {
1236 self.dumper.use_glob(UseGlobData {
1237 span: sub_span.expect("No span found for use glob"),
1240 scope: self.cur_scope,
1241 visibility: From::from(&item.vis),
1244 self.write_sub_paths(path);
1246 ast::ViewPathList(ref path, ref list) => {
1248 let scope = self.cur_scope;
1249 let id = plid.node.id;
1250 if let Some(def_id) = self.lookup_def_id(id) {
1251 let span = plid.span;
1252 self.process_def_kind(id, span, Some(span), def_id, scope);
1256 self.write_sub_paths(path);
1260 ExternCrate(ref s) => {
1261 let location = match *s {
1262 Some(s) => s.to_string(),
1263 None => item.ident.to_string(),
1265 let alias_span = self.span.span_for_last_ident(item.span);
1266 let cnum = match self.sess.cstore.extern_mod_stmt_cnum(item.id) {
1268 None => LOCAL_CRATE,
1271 if !self.span.filter_generated(alias_span, item.span) {
1272 self.dumper.extern_crate(ExternCrateData {
1274 name: item.ident.to_string(),
1277 span: alias_span.expect("No span found for extern crate"),
1278 scope: self.cur_scope,
1282 Fn(ref decl, .., ref ty_params, ref body) =>
1283 self.process_fn(item, &decl, ty_params, &body),
1284 Static(ref typ, _, ref expr) =>
1285 self.process_static_or_const_item(item, typ, expr),
1286 Const(ref typ, ref expr) =>
1287 self.process_static_or_const_item(item, &typ, &expr),
1288 Struct(ref def, ref ty_params) => self.process_struct(item, def, ty_params),
1289 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1294 ref impl_items) => {
1295 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1297 Trait(_, ref generics, ref trait_refs, ref methods) =>
1298 self.process_trait(item, generics, trait_refs, methods),
1300 self.process_mod(item);
1301 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1303 Ty(ref ty, ref ty_params) => {
1304 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1305 let value = ty_to_string(&ty);
1306 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1307 if !self.span.filter_generated(sub_span, item.span) {
1308 self.dumper.typedef(TypeDefData {
1309 span: sub_span.expect("No span found for typedef"),
1310 name: item.ident.to_string(),
1312 qualname: qualname.clone(),
1314 visibility: From::from(&item.vis),
1316 docs: docs_for_attrs(&item.attrs),
1317 sig: Some(self.save_ctxt.sig_base(item)),
1322 self.process_generic_params(ty_params, item.span, &qualname, item.id);
1325 _ => visit::walk_item(self, item),
1329 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1330 for param in generics.ty_params.iter() {
1331 for bound in param.bounds.iter() {
1332 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
1333 self.process_trait_ref(&trait_ref.trait_ref);
1336 if let Some(ref ty) = param.default {
1342 fn visit_ty(&mut self, t: &'l ast::Ty) {
1343 self.process_macro_use(t.span, t.id);
1345 ast::TyKind::Path(_, ref path) => {
1346 if generated_code(t.span) {
1350 if let Some(id) = self.lookup_def_id(t.id) {
1351 if let Some(sub_span) = self.span.sub_span_for_type_name(t.span) {
1352 self.dumper.type_ref(TypeRefData {
1355 scope: self.cur_scope,
1356 qualname: String::new()
1361 self.write_sub_paths_truncated(path);
1362 visit::walk_path(self, path);
1364 ast::TyKind::Array(ref element, ref length) => {
1365 self.visit_ty(element);
1366 self.nest_tables(length.id, |v| v.visit_expr(length));
1368 _ => visit::walk_ty(self, t),
1372 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1373 debug!("visit_expr {:?}", ex.node);
1374 self.process_macro_use(ex.span, ex.id);
1376 ast::ExprKind::Call(ref _f, ref _args) => {
1377 // Don't need to do anything for function calls,
1378 // because just walking the callee path does what we want.
1379 visit::walk_expr(self, ex);
1381 ast::ExprKind::Path(_, ref path) => {
1382 self.process_path(ex.id, path, None);
1383 visit::walk_expr(self, ex);
1385 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1386 let hir_expr = self.save_ctxt.tcx.hir.expect_expr(ex.id);
1387 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1388 Some(ty) => ty.ty_adt_def().unwrap(),
1390 visit::walk_expr(self, ex);
1394 let def = self.save_ctxt.get_path_def(hir_expr.id);
1395 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1397 ast::ExprKind::MethodCall(.., ref args) => self.process_method_call(ex, args),
1398 ast::ExprKind::Field(ref sub_ex, _) => {
1399 self.visit_expr(&sub_ex);
1401 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1402 down_cast_data!(field_data, VariableRefData, ex.span);
1403 if !self.span.filter_generated(Some(field_data.span), ex.span) {
1404 self.dumper.variable_ref(field_data.lower(self.tcx));
1408 ast::ExprKind::TupField(ref sub_ex, idx) => {
1409 self.visit_expr(&sub_ex);
1411 let hir_node = match self.save_ctxt.tcx.hir.find(sub_ex.id) {
1412 Some(Node::NodeExpr(expr)) => expr,
1414 debug!("Missing or weird node for sub-expression {} in {:?}",
1419 let ty = match self.save_ctxt.tables.expr_ty_adjusted_opt(&hir_node) {
1420 Some(ty) => &ty.sty,
1422 visit::walk_expr(self, ex);
1427 ty::TyAdt(def, _) => {
1428 let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1429 if !self.span.filter_generated(sub_span, ex.span) {
1430 self.dumper.variable_ref(VariableRefData {
1431 span: sub_span.expect("No span found for var ref"),
1432 ref_id: def.struct_variant().fields[idx.node].did,
1433 scope: self.cur_scope,
1438 ty::TyTuple(_) => {}
1439 _ => span_bug!(ex.span,
1440 "Expected struct or tuple type, found {:?}",
1444 ast::ExprKind::Closure(_, ref decl, ref body, _fn_decl_span) => {
1445 let mut id = String::from("$");
1446 id.push_str(&ex.id.to_string());
1448 // walk arg and return types
1449 for arg in &decl.inputs {
1450 self.visit_ty(&arg.ty);
1453 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1454 self.visit_ty(&ret_ty);
1458 self.nest_tables(ex.id, |v| {
1459 v.process_formals(&decl.inputs, &id);
1460 v.nest_scope(ex.id, |v| v.visit_expr(body))
1463 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) |
1464 ast::ExprKind::WhileLet(ref pattern, ref subexpression, ref block, _) => {
1465 let value = self.span.snippet(subexpression.span);
1466 self.process_var_decl(pattern, value);
1467 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1468 visit::walk_expr(self, subexpression);
1469 visit::walk_block(self, block);
1471 ast::ExprKind::IfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
1472 let value = self.span.snippet(subexpression.span);
1473 self.process_var_decl(pattern, value);
1474 visit::walk_expr(self, subexpression);
1475 visit::walk_block(self, block);
1476 opt_else.as_ref().map(|el| visit::walk_expr(self, el));
1478 ast::ExprKind::Repeat(ref element, ref count) => {
1479 self.visit_expr(element);
1480 self.nest_tables(count.id, |v| v.visit_expr(count));
1483 visit::walk_expr(self, ex)
1488 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1489 // These shouldn't exist in the AST at this point, log a span bug.
1490 span_bug!(mac.span, "macro invocation should have been expanded out of AST");
1493 fn visit_pat(&mut self, p: &'l ast::Pat) {
1494 self.process_macro_use(p.span, p.id);
1495 self.process_pat(p);
1498 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1499 let mut collector = PathCollector::new();
1500 for pattern in &arm.pats {
1501 // collect paths from the arm's patterns
1502 collector.visit_pat(&pattern);
1503 self.visit_pat(&pattern);
1506 // This is to get around borrow checking, because we need mut self to call process_path.
1507 let mut paths_to_process = vec![];
1509 // process collected paths
1510 for &(id, ref p, immut, ref_kind) in &collector.collected_paths {
1511 match self.save_ctxt.get_path_def(id) {
1512 Def::Local(def_id) => {
1513 let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1514 let mut value = if immut == ast::Mutability::Immutable {
1515 self.span.snippet(p.span).to_string()
1517 "<mutable>".to_string()
1519 let typ = self.save_ctxt.tables.node_types
1520 .get(&id).map(|t| t.to_string()).unwrap_or(String::new());
1521 value.push_str(": ");
1522 value.push_str(&typ);
1524 assert!(p.segments.len() == 1,
1525 "qualified path for local variable def in arm");
1526 if !self.span.filter_generated(Some(p.span), p.span) {
1527 self.dumper.variable(VariableData {
1529 kind: VariableKind::Local,
1531 name: path_to_string(p),
1532 qualname: format!("{}${}", path_to_string(p), id),
1535 scope: CRATE_NODE_ID,
1537 visibility: Visibility::Inherited,
1538 docs: String::new(),
1543 Def::StructCtor(..) | Def::VariantCtor(..) |
1544 Def::Const(..) | Def::AssociatedConst(..) |
1545 Def::Struct(..) | Def::Variant(..) |
1546 Def::TyAlias(..) | Def::AssociatedTy(..) |
1547 Def::SelfTy(..) => {
1548 paths_to_process.push((id, p.clone(), Some(ref_kind)))
1550 def => error!("unexpected definition kind when processing collected paths: {:?}",
1555 for &(id, ref path, ref_kind) in &paths_to_process {
1556 self.process_path(id, path, ref_kind);
1558 walk_list!(self, visit_expr, &arm.guard);
1559 self.visit_expr(&arm.body);
1562 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1563 self.process_path(id, p, None);
1566 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1567 self.process_macro_use(s.span, s.id);
1568 visit::walk_stmt(self, s)
1571 fn visit_local(&mut self, l: &'l ast::Local) {
1572 self.process_macro_use(l.span, l.id);
1573 let value = l.init.as_ref().map(|i| self.span.snippet(i.span)).unwrap_or(String::new());
1574 self.process_var_decl(&l.pat, value);
1576 // Just walk the initialiser and type (don't want to walk the pattern again).
1577 walk_list!(self, visit_ty, &l.ty);
1578 walk_list!(self, visit_expr, &l.init);