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 Dumper 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};
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::dumper::{Access, Dumper};
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> {
79 pub save_ctxt: SaveContext<'l, 'tcx>,
85 // Set of macro definition (callee) spans, and the set
86 // of macro use (callsite) spans. We store these to ensure
87 // we only write one macro def per unique macro definition, and
88 // one macro use per unique callsite span.
89 // mac_defs: FxHashSet<Span>,
90 // macro_calls: FxHashSet<Span>,
93 impl<'l, 'tcx> DumpVisitor<'l, 'tcx> {
95 save_ctxt: SaveContext<'l, 'tcx>,
96 ) -> DumpVisitor<'l, 'tcx> {
97 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
98 let dumper = Dumper::new(save_ctxt.config.clone());
104 // mac_defs: FxHashSet::default(),
105 // macro_calls: FxHashSet::default(),
109 pub fn analysis(&self) -> &rls_data::Analysis {
110 self.dumper.analysis()
113 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
115 F: FnOnce(&mut Self),
117 let item_def_id = self.tcx.hir().local_def_id_from_node_id(item_id);
118 if self.tcx.has_typeck_tables(item_def_id) {
119 let tables = self.tcx.typeck_tables_of(item_def_id);
120 let old_tables = self.save_ctxt.tables;
121 self.save_ctxt.tables = tables;
123 self.save_ctxt.tables = old_tables;
129 fn span_from_span(&self, span: Span) -> SpanData {
130 self.save_ctxt.span_from_span(span)
133 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
134 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
135 let crate_root = source_file.map(|source_file| {
136 let source_file = Path::new(source_file);
137 match source_file.file_name() {
138 Some(_) => source_file.parent().unwrap().display(),
139 None => source_file.display(),
143 let data = CratePreludeData {
144 crate_id: GlobalCrateId {
146 disambiguator: self.tcx
148 .local_crate_disambiguator()
152 crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
153 external_crates: self.save_ctxt.get_external_crates(),
154 span: self.span_from_span(krate.span),
157 self.dumper.crate_prelude(data);
160 pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
161 // Apply possible `remap-path-prefix` remapping to the input source file
162 // (and don't include remapping args anymore)
163 let (program, arguments) = {
164 let remap_arg_indices = {
165 let mut indices = FxHashSet::default();
166 // Args are guaranteed to be valid UTF-8 (checked early)
167 for (i, e) in env::args().enumerate() {
168 if e.starts_with("--remap-path-prefix=") {
170 } else if e == "--remap-path-prefix" {
172 indices.insert(i + 1);
178 let mut args = env::args()
180 .filter(|(i, _)| !remap_arg_indices.contains(i))
183 Input::File(ref path) if path == Path::new(&arg) => {
184 let mapped = &self.tcx.sess.local_crate_source_file;
195 (args.next().unwrap(), args.collect())
198 let data = CompilationOptions {
199 directory: self.tcx.sess.working_dir.0.clone(),
202 output: self.save_ctxt.compilation_output(crate_name),
205 self.dumper.compilation_opts(data);
208 fn write_sub_paths(&mut self, path: &ast::Path) {
209 for seg in &path.segments {
210 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
211 self.dumper.dump_ref(data);
216 // As write_sub_paths, but does not process the last ident in the path (assuming it
217 // will be processed elsewhere). See note on write_sub_paths about global.
218 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
219 for seg in &path.segments[..path.segments.len() - 1] {
220 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
221 self.dumper.dump_ref(data);
226 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
227 match self.save_ctxt.get_path_res(ref_id) {
228 Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => None,
229 def => Some(def.def_id()),
233 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
235 self.visit_pat(&arg.pat);
236 let mut collector = PathCollector::new();
237 collector.visit_pat(&arg.pat);
239 for (id, ident, ..) in collector.collected_idents {
240 let hir_id = self.tcx.hir().node_to_hir_id(id);
241 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
242 Some(s) => s.to_string(),
245 if !self.span.filter_generated(ident.span) {
246 let id = id_from_node_id(id, &self.save_ctxt);
247 let span = self.span_from_span(ident.span);
249 self.dumper.dump_def(
255 kind: DefKind::Local,
258 name: ident.to_string(),
259 qualname: format!("{}::{}", qualname, ident.to_string()),
276 sig: &'l ast::MethodSig,
277 body: Option<&'l ast::Block>,
280 generics: &'l ast::Generics,
281 vis: ast::Visibility,
284 debug!("process_method: {}:{}", id, ident);
286 if let Some(mut method_data) = self.save_ctxt.get_method_data(id, ident, span) {
287 let sig_str = crate::make_signature(&sig.decl, &generics);
291 |v| v.process_formals(&sig.decl.inputs, &method_data.qualname),
295 self.process_generic_params(&generics, &method_data.qualname, id);
297 method_data.value = sig_str;
298 method_data.sig = sig::method_signature(id, ident, generics, sig, &self.save_ctxt);
299 let hir_id = self.tcx.hir().node_to_hir_id(id);
300 self.dumper.dump_def(&access_from_vis!(self.save_ctxt, vis, hir_id), method_data);
303 // walk arg and return types
304 for arg in &sig.decl.inputs {
305 self.visit_ty(&arg.ty);
308 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
309 self.visit_ty(ret_ty);
313 if let Some(body) = body {
314 self.nest_tables(id, |v| v.visit_block(body));
318 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
319 let field_data = self.save_ctxt.get_field_data(field, parent_id);
320 if let Some(field_data) = field_data {
321 let hir_id = self.tcx.hir().node_to_hir_id(field.id);
322 self.dumper.dump_def(&access_from!(self.save_ctxt, field, hir_id), field_data);
326 // Dump generic params bindings, then visit_generics
327 fn process_generic_params(
329 generics: &'l ast::Generics,
333 for param in &generics.params {
335 ast::GenericParamKind::Lifetime { .. } => {}
336 ast::GenericParamKind::Type { .. } => {
337 let param_ss = param.ident.span;
338 let name = escape(self.span.snippet(param_ss));
339 // Append $id to name to make sure each one is unique.
340 let qualname = format!("{}::{}${}", prefix, name, id);
341 if !self.span.filter_generated(param_ss) {
342 let id = id_from_node_id(param.id, &self.save_ctxt);
343 let span = self.span_from_span(param_ss);
345 self.dumper.dump_def(
356 value: String::new(),
367 ast::GenericParamKind::Const { .. } => {}
370 self.visit_generics(generics);
376 decl: &'l ast::FnDecl,
377 ty_params: &'l ast::Generics,
378 body: &'l ast::Block,
380 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
381 down_cast_data!(fn_data, DefData, item.span);
384 |v| v.process_formals(&decl.inputs, &fn_data.qualname),
386 self.process_generic_params(ty_params, &fn_data.qualname, item.id);
387 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
388 self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), fn_data);
391 for arg in &decl.inputs {
392 self.visit_ty(&arg.ty);
395 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
396 self.visit_ty(&ret_ty);
399 self.nest_tables(item.id, |v| v.visit_block(&body));
402 fn process_static_or_const_item(
408 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
409 self.nest_tables(item.id, |v| {
410 if let Some(var_data) = v.save_ctxt.get_item_data(item) {
411 down_cast_data!(var_data, DefData, item.span);
412 v.dumper.dump_def(&access_from!(v.save_ctxt, item, hir_id), var_data);
419 fn process_assoc_const(
424 expr: Option<&'l ast::Expr>,
426 vis: ast::Visibility,
427 attrs: &'l [Attribute],
429 let qualname = format!("::{}",
430 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
432 if !self.span.filter_generated(ident.span) {
433 let sig = sig::assoc_const_signature(id, ident.name, typ, expr, &self.save_ctxt);
434 let span = self.span_from_span(ident.span);
435 let hir_id = self.tcx.hir().node_to_hir_id(id);
437 self.dumper.dump_def(
438 &access_from_vis!(self.save_ctxt, vis, hir_id),
440 kind: DefKind::Const,
441 id: id_from_node_id(id, &self.save_ctxt),
443 name: ident.name.to_string(),
445 value: ty_to_string(&typ),
446 parent: Some(id_from_def_id(parent_id)),
449 docs: self.save_ctxt.docs_for_attrs(attrs),
451 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
456 // walk type and init value
457 self.nest_tables(id, |v| {
459 if let Some(expr) = expr {
465 // FIXME tuple structs should generate tuple-specific data.
469 def: &'l ast::VariantData,
470 ty_params: &'l ast::Generics,
472 debug!("process_struct {:?} {:?}", item, item.span);
473 let name = item.ident.to_string();
474 let qualname = format!("::{}",
475 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
477 let kind = match item.node {
478 ast::ItemKind::Struct(_, _) => DefKind::Struct,
479 ast::ItemKind::Union(_, _) => DefKind::Union,
483 let (value, fields) = match item.node {
484 ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, ..), ..) |
485 ast::ItemKind::Union(ast::VariantData::Struct(ref fields, ..), ..) => {
486 let include_priv_fields = !self.save_ctxt.config.pub_only;
487 let fields_str = fields
490 .filter_map(|(i, f)| {
491 if include_priv_fields || f.vis.node.is_pub() {
493 .map(|i| i.to_string())
494 .or_else(|| Some(i.to_string()))
501 let value = format!("{} {{ {} }}", name, fields_str);
506 .map(|f| id_from_node_id(f.id, &self.save_ctxt))
510 _ => (String::new(), vec![]),
513 if !self.span.filter_generated(item.ident.span) {
514 let span = self.span_from_span(item.ident.span);
515 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
516 self.dumper.dump_def(
517 &access_from!(self.save_ctxt, item, hir_id),
520 id: id_from_node_id(item.id, &self.save_ctxt),
523 qualname: qualname.clone(),
528 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
529 sig: sig::item_signature(item, &self.save_ctxt),
530 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
535 for field in def.fields() {
536 self.process_struct_field_def(field, item.id);
537 self.visit_ty(&field.ty);
540 self.process_generic_params(ty_params, &qualname, item.id);
546 enum_definition: &'l ast::EnumDef,
547 ty_params: &'l ast::Generics,
549 let enum_data = self.save_ctxt.get_item_data(item);
550 let enum_data = match enum_data {
554 down_cast_data!(enum_data, DefData, item.span);
556 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
557 let access = access_from!(self.save_ctxt, item, hir_id);
559 for variant in &enum_definition.variants {
560 let name = variant.node.ident.name.to_string();
561 let qualname = format!("{}::{}", enum_data.qualname, name);
562 let name_span = variant.node.ident.span;
564 match variant.node.data {
565 ast::VariantData::Struct(ref fields, ..) => {
566 let fields_str = fields
570 f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
574 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
575 if !self.span.filter_generated(name_span) {
576 let span = self.span_from_span(name_span);
577 let id = id_from_node_id(variant.node.id, &self.save_ctxt);
578 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
580 self.dumper.dump_def(
583 kind: DefKind::StructVariant,
592 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
593 sig: sig::variant_signature(variant, &self.save_ctxt),
594 attributes: lower_attributes(
595 variant.node.attrs.clone(),
603 let mut value = format!("{}::{}", enum_data.name, name);
604 if let &ast::VariantData::Tuple(ref fields, _) = v {
606 value.push_str(&fields
608 .map(|f| ty_to_string(&f.ty))
613 if !self.span.filter_generated(name_span) {
614 let span = self.span_from_span(name_span);
615 let id = id_from_node_id(variant.node.id, &self.save_ctxt);
616 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
618 self.dumper.dump_def(
621 kind: DefKind::TupleVariant,
630 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
631 sig: sig::variant_signature(variant, &self.save_ctxt),
632 attributes: lower_attributes(
633 variant.node.attrs.clone(),
643 for field in variant.node.data.fields() {
644 self.process_struct_field_def(field, variant.node.id);
645 self.visit_ty(&field.ty);
648 self.process_generic_params(ty_params, &enum_data.qualname, item.id);
649 self.dumper.dump_def(&access, enum_data);
655 generics: &'l ast::Generics,
656 trait_ref: &'l Option<ast::TraitRef>,
658 impl_items: &'l [ast::ImplItem],
660 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
661 if !self.span.filter_generated(item.span) {
662 if let super::Data::RelationData(rel, imp) = impl_data {
663 self.dumper.dump_relation(rel);
664 self.dumper.dump_impl(imp);
666 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
671 if let &Some(ref trait_ref) = trait_ref {
672 self.process_path(trait_ref.ref_id, &trait_ref.path);
674 self.process_generic_params(generics, "", item.id);
675 for impl_item in impl_items {
676 let map = &self.tcx.hir();
677 self.process_impl_item(impl_item, map.local_def_id_from_node_id(item.id));
684 generics: &'l ast::Generics,
685 trait_refs: &'l ast::GenericBounds,
686 methods: &'l [ast::TraitItem],
688 let name = item.ident.to_string();
689 let qualname = format!("::{}",
690 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
691 let mut val = name.clone();
692 if !generics.params.is_empty() {
693 val.push_str(&generic_params_to_string(&generics.params));
695 if !trait_refs.is_empty() {
697 val.push_str(&bounds_to_string(trait_refs));
699 if !self.span.filter_generated(item.ident.span) {
700 let id = id_from_node_id(item.id, &self.save_ctxt);
701 let span = self.span_from_span(item.ident.span);
702 let children = methods
704 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
706 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
707 self.dumper.dump_def(
708 &access_from!(self.save_ctxt, item, hir_id),
710 kind: DefKind::Trait,
714 qualname: qualname.clone(),
719 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
720 sig: sig::item_signature(item, &self.save_ctxt),
721 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
727 for super_bound in trait_refs.iter() {
728 let trait_ref = match *super_bound {
729 ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
730 ast::GenericBound::Outlives(..) => continue,
733 let trait_ref = &trait_ref.trait_ref;
734 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
735 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
736 if !self.span.filter_generated(sub_span) {
737 let span = self.span_from_span(sub_span);
738 self.dumper.dump_ref(Ref {
741 ref_id: id_from_def_id(id),
744 self.dumper.dump_relation(Relation {
745 kind: RelationKind::SuperTrait,
747 from: id_from_def_id(id),
748 to: id_from_node_id(item.id, &self.save_ctxt),
754 // walk generics and methods
755 self.process_generic_params(generics, &qualname, item.id);
756 for method in methods {
757 let map = &self.tcx.hir();
758 self.process_trait_item(method, map.local_def_id_from_node_id(item.id))
762 // `item` is the module in question, represented as an item.
763 fn process_mod(&mut self, item: &ast::Item) {
764 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
765 down_cast_data!(mod_data, DefData, item.span);
766 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
767 self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), mod_data);
771 fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
772 let path_data = self.save_ctxt.get_path_data(id, path);
773 if let Some(path_data) = path_data {
774 self.dumper.dump_ref(path_data);
778 fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
779 if self.span.filter_generated(path.span) {
782 self.dump_path_ref(id, path);
785 for seg in &path.segments {
786 if let Some(ref generic_args) = seg.args {
787 match **generic_args {
788 ast::GenericArgs::AngleBracketed(ref data) => {
789 for arg in &data.args {
791 ast::GenericArg::Type(ty) => self.visit_ty(ty),
796 ast::GenericArgs::Parenthesized(ref data) => {
797 for t in &data.inputs {
800 if let Some(ref t) = data.output {
808 self.write_sub_paths_truncated(path);
811 fn process_struct_lit(
815 fields: &'l [ast::Field],
816 variant: &'l ty::VariantDef,
817 base: &'l Option<P<ast::Expr>>,
819 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
820 self.write_sub_paths_truncated(path);
821 down_cast_data!(struct_lit_data, RefData, ex.span);
822 if !generated_code(ex.span) {
823 self.dumper.dump_ref(struct_lit_data);
826 for field in fields {
827 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
828 self.dumper.dump_ref(field_data);
831 self.visit_expr(&field.expr)
835 walk_list!(self, visit_expr, base);
838 fn process_method_call(
841 seg: &'l ast::PathSegment,
842 args: &'l [P<ast::Expr>],
844 debug!("process_method_call {:?} {:?}", ex, ex.span);
845 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
846 down_cast_data!(mcd, RefData, ex.span);
847 if !generated_code(ex.span) {
848 self.dumper.dump_ref(mcd);
852 // Explicit types in the turbo-fish.
853 if let Some(ref generic_args) = seg.args {
854 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
855 for arg in &data.args {
857 ast::GenericArg::Type(ty) => self.visit_ty(ty),
864 // walk receiver and args
865 walk_list!(self, visit_expr, args);
868 fn process_pat(&mut self, p: &'l ast::Pat) {
870 PatKind::Struct(ref _path, ref fields, _) => {
871 // FIXME do something with _path?
872 let hir_id = self.tcx.hir().node_to_hir_id(p.id);
873 let adt = match self.save_ctxt.tables.node_type_opt(hir_id) {
874 Some(ty) => ty.ty_adt_def().unwrap(),
876 visit::walk_pat(self, p);
880 let variant = adt.variant_of_res(self.save_ctxt.get_path_res(p.id));
882 for &Spanned { node: ref field, .. } in fields {
883 if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
884 if !self.span.filter_generated(field.ident.span) {
885 let span = self.span_from_span(field.ident.span);
886 self.dumper.dump_ref(Ref {
887 kind: RefKind::Variable,
889 ref_id: id_from_def_id(variant.fields[index].did),
893 self.visit_pat(&field.pat);
896 _ => visit::walk_pat(self, p),
900 fn process_var_decl_multi(&mut self, pats: &'l [P<ast::Pat>]) {
901 let mut collector = PathCollector::new();
902 for pattern in pats {
903 // collect paths from the arm's patterns
904 collector.visit_pat(&pattern);
905 self.visit_pat(&pattern);
908 // process collected paths
909 for (id, ident, immut) in collector.collected_idents {
910 match self.save_ctxt.get_path_res(id) {
911 Res::Local(hir_id) => {
912 let mut value = if immut == ast::Mutability::Immutable {
913 self.span.snippet(ident.span)
915 "<mutable>".to_owned()
917 let id = self.tcx.hir().hir_to_node_id(hir_id);
918 let typ = self.save_ctxt
920 .node_type_opt(hir_id)
921 .map(|t| t.to_string())
922 .unwrap_or_default();
923 value.push_str(": ");
924 value.push_str(&typ);
926 if !self.span.filter_generated(ident.span) {
927 let qualname = format!("{}${}", ident.to_string(), id);
928 let id = id_from_node_id(id, &self.save_ctxt);
929 let span = self.span_from_span(ident.span);
931 self.dumper.dump_def(
937 kind: DefKind::Local,
940 name: ident.to_string(),
953 Res::Def(HirDefKind::Ctor(..), _) |
954 Res::Def(HirDefKind::Const, _) |
955 Res::Def(HirDefKind::AssocConst, _) |
956 Res::Def(HirDefKind::Struct, _) |
957 Res::Def(HirDefKind::Variant, _) |
958 Res::Def(HirDefKind::TyAlias, _) |
959 Res::Def(HirDefKind::AssocTy, _) |
961 self.dump_path_ref(id, &ast::Path::from_ident(ident));
964 "unexpected definition kind when processing collected idents: {:?}",
970 for (id, ref path) in collector.collected_paths {
971 self.process_path(id, path);
975 fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
976 // The local could declare multiple new vars, we must walk the
977 // pattern and collect them all.
978 let mut collector = PathCollector::new();
979 collector.visit_pat(&p);
982 for (id, ident, immut) in collector.collected_idents {
983 let mut value = match immut {
984 ast::Mutability::Immutable => value.to_string(),
987 let hir_id = self.tcx.hir().node_to_hir_id(id);
988 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
990 let typ = typ.to_string();
991 if !value.is_empty() {
992 value.push_str(": ");
994 value.push_str(&typ);
997 None => String::new(),
1000 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1001 if !self.span.filter_generated(ident.span) {
1002 let qualname = format!("{}${}", ident.to_string(), id);
1003 let id = id_from_node_id(id, &self.save_ctxt);
1004 let span = self.span_from_span(ident.span);
1006 self.dumper.dump_def(
1012 kind: DefKind::Local,
1015 name: ident.to_string(),
1021 docs: String::new(),
1030 /// Extracts macro use and definition information from the AST node defined
1031 /// by the given NodeId, using the expansion information from the node's
1034 /// If the span is not macro-generated, do nothing, else use callee and
1035 /// callsite spans to record macro definition and use data, using the
1036 /// mac_uses and mac_defs sets to prevent multiples.
1037 fn process_macro_use(&mut self, _span: Span) {
1038 // FIXME if we're not dumping the defs (see below), there is no point
1039 // dumping refs either.
1040 // let source_span = span.source_callsite();
1041 // if !self.macro_calls.insert(source_span) {
1045 // let data = match self.save_ctxt.get_macro_use_data(span) {
1047 // Some(data) => data,
1050 // self.dumper.macro_use(data);
1052 // FIXME write the macro def
1053 // let mut hasher = DefaultHasher::new();
1054 // data.callee_span.hash(&mut hasher);
1055 // let hash = hasher.finish();
1056 // let qualname = format!("{}::{}", data.name, hash);
1057 // Don't write macro definition for imported macros
1058 // if !self.mac_defs.contains(&data.callee_span)
1059 // && !data.imported {
1060 // self.mac_defs.insert(data.callee_span);
1061 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1062 // self.dumper.macro_data(MacroData {
1064 // name: data.name.clone(),
1065 // qualname: qualname.clone(),
1066 // // FIXME where do macro docs come from?
1067 // docs: String::new(),
1068 // }.lower(self.tcx));
1073 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1074 self.process_macro_use(trait_item.span);
1075 let vis_span = trait_item.span.shrink_to_lo();
1076 match trait_item.node {
1077 ast::TraitItemKind::Const(ref ty, ref expr) => {
1078 self.process_assoc_const(
1082 expr.as_ref().map(|e| &**e),
1084 respan(vis_span, ast::VisibilityKind::Public),
1088 ast::TraitItemKind::Method(ref sig, ref body) => {
1089 self.process_method(
1091 body.as_ref().map(|x| &**x),
1094 &trait_item.generics,
1095 respan(vis_span, ast::VisibilityKind::Public),
1099 ast::TraitItemKind::Type(ref bounds, ref default_ty) => {
1100 // FIXME do something with _bounds (for type refs)
1101 let name = trait_item.ident.name.to_string();
1102 let qualname = format!("::{}",
1103 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(trait_item.id)));
1105 if !self.span.filter_generated(trait_item.ident.span) {
1106 let span = self.span_from_span(trait_item.ident.span);
1107 let id = id_from_node_id(trait_item.id, &self.save_ctxt);
1109 self.dumper.dump_def(
1115 kind: DefKind::Type,
1120 value: self.span.snippet(trait_item.span),
1121 parent: Some(id_from_def_id(trait_id)),
1124 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1125 sig: sig::assoc_type_signature(
1129 default_ty.as_ref().map(|ty| &**ty),
1132 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1137 if let &Some(ref default_ty) = default_ty {
1138 self.visit_ty(default_ty)
1141 ast::TraitItemKind::Macro(_) => {}
1145 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1146 self.process_macro_use(impl_item.span);
1147 match impl_item.node {
1148 ast::ImplItemKind::Const(ref ty, ref expr) => {
1149 self.process_assoc_const(
1155 impl_item.vis.clone(),
1159 ast::ImplItemKind::Method(ref sig, ref body) => {
1160 self.process_method(
1165 &impl_item.generics,
1166 impl_item.vis.clone(),
1170 ast::ImplItemKind::Type(ref ty) => {
1171 // FIXME: uses of the assoc type should ideally point to this
1172 // 'def' and the name here should be a ref to the def in the
1176 ast::ImplItemKind::Existential(ref bounds) => {
1177 // FIXME: uses of the assoc type should ideally point to this
1178 // 'def' and the name here should be a ref to the def in the
1180 for bound in bounds.iter() {
1181 if let ast::GenericBound::Trait(trait_ref, _) = bound {
1182 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1186 ast::ImplItemKind::Macro(_) => {}
1190 /// Dumps imports in a use tree recursively.
1192 /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1193 /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1194 /// ID and path. `root_item` is the topmost use tree in the hierarchy.
1196 /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1197 /// each child use tree is dumped recursively.
1198 fn process_use_tree(&mut self,
1199 use_tree: &'l ast::UseTree,
1201 root_item: &'l ast::Item,
1202 prefix: &ast::Path) {
1203 let path = &use_tree.prefix;
1205 // The access is calculated using the current tree ID, but with the root tree's visibility
1206 // (since nested trees don't have their own visibility).
1207 let hir_id = self.tcx.hir().node_to_hir_id(id);
1208 let access = access_from!(self.save_ctxt, root_item, hir_id);
1210 // The parent `DefId` of a given use tree is always the enclosing item.
1211 let parent = self.save_ctxt.tcx.hir().opt_local_def_id_from_node_id(id)
1212 .and_then(|id| self.save_ctxt.tcx.parent(id))
1213 .map(id_from_def_id);
1215 match use_tree.kind {
1216 ast::UseTreeKind::Simple(alias, ..) => {
1217 let ident = use_tree.ident();
1218 let path = ast::Path {
1219 segments: prefix.segments
1221 .chain(path.segments.iter())
1227 let sub_span = path.segments.last().unwrap().ident.span;
1228 if !self.span.filter_generated(sub_span) {
1229 let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id));
1230 let alias_span = alias.map(|i| self.span_from_span(i.span));
1231 let span = self.span_from_span(sub_span);
1232 self.dumper.import(&access, Import {
1233 kind: ImportKind::Use,
1237 name: ident.to_string(),
1238 value: String::new(),
1241 self.write_sub_paths_truncated(&path);
1244 ast::UseTreeKind::Glob => {
1245 let path = ast::Path {
1246 segments: prefix.segments
1248 .chain(path.segments.iter())
1254 // Make a comma-separated list of names of imported modules.
1255 let def_id = self.tcx.hir().local_def_id_from_node_id(id);
1256 let names = self.tcx.names_imported_by_glob_use(def_id);
1257 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1259 // Otherwise it's a span with wrong macro expansion info, which
1260 // we don't want to track anyway, since it's probably macro-internal `use`
1261 if let Some(sub_span) =
1262 self.span.sub_span_of_token(use_tree.span, token::BinOp(token::Star))
1264 if !self.span.filter_generated(use_tree.span) {
1265 let span = self.span_from_span(sub_span);
1267 self.dumper.import(&access, Import {
1268 kind: ImportKind::GlobUse,
1272 name: "*".to_owned(),
1273 value: names.join(", "),
1276 self.write_sub_paths(&path);
1280 ast::UseTreeKind::Nested(ref nested_items) => {
1281 let prefix = ast::Path {
1282 segments: prefix.segments
1284 .chain(path.segments.iter())
1289 for &(ref tree, id) in nested_items {
1290 self.process_use_tree(tree, id, root_item, &prefix);
1296 fn process_bounds(&mut self, bounds: &'l ast::GenericBounds) {
1297 for bound in bounds {
1298 if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1299 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1305 impl<'l, 'tcx> Visitor<'l> for DumpVisitor<'l, 'tcx> {
1306 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1307 // Since we handle explicit modules ourselves in visit_item, this should
1308 // only get called for the root module of a crate.
1309 assert_eq!(id, ast::CRATE_NODE_ID);
1311 let qualname = format!("::{}",
1312 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
1314 let cm = self.tcx.sess.source_map();
1315 let filename = cm.span_to_filename(span);
1316 let data_id = id_from_node_id(id, &self.save_ctxt);
1317 let children = m.items
1319 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
1321 let span = self.span_from_span(span);
1323 self.dumper.dump_def(
1331 name: String::new(),
1334 value: filename.to_string(),
1338 docs: self.save_ctxt.docs_for_attrs(attrs),
1340 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1343 visit::walk_mod(self, m);
1346 fn visit_item(&mut self, item: &'l ast::Item) {
1347 use syntax::ast::ItemKind::*;
1348 self.process_macro_use(item.span);
1350 Use(ref use_tree) => {
1351 let prefix = ast::Path {
1355 self.process_use_tree(use_tree, item.id, item, &prefix);
1358 let name_span = item.ident.span;
1359 if !self.span.filter_generated(name_span) {
1360 let span = self.span_from_span(name_span);
1361 let parent = self.save_ctxt.tcx.hir().opt_local_def_id_from_node_id(item.id)
1362 .and_then(|id| self.save_ctxt.tcx.parent(id))
1363 .map(id_from_def_id);
1370 kind: ImportKind::ExternCrate,
1374 name: item.ident.to_string(),
1375 value: String::new(),
1381 Fn(ref decl, .., ref ty_params, ref body) => {
1382 self.process_fn(item, &decl, ty_params, &body)
1384 Static(ref typ, _, ref expr) => self.process_static_or_const_item(item, typ, expr),
1385 Const(ref typ, ref expr) => self.process_static_or_const_item(item, &typ, &expr),
1386 Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1387 self.process_struct(item, def, ty_params)
1389 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1390 Impl(.., ref ty_params, ref trait_ref, ref typ, ref impl_items) => {
1391 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1393 Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1394 self.process_trait(item, generics, trait_refs, methods)
1397 self.process_mod(item);
1398 visit::walk_mod(self, m);
1400 Ty(ref ty, ref ty_params) => {
1401 let qualname = format!("::{}",
1402 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
1403 let value = ty_to_string(&ty);
1404 if !self.span.filter_generated(item.ident.span) {
1405 let span = self.span_from_span(item.ident.span);
1406 let id = id_from_node_id(item.id, &self.save_ctxt);
1407 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1409 self.dumper.dump_def(
1410 &access_from!(self.save_ctxt, item, hir_id),
1412 kind: DefKind::Type,
1415 name: item.ident.to_string(),
1416 qualname: qualname.clone(),
1421 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1422 sig: sig::item_signature(item, &self.save_ctxt),
1423 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1429 self.process_generic_params(ty_params, &qualname, item.id);
1431 Existential(ref _bounds, ref ty_params) => {
1432 let qualname = format!("::{}",
1433 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
1434 // FIXME do something with _bounds
1435 let value = String::new();
1436 if !self.span.filter_generated(item.ident.span) {
1437 let span = self.span_from_span(item.ident.span);
1438 let id = id_from_node_id(item.id, &self.save_ctxt);
1439 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1441 self.dumper.dump_def(
1442 &access_from!(self.save_ctxt, item, hir_id),
1444 kind: DefKind::Type,
1447 name: item.ident.to_string(),
1448 qualname: qualname.clone(),
1453 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1454 sig: sig::item_signature(item, &self.save_ctxt),
1455 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1460 self.process_generic_params(ty_params, &qualname, item.id);
1463 _ => visit::walk_item(self, item),
1467 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1468 for param in &generics.params {
1470 ast::GenericParamKind::Lifetime { .. } => {}
1471 ast::GenericParamKind::Type { ref default, .. } => {
1472 self.process_bounds(¶m.bounds);
1473 if let Some(ref ty) = default {
1477 ast::GenericParamKind::Const { ref ty } => {
1478 self.process_bounds(¶m.bounds);
1483 for pred in &generics.where_clause.predicates {
1484 if let ast::WherePredicate::BoundPredicate(ref wbp) = *pred {
1485 self.process_bounds(&wbp.bounds);
1486 self.visit_ty(&wbp.bounded_ty);
1491 fn visit_ty(&mut self, t: &'l ast::Ty) {
1492 self.process_macro_use(t.span);
1494 ast::TyKind::Path(_, ref path) => {
1495 if generated_code(t.span) {
1499 if let Some(id) = self.lookup_def_id(t.id) {
1500 let sub_span = path.segments.last().unwrap().ident.span;
1501 let span = self.span_from_span(sub_span);
1502 self.dumper.dump_ref(Ref {
1503 kind: RefKind::Type,
1505 ref_id: id_from_def_id(id),
1509 self.write_sub_paths_truncated(path);
1510 visit::walk_path(self, path);
1512 ast::TyKind::Array(ref element, ref length) => {
1513 self.visit_ty(element);
1514 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1516 _ => visit::walk_ty(self, t),
1520 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1521 debug!("visit_expr {:?}", ex.node);
1522 self.process_macro_use(ex.span);
1524 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1525 let expr_hir_id = self.save_ctxt.tcx.hir().node_to_hir_id(ex.id);
1526 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(expr_hir_id);
1527 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1528 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1530 visit::walk_expr(self, ex);
1534 let node_id = self.save_ctxt.tcx.hir().hir_to_node_id(hir_expr.hir_id);
1535 let res = self.save_ctxt.get_path_res(node_id);
1536 self.process_struct_lit(ex, path, fields, adt.variant_of_res(res), base)
1538 ast::ExprKind::MethodCall(ref seg, ref args) => self.process_method_call(ex, seg, args),
1539 ast::ExprKind::Field(ref sub_ex, _) => {
1540 self.visit_expr(&sub_ex);
1542 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1543 down_cast_data!(field_data, RefData, ex.span);
1544 if !generated_code(ex.span) {
1545 self.dumper.dump_ref(field_data);
1549 ast::ExprKind::Closure(_, _, _, ref decl, ref body, _fn_decl_span) => {
1550 let id = format!("${}", ex.id);
1552 // walk arg and return types
1553 for arg in &decl.inputs {
1554 self.visit_ty(&arg.ty);
1557 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1558 self.visit_ty(&ret_ty);
1562 self.nest_tables(ex.id, |v| {
1563 v.process_formals(&decl.inputs, &id);
1567 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1568 let value = self.span.snippet(subexpression.span);
1569 self.process_var_decl(pattern, value);
1570 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1571 self.visit_expr(subexpression);
1572 visit::walk_block(self, block);
1574 ast::ExprKind::Let(ref pats, ref scrutinee) => {
1575 self.process_var_decl_multi(pats);
1576 self.visit_expr(scrutinee);
1578 ast::ExprKind::Repeat(ref element, ref count) => {
1579 self.visit_expr(element);
1580 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1582 // In particular, we take this branch for call and path expressions,
1583 // where we'll index the idents involved just by continuing to walk.
1584 _ => visit::walk_expr(self, ex),
1588 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1589 // These shouldn't exist in the AST at this point, log a span bug.
1592 "macro invocation should have been expanded out of AST"
1596 fn visit_pat(&mut self, p: &'l ast::Pat) {
1597 self.process_macro_use(p.span);
1598 self.process_pat(p);
1601 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1602 self.process_var_decl_multi(&arm.pats);
1603 if let Some(expr) = &arm.guard {
1604 self.visit_expr(expr);
1606 self.visit_expr(&arm.body);
1609 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1610 self.process_path(id, p);
1613 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1614 self.process_macro_use(s.span);
1615 visit::walk_stmt(self, s)
1618 fn visit_local(&mut self, l: &'l ast::Local) {
1619 self.process_macro_use(l.span);
1622 .map(|i| self.span.snippet(i.span))
1623 .unwrap_or_default();
1624 self.process_var_decl(&l.pat, value);
1626 // Just walk the initialiser and type (don't want to walk the pattern again).
1627 walk_list!(self, visit_ty, &l.ty);
1628 walk_list!(self, visit_expr, &l.init);
1631 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1632 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1633 let access = access_from!(self.save_ctxt, item, hir_id);
1636 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1637 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1638 down_cast_data!(fn_data, DefData, item.span);
1640 self.process_generic_params(generics, &fn_data.qualname, item.id);
1641 self.dumper.dump_def(&access, fn_data);
1644 for arg in &decl.inputs {
1645 self.visit_ty(&arg.ty);
1648 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1649 self.visit_ty(&ret_ty);
1652 ast::ForeignItemKind::Static(ref ty, _) => {
1653 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1654 down_cast_data!(var_data, DefData, item.span);
1655 self.dumper.dump_def(&access, var_data);
1660 ast::ForeignItemKind::Ty => {
1661 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1662 down_cast_data!(var_data, DefData, item.span);
1663 self.dumper.dump_def(&access, var_data);
1666 ast::ForeignItemKind::Macro(..) => {}