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::{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 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
134 self.save_ctxt.lookup_def_id(ref_id)
137 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
138 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
139 let crate_root = source_file.map(|source_file| {
140 let source_file = Path::new(source_file);
141 match source_file.file_name() {
142 Some(_) => source_file.parent().unwrap().display(),
143 None => source_file.display(),
147 let data = CratePreludeData {
148 crate_id: GlobalCrateId {
150 disambiguator: self.tcx
152 .local_crate_disambiguator()
156 crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
157 external_crates: self.save_ctxt.get_external_crates(),
158 span: self.span_from_span(krate.span),
161 self.dumper.crate_prelude(data);
164 pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
165 // Apply possible `remap-path-prefix` remapping to the input source file
166 // (and don't include remapping args anymore)
167 let (program, arguments) = {
168 let remap_arg_indices = {
169 let mut indices = FxHashSet::default();
170 // Args are guaranteed to be valid UTF-8 (checked early)
171 for (i, e) in env::args().enumerate() {
172 if e.starts_with("--remap-path-prefix=") {
174 } else if e == "--remap-path-prefix" {
176 indices.insert(i + 1);
182 let mut args = env::args()
184 .filter(|(i, _)| !remap_arg_indices.contains(i))
187 Input::File(ref path) if path == Path::new(&arg) => {
188 let mapped = &self.tcx.sess.local_crate_source_file;
199 (args.next().unwrap(), args.collect())
202 let data = CompilationOptions {
203 directory: self.tcx.sess.working_dir.0.clone(),
206 output: self.save_ctxt.compilation_output(crate_name),
209 self.dumper.compilation_opts(data);
212 fn write_sub_paths(&mut self, path: &ast::Path) {
213 for seg in &path.segments {
214 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
215 self.dumper.dump_ref(data);
220 // As write_sub_paths, but does not process the last ident in the path (assuming it
221 // will be processed elsewhere). See note on write_sub_paths about global.
222 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
223 for seg in &path.segments[..path.segments.len() - 1] {
224 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
225 self.dumper.dump_ref(data);
230 fn process_formals(&mut self, formals: &'l [ast::Param], qualname: &str) {
232 self.visit_pat(&arg.pat);
233 let mut collector = PathCollector::new();
234 collector.visit_pat(&arg.pat);
236 for (id, ident, ..) in collector.collected_idents {
237 let hir_id = self.tcx.hir().node_to_hir_id(id);
238 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
239 Some(s) => s.to_string(),
242 if !self.span.filter_generated(ident.span) {
243 let id = id_from_node_id(id, &self.save_ctxt);
244 let span = self.span_from_span(ident.span);
246 self.dumper.dump_def(
252 kind: DefKind::Local,
255 name: ident.to_string(),
256 qualname: format!("{}::{}", qualname, ident.to_string()),
273 sig: &'l ast::MethodSig,
274 body: Option<&'l ast::Block>,
277 generics: &'l ast::Generics,
278 vis: ast::Visibility,
281 debug!("process_method: {}:{}", id, ident);
283 let hir_id = self.tcx.hir().node_to_hir_id(id);
284 self.nest_tables(id, |v| {
285 if let Some(mut method_data) = v.save_ctxt.get_method_data(id, ident, span) {
286 v.process_formals(&sig.decl.inputs, &method_data.qualname);
287 v.process_generic_params(&generics, &method_data.qualname, id);
289 method_data.value = crate::make_signature(&sig.decl, &generics);
290 method_data.sig = sig::method_signature(id, ident, generics, sig, &v.save_ctxt);
292 v.dumper.dump_def(&access_from_vis!(v.save_ctxt, vis, hir_id), method_data);
295 // walk arg and return types
296 for arg in &sig.decl.inputs {
300 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
305 if let Some(body) = body {
311 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
312 let field_data = self.save_ctxt.get_field_data(field, parent_id);
313 if let Some(field_data) = field_data {
314 let hir_id = self.tcx.hir().node_to_hir_id(field.id);
315 self.dumper.dump_def(&access_from!(self.save_ctxt, field, hir_id), field_data);
319 // Dump generic params bindings, then visit_generics
320 fn process_generic_params(
322 generics: &'l ast::Generics,
326 for param in &generics.params {
328 ast::GenericParamKind::Lifetime { .. } => {}
329 ast::GenericParamKind::Type { .. } => {
330 let param_ss = param.ident.span;
331 let name = escape(self.span.snippet(param_ss));
332 // Append $id to name to make sure each one is unique.
333 let qualname = format!("{}::{}${}", prefix, name, id);
334 if !self.span.filter_generated(param_ss) {
335 let id = id_from_node_id(param.id, &self.save_ctxt);
336 let span = self.span_from_span(param_ss);
338 self.dumper.dump_def(
349 value: String::new(),
360 ast::GenericParamKind::Const { .. } => {}
363 self.visit_generics(generics);
369 decl: &'l ast::FnDecl,
370 ty_params: &'l ast::Generics,
371 body: &'l ast::Block,
373 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
374 self.nest_tables(item.id, |v| {
375 if let Some(fn_data) = v.save_ctxt.get_item_data(item) {
376 down_cast_data!(fn_data, DefData, item.span);
377 v.process_formals(&decl.inputs, &fn_data.qualname);
378 v.process_generic_params(ty_params, &fn_data.qualname, item.id);
380 v.dumper.dump_def(&access_from!(v.save_ctxt, item, hir_id), fn_data);
383 for arg in &decl.inputs {
387 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
388 if let ast::TyKind::ImplTrait(..) = ret_ty.node {
389 // FIXME: Opaque type desugaring prevents us from easily
390 // processing trait bounds. See `visit_ty` for more details.
396 v.visit_block(&body);
400 fn process_static_or_const_item(
406 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
407 self.nest_tables(item.id, |v| {
408 if let Some(var_data) = v.save_ctxt.get_item_data(item) {
409 down_cast_data!(var_data, DefData, item.span);
410 v.dumper.dump_def(&access_from!(v.save_ctxt, item, hir_id), var_data);
417 fn process_assoc_const(
422 expr: Option<&'l ast::Expr>,
424 vis: ast::Visibility,
425 attrs: &'l [Attribute],
427 let qualname = format!("::{}",
428 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
430 if !self.span.filter_generated(ident.span) {
431 let sig = sig::assoc_const_signature(id, ident.name, typ, expr, &self.save_ctxt);
432 let span = self.span_from_span(ident.span);
433 let hir_id = self.tcx.hir().node_to_hir_id(id);
435 self.dumper.dump_def(
436 &access_from_vis!(self.save_ctxt, vis, hir_id),
438 kind: DefKind::Const,
439 id: id_from_node_id(id, &self.save_ctxt),
441 name: ident.name.to_string(),
443 value: ty_to_string(&typ),
444 parent: Some(id_from_def_id(parent_id)),
447 docs: self.save_ctxt.docs_for_attrs(attrs),
449 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
454 // walk type and init value
455 self.nest_tables(id, |v| {
457 if let Some(expr) = expr {
463 // FIXME tuple structs should generate tuple-specific data.
467 def: &'l ast::VariantData,
468 ty_params: &'l ast::Generics,
470 debug!("process_struct {:?} {:?}", item, item.span);
471 let name = item.ident.to_string();
472 let qualname = format!("::{}",
473 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
475 let kind = match item.node {
476 ast::ItemKind::Struct(_, _) => DefKind::Struct,
477 ast::ItemKind::Union(_, _) => DefKind::Union,
481 let (value, fields) = match item.node {
482 ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, ..), ..) |
483 ast::ItemKind::Union(ast::VariantData::Struct(ref fields, ..), ..) => {
484 let include_priv_fields = !self.save_ctxt.config.pub_only;
485 let fields_str = fields
488 .filter_map(|(i, f)| {
489 if include_priv_fields || f.vis.node.is_pub() {
491 .map(|i| i.to_string())
492 .or_else(|| Some(i.to_string()))
499 let value = format!("{} {{ {} }}", name, fields_str);
504 .map(|f| id_from_node_id(f.id, &self.save_ctxt))
508 _ => (String::new(), vec![]),
511 if !self.span.filter_generated(item.ident.span) {
512 let span = self.span_from_span(item.ident.span);
513 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
514 self.dumper.dump_def(
515 &access_from!(self.save_ctxt, item, hir_id),
518 id: id_from_node_id(item.id, &self.save_ctxt),
521 qualname: qualname.clone(),
526 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
527 sig: sig::item_signature(item, &self.save_ctxt),
528 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
533 for field in def.fields() {
534 self.process_struct_field_def(field, item.id);
535 self.visit_ty(&field.ty);
538 self.process_generic_params(ty_params, &qualname, item.id);
544 enum_definition: &'l ast::EnumDef,
545 ty_params: &'l ast::Generics,
547 let enum_data = self.save_ctxt.get_item_data(item);
548 let enum_data = match enum_data {
552 down_cast_data!(enum_data, DefData, item.span);
554 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
555 let access = access_from!(self.save_ctxt, item, hir_id);
557 for variant in &enum_definition.variants {
558 let name = variant.ident.name.to_string();
559 let qualname = format!("{}::{}", enum_data.qualname, name);
560 let name_span = variant.ident.span;
563 ast::VariantData::Struct(ref fields, ..) => {
564 let fields_str = fields
568 f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
572 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
573 if !self.span.filter_generated(name_span) {
574 let span = self.span_from_span(name_span);
575 let id = id_from_node_id(variant.id, &self.save_ctxt);
576 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
578 self.dumper.dump_def(
581 kind: DefKind::StructVariant,
590 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
591 sig: sig::variant_signature(variant, &self.save_ctxt),
592 attributes: lower_attributes(
593 variant.attrs.clone(),
601 let mut value = format!("{}::{}", enum_data.name, name);
602 if let &ast::VariantData::Tuple(ref fields, _) = v {
604 value.push_str(&fields
606 .map(|f| ty_to_string(&f.ty))
611 if !self.span.filter_generated(name_span) {
612 let span = self.span_from_span(name_span);
613 let id = id_from_node_id(variant.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::TupleVariant,
628 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
629 sig: sig::variant_signature(variant, &self.save_ctxt),
630 attributes: lower_attributes(
631 variant.attrs.clone(),
641 for field in variant.data.fields() {
642 self.process_struct_field_def(field, variant.id);
643 self.visit_ty(&field.ty);
646 self.process_generic_params(ty_params, &enum_data.qualname, item.id);
647 self.dumper.dump_def(&access, enum_data);
653 generics: &'l ast::Generics,
654 trait_ref: &'l Option<ast::TraitRef>,
656 impl_items: &'l [ast::ImplItem],
658 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
659 if !self.span.filter_generated(item.span) {
660 if let super::Data::RelationData(rel, imp) = impl_data {
661 self.dumper.dump_relation(rel);
662 self.dumper.dump_impl(imp);
664 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
669 if let &Some(ref trait_ref) = trait_ref {
670 self.process_path(trait_ref.ref_id, &trait_ref.path);
672 self.process_generic_params(generics, "", item.id);
673 for impl_item in impl_items {
674 let map = &self.tcx.hir();
675 self.process_impl_item(impl_item, map.local_def_id_from_node_id(item.id));
682 generics: &'l ast::Generics,
683 trait_refs: &'l ast::GenericBounds,
684 methods: &'l [ast::TraitItem],
686 let name = item.ident.to_string();
687 let qualname = format!("::{}",
688 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
689 let mut val = name.clone();
690 if !generics.params.is_empty() {
691 val.push_str(&generic_params_to_string(&generics.params));
693 if !trait_refs.is_empty() {
695 val.push_str(&bounds_to_string(trait_refs));
697 if !self.span.filter_generated(item.ident.span) {
698 let id = id_from_node_id(item.id, &self.save_ctxt);
699 let span = self.span_from_span(item.ident.span);
700 let children = methods
702 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
704 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
705 self.dumper.dump_def(
706 &access_from!(self.save_ctxt, item, hir_id),
708 kind: DefKind::Trait,
712 qualname: qualname.clone(),
717 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
718 sig: sig::item_signature(item, &self.save_ctxt),
719 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
725 for super_bound in trait_refs.iter() {
726 let trait_ref = match *super_bound {
727 ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
728 ast::GenericBound::Outlives(..) => continue,
731 let trait_ref = &trait_ref.trait_ref;
732 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
733 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
734 if !self.span.filter_generated(sub_span) {
735 let span = self.span_from_span(sub_span);
736 self.dumper.dump_ref(Ref {
739 ref_id: id_from_def_id(id),
742 self.dumper.dump_relation(Relation {
743 kind: RelationKind::SuperTrait,
745 from: id_from_def_id(id),
746 to: id_from_node_id(item.id, &self.save_ctxt),
752 // walk generics and methods
753 self.process_generic_params(generics, &qualname, item.id);
754 for method in methods {
755 let map = &self.tcx.hir();
756 self.process_trait_item(method, map.local_def_id_from_node_id(item.id))
760 // `item` is the module in question, represented as an item.
761 fn process_mod(&mut self, item: &ast::Item) {
762 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
763 down_cast_data!(mod_data, DefData, item.span);
764 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
765 self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), mod_data);
769 fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
770 let path_data = self.save_ctxt.get_path_data(id, path);
771 if let Some(path_data) = path_data {
772 self.dumper.dump_ref(path_data);
776 fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
777 if self.span.filter_generated(path.span) {
780 self.dump_path_ref(id, path);
783 for seg in &path.segments {
784 if let Some(ref generic_args) = seg.args {
785 match **generic_args {
786 ast::GenericArgs::AngleBracketed(ref data) => {
787 for arg in &data.args {
789 ast::GenericArg::Type(ty) => self.visit_ty(ty),
794 ast::GenericArgs::Parenthesized(ref data) => {
795 for t in &data.inputs {
798 if let Some(ref t) = data.output {
806 self.write_sub_paths_truncated(path);
809 fn process_struct_lit(
813 fields: &'l [ast::Field],
814 variant: &'l ty::VariantDef,
815 base: &'l Option<P<ast::Expr>>,
817 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
818 self.write_sub_paths_truncated(path);
819 down_cast_data!(struct_lit_data, RefData, ex.span);
820 if !generated_code(ex.span) {
821 self.dumper.dump_ref(struct_lit_data);
824 for field in fields {
825 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
826 self.dumper.dump_ref(field_data);
829 self.visit_expr(&field.expr)
833 walk_list!(self, visit_expr, base);
836 fn process_method_call(
839 seg: &'l ast::PathSegment,
840 args: &'l [P<ast::Expr>],
842 debug!("process_method_call {:?} {:?}", ex, ex.span);
843 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
844 down_cast_data!(mcd, RefData, ex.span);
845 if !generated_code(ex.span) {
846 self.dumper.dump_ref(mcd);
850 // Explicit types in the turbo-fish.
851 if let Some(ref generic_args) = seg.args {
852 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
853 for arg in &data.args {
855 ast::GenericArg::Type(ty) => self.visit_ty(ty),
862 // walk receiver and args
863 walk_list!(self, visit_expr, args);
866 fn process_pat(&mut self, p: &'l ast::Pat) {
868 PatKind::Struct(ref _path, ref fields, _) => {
869 // FIXME do something with _path?
870 let hir_id = self.tcx.hir().node_to_hir_id(p.id);
871 let adt = match self.save_ctxt.tables.node_type_opt(hir_id) {
872 Some(ty) => ty.ty_adt_def().unwrap(),
874 visit::walk_pat(self, p);
878 let variant = adt.variant_of_res(self.save_ctxt.get_path_res(p.id));
880 for field in fields {
881 if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
882 if !self.span.filter_generated(field.ident.span) {
883 let span = self.span_from_span(field.ident.span);
884 self.dumper.dump_ref(Ref {
885 kind: RefKind::Variable,
887 ref_id: id_from_def_id(variant.fields[index].did),
891 self.visit_pat(&field.pat);
894 _ => visit::walk_pat(self, p),
898 fn process_var_decl(&mut self, pat: &'l ast::Pat) {
899 // The pattern could declare multiple new vars,
900 // we must walk the pattern and collect them all.
901 let mut collector = PathCollector::new();
902 collector.visit_pat(&pat);
903 self.visit_pat(&pat);
905 // Process collected paths.
906 for (id, ident, _) in collector.collected_idents {
907 match self.save_ctxt.get_path_res(id) {
908 Res::Local(hir_id) => {
909 let id = self.tcx.hir().hir_to_node_id(hir_id);
910 let typ = self.save_ctxt.tables.node_type_opt(hir_id)
911 .map(|t| t.to_string())
912 .unwrap_or_default();
914 // Rust uses the id of the pattern for var lookups, so we'll use it too.
915 if !self.span.filter_generated(ident.span) {
916 let qualname = format!("{}${}", ident.to_string(), id);
917 let id = id_from_node_id(id, &self.save_ctxt);
918 let span = self.span_from_span(ident.span);
920 self.dumper.dump_def(
926 kind: DefKind::Local,
929 name: ident.to_string(),
942 Res::Def(HirDefKind::Ctor(..), _) |
943 Res::Def(HirDefKind::Const, _) |
944 Res::Def(HirDefKind::AssocConst, _) |
945 Res::Def(HirDefKind::Struct, _) |
946 Res::Def(HirDefKind::Variant, _) |
947 Res::Def(HirDefKind::TyAlias, _) |
948 Res::Def(HirDefKind::AssocTy, _) |
950 self.dump_path_ref(id, &ast::Path::from_ident(ident));
953 "unexpected definition kind when processing collected idents: {:?}",
959 for (id, ref path) in collector.collected_paths {
960 self.process_path(id, path);
964 /// Extracts macro use and definition information from the AST node defined
965 /// by the given NodeId, using the expansion information from the node's
968 /// If the span is not macro-generated, do nothing, else use callee and
969 /// callsite spans to record macro definition and use data, using the
970 /// mac_uses and mac_defs sets to prevent multiples.
971 fn process_macro_use(&mut self, _span: Span) {
972 // FIXME if we're not dumping the defs (see below), there is no point
973 // dumping refs either.
974 // let source_span = span.source_callsite();
975 // if !self.macro_calls.insert(source_span) {
979 // let data = match self.save_ctxt.get_macro_use_data(span) {
981 // Some(data) => data,
984 // self.dumper.macro_use(data);
986 // FIXME write the macro def
987 // let mut hasher = DefaultHasher::new();
988 // data.callee_span.hash(&mut hasher);
989 // let hash = hasher.finish();
990 // let qualname = format!("{}::{}", data.name, hash);
991 // Don't write macro definition for imported macros
992 // if !self.mac_defs.contains(&data.callee_span)
993 // && !data.imported {
994 // self.mac_defs.insert(data.callee_span);
995 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
996 // self.dumper.macro_data(MacroData {
998 // name: data.name.clone(),
999 // qualname: qualname.clone(),
1000 // // FIXME where do macro docs come from?
1001 // docs: String::new(),
1002 // }.lower(self.tcx));
1007 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1008 self.process_macro_use(trait_item.span);
1009 let vis_span = trait_item.span.shrink_to_lo();
1010 match trait_item.node {
1011 ast::TraitItemKind::Const(ref ty, ref expr) => {
1012 self.process_assoc_const(
1016 expr.as_ref().map(|e| &**e),
1018 respan(vis_span, ast::VisibilityKind::Public),
1022 ast::TraitItemKind::Method(ref sig, ref body) => {
1023 self.process_method(
1025 body.as_ref().map(|x| &**x),
1028 &trait_item.generics,
1029 respan(vis_span, ast::VisibilityKind::Public),
1033 ast::TraitItemKind::Type(ref bounds, ref default_ty) => {
1034 // FIXME do something with _bounds (for type refs)
1035 let name = trait_item.ident.name.to_string();
1036 let qualname = format!("::{}",
1037 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(trait_item.id)));
1039 if !self.span.filter_generated(trait_item.ident.span) {
1040 let span = self.span_from_span(trait_item.ident.span);
1041 let id = id_from_node_id(trait_item.id, &self.save_ctxt);
1043 self.dumper.dump_def(
1049 kind: DefKind::Type,
1054 value: self.span.snippet(trait_item.span),
1055 parent: Some(id_from_def_id(trait_id)),
1058 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1059 sig: sig::assoc_type_signature(
1063 default_ty.as_ref().map(|ty| &**ty),
1066 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1071 if let &Some(ref default_ty) = default_ty {
1072 self.visit_ty(default_ty)
1075 ast::TraitItemKind::Macro(_) => {}
1079 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1080 self.process_macro_use(impl_item.span);
1081 match impl_item.node {
1082 ast::ImplItemKind::Const(ref ty, ref expr) => {
1083 self.process_assoc_const(
1089 impl_item.vis.clone(),
1093 ast::ImplItemKind::Method(ref sig, ref body) => {
1094 self.process_method(
1099 &impl_item.generics,
1100 impl_item.vis.clone(),
1104 ast::ImplItemKind::TyAlias(ref ty) => {
1105 // FIXME: uses of the assoc type should ideally point to this
1106 // 'def' and the name here should be a ref to the def in the
1110 ast::ImplItemKind::OpaqueTy(ref bounds) => {
1111 // FIXME: uses of the assoc type should ideally point to this
1112 // 'def' and the name here should be a ref to the def in the
1114 self.process_bounds(&bounds);
1116 ast::ImplItemKind::Macro(_) => {}
1120 /// Dumps imports in a use tree recursively.
1122 /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1123 /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1124 /// ID and path. `root_item` is the topmost use tree in the hierarchy.
1126 /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1127 /// each child use tree is dumped recursively.
1128 fn process_use_tree(&mut self,
1129 use_tree: &'l ast::UseTree,
1131 root_item: &'l ast::Item,
1132 prefix: &ast::Path) {
1133 let path = &use_tree.prefix;
1135 // The access is calculated using the current tree ID, but with the root tree's visibility
1136 // (since nested trees don't have their own visibility).
1137 let hir_id = self.tcx.hir().node_to_hir_id(id);
1138 let access = access_from!(self.save_ctxt, root_item, hir_id);
1140 // The parent `DefId` of a given use tree is always the enclosing item.
1141 let parent = self.save_ctxt.tcx.hir().opt_local_def_id_from_node_id(id)
1142 .and_then(|id| self.save_ctxt.tcx.parent(id))
1143 .map(id_from_def_id);
1145 match use_tree.kind {
1146 ast::UseTreeKind::Simple(alias, ..) => {
1147 let ident = use_tree.ident();
1148 let path = ast::Path {
1149 segments: prefix.segments
1151 .chain(path.segments.iter())
1157 let sub_span = path.segments.last().unwrap().ident.span;
1158 if !self.span.filter_generated(sub_span) {
1159 let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id));
1160 let alias_span = alias.map(|i| self.span_from_span(i.span));
1161 let span = self.span_from_span(sub_span);
1162 self.dumper.import(&access, Import {
1163 kind: ImportKind::Use,
1167 name: ident.to_string(),
1168 value: String::new(),
1171 self.write_sub_paths_truncated(&path);
1174 ast::UseTreeKind::Glob => {
1175 let path = ast::Path {
1176 segments: prefix.segments
1178 .chain(path.segments.iter())
1184 // Make a comma-separated list of names of imported modules.
1185 let def_id = self.tcx.hir().local_def_id_from_node_id(id);
1186 let names = self.tcx.names_imported_by_glob_use(def_id);
1187 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1189 // Otherwise it's a span with wrong macro expansion info, which
1190 // we don't want to track anyway, since it's probably macro-internal `use`
1191 if let Some(sub_span) =
1192 self.span.sub_span_of_token(use_tree.span, token::BinOp(token::Star))
1194 if !self.span.filter_generated(use_tree.span) {
1195 let span = self.span_from_span(sub_span);
1197 self.dumper.import(&access, Import {
1198 kind: ImportKind::GlobUse,
1202 name: "*".to_owned(),
1203 value: names.join(", "),
1206 self.write_sub_paths(&path);
1210 ast::UseTreeKind::Nested(ref nested_items) => {
1211 let prefix = ast::Path {
1212 segments: prefix.segments
1214 .chain(path.segments.iter())
1219 for &(ref tree, id) in nested_items {
1220 self.process_use_tree(tree, id, root_item, &prefix);
1226 fn process_bounds(&mut self, bounds: &'l ast::GenericBounds) {
1227 for bound in bounds {
1228 if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1229 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1235 impl<'l, 'tcx> Visitor<'l> for DumpVisitor<'l, 'tcx> {
1236 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1237 // Since we handle explicit modules ourselves in visit_item, this should
1238 // only get called for the root module of a crate.
1239 assert_eq!(id, ast::CRATE_NODE_ID);
1241 let qualname = format!("::{}",
1242 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
1244 let cm = self.tcx.sess.source_map();
1245 let filename = cm.span_to_filename(span);
1246 let data_id = id_from_node_id(id, &self.save_ctxt);
1247 let children = m.items
1249 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
1251 let span = self.span_from_span(span);
1253 self.dumper.dump_def(
1261 name: String::new(),
1264 value: filename.to_string(),
1268 docs: self.save_ctxt.docs_for_attrs(attrs),
1270 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1273 visit::walk_mod(self, m);
1276 fn visit_item(&mut self, item: &'l ast::Item) {
1277 use syntax::ast::ItemKind::*;
1278 self.process_macro_use(item.span);
1280 Use(ref use_tree) => {
1281 let prefix = ast::Path {
1285 self.process_use_tree(use_tree, item.id, item, &prefix);
1288 let name_span = item.ident.span;
1289 if !self.span.filter_generated(name_span) {
1290 let span = self.span_from_span(name_span);
1291 let parent = self.save_ctxt.tcx.hir().opt_local_def_id_from_node_id(item.id)
1292 .and_then(|id| self.save_ctxt.tcx.parent(id))
1293 .map(id_from_def_id);
1300 kind: ImportKind::ExternCrate,
1304 name: item.ident.to_string(),
1305 value: String::new(),
1311 Fn(ref decl, .., ref ty_params, ref body) => {
1312 self.process_fn(item, &decl, ty_params, &body)
1314 Static(ref typ, _, ref expr) => self.process_static_or_const_item(item, typ, expr),
1315 Const(ref typ, ref expr) => self.process_static_or_const_item(item, &typ, &expr),
1316 Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1317 self.process_struct(item, def, ty_params)
1319 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1320 Impl(.., ref ty_params, ref trait_ref, ref typ, ref impl_items) => {
1321 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1323 Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1324 self.process_trait(item, generics, trait_refs, methods)
1327 self.process_mod(item);
1328 visit::walk_mod(self, m);
1330 TyAlias(ref ty, ref ty_params) => {
1331 let qualname = format!("::{}",
1332 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
1333 let value = ty_to_string(&ty);
1334 if !self.span.filter_generated(item.ident.span) {
1335 let span = self.span_from_span(item.ident.span);
1336 let id = id_from_node_id(item.id, &self.save_ctxt);
1337 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1339 self.dumper.dump_def(
1340 &access_from!(self.save_ctxt, item, hir_id),
1342 kind: DefKind::Type,
1345 name: item.ident.to_string(),
1346 qualname: qualname.clone(),
1351 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1352 sig: sig::item_signature(item, &self.save_ctxt),
1353 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1359 self.process_generic_params(ty_params, &qualname, item.id);
1361 OpaqueTy(ref bounds, ref ty_params) => {
1362 let qualname = format!("::{}",
1363 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
1365 let value = String::new();
1366 if !self.span.filter_generated(item.ident.span) {
1367 let span = self.span_from_span(item.ident.span);
1368 let id = id_from_node_id(item.id, &self.save_ctxt);
1369 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1371 self.dumper.dump_def(
1372 &access_from!(self.save_ctxt, item, hir_id),
1374 kind: DefKind::Type,
1377 name: item.ident.to_string(),
1378 qualname: qualname.clone(),
1383 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1384 sig: sig::item_signature(item, &self.save_ctxt),
1385 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1390 self.process_bounds(bounds);
1391 self.process_generic_params(ty_params, &qualname, item.id);
1394 _ => visit::walk_item(self, item),
1398 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1399 for param in &generics.params {
1401 ast::GenericParamKind::Lifetime { .. } => {}
1402 ast::GenericParamKind::Type { ref default, .. } => {
1403 self.process_bounds(¶m.bounds);
1404 if let Some(ref ty) = default {
1408 ast::GenericParamKind::Const { ref ty } => {
1409 self.process_bounds(¶m.bounds);
1414 for pred in &generics.where_clause.predicates {
1415 if let ast::WherePredicate::BoundPredicate(ref wbp) = *pred {
1416 self.process_bounds(&wbp.bounds);
1417 self.visit_ty(&wbp.bounded_ty);
1422 fn visit_ty(&mut self, t: &'l ast::Ty) {
1423 self.process_macro_use(t.span);
1425 ast::TyKind::Path(_, ref path) => {
1426 if generated_code(t.span) {
1430 if let Some(id) = self.lookup_def_id(t.id) {
1431 let sub_span = path.segments.last().unwrap().ident.span;
1432 let span = self.span_from_span(sub_span);
1433 self.dumper.dump_ref(Ref {
1434 kind: RefKind::Type,
1436 ref_id: id_from_def_id(id),
1440 self.write_sub_paths_truncated(path);
1441 visit::walk_path(self, path);
1443 ast::TyKind::Array(ref element, ref length) => {
1444 self.visit_ty(element);
1445 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1447 ast::TyKind::ImplTrait(id, ref bounds) => {
1448 // FIXME: As of writing, the opaque type lowering introduces
1449 // another DefPath scope/segment (used to declare the resulting
1450 // opaque type item).
1451 // However, the synthetic scope does *not* have associated
1452 // typeck tables, which means we can't nest it and we fire an
1453 // assertion when resolving the qualified type paths in trait
1455 // This will panic if called on return type `impl Trait`, which
1456 // we guard against in `process_fn`.
1457 self.nest_tables(id, |v| v.process_bounds(bounds));
1459 _ => visit::walk_ty(self, t),
1463 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1464 debug!("visit_expr {:?}", ex.kind);
1465 self.process_macro_use(ex.span);
1467 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1468 let expr_hir_id = self.save_ctxt.tcx.hir().node_to_hir_id(ex.id);
1469 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(expr_hir_id);
1470 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1471 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1473 visit::walk_expr(self, ex);
1477 let node_id = self.save_ctxt.tcx.hir().hir_to_node_id(hir_expr.hir_id);
1478 let res = self.save_ctxt.get_path_res(node_id);
1479 self.process_struct_lit(ex, path, fields, adt.variant_of_res(res), base)
1481 ast::ExprKind::MethodCall(ref seg, ref args) => self.process_method_call(ex, seg, args),
1482 ast::ExprKind::Field(ref sub_ex, _) => {
1483 self.visit_expr(&sub_ex);
1485 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1486 down_cast_data!(field_data, RefData, ex.span);
1487 if !generated_code(ex.span) {
1488 self.dumper.dump_ref(field_data);
1492 ast::ExprKind::Closure(_, _, _, ref decl, ref body, _fn_decl_span) => {
1493 let id = format!("${}", ex.id);
1495 // walk arg and return types
1496 for arg in &decl.inputs {
1497 self.visit_ty(&arg.ty);
1500 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1501 self.visit_ty(&ret_ty);
1505 self.nest_tables(ex.id, |v| {
1506 v.process_formals(&decl.inputs, &id);
1510 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1511 self.process_var_decl(pattern);
1512 debug!("for loop, walk sub-expr: {:?}", subexpression.kind);
1513 self.visit_expr(subexpression);
1514 visit::walk_block(self, block);
1516 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1517 self.process_var_decl(pat);
1518 self.visit_expr(scrutinee);
1520 ast::ExprKind::Repeat(ref element, ref count) => {
1521 self.visit_expr(element);
1522 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1524 // In particular, we take this branch for call and path expressions,
1525 // where we'll index the idents involved just by continuing to walk.
1526 _ => visit::walk_expr(self, ex),
1530 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1531 // These shouldn't exist in the AST at this point, log a span bug.
1534 "macro invocation should have been expanded out of AST"
1538 fn visit_pat(&mut self, p: &'l ast::Pat) {
1539 self.process_macro_use(p.span);
1540 self.process_pat(p);
1543 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1544 self.process_var_decl(&arm.pat);
1545 if let Some(expr) = &arm.guard {
1546 self.visit_expr(expr);
1548 self.visit_expr(&arm.body);
1551 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1552 self.process_path(id, p);
1555 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1556 self.process_macro_use(s.span);
1557 visit::walk_stmt(self, s)
1560 fn visit_local(&mut self, l: &'l ast::Local) {
1561 self.process_macro_use(l.span);
1562 self.process_var_decl(&l.pat);
1564 // Just walk the initialiser and type (don't want to walk the pattern again).
1565 walk_list!(self, visit_ty, &l.ty);
1566 walk_list!(self, visit_expr, &l.init);
1569 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1570 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1571 let access = access_from!(self.save_ctxt, item, hir_id);
1574 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1575 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1576 down_cast_data!(fn_data, DefData, item.span);
1578 self.process_generic_params(generics, &fn_data.qualname, item.id);
1579 self.dumper.dump_def(&access, fn_data);
1582 for arg in &decl.inputs {
1583 self.visit_ty(&arg.ty);
1586 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1587 self.visit_ty(&ret_ty);
1590 ast::ForeignItemKind::Static(ref ty, _) => {
1591 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1592 down_cast_data!(var_data, DefData, item.span);
1593 self.dumper.dump_def(&access, var_data);
1598 ast::ForeignItemKind::Ty => {
1599 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1600 down_cast_data!(var_data, DefData, item.span);
1601 self.dumper.dump_def(&access, var_data);
1604 ast::ForeignItemKind::Macro(..) => {}