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.
13 //! Dumping the analysis is implemented by walking the AST and getting a bunch of
14 //! info out from all over the place. We use Def IDs to identify objects. The
15 //! tricky part is getting syntactic (span, source text) and semantic (reference
16 //! Def IDs) information for parts of expressions which the compiler has discarded.
17 //! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
18 //! path and a reference to `baz`, but we want spans and references for all three
21 //! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
22 //! from spans (e.g., the span for `bar` from the above example path).
23 //! DumpVisitor walks the AST and processes it, and JsonDumper is used for
24 //! recording the output.
26 use rustc::hir::def::Def as HirDef;
27 use rustc::hir::def_id::DefId;
28 use rustc::ty::{self, TyCtxt};
29 use rustc_data_structures::fx::FxHashSet;
33 use syntax::ast::{self, Attribute, NodeId, PatKind, CRATE_NODE_ID};
34 use syntax::parse::token;
35 use syntax::symbol::keywords;
36 use syntax::visit::{self, Visitor};
37 use syntax::print::pprust::{
39 generic_params_to_string,
44 use syntax::codemap::{Spanned, DUMMY_SP, respan};
47 use {escape, generated_code, lower_attributes, PathCollector, SaveContext};
48 use json_dumper::{Access, DumpOutput, JsonDumper};
49 use span_utils::SpanUtils;
52 use rls_data::{CratePreludeData, Def, DefKind, GlobalCrateId, Import, ImportKind, Ref, RefKind,
53 Relation, RelationKind, SpanData};
55 macro_rules! down_cast_data {
56 ($id:ident, $kind:ident, $sp:expr) => {
57 let $id = if let super::Data::$kind(data) = $id {
60 span_bug!($sp, "unexpected data kind: {:?}", $id);
65 macro_rules! access_from {
66 ($save_ctxt:expr, $vis:expr, $id:expr) => {
68 public: $vis.node == ast::VisibilityKind::Public,
69 reachable: $save_ctxt.analysis.access_levels.is_reachable($id),
73 ($save_ctxt:expr, $item:expr) => {
75 public: $item.vis.node == ast::VisibilityKind::Public,
76 reachable: $save_ctxt.analysis.access_levels.is_reachable($item.id),
81 pub struct DumpVisitor<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> {
82 save_ctxt: SaveContext<'l, 'tcx>,
83 tcx: TyCtxt<'l, 'tcx, 'tcx>,
84 dumper: &'ll mut JsonDumper<O>,
90 // Set of macro definition (callee) spans, and the set
91 // of macro use (callsite) spans. We store these to ensure
92 // we only write one macro def per unique macro definition, and
93 // one macro use per unique callsite span.
94 // mac_defs: HashSet<Span>,
95 macro_calls: FxHashSet<Span>,
98 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> {
100 save_ctxt: SaveContext<'l, 'tcx>,
101 dumper: &'ll mut JsonDumper<O>,
102 ) -> DumpVisitor<'l, 'tcx, 'll, O> {
103 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
108 span: span_utils.clone(),
109 cur_scope: CRATE_NODE_ID,
110 // mac_defs: HashSet::new(),
111 macro_calls: FxHashSet(),
115 fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
117 F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
119 let parent_scope = self.cur_scope;
120 self.cur_scope = scope_id;
122 self.cur_scope = parent_scope;
125 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
127 F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
129 let item_def_id = self.tcx.hir.local_def_id(item_id);
130 if self.tcx.has_typeck_tables(item_def_id) {
131 let tables = self.tcx.typeck_tables_of(item_def_id);
132 let old_tables = self.save_ctxt.tables;
133 self.save_ctxt.tables = tables;
135 self.save_ctxt.tables = old_tables;
141 fn span_from_span(&self, span: Span) -> SpanData {
142 self.save_ctxt.span_from_span(span)
145 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
146 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
147 let crate_root = source_file.map(|source_file| {
148 let source_file = Path::new(source_file);
149 match source_file.file_name() {
150 Some(_) => source_file.parent().unwrap().display().to_string(),
151 None => source_file.display().to_string(),
155 let data = CratePreludeData {
156 crate_id: GlobalCrateId {
158 disambiguator: self.tcx
160 .local_crate_disambiguator()
164 crate_root: crate_root.unwrap_or("<no source>".to_owned()),
165 external_crates: self.save_ctxt.get_external_crates(),
166 span: self.span_from_span(krate.span),
169 self.dumper.crate_prelude(data);
172 // Return all non-empty prefixes of a path.
173 // For each prefix, we return the span for the last segment in the prefix and
174 // a str representation of the entire prefix.
175 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
176 let segments = &path.segments[if path.is_global() { 1 } else { 0 }..];
178 let mut result = Vec::with_capacity(segments.len());
180 let mut segs = vec![];
181 for (i, seg) in segments.iter().enumerate() {
182 segs.push(seg.clone());
183 let sub_path = ast::Path {
184 span: seg.ident.span, // span for the last segment
187 let qualname = if i == 0 && path.is_global() {
188 format!("::{}", path_to_string(&sub_path))
190 path_to_string(&sub_path)
192 result.push((seg.ident.span, qualname));
193 segs = sub_path.segments;
199 fn write_sub_paths(&mut self, path: &ast::Path) {
200 let sub_paths = self.process_path_prefixes(path);
201 for (span, _) in sub_paths {
202 let span = self.span_from_span(span);
203 self.dumper.dump_ref(Ref {
211 // As write_sub_paths, but does not process the last ident in the path (assuming it
212 // will be processed elsewhere). See note on write_sub_paths about global.
213 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
214 let sub_paths = self.process_path_prefixes(path);
215 let len = sub_paths.len();
220 for (span, _) in sub_paths.into_iter().take(len - 1) {
221 let span = self.span_from_span(span);
222 self.dumper.dump_ref(Ref {
230 // As write_sub_paths, but expects a path of the form module_path::trait::method
231 // Where trait could actually be a struct too.
232 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
233 let sub_paths = self.process_path_prefixes(path);
234 let len = sub_paths.len();
238 let sub_paths = &sub_paths[..(len - 1)];
240 // write the trait part of the sub-path
241 let (ref span, _) = sub_paths[len - 2];
242 let span = self.span_from_span(*span);
243 self.dumper.dump_ref(Ref {
249 // write the other sub-paths
253 let sub_paths = &sub_paths[..len - 2];
254 for &(ref span, _) in sub_paths {
255 let span = self.span_from_span(*span);
256 self.dumper.dump_ref(Ref {
264 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
265 match self.save_ctxt.get_path_def(ref_id) {
266 HirDef::PrimTy(..) | HirDef::SelfTy(..) | HirDef::Err => None,
267 def => Some(def.def_id()),
271 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
273 self.visit_pat(&arg.pat);
274 let mut collector = PathCollector::new();
275 collector.visit_pat(&arg.pat);
276 let span_utils = self.span.clone();
278 for (id, ident, ..) in collector.collected_idents {
279 let hir_id = self.tcx.hir.node_to_hir_id(id);
280 let typ = match self.save_ctxt.tables.node_id_to_type_opt(hir_id) {
281 Some(s) => s.to_string(),
284 let sub_span = span_utils.span_for_last_ident(ident.span);
285 if !self.span.filter_generated(sub_span, ident.span) {
286 let id = ::id_from_node_id(id, &self.save_ctxt);
287 let span = self.span_from_span(sub_span.expect("No span found for variable"));
289 self.dumper.dump_def(
295 kind: DefKind::Local,
298 name: ident.to_string(),
299 qualname: format!("{}::{}", qualname, ident.to_string()),
316 sig: &'l ast::MethodSig,
317 body: Option<&'l ast::Block>,
320 generics: &'l ast::Generics,
321 vis: ast::Visibility,
324 debug!("process_method: {}:{}", id, name);
326 if let Some(mut method_data) = self.save_ctxt.get_method_data(id, name.name, span) {
327 let sig_str = ::make_signature(&sig.decl, &generics);
331 |v| v.process_formals(&sig.decl.inputs, &method_data.qualname),
335 self.process_generic_params(&generics, span, &method_data.qualname, id);
337 method_data.value = sig_str;
338 method_data.sig = sig::method_signature(id, name, generics, sig, &self.save_ctxt);
339 self.dumper.dump_def(&access_from!(self.save_ctxt, vis, id), method_data);
342 // walk arg and return types
343 for arg in &sig.decl.inputs {
344 self.visit_ty(&arg.ty);
347 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
348 self.visit_ty(ret_ty);
352 if let Some(body) = body {
353 self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
357 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
358 let field_data = self.save_ctxt.get_field_data(field, parent_id);
359 if let Some(field_data) = field_data {
360 self.dumper.dump_def(&access_from!(self.save_ctxt, field), field_data);
364 // Dump generic params bindings, then visit_generics
365 fn process_generic_params(
367 generics: &'l ast::Generics,
372 for param in &generics.params {
374 ast::GenericParamKind::Lifetime { .. } => {}
375 ast::GenericParamKind::Type { .. } => {
376 let param_ss = param.ident.span;
377 let name = escape(self.span.snippet(param_ss));
378 // Append $id to name to make sure each one is unique.
379 let qualname = format!("{}::{}${}", prefix, name, id);
380 if !self.span.filter_generated(Some(param_ss), full_span) {
381 let id = ::id_from_node_id(param.id, &self.save_ctxt);
382 let span = self.span_from_span(param_ss);
384 self.dumper.dump_def(
395 value: String::new(),
408 self.visit_generics(generics);
414 decl: &'l ast::FnDecl,
415 ty_params: &'l ast::Generics,
416 body: &'l ast::Block,
418 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
419 down_cast_data!(fn_data, DefData, item.span);
422 |v| v.process_formals(&decl.inputs, &fn_data.qualname),
424 self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
425 self.dumper.dump_def(&access_from!(self.save_ctxt, item), fn_data);
428 for arg in &decl.inputs {
429 self.visit_ty(&arg.ty);
432 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
433 self.visit_ty(&ret_ty);
436 self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
439 fn process_static_or_const_item(
445 self.nest_tables(item.id, |v| {
446 if let Some(var_data) = v.save_ctxt.get_item_data(item) {
447 down_cast_data!(var_data, DefData, item.span);
448 v.dumper.dump_def(&access_from!(v.save_ctxt, item), var_data);
455 fn process_assoc_const(
461 expr: Option<&'l ast::Expr>,
463 vis: ast::Visibility,
464 attrs: &'l [Attribute],
466 let qualname = format!("::{}", self.tcx.node_path_str(id));
468 let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
470 if !self.span.filter_generated(sub_span, span) {
471 let sig = sig::assoc_const_signature(id, name, typ, expr, &self.save_ctxt);
472 let span = self.span_from_span(sub_span.expect("No span found for variable"));
474 self.dumper.dump_def(
475 &access_from!(self.save_ctxt, vis, id),
477 kind: DefKind::Const,
478 id: ::id_from_node_id(id, &self.save_ctxt),
480 name: name.to_string(),
482 value: ty_to_string(&typ),
483 parent: Some(::id_from_def_id(parent_id)),
486 docs: self.save_ctxt.docs_for_attrs(attrs),
488 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
493 // walk type and init value
495 if let Some(expr) = expr {
496 self.visit_expr(expr);
500 // FIXME tuple structs should generate tuple-specific data.
504 def: &'l ast::VariantData,
505 ty_params: &'l ast::Generics,
507 debug!("process_struct {:?} {:?}", item, item.span);
508 let name = item.ident.to_string();
509 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
511 let (kind, keyword) = match item.node {
512 ast::ItemKind::Struct(_, _) => (DefKind::Struct, keywords::Struct),
513 ast::ItemKind::Union(_, _) => (DefKind::Union, keywords::Union),
517 let sub_span = self.span.sub_span_after_keyword(item.span, keyword);
518 let (value, fields) = match item.node {
519 ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, _), _) |
520 ast::ItemKind::Union(ast::VariantData::Struct(ref fields, _), _) => {
521 let include_priv_fields = !self.save_ctxt.config.pub_only;
522 let fields_str = fields
525 .filter_map(|(i, f)| {
526 if include_priv_fields || f.vis.node == ast::VisibilityKind::Public {
528 .map(|i| i.to_string())
529 .or_else(|| Some(i.to_string()))
536 let value = format!("{} {{ {} }}", name, fields_str);
541 .map(|f| ::id_from_node_id(f.id, &self.save_ctxt))
545 _ => (String::new(), vec![]),
548 if !self.span.filter_generated(sub_span, item.span) {
549 let span = self.span_from_span(sub_span.expect("No span found for struct"));
550 self.dumper.dump_def(
551 &access_from!(self.save_ctxt, item),
554 id: ::id_from_node_id(item.id, &self.save_ctxt),
557 qualname: qualname.clone(),
562 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
563 sig: sig::item_signature(item, &self.save_ctxt),
564 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
569 for field in def.fields() {
570 self.process_struct_field_def(field, item.id);
571 self.visit_ty(&field.ty);
574 self.process_generic_params(ty_params, item.span, &qualname, item.id);
580 enum_definition: &'l ast::EnumDef,
581 ty_params: &'l ast::Generics,
583 let enum_data = self.save_ctxt.get_item_data(item);
584 let enum_data = match enum_data {
588 down_cast_data!(enum_data, DefData, item.span);
590 let access = access_from!(self.save_ctxt, item);
592 for variant in &enum_definition.variants {
593 let name = variant.node.ident.name.to_string();
594 let mut qualname = enum_data.qualname.clone();
595 qualname.push_str("::");
596 qualname.push_str(&name);
598 match variant.node.data {
599 ast::VariantData::Struct(ref fields, _) => {
600 let sub_span = self.span.span_for_first_ident(variant.span);
601 let fields_str = fields
605 f.ident.map(|i| i.to_string()).unwrap_or(i.to_string())
609 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
610 if !self.span.filter_generated(sub_span, variant.span) {
612 .span_from_span(sub_span.expect("No span found for struct variant"));
613 let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
614 let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
616 self.dumper.dump_def(
619 kind: DefKind::StructVariant,
628 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
629 sig: sig::variant_signature(variant, &self.save_ctxt),
630 attributes: lower_attributes(
631 variant.node.attrs.clone(),
639 let sub_span = self.span.span_for_first_ident(variant.span);
640 let mut value = format!("{}::{}", enum_data.name, name);
641 if let &ast::VariantData::Tuple(ref fields, _) = v {
643 value.push_str(&fields
645 .map(|f| ty_to_string(&f.ty))
650 if !self.span.filter_generated(sub_span, variant.span) {
652 self.span_from_span(sub_span.expect("No span found for tuple variant"));
653 let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
654 let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
656 self.dumper.dump_def(
659 kind: DefKind::TupleVariant,
668 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
669 sig: sig::variant_signature(variant, &self.save_ctxt),
670 attributes: lower_attributes(
671 variant.node.attrs.clone(),
681 for field in variant.node.data.fields() {
682 self.process_struct_field_def(field, variant.node.data.id());
683 self.visit_ty(&field.ty);
686 self.process_generic_params(ty_params, item.span, &enum_data.qualname, item.id);
687 self.dumper.dump_def(&access, enum_data);
693 type_parameters: &'l ast::Generics,
694 trait_ref: &'l Option<ast::TraitRef>,
696 impl_items: &'l [ast::ImplItem],
698 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
699 if let super::Data::RelationData(rel, imp) = impl_data {
700 self.dumper.dump_relation(rel);
701 self.dumper.dump_impl(imp);
703 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
707 if let &Some(ref trait_ref) = trait_ref {
708 self.process_path(trait_ref.ref_id, &trait_ref.path);
710 self.process_generic_params(type_parameters, item.span, "", item.id);
711 for impl_item in impl_items {
712 let map = &self.tcx.hir;
713 self.process_impl_item(impl_item, map.local_def_id(item.id));
720 generics: &'l ast::Generics,
721 trait_refs: &'l ast::GenericBounds,
722 methods: &'l [ast::TraitItem],
724 let name = item.ident.to_string();
725 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
726 let mut val = name.clone();
727 if !generics.params.is_empty() {
728 val.push_str(&generic_params_to_string(&generics.params));
730 if !trait_refs.is_empty() {
732 val.push_str(&bounds_to_string(trait_refs));
734 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
735 if !self.span.filter_generated(sub_span, item.span) {
736 let id = ::id_from_node_id(item.id, &self.save_ctxt);
737 let span = self.span_from_span(sub_span.expect("No span found for trait"));
738 let children = methods
740 .map(|i| ::id_from_node_id(i.id, &self.save_ctxt))
742 self.dumper.dump_def(
743 &access_from!(self.save_ctxt, item),
745 kind: DefKind::Trait,
749 qualname: qualname.clone(),
754 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
755 sig: sig::item_signature(item, &self.save_ctxt),
756 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
762 for super_bound in trait_refs.iter() {
763 let trait_ref = match *super_bound {
764 ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
765 ast::GenericBound::Outlives(..) => continue,
768 let trait_ref = &trait_ref.trait_ref;
769 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
770 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
771 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
772 let span = self.span_from_span(sub_span.expect("No span found for trait ref"));
773 self.dumper.dump_ref(Ref {
776 ref_id: ::id_from_def_id(id),
780 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
781 let sub_span = self.span_from_span(sub_span.expect("No span for inheritance"));
782 self.dumper.dump_relation(Relation {
783 kind: RelationKind::SuperTrait,
785 from: ::id_from_def_id(id),
786 to: ::id_from_node_id(item.id, &self.save_ctxt),
792 // walk generics and methods
793 self.process_generic_params(generics, item.span, &qualname, item.id);
794 for method in methods {
795 let map = &self.tcx.hir;
796 self.process_trait_item(method, map.local_def_id(item.id))
800 // `item` is the module in question, represented as an item.
801 fn process_mod(&mut self, item: &ast::Item) {
802 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
803 down_cast_data!(mod_data, DefData, item.span);
804 self.dumper.dump_def(&access_from!(self.save_ctxt, item), mod_data);
808 fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
809 let path_data = self.save_ctxt.get_path_data(id, path);
810 if let Some(path_data) = path_data {
811 self.dumper.dump_ref(path_data);
815 fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
816 debug!("process_path {:?}", path);
817 if generated_code(path.span) {
820 self.dump_path_ref(id, path);
823 for seg in &path.segments {
824 if let Some(ref generic_args) = seg.args {
825 match **generic_args {
826 ast::GenericArgs::AngleBracketed(ref data) => {
827 data.args.iter().for_each(|arg| match arg {
828 ast::GenericArg::Type(ty) => self.visit_ty(ty),
832 ast::GenericArgs::Parenthesized(ref data) => {
833 for t in &data.inputs {
836 if let Some(ref t) = data.output {
844 // Modules or types in the path prefix.
845 match self.save_ctxt.get_path_def(id) {
846 HirDef::Method(did) => {
847 let ti = self.tcx.associated_item(did);
848 if ti.kind == ty::AssociatedKind::Method && ti.method_has_self_argument {
849 self.write_sub_path_trait_truncated(path);
855 HirDef::StructCtor(..) |
856 HirDef::VariantCtor(..) |
857 HirDef::AssociatedConst(..) |
862 HirDef::Variant(..) |
863 HirDef::TyAlias(..) |
864 HirDef::AssociatedTy(..) => self.write_sub_paths_truncated(path),
869 fn process_struct_lit(
873 fields: &'l [ast::Field],
874 variant: &'l ty::VariantDef,
875 base: &'l Option<P<ast::Expr>>,
877 self.write_sub_paths_truncated(path);
879 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
880 down_cast_data!(struct_lit_data, RefData, ex.span);
881 if !generated_code(ex.span) {
882 self.dumper.dump_ref(struct_lit_data);
885 for field in fields {
886 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
887 self.dumper.dump_ref(field_data);
890 self.visit_expr(&field.expr)
894 walk_list!(self, visit_expr, base);
897 fn process_method_call(
900 seg: &'l ast::PathSegment,
901 args: &'l [P<ast::Expr>],
903 debug!("process_method_call {:?} {:?}", ex, ex.span);
904 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
905 down_cast_data!(mcd, RefData, ex.span);
906 if !generated_code(ex.span) {
907 self.dumper.dump_ref(mcd);
911 // Explicit types in the turbo-fish.
912 if let Some(ref generic_args) = seg.args {
913 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
914 data.args.iter().for_each(|arg| match arg {
915 ast::GenericArg::Type(ty) => self.visit_ty(ty),
921 // walk receiver and args
922 walk_list!(self, visit_expr, args);
925 fn process_pat(&mut self, p: &'l ast::Pat) {
927 PatKind::Struct(ref _path, ref fields, _) => {
928 // FIXME do something with _path?
929 let hir_id = self.tcx.hir.node_to_hir_id(p.id);
930 let adt = match self.save_ctxt.tables.node_id_to_type_opt(hir_id) {
931 Some(ty) => ty.ty_adt_def().unwrap(),
933 visit::walk_pat(self, p);
937 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
939 for &Spanned { node: ref field, span } in fields {
940 let sub_span = self.span.span_for_first_ident(span);
941 if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
942 if !self.span.filter_generated(sub_span, span) {
944 self.span_from_span(sub_span.expect("No span fund for var ref"));
945 self.dumper.dump_ref(Ref {
946 kind: RefKind::Variable,
948 ref_id: ::id_from_def_id(variant.fields[index].did),
952 self.visit_pat(&field.pat);
955 _ => visit::walk_pat(self, p),
959 fn process_var_decl_multi(&mut self, pats: &'l [P<ast::Pat>]) {
960 let mut collector = PathCollector::new();
961 for pattern in pats {
962 // collect paths from the arm's patterns
963 collector.visit_pat(&pattern);
964 self.visit_pat(&pattern);
967 // process collected paths
968 for (id, ident, immut) in collector.collected_idents {
969 match self.save_ctxt.get_path_def(id) {
970 HirDef::Local(id) => {
971 let mut value = if immut == ast::Mutability::Immutable {
972 self.span.snippet(ident.span).to_string()
974 "<mutable>".to_string()
976 let hir_id = self.tcx.hir.node_to_hir_id(id);
977 let typ = self.save_ctxt
979 .node_id_to_type_opt(hir_id)
980 .map(|t| t.to_string())
981 .unwrap_or(String::new());
982 value.push_str(": ");
983 value.push_str(&typ);
985 if !self.span.filter_generated(Some(ident.span), ident.span) {
986 let qualname = format!("{}${}", ident.to_string(), id);
987 let id = ::id_from_node_id(id, &self.save_ctxt);
988 let span = self.span_from_span(ident.span);
990 self.dumper.dump_def(
996 kind: DefKind::Local,
999 name: ident.to_string(),
1005 docs: String::new(),
1012 HirDef::StructCtor(..) |
1013 HirDef::VariantCtor(..) |
1015 HirDef::AssociatedConst(..) |
1016 HirDef::Struct(..) |
1017 HirDef::Variant(..) |
1018 HirDef::TyAlias(..) |
1019 HirDef::AssociatedTy(..) |
1020 HirDef::SelfTy(..) => {
1021 self.dump_path_ref(id, &ast::Path::from_ident(ident));
1024 "unexpected definition kind when processing collected idents: {:?}",
1030 for (id, ref path) in collector.collected_paths {
1031 self.process_path(id, path);
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, ident, immut) in collector.collected_idents {
1043 let mut value = match immut {
1044 ast::Mutability::Immutable => value.to_string(),
1047 let hir_id = self.tcx.hir.node_to_hir_id(id);
1048 let typ = match self.save_ctxt.tables.node_id_to_type_opt(hir_id) {
1050 let typ = typ.to_string();
1051 if !value.is_empty() {
1052 value.push_str(": ");
1054 value.push_str(&typ);
1057 None => String::new(),
1060 // Get the span only for the name of the variable (I hope the path
1061 // is only ever a variable name, but who knows?).
1062 let sub_span = self.span.span_for_last_ident(ident.span);
1063 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1064 if !self.span.filter_generated(sub_span, ident.span) {
1065 let qualname = format!("{}${}", ident.to_string(), id);
1066 let id = ::id_from_node_id(id, &self.save_ctxt);
1067 let span = self.span_from_span(sub_span.expect("No span found for variable"));
1069 self.dumper.dump_def(
1075 kind: DefKind::Local,
1078 name: ident.to_string(),
1084 docs: String::new(),
1093 /// Extract macro use and definition information from the AST node defined
1094 /// by the given NodeId, using the expansion information from the node's
1097 /// If the span is not macro-generated, do nothing, else use callee and
1098 /// callsite spans to record macro definition and use data, using the
1099 /// mac_uses and mac_defs sets to prevent multiples.
1100 fn process_macro_use(&mut self, span: Span) {
1101 let source_span = span.source_callsite();
1102 if self.macro_calls.contains(&source_span) {
1105 self.macro_calls.insert(source_span);
1107 let data = match self.save_ctxt.get_macro_use_data(span) {
1112 self.dumper.macro_use(data);
1114 // FIXME write the macro def
1115 // let mut hasher = DefaultHasher::new();
1116 // data.callee_span.hash(&mut hasher);
1117 // let hash = hasher.finish();
1118 // let qualname = format!("{}::{}", data.name, hash);
1119 // Don't write macro definition for imported macros
1120 // if !self.mac_defs.contains(&data.callee_span)
1121 // && !data.imported {
1122 // self.mac_defs.insert(data.callee_span);
1123 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1124 // self.dumper.macro_data(MacroData {
1126 // name: data.name.clone(),
1127 // qualname: qualname.clone(),
1128 // // FIXME where do macro docs come from?
1129 // docs: String::new(),
1130 // }.lower(self.tcx));
1135 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1136 self.process_macro_use(trait_item.span);
1137 let vis_span = trait_item.span.shrink_to_lo();
1138 match trait_item.node {
1139 ast::TraitItemKind::Const(ref ty, ref expr) => {
1140 self.process_assoc_const(
1142 trait_item.ident.name,
1145 expr.as_ref().map(|e| &**e),
1147 respan(vis_span, ast::VisibilityKind::Public),
1151 ast::TraitItemKind::Method(ref sig, ref body) => {
1152 self.process_method(
1154 body.as_ref().map(|x| &**x),
1157 &trait_item.generics,
1158 respan(vis_span, ast::VisibilityKind::Public),
1162 ast::TraitItemKind::Type(ref bounds, ref default_ty) => {
1163 // FIXME do something with _bounds (for type refs)
1164 let name = trait_item.ident.name.to_string();
1165 let qualname = format!("::{}", self.tcx.node_path_str(trait_item.id));
1166 let sub_span = self.span
1167 .sub_span_after_keyword(trait_item.span, keywords::Type);
1169 if !self.span.filter_generated(sub_span, trait_item.span) {
1170 let span = self.span_from_span(sub_span.expect("No span found for assoc type"));
1171 let id = ::id_from_node_id(trait_item.id, &self.save_ctxt);
1173 self.dumper.dump_def(
1179 kind: DefKind::Type,
1184 value: self.span.snippet(trait_item.span),
1185 parent: Some(::id_from_def_id(trait_id)),
1188 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1189 sig: sig::assoc_type_signature(
1193 default_ty.as_ref().map(|ty| &**ty),
1196 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1201 if let &Some(ref default_ty) = default_ty {
1202 self.visit_ty(default_ty)
1205 ast::TraitItemKind::Macro(_) => {}
1209 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1210 self.process_macro_use(impl_item.span);
1211 match impl_item.node {
1212 ast::ImplItemKind::Const(ref ty, ref expr) => {
1213 self.process_assoc_const(
1215 impl_item.ident.name,
1220 impl_item.vis.clone(),
1224 ast::ImplItemKind::Method(ref sig, ref body) => {
1225 self.process_method(
1230 &impl_item.generics,
1231 impl_item.vis.clone(),
1235 ast::ImplItemKind::Type(ref ty) => {
1236 // FIXME uses of the assoc type should ideally point to this
1237 // 'def' and the name here should be a ref to the def in the
1241 ast::ImplItemKind::Macro(_) => {}
1245 /// Dumps imports in a use tree recursively.
1247 /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1248 /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1249 /// id and path. `root_item` is the topmost use tree in the hierarchy.
1251 /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1252 /// each child use tree is dumped recursively.
1253 fn process_use_tree(&mut self,
1254 use_tree: &'l ast::UseTree,
1256 root_item: &'l ast::Item,
1257 prefix: &ast::Path) {
1258 let path = &use_tree.prefix;
1260 // The access is calculated using the current tree ID, but with the root tree's visibility
1261 // (since nested trees don't have their own visibility).
1262 let access = access_from!(self.save_ctxt, root_item.vis, id);
1264 // The parent def id of a given use tree is always the enclosing item.
1265 let parent = self.save_ctxt.tcx.hir.opt_local_def_id(id)
1266 .and_then(|id| self.save_ctxt.tcx.parent_def_id(id))
1267 .map(::id_from_def_id);
1269 match use_tree.kind {
1270 ast::UseTreeKind::Simple(..) => {
1271 let ident = use_tree.ident();
1272 let path = ast::Path {
1273 segments: prefix.segments
1275 .chain(path.segments.iter())
1281 let sub_span = self.span.span_for_last_ident(path.span);
1282 let alias_span = self.span.sub_span_after_keyword(use_tree.span, keywords::As);
1283 let ref_id = self.lookup_def_id(id);
1285 if !self.span.filter_generated(sub_span, path.span) {
1286 let span = self.span_from_span(sub_span.expect("No span found for use"));
1287 let alias_span = alias_span.map(|sp| self.span_from_span(sp));
1288 self.dumper.import(&access, Import {
1289 kind: ImportKind::Use,
1290 ref_id: ref_id.map(|id| ::id_from_def_id(id)),
1293 name: ident.to_string(),
1294 value: String::new(),
1298 self.write_sub_paths_truncated(&path);
1300 ast::UseTreeKind::Glob => {
1301 let path = ast::Path {
1302 segments: prefix.segments
1304 .chain(path.segments.iter())
1310 // Make a comma-separated list of names of imported modules.
1311 let mut names = vec![];
1312 let glob_map = &self.save_ctxt.analysis.glob_map;
1313 let glob_map = glob_map.as_ref().unwrap();
1314 if glob_map.contains_key(&id) {
1315 for n in glob_map.get(&id).unwrap() {
1316 names.push(n.to_string());
1320 let sub_span = self.span.sub_span_of_token(use_tree.span,
1321 token::BinOp(token::Star));
1322 if !self.span.filter_generated(sub_span, use_tree.span) {
1324 self.span_from_span(sub_span.expect("No span found for use glob"));
1325 self.dumper.import(&access, Import {
1326 kind: ImportKind::GlobUse,
1330 name: "*".to_owned(),
1331 value: names.join(", "),
1335 self.write_sub_paths(&path);
1337 ast::UseTreeKind::Nested(ref nested_items) => {
1338 let prefix = ast::Path {
1339 segments: prefix.segments
1341 .chain(path.segments.iter())
1346 for &(ref tree, id) in nested_items {
1347 self.process_use_tree(tree, id, root_item, &prefix);
1354 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, O> {
1355 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1356 // Since we handle explicit modules ourselves in visit_item, this should
1357 // only get called for the root module of a crate.
1358 assert_eq!(id, ast::CRATE_NODE_ID);
1360 let qualname = format!("::{}", self.tcx.node_path_str(id));
1362 let cm = self.tcx.sess.codemap();
1363 let filename = cm.span_to_filename(span);
1364 let data_id = ::id_from_node_id(id, &self.save_ctxt);
1365 let children = m.items
1367 .map(|i| ::id_from_node_id(i.id, &self.save_ctxt))
1369 let span = self.span_from_span(span);
1371 self.dumper.dump_def(
1379 name: String::new(),
1382 value: filename.to_string(),
1386 docs: self.save_ctxt.docs_for_attrs(attrs),
1388 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1391 self.nest_scope(id, |v| visit::walk_mod(v, m));
1394 fn visit_item(&mut self, item: &'l ast::Item) {
1395 use syntax::ast::ItemKind::*;
1396 self.process_macro_use(item.span);
1398 Use(ref use_tree) => {
1399 let prefix = ast::Path {
1403 self.process_use_tree(use_tree, item.id, item, &prefix);
1406 let alias_span = self.span.span_for_last_ident(item.span);
1408 if !self.span.filter_generated(alias_span, item.span) {
1410 self.span_from_span(alias_span.expect("No span found for extern crate"));
1411 let parent = self.save_ctxt.tcx.hir.opt_local_def_id(item.id)
1412 .and_then(|id| self.save_ctxt.tcx.parent_def_id(id))
1413 .map(::id_from_def_id);
1420 kind: ImportKind::ExternCrate,
1424 name: item.ident.to_string(),
1425 value: String::new(),
1431 Fn(ref decl, .., ref ty_params, ref body) => {
1432 self.process_fn(item, &decl, ty_params, &body)
1434 Static(ref typ, _, ref expr) => self.process_static_or_const_item(item, typ, expr),
1435 Const(ref typ, ref expr) => self.process_static_or_const_item(item, &typ, &expr),
1436 Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1437 self.process_struct(item, def, ty_params)
1439 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1440 Impl(.., ref ty_params, ref trait_ref, ref typ, ref impl_items) => {
1441 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1443 Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1444 self.process_trait(item, generics, trait_refs, methods)
1447 self.process_mod(item);
1448 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1450 Ty(ref ty, ref ty_params) => {
1451 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1452 let value = ty_to_string(&ty);
1453 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1454 if !self.span.filter_generated(sub_span, item.span) {
1455 let span = self.span_from_span(sub_span.expect("No span found for typedef"));
1456 let id = ::id_from_node_id(item.id, &self.save_ctxt);
1458 self.dumper.dump_def(
1459 &access_from!(self.save_ctxt, item),
1461 kind: DefKind::Type,
1464 name: item.ident.to_string(),
1465 qualname: qualname.clone(),
1470 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1471 sig: sig::item_signature(item, &self.save_ctxt),
1472 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1478 self.process_generic_params(ty_params, item.span, &qualname, item.id);
1481 _ => visit::walk_item(self, item),
1485 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1486 generics.params.iter().for_each(|param| match param.kind {
1487 ast::GenericParamKind::Lifetime { .. } => {}
1488 ast::GenericParamKind::Type { ref default, .. } => {
1489 for bound in ¶m.bounds {
1490 if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1491 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1494 if let Some(ref ty) = default {
1501 fn visit_ty(&mut self, t: &'l ast::Ty) {
1502 self.process_macro_use(t.span);
1504 ast::TyKind::Path(_, ref path) => {
1505 if generated_code(t.span) {
1509 if let Some(id) = self.lookup_def_id(t.id) {
1510 if let Some(sub_span) = self.span.sub_span_for_type_name(t.span) {
1511 let span = self.span_from_span(sub_span);
1512 self.dumper.dump_ref(Ref {
1513 kind: RefKind::Type,
1515 ref_id: ::id_from_def_id(id),
1520 self.write_sub_paths_truncated(path);
1521 visit::walk_path(self, path);
1523 ast::TyKind::Array(ref element, ref length) => {
1524 self.visit_ty(element);
1525 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1527 _ => visit::walk_ty(self, t),
1531 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1532 debug!("visit_expr {:?}", ex.node);
1533 self.process_macro_use(ex.span);
1535 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1536 let hir_expr = self.save_ctxt.tcx.hir.expect_expr(ex.id);
1537 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1538 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1540 visit::walk_expr(self, ex);
1544 let def = self.save_ctxt.get_path_def(hir_expr.id);
1545 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1547 ast::ExprKind::MethodCall(ref seg, ref args) => self.process_method_call(ex, seg, args),
1548 ast::ExprKind::Field(ref sub_ex, _) => {
1549 self.visit_expr(&sub_ex);
1551 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1552 down_cast_data!(field_data, RefData, ex.span);
1553 if !generated_code(ex.span) {
1554 self.dumper.dump_ref(field_data);
1558 ast::ExprKind::Closure(_, _, _, ref decl, ref body, _fn_decl_span) => {
1559 let mut id = String::from("$");
1560 id.push_str(&ex.id.to_string());
1562 // walk arg and return types
1563 for arg in &decl.inputs {
1564 self.visit_ty(&arg.ty);
1567 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1568 self.visit_ty(&ret_ty);
1572 self.nest_tables(ex.id, |v| {
1573 v.process_formals(&decl.inputs, &id);
1574 v.nest_scope(ex.id, |v| v.visit_expr(body))
1577 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1578 let value = self.span.snippet(subexpression.span);
1579 self.process_var_decl(pattern, value);
1580 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1581 self.visit_expr(subexpression);
1582 visit::walk_block(self, block);
1584 ast::ExprKind::WhileLet(ref pats, ref subexpression, ref block, _) => {
1585 self.process_var_decl_multi(pats);
1586 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1587 self.visit_expr(subexpression);
1588 visit::walk_block(self, block);
1590 ast::ExprKind::IfLet(ref pats, ref subexpression, ref block, ref opt_else) => {
1591 self.process_var_decl_multi(pats);
1592 self.visit_expr(subexpression);
1593 visit::walk_block(self, block);
1594 opt_else.as_ref().map(|el| self.visit_expr(el));
1596 ast::ExprKind::Repeat(ref element, ref count) => {
1597 self.visit_expr(element);
1598 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1600 // In particular, we take this branch for call and path expressions,
1601 // where we'll index the idents involved just by continuing to walk.
1602 _ => visit::walk_expr(self, ex),
1606 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1607 // These shouldn't exist in the AST at this point, log a span bug.
1610 "macro invocation should have been expanded out of AST"
1614 fn visit_pat(&mut self, p: &'l ast::Pat) {
1615 self.process_macro_use(p.span);
1616 self.process_pat(p);
1619 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1620 self.process_var_decl_multi(&arm.pats);
1621 walk_list!(self, visit_expr, &arm.guard);
1622 self.visit_expr(&arm.body);
1625 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1626 self.process_path(id, p);
1629 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1630 self.process_macro_use(s.span);
1631 visit::walk_stmt(self, s)
1634 fn visit_local(&mut self, l: &'l ast::Local) {
1635 self.process_macro_use(l.span);
1638 .map(|i| self.span.snippet(i.span))
1639 .unwrap_or(String::new());
1640 self.process_var_decl(&l.pat, value);
1642 // Just walk the initialiser and type (don't want to walk the pattern again).
1643 walk_list!(self, visit_ty, &l.ty);
1644 walk_list!(self, visit_expr, &l.init);
1647 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1648 let access = access_from!(self.save_ctxt, item);
1651 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1652 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1653 down_cast_data!(fn_data, DefData, item.span);
1657 |v| v.process_formals(&decl.inputs, &fn_data.qualname),
1659 self.process_generic_params(generics, item.span, &fn_data.qualname, item.id);
1660 self.dumper.dump_def(&access, fn_data);
1663 for arg in &decl.inputs {
1664 self.visit_ty(&arg.ty);
1667 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1668 self.visit_ty(&ret_ty);
1671 ast::ForeignItemKind::Static(ref ty, _) => {
1672 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1673 down_cast_data!(var_data, DefData, item.span);
1674 self.dumper.dump_def(&access, var_data);
1679 ast::ForeignItemKind::Ty => {
1680 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1681 down_cast_data!(var_data, DefData, item.span);
1682 self.dumper.dump_def(&access, var_data);
1685 ast::ForeignItemKind::Macro(..) => {}