1 //! Write the output of rustc's analysis to an implementor of Dump.
3 //! Dumping the analysis is implemented by walking the AST and getting a bunch of
4 //! info out from all over the place. We use `DefId`s to identify objects. The
5 //! tricky part is getting syntactic (span, source text) and semantic (reference
6 //! `DefId`s) information for parts of expressions which the compiler has discarded.
7 //! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
8 //! path and a reference to `baz`, but we want spans and references for all three
11 //! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
12 //! from spans (e.g., the span for `bar` from the above example path).
13 //! DumpVisitor walks the AST and processes it, and JsonDumper is used for
14 //! recording the output.
16 use rustc::hir::def::{Res, DefKind as HirDefKind};
17 use rustc::hir::def_id::DefId;
18 use rustc::session::config::Input;
20 use rustc::ty::{self, DefIdTree, TyCtxt};
21 use rustc_data_structures::fx::FxHashSet;
26 use syntax::ast::{self, Attribute, NodeId, PatKind, CRATE_NODE_ID};
27 use syntax::parse::token;
28 use syntax::visit::{self, Visitor};
29 use syntax::print::pprust::{
31 generic_params_to_string,
35 use syntax::source_map::{Spanned, DUMMY_SP, respan};
36 use syntax::walk_list;
39 use crate::{escape, generated_code, id_from_def_id, id_from_node_id, lower_attributes,
40 PathCollector, SaveContext};
41 use crate::json_dumper::{Access, DumpOutput, JsonDumper};
42 use crate::span_utils::SpanUtils;
45 use rls_data::{CompilationOptions, CratePreludeData, Def, DefKind, GlobalCrateId, Import,
46 ImportKind, Ref, RefKind, Relation, RelationKind, SpanData};
48 use log::{debug, error};
50 macro_rules! down_cast_data {
51 ($id:ident, $kind:ident, $sp:expr) => {
52 let $id = if let super::Data::$kind(data) = $id {
55 span_bug!($sp, "unexpected data kind: {:?}", $id);
60 macro_rules! access_from {
61 ($save_ctxt:expr, $item:expr, $id:expr) => {
63 public: $item.vis.node.is_pub(),
64 reachable: $save_ctxt.access_levels.is_reachable($id),
69 macro_rules! access_from_vis {
70 ($save_ctxt:expr, $vis:expr, $id:expr) => {
72 public: $vis.node.is_pub(),
73 reachable: $save_ctxt.access_levels.is_reachable($id),
78 pub struct DumpVisitor<'l, 'tcx, 'll, O: DumpOutput> {
79 save_ctxt: SaveContext<'l, 'tcx>,
81 dumper: &'ll mut JsonDumper<O>,
87 // Set of macro definition (callee) spans, and the set
88 // of macro use (callsite) spans. We store these to ensure
89 // we only write one macro def per unique macro definition, and
90 // one macro use per unique callsite span.
91 // mac_defs: FxHashSet<Span>,
92 // macro_calls: FxHashSet<Span>,
95 impl<'l, 'tcx, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> {
97 save_ctxt: SaveContext<'l, 'tcx>,
98 dumper: &'ll mut JsonDumper<O>,
99 ) -> DumpVisitor<'l, 'tcx, 'll, O> {
100 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
106 cur_scope: CRATE_NODE_ID,
107 // mac_defs: FxHashSet::default(),
108 // macro_calls: FxHashSet::default(),
112 fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
114 F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
116 let parent_scope = self.cur_scope;
117 self.cur_scope = scope_id;
119 self.cur_scope = parent_scope;
122 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
124 F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
126 let item_def_id = self.tcx.hir().local_def_id(item_id);
127 if self.tcx.has_typeck_tables(item_def_id) {
128 let tables = self.tcx.typeck_tables_of(item_def_id);
129 let old_tables = self.save_ctxt.tables;
130 self.save_ctxt.tables = tables;
132 self.save_ctxt.tables = old_tables;
138 fn span_from_span(&self, span: Span) -> SpanData {
139 self.save_ctxt.span_from_span(span)
142 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
143 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
144 let crate_root = source_file.map(|source_file| {
145 let source_file = Path::new(source_file);
146 match source_file.file_name() {
147 Some(_) => source_file.parent().unwrap().display(),
148 None => source_file.display(),
152 let data = CratePreludeData {
153 crate_id: GlobalCrateId {
155 disambiguator: self.tcx
157 .local_crate_disambiguator()
161 crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
162 external_crates: self.save_ctxt.get_external_crates(),
163 span: self.span_from_span(krate.span),
166 self.dumper.crate_prelude(data);
169 pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
170 // Apply possible `remap-path-prefix` remapping to the input source file
171 // (and don't include remapping args anymore)
172 let (program, arguments) = {
173 let remap_arg_indices = {
174 let mut indices = FxHashSet::default();
175 // Args are guaranteed to be valid UTF-8 (checked early)
176 for (i, e) in env::args().enumerate() {
177 if e.starts_with("--remap-path-prefix=") {
179 } else if e == "--remap-path-prefix" {
181 indices.insert(i + 1);
187 let mut args = env::args()
189 .filter(|(i, _)| !remap_arg_indices.contains(i))
192 Input::File(ref path) if path == Path::new(&arg) => {
193 let mapped = &self.tcx.sess.local_crate_source_file;
204 (args.next().unwrap(), args.collect())
207 let data = CompilationOptions {
208 directory: self.tcx.sess.working_dir.0.clone(),
211 output: self.save_ctxt.compilation_output(crate_name),
214 self.dumper.compilation_opts(data);
217 fn write_sub_paths(&mut self, path: &ast::Path) {
218 for seg in &path.segments {
219 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
220 self.dumper.dump_ref(data);
225 // As write_sub_paths, but does not process the last ident in the path (assuming it
226 // will be processed elsewhere). See note on write_sub_paths about global.
227 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
228 for seg in &path.segments[..path.segments.len() - 1] {
229 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
230 self.dumper.dump_ref(data);
235 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
236 match self.save_ctxt.get_path_res(ref_id) {
237 Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => None,
238 def => Some(def.def_id()),
242 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
244 self.visit_pat(&arg.pat);
245 let mut collector = PathCollector::new();
246 collector.visit_pat(&arg.pat);
248 for (id, ident, ..) in collector.collected_idents {
249 let hir_id = self.tcx.hir().node_to_hir_id(id);
250 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
251 Some(s) => s.to_string(),
254 if !self.span.filter_generated(ident.span) {
255 let id = id_from_node_id(id, &self.save_ctxt);
256 let span = self.span_from_span(ident.span);
258 self.dumper.dump_def(
264 kind: DefKind::Local,
267 name: ident.to_string(),
268 qualname: format!("{}::{}", qualname, ident.to_string()),
285 sig: &'l ast::MethodSig,
286 body: Option<&'l ast::Block>,
289 generics: &'l ast::Generics,
290 vis: ast::Visibility,
293 debug!("process_method: {}:{}", id, ident);
295 if let Some(mut method_data) = self.save_ctxt.get_method_data(id, ident, span) {
296 let sig_str = crate::make_signature(&sig.decl, &generics);
300 |v| v.process_formals(&sig.decl.inputs, &method_data.qualname),
304 self.process_generic_params(&generics, &method_data.qualname, id);
306 method_data.value = sig_str;
307 method_data.sig = sig::method_signature(id, ident, generics, sig, &self.save_ctxt);
308 let hir_id = self.tcx.hir().node_to_hir_id(id);
309 self.dumper.dump_def(&access_from_vis!(self.save_ctxt, vis, hir_id), method_data);
312 // walk arg and return types
313 for arg in &sig.decl.inputs {
314 self.visit_ty(&arg.ty);
317 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
318 self.visit_ty(ret_ty);
322 if let Some(body) = body {
323 self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
327 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
328 let field_data = self.save_ctxt.get_field_data(field, parent_id);
329 if let Some(field_data) = field_data {
330 let hir_id = self.tcx.hir().node_to_hir_id(field.id);
331 self.dumper.dump_def(&access_from!(self.save_ctxt, field, hir_id), field_data);
335 // Dump generic params bindings, then visit_generics
336 fn process_generic_params(
338 generics: &'l ast::Generics,
342 for param in &generics.params {
344 ast::GenericParamKind::Lifetime { .. } => {}
345 ast::GenericParamKind::Type { .. } => {
346 let param_ss = param.ident.span;
347 let name = escape(self.span.snippet(param_ss));
348 // Append $id to name to make sure each one is unique.
349 let qualname = format!("{}::{}${}", prefix, name, id);
350 if !self.span.filter_generated(param_ss) {
351 let id = id_from_node_id(param.id, &self.save_ctxt);
352 let span = self.span_from_span(param_ss);
354 self.dumper.dump_def(
365 value: String::new(),
376 ast::GenericParamKind::Const { .. } => {}
379 self.visit_generics(generics);
385 decl: &'l ast::FnDecl,
386 ty_params: &'l ast::Generics,
387 body: &'l ast::Block,
389 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
390 down_cast_data!(fn_data, DefData, item.span);
393 |v| v.process_formals(&decl.inputs, &fn_data.qualname),
395 self.process_generic_params(ty_params, &fn_data.qualname, item.id);
396 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
397 self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), fn_data);
400 for arg in &decl.inputs {
401 self.visit_ty(&arg.ty);
404 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
405 self.visit_ty(&ret_ty);
408 self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
411 fn process_static_or_const_item(
417 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
418 self.nest_tables(item.id, |v| {
419 if let Some(var_data) = v.save_ctxt.get_item_data(item) {
420 down_cast_data!(var_data, DefData, item.span);
421 v.dumper.dump_def(&access_from!(v.save_ctxt, item, hir_id), var_data);
428 fn process_assoc_const(
433 expr: Option<&'l ast::Expr>,
435 vis: ast::Visibility,
436 attrs: &'l [Attribute],
438 let qualname = format!("::{}",
439 self.tcx.def_path_str(self.tcx.hir().local_def_id(id)));
441 if !self.span.filter_generated(ident.span) {
442 let sig = sig::assoc_const_signature(id, ident.name, typ, expr, &self.save_ctxt);
443 let span = self.span_from_span(ident.span);
444 let hir_id = self.tcx.hir().node_to_hir_id(id);
446 self.dumper.dump_def(
447 &access_from_vis!(self.save_ctxt, vis, hir_id),
449 kind: DefKind::Const,
450 id: id_from_node_id(id, &self.save_ctxt),
452 name: ident.name.to_string(),
454 value: ty_to_string(&typ),
455 parent: Some(id_from_def_id(parent_id)),
458 docs: self.save_ctxt.docs_for_attrs(attrs),
460 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
465 // walk type and init value
466 self.nest_tables(id, |v| {
468 if let Some(expr) = expr {
474 // FIXME tuple structs should generate tuple-specific data.
478 def: &'l ast::VariantData,
479 ty_params: &'l ast::Generics,
481 debug!("process_struct {:?} {:?}", item, item.span);
482 let name = item.ident.to_string();
483 let qualname = format!("::{}",
484 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
486 let kind = match item.node {
487 ast::ItemKind::Struct(_, _) => DefKind::Struct,
488 ast::ItemKind::Union(_, _) => DefKind::Union,
492 let (value, fields) = match item.node {
493 ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, ..), ..) |
494 ast::ItemKind::Union(ast::VariantData::Struct(ref fields, ..), ..) => {
495 let include_priv_fields = !self.save_ctxt.config.pub_only;
496 let fields_str = fields
499 .filter_map(|(i, f)| {
500 if include_priv_fields || f.vis.node.is_pub() {
502 .map(|i| i.to_string())
503 .or_else(|| Some(i.to_string()))
510 let value = format!("{} {{ {} }}", name, fields_str);
515 .map(|f| id_from_node_id(f.id, &self.save_ctxt))
519 _ => (String::new(), vec![]),
522 if !self.span.filter_generated(item.ident.span) {
523 let span = self.span_from_span(item.ident.span);
524 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
525 self.dumper.dump_def(
526 &access_from!(self.save_ctxt, item, hir_id),
529 id: id_from_node_id(item.id, &self.save_ctxt),
532 qualname: qualname.clone(),
537 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
538 sig: sig::item_signature(item, &self.save_ctxt),
539 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
544 for field in def.fields() {
545 self.process_struct_field_def(field, item.id);
546 self.visit_ty(&field.ty);
549 self.process_generic_params(ty_params, &qualname, item.id);
555 enum_definition: &'l ast::EnumDef,
556 ty_params: &'l ast::Generics,
558 let enum_data = self.save_ctxt.get_item_data(item);
559 let enum_data = match enum_data {
563 down_cast_data!(enum_data, DefData, item.span);
565 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
566 let access = access_from!(self.save_ctxt, item, hir_id);
568 for variant in &enum_definition.variants {
569 let name = variant.node.ident.name.to_string();
570 let qualname = format!("{}::{}", enum_data.qualname, name);
571 let name_span = variant.node.ident.span;
573 match variant.node.data {
574 ast::VariantData::Struct(ref fields, ..) => {
575 let fields_str = fields
579 f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
583 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
584 if !self.span.filter_generated(name_span) {
585 let span = self.span_from_span(name_span);
586 let id = id_from_node_id(variant.node.id, &self.save_ctxt);
587 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
589 self.dumper.dump_def(
592 kind: DefKind::StructVariant,
601 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
602 sig: sig::variant_signature(variant, &self.save_ctxt),
603 attributes: lower_attributes(
604 variant.node.attrs.clone(),
612 let mut value = format!("{}::{}", enum_data.name, name);
613 if let &ast::VariantData::Tuple(ref fields, _) = v {
615 value.push_str(&fields
617 .map(|f| ty_to_string(&f.ty))
622 if !self.span.filter_generated(name_span) {
623 let span = self.span_from_span(name_span);
624 let id = id_from_node_id(variant.node.id, &self.save_ctxt);
625 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
627 self.dumper.dump_def(
630 kind: DefKind::TupleVariant,
639 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
640 sig: sig::variant_signature(variant, &self.save_ctxt),
641 attributes: lower_attributes(
642 variant.node.attrs.clone(),
652 for field in variant.node.data.fields() {
653 self.process_struct_field_def(field, variant.node.id);
654 self.visit_ty(&field.ty);
657 self.process_generic_params(ty_params, &enum_data.qualname, item.id);
658 self.dumper.dump_def(&access, enum_data);
664 generics: &'l ast::Generics,
665 trait_ref: &'l Option<ast::TraitRef>,
667 impl_items: &'l [ast::ImplItem],
669 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
670 if !self.span.filter_generated(item.span) {
671 if let super::Data::RelationData(rel, imp) = impl_data {
672 self.dumper.dump_relation(rel);
673 self.dumper.dump_impl(imp);
675 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
680 if let &Some(ref trait_ref) = trait_ref {
681 self.process_path(trait_ref.ref_id, &trait_ref.path);
683 self.process_generic_params(generics, "", item.id);
684 for impl_item in impl_items {
685 let map = &self.tcx.hir();
686 self.process_impl_item(impl_item, map.local_def_id(item.id));
693 generics: &'l ast::Generics,
694 trait_refs: &'l ast::GenericBounds,
695 methods: &'l [ast::TraitItem],
697 let name = item.ident.to_string();
698 let qualname = format!("::{}",
699 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
700 let mut val = name.clone();
701 if !generics.params.is_empty() {
702 val.push_str(&generic_params_to_string(&generics.params));
704 if !trait_refs.is_empty() {
706 val.push_str(&bounds_to_string(trait_refs));
708 if !self.span.filter_generated(item.ident.span) {
709 let id = id_from_node_id(item.id, &self.save_ctxt);
710 let span = self.span_from_span(item.ident.span);
711 let children = methods
713 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
715 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
716 self.dumper.dump_def(
717 &access_from!(self.save_ctxt, item, hir_id),
719 kind: DefKind::Trait,
723 qualname: qualname.clone(),
728 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
729 sig: sig::item_signature(item, &self.save_ctxt),
730 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
736 for super_bound in trait_refs.iter() {
737 let trait_ref = match *super_bound {
738 ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
739 ast::GenericBound::Outlives(..) => continue,
742 let trait_ref = &trait_ref.trait_ref;
743 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
744 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
745 if !self.span.filter_generated(sub_span) {
746 let span = self.span_from_span(sub_span);
747 self.dumper.dump_ref(Ref {
750 ref_id: id_from_def_id(id),
753 self.dumper.dump_relation(Relation {
754 kind: RelationKind::SuperTrait,
756 from: id_from_def_id(id),
757 to: id_from_node_id(item.id, &self.save_ctxt),
763 // walk generics and methods
764 self.process_generic_params(generics, &qualname, item.id);
765 for method in methods {
766 let map = &self.tcx.hir();
767 self.process_trait_item(method, map.local_def_id(item.id))
771 // `item` is the module in question, represented as an item.
772 fn process_mod(&mut self, item: &ast::Item) {
773 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
774 down_cast_data!(mod_data, DefData, item.span);
775 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
776 self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), mod_data);
780 fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
781 let path_data = self.save_ctxt.get_path_data(id, path);
782 if let Some(path_data) = path_data {
783 self.dumper.dump_ref(path_data);
787 fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
788 if self.span.filter_generated(path.span) {
791 self.dump_path_ref(id, path);
794 for seg in &path.segments {
795 if let Some(ref generic_args) = seg.args {
796 match **generic_args {
797 ast::GenericArgs::AngleBracketed(ref data) => {
798 for arg in &data.args {
800 ast::GenericArg::Type(ty) => self.visit_ty(ty),
805 ast::GenericArgs::Parenthesized(ref data) => {
806 for t in &data.inputs {
809 if let Some(ref t) = data.output {
817 self.write_sub_paths_truncated(path);
820 fn process_struct_lit(
824 fields: &'l [ast::Field],
825 variant: &'l ty::VariantDef,
826 base: &'l Option<P<ast::Expr>>,
828 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
829 self.write_sub_paths_truncated(path);
830 down_cast_data!(struct_lit_data, RefData, ex.span);
831 if !generated_code(ex.span) {
832 self.dumper.dump_ref(struct_lit_data);
835 for field in fields {
836 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
837 self.dumper.dump_ref(field_data);
840 self.visit_expr(&field.expr)
844 walk_list!(self, visit_expr, base);
847 fn process_method_call(
850 seg: &'l ast::PathSegment,
851 args: &'l [P<ast::Expr>],
853 debug!("process_method_call {:?} {:?}", ex, ex.span);
854 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
855 down_cast_data!(mcd, RefData, ex.span);
856 if !generated_code(ex.span) {
857 self.dumper.dump_ref(mcd);
861 // Explicit types in the turbo-fish.
862 if let Some(ref generic_args) = seg.args {
863 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
864 for arg in &data.args {
866 ast::GenericArg::Type(ty) => self.visit_ty(ty),
873 // walk receiver and args
874 walk_list!(self, visit_expr, args);
877 fn process_pat(&mut self, p: &'l ast::Pat) {
879 PatKind::Struct(ref _path, ref fields, _) => {
880 // FIXME do something with _path?
881 let hir_id = self.tcx.hir().node_to_hir_id(p.id);
882 let adt = match self.save_ctxt.tables.node_type_opt(hir_id) {
883 Some(ty) => ty.ty_adt_def().unwrap(),
885 visit::walk_pat(self, p);
889 let variant = adt.variant_of_res(self.save_ctxt.get_path_res(p.id));
891 for &Spanned { node: ref field, .. } in fields {
892 if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
893 if !self.span.filter_generated(field.ident.span) {
894 let span = self.span_from_span(field.ident.span);
895 self.dumper.dump_ref(Ref {
896 kind: RefKind::Variable,
898 ref_id: id_from_def_id(variant.fields[index].did),
902 self.visit_pat(&field.pat);
905 _ => visit::walk_pat(self, p),
909 fn process_var_decl_multi(&mut self, pats: &'l [P<ast::Pat>]) {
910 let mut collector = PathCollector::new();
911 for pattern in pats {
912 // collect paths from the arm's patterns
913 collector.visit_pat(&pattern);
914 self.visit_pat(&pattern);
917 // process collected paths
918 for (id, ident, immut) in collector.collected_idents {
919 match self.save_ctxt.get_path_res(id) {
920 Res::Local(hir_id) => {
921 let mut value = if immut == ast::Mutability::Immutable {
922 self.span.snippet(ident.span)
924 "<mutable>".to_owned()
926 let id = self.tcx.hir().hir_to_node_id(hir_id);
927 let typ = self.save_ctxt
929 .node_type_opt(hir_id)
930 .map(|t| t.to_string())
931 .unwrap_or_default();
932 value.push_str(": ");
933 value.push_str(&typ);
935 if !self.span.filter_generated(ident.span) {
936 let qualname = format!("{}${}", ident.to_string(), id);
937 let id = id_from_node_id(id, &self.save_ctxt);
938 let span = self.span_from_span(ident.span);
940 self.dumper.dump_def(
946 kind: DefKind::Local,
949 name: ident.to_string(),
962 Res::Def(HirDefKind::Ctor(..), _) |
963 Res::Def(HirDefKind::Const, _) |
964 Res::Def(HirDefKind::AssocConst, _) |
965 Res::Def(HirDefKind::Struct, _) |
966 Res::Def(HirDefKind::Variant, _) |
967 Res::Def(HirDefKind::TyAlias, _) |
968 Res::Def(HirDefKind::AssocTy, _) |
970 self.dump_path_ref(id, &ast::Path::from_ident(ident));
973 "unexpected definition kind when processing collected idents: {:?}",
979 for (id, ref path) in collector.collected_paths {
980 self.process_path(id, path);
984 fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
985 // The local could declare multiple new vars, we must walk the
986 // pattern and collect them all.
987 let mut collector = PathCollector::new();
988 collector.visit_pat(&p);
991 for (id, ident, immut) in collector.collected_idents {
992 let mut value = match immut {
993 ast::Mutability::Immutable => value.to_string(),
996 let hir_id = self.tcx.hir().node_to_hir_id(id);
997 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
999 let typ = typ.to_string();
1000 if !value.is_empty() {
1001 value.push_str(": ");
1003 value.push_str(&typ);
1006 None => String::new(),
1009 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1010 if !self.span.filter_generated(ident.span) {
1011 let qualname = format!("{}${}", ident.to_string(), id);
1012 let id = id_from_node_id(id, &self.save_ctxt);
1013 let span = self.span_from_span(ident.span);
1015 self.dumper.dump_def(
1021 kind: DefKind::Local,
1024 name: ident.to_string(),
1030 docs: String::new(),
1039 /// Extracts macro use and definition information from the AST node defined
1040 /// by the given NodeId, using the expansion information from the node's
1043 /// If the span is not macro-generated, do nothing, else use callee and
1044 /// callsite spans to record macro definition and use data, using the
1045 /// mac_uses and mac_defs sets to prevent multiples.
1046 fn process_macro_use(&mut self, _span: Span) {
1047 // FIXME if we're not dumping the defs (see below), there is no point
1048 // dumping refs either.
1049 // let source_span = span.source_callsite();
1050 // if !self.macro_calls.insert(source_span) {
1054 // let data = match self.save_ctxt.get_macro_use_data(span) {
1056 // Some(data) => data,
1059 // self.dumper.macro_use(data);
1061 // FIXME write the macro def
1062 // let mut hasher = DefaultHasher::new();
1063 // data.callee_span.hash(&mut hasher);
1064 // let hash = hasher.finish();
1065 // let qualname = format!("{}::{}", data.name, hash);
1066 // Don't write macro definition for imported macros
1067 // if !self.mac_defs.contains(&data.callee_span)
1068 // && !data.imported {
1069 // self.mac_defs.insert(data.callee_span);
1070 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1071 // self.dumper.macro_data(MacroData {
1073 // name: data.name.clone(),
1074 // qualname: qualname.clone(),
1075 // // FIXME where do macro docs come from?
1076 // docs: String::new(),
1077 // }.lower(self.tcx));
1082 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1083 self.process_macro_use(trait_item.span);
1084 let vis_span = trait_item.span.shrink_to_lo();
1085 match trait_item.node {
1086 ast::TraitItemKind::Const(ref ty, ref expr) => {
1087 self.process_assoc_const(
1091 expr.as_ref().map(|e| &**e),
1093 respan(vis_span, ast::VisibilityKind::Public),
1097 ast::TraitItemKind::Method(ref sig, ref body) => {
1098 self.process_method(
1100 body.as_ref().map(|x| &**x),
1103 &trait_item.generics,
1104 respan(vis_span, ast::VisibilityKind::Public),
1108 ast::TraitItemKind::Type(ref bounds, ref default_ty) => {
1109 // FIXME do something with _bounds (for type refs)
1110 let name = trait_item.ident.name.to_string();
1111 let qualname = format!("::{}",
1112 self.tcx.def_path_str(self.tcx.hir().local_def_id(trait_item.id)));
1114 if !self.span.filter_generated(trait_item.ident.span) {
1115 let span = self.span_from_span(trait_item.ident.span);
1116 let id = id_from_node_id(trait_item.id, &self.save_ctxt);
1118 self.dumper.dump_def(
1124 kind: DefKind::Type,
1129 value: self.span.snippet(trait_item.span),
1130 parent: Some(id_from_def_id(trait_id)),
1133 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1134 sig: sig::assoc_type_signature(
1138 default_ty.as_ref().map(|ty| &**ty),
1141 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1146 if let &Some(ref default_ty) = default_ty {
1147 self.visit_ty(default_ty)
1150 ast::TraitItemKind::Macro(_) => {}
1154 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1155 self.process_macro_use(impl_item.span);
1156 match impl_item.node {
1157 ast::ImplItemKind::Const(ref ty, ref expr) => {
1158 self.process_assoc_const(
1164 impl_item.vis.clone(),
1168 ast::ImplItemKind::Method(ref sig, ref body) => {
1169 self.process_method(
1174 &impl_item.generics,
1175 impl_item.vis.clone(),
1179 ast::ImplItemKind::Type(ref ty) => {
1180 // FIXME: uses of the assoc type should ideally point to this
1181 // 'def' and the name here should be a ref to the def in the
1185 ast::ImplItemKind::Existential(ref bounds) => {
1186 // FIXME: uses of the assoc type should ideally point to this
1187 // 'def' and the name here should be a ref to the def in the
1189 for bound in bounds.iter() {
1190 if let ast::GenericBound::Trait(trait_ref, _) = bound {
1191 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1195 ast::ImplItemKind::Macro(_) => {}
1199 /// Dumps imports in a use tree recursively.
1201 /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1202 /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1203 /// ID and path. `root_item` is the topmost use tree in the hierarchy.
1205 /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1206 /// each child use tree is dumped recursively.
1207 fn process_use_tree(&mut self,
1208 use_tree: &'l ast::UseTree,
1210 root_item: &'l ast::Item,
1211 prefix: &ast::Path) {
1212 let path = &use_tree.prefix;
1214 // The access is calculated using the current tree ID, but with the root tree's visibility
1215 // (since nested trees don't have their own visibility).
1216 let hir_id = self.tcx.hir().node_to_hir_id(id);
1217 let access = access_from!(self.save_ctxt, root_item, hir_id);
1219 // The parent `DefId` of a given use tree is always the enclosing item.
1220 let parent = self.save_ctxt.tcx.hir().opt_local_def_id(id)
1221 .and_then(|id| self.save_ctxt.tcx.parent(id))
1222 .map(id_from_def_id);
1224 match use_tree.kind {
1225 ast::UseTreeKind::Simple(alias, ..) => {
1226 let ident = use_tree.ident();
1227 let path = ast::Path {
1228 segments: prefix.segments
1230 .chain(path.segments.iter())
1236 let sub_span = path.segments.last().unwrap().ident.span;
1237 if !self.span.filter_generated(sub_span) {
1238 let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id));
1239 let alias_span = alias.map(|i| self.span_from_span(i.span));
1240 let span = self.span_from_span(sub_span);
1241 self.dumper.import(&access, Import {
1242 kind: ImportKind::Use,
1246 name: ident.to_string(),
1247 value: String::new(),
1250 self.write_sub_paths_truncated(&path);
1253 ast::UseTreeKind::Glob => {
1254 let path = ast::Path {
1255 segments: prefix.segments
1257 .chain(path.segments.iter())
1263 // Make a comma-separated list of names of imported modules.
1264 let def_id = self.tcx.hir().local_def_id(id);
1265 let names = self.tcx.names_imported_by_glob_use(def_id);
1266 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1268 // Otherwise it's a span with wrong macro expansion info, which
1269 // we don't want to track anyway, since it's probably macro-internal `use`
1270 if let Some(sub_span) =
1271 self.span.sub_span_of_token(use_tree.span, token::BinOp(token::Star))
1273 if !self.span.filter_generated(use_tree.span) {
1274 let span = self.span_from_span(sub_span);
1276 self.dumper.import(&access, Import {
1277 kind: ImportKind::GlobUse,
1281 name: "*".to_owned(),
1282 value: names.join(", "),
1285 self.write_sub_paths(&path);
1289 ast::UseTreeKind::Nested(ref nested_items) => {
1290 let prefix = ast::Path {
1291 segments: prefix.segments
1293 .chain(path.segments.iter())
1298 for &(ref tree, id) in nested_items {
1299 self.process_use_tree(tree, id, root_item, &prefix);
1305 fn process_bounds(&mut self, bounds: &'l ast::GenericBounds) {
1306 for bound in bounds {
1307 if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1308 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1314 impl<'l, 'tcx, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, O> {
1315 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1316 // Since we handle explicit modules ourselves in visit_item, this should
1317 // only get called for the root module of a crate.
1318 assert_eq!(id, ast::CRATE_NODE_ID);
1320 let qualname = format!("::{}",
1321 self.tcx.def_path_str(self.tcx.hir().local_def_id(id)));
1323 let cm = self.tcx.sess.source_map();
1324 let filename = cm.span_to_filename(span);
1325 let data_id = id_from_node_id(id, &self.save_ctxt);
1326 let children = m.items
1328 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
1330 let span = self.span_from_span(span);
1332 self.dumper.dump_def(
1340 name: String::new(),
1343 value: filename.to_string(),
1347 docs: self.save_ctxt.docs_for_attrs(attrs),
1349 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1352 self.nest_scope(id, |v| visit::walk_mod(v, m));
1355 fn visit_item(&mut self, item: &'l ast::Item) {
1356 use syntax::ast::ItemKind::*;
1357 self.process_macro_use(item.span);
1359 Use(ref use_tree) => {
1360 let prefix = ast::Path {
1364 self.process_use_tree(use_tree, item.id, item, &prefix);
1367 let name_span = item.ident.span;
1368 if !self.span.filter_generated(name_span) {
1369 let span = self.span_from_span(name_span);
1370 let parent = self.save_ctxt.tcx.hir().opt_local_def_id(item.id)
1371 .and_then(|id| self.save_ctxt.tcx.parent(id))
1372 .map(id_from_def_id);
1379 kind: ImportKind::ExternCrate,
1383 name: item.ident.to_string(),
1384 value: String::new(),
1390 Fn(ref decl, .., ref ty_params, ref body) => {
1391 self.process_fn(item, &decl, ty_params, &body)
1393 Static(ref typ, _, ref expr) => self.process_static_or_const_item(item, typ, expr),
1394 Const(ref typ, ref expr) => self.process_static_or_const_item(item, &typ, &expr),
1395 Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1396 self.process_struct(item, def, ty_params)
1398 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1399 Impl(.., ref ty_params, ref trait_ref, ref typ, ref impl_items) => {
1400 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1402 Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1403 self.process_trait(item, generics, trait_refs, methods)
1406 self.process_mod(item);
1407 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1409 Ty(ref ty, ref ty_params) => {
1410 let qualname = format!("::{}",
1411 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
1412 let value = ty_to_string(&ty);
1413 if !self.span.filter_generated(item.ident.span) {
1414 let span = self.span_from_span(item.ident.span);
1415 let id = id_from_node_id(item.id, &self.save_ctxt);
1416 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1418 self.dumper.dump_def(
1419 &access_from!(self.save_ctxt, item, hir_id),
1421 kind: DefKind::Type,
1424 name: item.ident.to_string(),
1425 qualname: qualname.clone(),
1430 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1431 sig: sig::item_signature(item, &self.save_ctxt),
1432 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1438 self.process_generic_params(ty_params, &qualname, item.id);
1440 Existential(ref _bounds, ref ty_params) => {
1441 let qualname = format!("::{}",
1442 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
1443 // FIXME do something with _bounds
1444 let value = String::new();
1445 if !self.span.filter_generated(item.ident.span) {
1446 let span = self.span_from_span(item.ident.span);
1447 let id = id_from_node_id(item.id, &self.save_ctxt);
1448 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1450 self.dumper.dump_def(
1451 &access_from!(self.save_ctxt, item, hir_id),
1453 kind: DefKind::Type,
1456 name: item.ident.to_string(),
1457 qualname: qualname.clone(),
1462 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1463 sig: sig::item_signature(item, &self.save_ctxt),
1464 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1469 self.process_generic_params(ty_params, &qualname, item.id);
1472 _ => visit::walk_item(self, item),
1476 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1477 for param in &generics.params {
1479 ast::GenericParamKind::Lifetime { .. } => {}
1480 ast::GenericParamKind::Type { ref default, .. } => {
1481 self.process_bounds(¶m.bounds);
1482 if let Some(ref ty) = default {
1486 ast::GenericParamKind::Const { ref ty } => {
1487 self.process_bounds(¶m.bounds);
1492 for pred in &generics.where_clause.predicates {
1493 if let ast::WherePredicate::BoundPredicate(ref wbp) = *pred {
1494 self.process_bounds(&wbp.bounds);
1495 self.visit_ty(&wbp.bounded_ty);
1500 fn visit_ty(&mut self, t: &'l ast::Ty) {
1501 self.process_macro_use(t.span);
1503 ast::TyKind::Path(_, ref path) => {
1504 if generated_code(t.span) {
1508 if let Some(id) = self.lookup_def_id(t.id) {
1509 let sub_span = path.segments.last().unwrap().ident.span;
1510 let span = self.span_from_span(sub_span);
1511 self.dumper.dump_ref(Ref {
1512 kind: RefKind::Type,
1514 ref_id: id_from_def_id(id),
1518 self.write_sub_paths_truncated(path);
1519 visit::walk_path(self, path);
1521 ast::TyKind::Array(ref element, ref length) => {
1522 self.visit_ty(element);
1523 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1525 _ => visit::walk_ty(self, t),
1529 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1530 debug!("visit_expr {:?}", ex.node);
1531 self.process_macro_use(ex.span);
1533 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1534 let expr_hir_id = self.save_ctxt.tcx.hir().node_to_hir_id(ex.id);
1535 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(expr_hir_id);
1536 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1537 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1539 visit::walk_expr(self, ex);
1543 let node_id = self.save_ctxt.tcx.hir().hir_to_node_id(hir_expr.hir_id);
1544 let res = self.save_ctxt.get_path_res(node_id);
1545 self.process_struct_lit(ex, path, fields, adt.variant_of_res(res), 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 id = format!("${}", ex.id);
1561 // walk arg and return types
1562 for arg in &decl.inputs {
1563 self.visit_ty(&arg.ty);
1566 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1567 self.visit_ty(&ret_ty);
1571 self.nest_tables(ex.id, |v| {
1572 v.process_formals(&decl.inputs, &id);
1573 v.nest_scope(ex.id, |v| v.visit_expr(body))
1576 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1577 let value = self.span.snippet(subexpression.span);
1578 self.process_var_decl(pattern, value);
1579 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1580 self.visit_expr(subexpression);
1581 visit::walk_block(self, block);
1583 ast::ExprKind::Let(ref pats, ref scrutinee) => {
1584 self.process_var_decl_multi(pats);
1585 self.visit_expr(scrutinee);
1587 ast::ExprKind::Repeat(ref element, ref count) => {
1588 self.visit_expr(element);
1589 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1591 // In particular, we take this branch for call and path expressions,
1592 // where we'll index the idents involved just by continuing to walk.
1593 _ => visit::walk_expr(self, ex),
1597 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1598 // These shouldn't exist in the AST at this point, log a span bug.
1601 "macro invocation should have been expanded out of AST"
1605 fn visit_pat(&mut self, p: &'l ast::Pat) {
1606 self.process_macro_use(p.span);
1607 self.process_pat(p);
1610 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1611 self.process_var_decl_multi(&arm.pats);
1612 if let Some(expr) = &arm.guard {
1613 self.visit_expr(expr);
1615 self.visit_expr(&arm.body);
1618 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1619 self.process_path(id, p);
1622 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1623 self.process_macro_use(s.span);
1624 visit::walk_stmt(self, s)
1627 fn visit_local(&mut self, l: &'l ast::Local) {
1628 self.process_macro_use(l.span);
1631 .map(|i| self.span.snippet(i.span))
1632 .unwrap_or_default();
1633 self.process_var_decl(&l.pat, value);
1635 // Just walk the initialiser and type (don't want to walk the pattern again).
1636 walk_list!(self, visit_ty, &l.ty);
1637 walk_list!(self, visit_expr, &l.init);
1640 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1641 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1642 let access = access_from!(self.save_ctxt, item, hir_id);
1645 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1646 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1647 down_cast_data!(fn_data, DefData, item.span);
1649 self.process_generic_params(generics, &fn_data.qualname, item.id);
1650 self.dumper.dump_def(&access, fn_data);
1653 for arg in &decl.inputs {
1654 self.visit_ty(&arg.ty);
1657 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1658 self.visit_ty(&ret_ty);
1661 ast::ForeignItemKind::Static(ref ty, _) => {
1662 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1663 down_cast_data!(var_data, DefData, item.span);
1664 self.dumper.dump_def(&access, var_data);
1669 ast::ForeignItemKind::Ty => {
1670 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1671 down_cast_data!(var_data, DefData, item.span);
1672 self.dumper.dump_def(&access, var_data);
1675 ast::ForeignItemKind::Macro(..) => {}