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::Def as HirDef;
17 use rustc::hir::def_id::DefId;
18 use rustc::session::config::Input;
20 use rustc::ty::{self, 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, $vis:expr, $id:expr) => {
63 public: $vis.node.is_pub(),
64 reachable: $save_ctxt.access_levels.is_reachable($id),
68 ($save_ctxt:expr, $item:expr) => {
70 public: $item.vis.node.is_pub(),
71 reachable: $save_ctxt.access_levels.is_reachable($item.id),
76 pub struct DumpVisitor<'l, 'tcx: 'l, 'll, O: DumpOutput> {
77 save_ctxt: SaveContext<'l, 'tcx>,
78 tcx: TyCtxt<'l, 'tcx, 'tcx>,
79 dumper: &'ll mut JsonDumper<O>,
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: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> {
95 save_ctxt: SaveContext<'l, 'tcx>,
96 dumper: &'ll mut JsonDumper<O>,
97 ) -> DumpVisitor<'l, 'tcx, 'll, O> {
98 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
104 cur_scope: CRATE_NODE_ID,
105 // mac_defs: FxHashSet::default(),
106 // macro_calls: FxHashSet::default(),
110 fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
112 F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
114 let parent_scope = self.cur_scope;
115 self.cur_scope = scope_id;
117 self.cur_scope = parent_scope;
120 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
122 F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
124 let item_def_id = self.tcx.hir().local_def_id(item_id);
125 if self.tcx.has_typeck_tables(item_def_id) {
126 let tables = self.tcx.typeck_tables_of(item_def_id);
127 let old_tables = self.save_ctxt.tables;
128 self.save_ctxt.tables = tables;
130 self.save_ctxt.tables = old_tables;
136 fn span_from_span(&self, span: Span) -> SpanData {
137 self.save_ctxt.span_from_span(span)
140 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
141 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
142 let crate_root = source_file.map(|source_file| {
143 let source_file = Path::new(source_file);
144 match source_file.file_name() {
145 Some(_) => source_file.parent().unwrap().display(),
146 None => source_file.display(),
150 let data = CratePreludeData {
151 crate_id: GlobalCrateId {
153 disambiguator: self.tcx
155 .local_crate_disambiguator()
159 crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
160 external_crates: self.save_ctxt.get_external_crates(),
161 span: self.span_from_span(krate.span),
164 self.dumper.crate_prelude(data);
167 pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
168 // Apply possible `remap-path-prefix` remapping to the input source file
169 // (and don't include remapping args anymore)
170 let (program, arguments) = {
171 let remap_arg_indices = {
172 let mut indices = FxHashSet::default();
173 // Args are guaranteed to be valid UTF-8 (checked early)
174 for (i, e) in env::args().enumerate() {
175 if e.starts_with("--remap-path-prefix=") {
177 } else if e == "--remap-path-prefix" {
179 indices.insert(i + 1);
185 let mut args = env::args()
187 .filter(|(i, _)| !remap_arg_indices.contains(i))
190 Input::File(ref path) if path == Path::new(&arg) => {
191 let mapped = &self.tcx.sess.local_crate_source_file;
202 (args.next().unwrap(), args.collect())
205 let data = CompilationOptions {
206 directory: self.tcx.sess.working_dir.0.clone(),
209 output: self.save_ctxt.compilation_output(crate_name),
212 self.dumper.compilation_opts(data);
215 fn write_sub_paths(&mut self, path: &ast::Path) {
216 for seg in &path.segments {
217 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
218 self.dumper.dump_ref(data);
223 // As write_sub_paths, but does not process the last ident in the path (assuming it
224 // will be processed elsewhere). See note on write_sub_paths about global.
225 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
226 for seg in &path.segments[..path.segments.len() - 1] {
227 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
228 self.dumper.dump_ref(data);
233 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
234 match self.save_ctxt.get_path_def(ref_id) {
235 HirDef::PrimTy(..) | HirDef::SelfTy(..) | HirDef::Err => None,
236 def => Some(def.def_id()),
240 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
242 self.visit_pat(&arg.pat);
243 let mut collector = PathCollector::new();
244 collector.visit_pat(&arg.pat);
246 for (id, ident, ..) in collector.collected_idents {
247 let hir_id = self.tcx.hir().node_to_hir_id(id);
248 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
249 Some(s) => s.to_string(),
252 if !self.span.filter_generated(ident.span) {
253 let id = id_from_node_id(id, &self.save_ctxt);
254 let span = self.span_from_span(ident.span);
256 self.dumper.dump_def(
262 kind: DefKind::Local,
265 name: ident.to_string(),
266 qualname: format!("{}::{}", qualname, ident.to_string()),
283 sig: &'l ast::MethodSig,
284 body: Option<&'l ast::Block>,
287 generics: &'l ast::Generics,
288 vis: ast::Visibility,
291 debug!("process_method: {}:{}", id, ident);
293 if let Some(mut method_data) = self.save_ctxt.get_method_data(id, ident, span) {
294 let sig_str = crate::make_signature(&sig.decl, &generics);
298 |v| v.process_formals(&sig.decl.inputs, &method_data.qualname),
302 self.process_generic_params(&generics, &method_data.qualname, id);
304 method_data.value = sig_str;
305 method_data.sig = sig::method_signature(id, ident, generics, sig, &self.save_ctxt);
306 self.dumper.dump_def(&access_from!(self.save_ctxt, vis, id), method_data);
309 // walk arg and return types
310 for arg in &sig.decl.inputs {
311 self.visit_ty(&arg.ty);
314 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
315 self.visit_ty(ret_ty);
319 if let Some(body) = body {
320 self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
324 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
325 let field_data = self.save_ctxt.get_field_data(field, parent_id);
326 if let Some(field_data) = field_data {
327 self.dumper.dump_def(&access_from!(self.save_ctxt, field), field_data);
331 // Dump generic params bindings, then visit_generics
332 fn process_generic_params(
334 generics: &'l ast::Generics,
338 for param in &generics.params {
340 ast::GenericParamKind::Lifetime { .. } => {}
341 ast::GenericParamKind::Type { .. } => {
342 let param_ss = param.ident.span;
343 let name = escape(self.span.snippet(param_ss));
344 // Append $id to name to make sure each one is unique.
345 let qualname = format!("{}::{}${}", prefix, name, id);
346 if !self.span.filter_generated(param_ss) {
347 let id = id_from_node_id(param.id, &self.save_ctxt);
348 let span = self.span_from_span(param_ss);
350 self.dumper.dump_def(
361 value: String::new(),
372 ast::GenericParamKind::Const { .. } => {}
375 self.visit_generics(generics);
381 decl: &'l ast::FnDecl,
382 ty_params: &'l ast::Generics,
383 body: &'l ast::Block,
385 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
386 down_cast_data!(fn_data, DefData, item.span);
389 |v| v.process_formals(&decl.inputs, &fn_data.qualname),
391 self.process_generic_params(ty_params, &fn_data.qualname, item.id);
392 self.dumper.dump_def(&access_from!(self.save_ctxt, item), fn_data);
395 for arg in &decl.inputs {
396 self.visit_ty(&arg.ty);
399 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
400 self.visit_ty(&ret_ty);
403 self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
406 fn process_static_or_const_item(
412 self.nest_tables(item.id, |v| {
413 if let Some(var_data) = v.save_ctxt.get_item_data(item) {
414 down_cast_data!(var_data, DefData, item.span);
415 v.dumper.dump_def(&access_from!(v.save_ctxt, item), var_data);
422 fn process_assoc_const(
427 expr: Option<&'l ast::Expr>,
429 vis: ast::Visibility,
430 attrs: &'l [Attribute],
432 let qualname = format!("::{}", self.tcx.node_path_str(id));
434 if !self.span.filter_generated(ident.span) {
435 let sig = sig::assoc_const_signature(id, ident.name, typ, expr, &self.save_ctxt);
436 let span = self.span_from_span(ident.span);
438 self.dumper.dump_def(
439 &access_from!(self.save_ctxt, vis, id),
441 kind: DefKind::Const,
442 id: id_from_node_id(id, &self.save_ctxt),
444 name: ident.name.to_string(),
446 value: ty_to_string(&typ),
447 parent: Some(id_from_def_id(parent_id)),
450 docs: self.save_ctxt.docs_for_attrs(attrs),
452 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
457 // walk type and init value
459 if let Some(expr) = expr {
460 self.visit_expr(expr);
464 // FIXME tuple structs should generate tuple-specific data.
468 def: &'l ast::VariantData,
469 ty_params: &'l ast::Generics,
471 debug!("process_struct {:?} {:?}", item, item.span);
472 let name = item.ident.to_string();
473 let qualname = format!("::{}", self.tcx.node_path_str(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 self.dumper.dump_def(
514 &access_from!(self.save_ctxt, item),
517 id: id_from_node_id(item.id, &self.save_ctxt),
520 qualname: qualname.clone(),
525 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
526 sig: sig::item_signature(item, &self.save_ctxt),
527 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
532 for field in def.fields() {
533 self.process_struct_field_def(field, item.id);
534 self.visit_ty(&field.ty);
537 self.process_generic_params(ty_params, &qualname, item.id);
543 enum_definition: &'l ast::EnumDef,
544 ty_params: &'l ast::Generics,
546 let enum_data = self.save_ctxt.get_item_data(item);
547 let enum_data = match enum_data {
551 down_cast_data!(enum_data, DefData, item.span);
553 let access = access_from!(self.save_ctxt, item);
555 for variant in &enum_definition.variants {
556 let name = variant.node.ident.name.to_string();
557 let qualname = format!("{}::{}", enum_data.qualname, name);
558 let name_span = variant.node.ident.span;
560 match variant.node.data {
561 ast::VariantData::Struct(ref fields, _) => {
562 let fields_str = fields
566 f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
570 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
571 if !self.span.filter_generated(name_span) {
572 let span = self.span_from_span(name_span);
573 let id = id_from_node_id(variant.node.data.id(), &self.save_ctxt);
574 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
576 self.dumper.dump_def(
579 kind: DefKind::StructVariant,
588 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
589 sig: sig::variant_signature(variant, &self.save_ctxt),
590 attributes: lower_attributes(
591 variant.node.attrs.clone(),
599 let mut value = format!("{}::{}", enum_data.name, name);
600 if let &ast::VariantData::Tuple(ref fields, _) = v {
602 value.push_str(&fields
604 .map(|f| ty_to_string(&f.ty))
609 if !self.span.filter_generated(name_span) {
610 let span = self.span_from_span(name_span);
611 let id = id_from_node_id(variant.node.data.id(), &self.save_ctxt);
612 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
614 self.dumper.dump_def(
617 kind: DefKind::TupleVariant,
626 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
627 sig: sig::variant_signature(variant, &self.save_ctxt),
628 attributes: lower_attributes(
629 variant.node.attrs.clone(),
639 for field in variant.node.data.fields() {
640 self.process_struct_field_def(field, variant.node.data.id());
641 self.visit_ty(&field.ty);
644 self.process_generic_params(ty_params, &enum_data.qualname, item.id);
645 self.dumper.dump_def(&access, enum_data);
651 type_parameters: &'l ast::Generics,
652 trait_ref: &'l Option<ast::TraitRef>,
654 impl_items: &'l [ast::ImplItem],
656 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
657 if !self.span.filter_generated(item.span) {
658 if let super::Data::RelationData(rel, imp) = impl_data {
659 self.dumper.dump_relation(rel);
660 self.dumper.dump_impl(imp);
662 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
667 if let &Some(ref trait_ref) = trait_ref {
668 self.process_path(trait_ref.ref_id, &trait_ref.path);
670 self.process_generic_params(type_parameters, "", item.id);
671 for impl_item in impl_items {
672 let map = &self.tcx.hir();
673 self.process_impl_item(impl_item, map.local_def_id(item.id));
680 generics: &'l ast::Generics,
681 trait_refs: &'l ast::GenericBounds,
682 methods: &'l [ast::TraitItem],
684 let name = item.ident.to_string();
685 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
686 let mut val = name.clone();
687 if !generics.params.is_empty() {
688 val.push_str(&generic_params_to_string(&generics.params));
690 if !trait_refs.is_empty() {
692 val.push_str(&bounds_to_string(trait_refs));
694 if !self.span.filter_generated(item.ident.span) {
695 let id = id_from_node_id(item.id, &self.save_ctxt);
696 let span = self.span_from_span(item.ident.span);
697 let children = methods
699 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
701 self.dumper.dump_def(
702 &access_from!(self.save_ctxt, item),
704 kind: DefKind::Trait,
708 qualname: qualname.clone(),
713 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
714 sig: sig::item_signature(item, &self.save_ctxt),
715 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
721 for super_bound in trait_refs.iter() {
722 let trait_ref = match *super_bound {
723 ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
724 ast::GenericBound::Outlives(..) => continue,
727 let trait_ref = &trait_ref.trait_ref;
728 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
729 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
730 if !self.span.filter_generated(sub_span) {
731 let span = self.span_from_span(sub_span);
732 self.dumper.dump_ref(Ref {
735 ref_id: id_from_def_id(id),
738 self.dumper.dump_relation(Relation {
739 kind: RelationKind::SuperTrait,
741 from: id_from_def_id(id),
742 to: id_from_node_id(item.id, &self.save_ctxt),
748 // walk generics and methods
749 self.process_generic_params(generics, &qualname, item.id);
750 for method in methods {
751 let map = &self.tcx.hir();
752 self.process_trait_item(method, map.local_def_id(item.id))
756 // `item` is the module in question, represented as an item.
757 fn process_mod(&mut self, item: &ast::Item) {
758 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
759 down_cast_data!(mod_data, DefData, item.span);
760 self.dumper.dump_def(&access_from!(self.save_ctxt, item), mod_data);
764 fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
765 let path_data = self.save_ctxt.get_path_data(id, path);
766 if let Some(path_data) = path_data {
767 self.dumper.dump_ref(path_data);
771 fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
772 if self.span.filter_generated(path.span) {
775 self.dump_path_ref(id, path);
778 for seg in &path.segments {
779 if let Some(ref generic_args) = seg.args {
780 match **generic_args {
781 ast::GenericArgs::AngleBracketed(ref data) => {
782 for arg in &data.args {
784 ast::GenericArg::Type(ty) => self.visit_ty(ty),
789 ast::GenericArgs::Parenthesized(ref data) => {
790 for t in &data.inputs {
793 if let Some(ref t) = data.output {
801 self.write_sub_paths_truncated(path);
804 fn process_struct_lit(
808 fields: &'l [ast::Field],
809 variant: &'l ty::VariantDef,
810 base: &'l Option<P<ast::Expr>>,
812 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
813 self.write_sub_paths_truncated(path);
814 down_cast_data!(struct_lit_data, RefData, ex.span);
815 if !generated_code(ex.span) {
816 self.dumper.dump_ref(struct_lit_data);
819 for field in fields {
820 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
821 self.dumper.dump_ref(field_data);
824 self.visit_expr(&field.expr)
828 walk_list!(self, visit_expr, base);
831 fn process_method_call(
834 seg: &'l ast::PathSegment,
835 args: &'l [P<ast::Expr>],
837 debug!("process_method_call {:?} {:?}", ex, ex.span);
838 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
839 down_cast_data!(mcd, RefData, ex.span);
840 if !generated_code(ex.span) {
841 self.dumper.dump_ref(mcd);
845 // Explicit types in the turbo-fish.
846 if let Some(ref generic_args) = seg.args {
847 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
848 for arg in &data.args {
850 ast::GenericArg::Type(ty) => self.visit_ty(ty),
857 // walk receiver and args
858 walk_list!(self, visit_expr, args);
861 fn process_pat(&mut self, p: &'l ast::Pat) {
863 PatKind::Struct(ref _path, ref fields, _) => {
864 // FIXME do something with _path?
865 let hir_id = self.tcx.hir().node_to_hir_id(p.id);
866 let adt = match self.save_ctxt.tables.node_type_opt(hir_id) {
867 Some(ty) => ty.ty_adt_def().unwrap(),
869 visit::walk_pat(self, p);
873 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
875 for &Spanned { node: ref field, .. } in fields {
876 if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
877 if !self.span.filter_generated(field.ident.span) {
878 let span = self.span_from_span(field.ident.span);
879 self.dumper.dump_ref(Ref {
880 kind: RefKind::Variable,
882 ref_id: id_from_def_id(variant.fields[index].did),
886 self.visit_pat(&field.pat);
889 _ => visit::walk_pat(self, p),
893 fn process_var_decl_multi(&mut self, pats: &'l [P<ast::Pat>]) {
894 let mut collector = PathCollector::new();
895 for pattern in pats {
896 // collect paths from the arm's patterns
897 collector.visit_pat(&pattern);
898 self.visit_pat(&pattern);
901 // process collected paths
902 for (id, ident, immut) in collector.collected_idents {
903 match self.save_ctxt.get_path_def(id) {
904 HirDef::Local(id) => {
905 let mut value = if immut == ast::Mutability::Immutable {
906 self.span.snippet(ident.span)
908 "<mutable>".to_owned()
910 let hir_id = self.tcx.hir().node_to_hir_id(id);
911 let typ = self.save_ctxt
913 .node_type_opt(hir_id)
914 .map(|t| t.to_string())
915 .unwrap_or_default();
916 value.push_str(": ");
917 value.push_str(&typ);
919 if !self.span.filter_generated(ident.span) {
920 let qualname = format!("{}${}", ident.to_string(), id);
921 let id = id_from_node_id(id, &self.save_ctxt);
922 let span = self.span_from_span(ident.span);
924 self.dumper.dump_def(
930 kind: DefKind::Local,
933 name: ident.to_string(),
946 HirDef::StructCtor(..) |
947 HirDef::VariantCtor(..) |
949 HirDef::AssociatedConst(..) |
951 HirDef::Variant(..) |
952 HirDef::TyAlias(..) |
953 HirDef::AssociatedTy(..) |
954 HirDef::SelfTy(..) => {
955 self.dump_path_ref(id, &ast::Path::from_ident(ident));
958 "unexpected definition kind when processing collected idents: {:?}",
964 for (id, ref path) in collector.collected_paths {
965 self.process_path(id, path);
969 fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
970 // The local could declare multiple new vars, we must walk the
971 // pattern and collect them all.
972 let mut collector = PathCollector::new();
973 collector.visit_pat(&p);
976 for (id, ident, immut) in collector.collected_idents {
977 let mut value = match immut {
978 ast::Mutability::Immutable => value.to_string(),
981 let hir_id = self.tcx.hir().node_to_hir_id(id);
982 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
984 let typ = typ.to_string();
985 if !value.is_empty() {
986 value.push_str(": ");
988 value.push_str(&typ);
991 None => String::new(),
994 // Rust uses the id of the pattern for var lookups, so we'll use it too.
995 if !self.span.filter_generated(ident.span) {
996 let qualname = format!("{}${}", ident.to_string(), id);
997 let id = id_from_node_id(id, &self.save_ctxt);
998 let span = self.span_from_span(ident.span);
1000 self.dumper.dump_def(
1006 kind: DefKind::Local,
1009 name: ident.to_string(),
1015 docs: String::new(),
1024 /// Extracts macro use and definition information from the AST node defined
1025 /// by the given NodeId, using the expansion information from the node's
1028 /// If the span is not macro-generated, do nothing, else use callee and
1029 /// callsite spans to record macro definition and use data, using the
1030 /// mac_uses and mac_defs sets to prevent multiples.
1031 fn process_macro_use(&mut self, _span: Span) {
1032 // FIXME if we're not dumping the defs (see below), there is no point
1033 // dumping refs either.
1034 // let source_span = span.source_callsite();
1035 // if !self.macro_calls.insert(source_span) {
1039 // let data = match self.save_ctxt.get_macro_use_data(span) {
1041 // Some(data) => data,
1044 // self.dumper.macro_use(data);
1046 // FIXME write the macro def
1047 // let mut hasher = DefaultHasher::new();
1048 // data.callee_span.hash(&mut hasher);
1049 // let hash = hasher.finish();
1050 // let qualname = format!("{}::{}", data.name, hash);
1051 // Don't write macro definition for imported macros
1052 // if !self.mac_defs.contains(&data.callee_span)
1053 // && !data.imported {
1054 // self.mac_defs.insert(data.callee_span);
1055 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1056 // self.dumper.macro_data(MacroData {
1058 // name: data.name.clone(),
1059 // qualname: qualname.clone(),
1060 // // FIXME where do macro docs come from?
1061 // docs: String::new(),
1062 // }.lower(self.tcx));
1067 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1068 self.process_macro_use(trait_item.span);
1069 let vis_span = trait_item.span.shrink_to_lo();
1070 match trait_item.node {
1071 ast::TraitItemKind::Const(ref ty, ref expr) => {
1072 self.process_assoc_const(
1076 expr.as_ref().map(|e| &**e),
1078 respan(vis_span, ast::VisibilityKind::Public),
1082 ast::TraitItemKind::Method(ref sig, ref body) => {
1083 self.process_method(
1085 body.as_ref().map(|x| &**x),
1088 &trait_item.generics,
1089 respan(vis_span, ast::VisibilityKind::Public),
1093 ast::TraitItemKind::Type(ref bounds, ref default_ty) => {
1094 // FIXME do something with _bounds (for type refs)
1095 let name = trait_item.ident.name.to_string();
1096 let qualname = format!("::{}", self.tcx.node_path_str(trait_item.id));
1098 if !self.span.filter_generated(trait_item.ident.span) {
1099 let span = self.span_from_span(trait_item.ident.span);
1100 let id = id_from_node_id(trait_item.id, &self.save_ctxt);
1102 self.dumper.dump_def(
1108 kind: DefKind::Type,
1113 value: self.span.snippet(trait_item.span),
1114 parent: Some(id_from_def_id(trait_id)),
1117 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1118 sig: sig::assoc_type_signature(
1122 default_ty.as_ref().map(|ty| &**ty),
1125 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1130 if let &Some(ref default_ty) = default_ty {
1131 self.visit_ty(default_ty)
1134 ast::TraitItemKind::Macro(_) => {}
1138 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1139 self.process_macro_use(impl_item.span);
1140 match impl_item.node {
1141 ast::ImplItemKind::Const(ref ty, ref expr) => {
1142 self.process_assoc_const(
1148 impl_item.vis.clone(),
1152 ast::ImplItemKind::Method(ref sig, ref body) => {
1153 self.process_method(
1158 &impl_item.generics,
1159 impl_item.vis.clone(),
1163 ast::ImplItemKind::Type(ref ty) => {
1164 // FIXME uses of the assoc type should ideally point to this
1165 // 'def' and the name here should be a ref to the def in the
1169 ast::ImplItemKind::Existential(ref bounds) => {
1170 // FIXME uses of the assoc type should ideally point to this
1171 // 'def' and the name here should be a ref to the def in the
1173 for bound in bounds.iter() {
1174 if let ast::GenericBound::Trait(trait_ref, _) = bound {
1175 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1179 ast::ImplItemKind::Macro(_) => {}
1183 /// Dumps imports in a use tree recursively.
1185 /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1186 /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1187 /// ID and path. `root_item` is the topmost use tree in the hierarchy.
1189 /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1190 /// each child use tree is dumped recursively.
1191 fn process_use_tree(&mut self,
1192 use_tree: &'l ast::UseTree,
1194 root_item: &'l ast::Item,
1195 prefix: &ast::Path) {
1196 let path = &use_tree.prefix;
1198 // The access is calculated using the current tree ID, but with the root tree's visibility
1199 // (since nested trees don't have their own visibility).
1200 let access = access_from!(self.save_ctxt, root_item.vis, id);
1202 // The parent def id of a given use tree is always the enclosing item.
1203 let parent = self.save_ctxt.tcx.hir().opt_local_def_id(id)
1204 .and_then(|id| self.save_ctxt.tcx.parent_def_id(id))
1205 .map(id_from_def_id);
1207 match use_tree.kind {
1208 ast::UseTreeKind::Simple(alias, ..) => {
1209 let ident = use_tree.ident();
1210 let path = ast::Path {
1211 segments: prefix.segments
1213 .chain(path.segments.iter())
1219 let sub_span = path.segments.last().unwrap().ident.span;
1220 if !self.span.filter_generated(sub_span) {
1221 let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id));
1222 let alias_span = alias.map(|i| self.span_from_span(i.span));
1223 let span = self.span_from_span(sub_span);
1224 self.dumper.import(&access, Import {
1225 kind: ImportKind::Use,
1229 name: ident.to_string(),
1230 value: String::new(),
1233 self.write_sub_paths_truncated(&path);
1236 ast::UseTreeKind::Glob => {
1237 let path = ast::Path {
1238 segments: prefix.segments
1240 .chain(path.segments.iter())
1246 // Make a comma-separated list of names of imported modules.
1247 let def_id = self.tcx.hir().local_def_id(id);
1248 let names = self.tcx.names_imported_by_glob_use(def_id);
1249 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1251 // Otherwise it's a span with wrong macro expansion info, which
1252 // we don't want to track anyway, since it's probably macro-internal `use`
1253 if let Some(sub_span) =
1254 self.span.sub_span_of_token(use_tree.span, token::BinOp(token::Star))
1256 if !self.span.filter_generated(use_tree.span) {
1257 let span = self.span_from_span(sub_span);
1259 self.dumper.import(&access, Import {
1260 kind: ImportKind::GlobUse,
1264 name: "*".to_owned(),
1265 value: names.join(", "),
1268 self.write_sub_paths(&path);
1272 ast::UseTreeKind::Nested(ref nested_items) => {
1273 let prefix = ast::Path {
1274 segments: prefix.segments
1276 .chain(path.segments.iter())
1281 for &(ref tree, id) in nested_items {
1282 self.process_use_tree(tree, id, root_item, &prefix);
1288 fn process_bounds(&mut self, bounds: &'l ast::GenericBounds) {
1289 for bound in bounds {
1290 if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1291 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1297 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, O> {
1298 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1299 // Since we handle explicit modules ourselves in visit_item, this should
1300 // only get called for the root module of a crate.
1301 assert_eq!(id, ast::CRATE_NODE_ID);
1303 let qualname = format!("::{}", self.tcx.node_path_str(id));
1305 let cm = self.tcx.sess.source_map();
1306 let filename = cm.span_to_filename(span);
1307 let data_id = id_from_node_id(id, &self.save_ctxt);
1308 let children = m.items
1310 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
1312 let span = self.span_from_span(span);
1314 self.dumper.dump_def(
1322 name: String::new(),
1325 value: filename.to_string(),
1329 docs: self.save_ctxt.docs_for_attrs(attrs),
1331 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1334 self.nest_scope(id, |v| visit::walk_mod(v, m));
1337 fn visit_item(&mut self, item: &'l ast::Item) {
1338 use syntax::ast::ItemKind::*;
1339 self.process_macro_use(item.span);
1341 Use(ref use_tree) => {
1342 let prefix = ast::Path {
1346 self.process_use_tree(use_tree, item.id, item, &prefix);
1349 let name_span = item.ident.span;
1350 if !self.span.filter_generated(name_span) {
1351 let span = self.span_from_span(name_span);
1352 let parent = self.save_ctxt.tcx.hir().opt_local_def_id(item.id)
1353 .and_then(|id| self.save_ctxt.tcx.parent_def_id(id))
1354 .map(id_from_def_id);
1361 kind: ImportKind::ExternCrate,
1365 name: item.ident.to_string(),
1366 value: String::new(),
1372 Fn(ref decl, .., ref ty_params, ref body) => {
1373 self.process_fn(item, &decl, ty_params, &body)
1375 Static(ref typ, _, ref expr) => self.process_static_or_const_item(item, typ, expr),
1376 Const(ref typ, ref expr) => self.process_static_or_const_item(item, &typ, &expr),
1377 Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1378 self.process_struct(item, def, ty_params)
1380 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1381 Impl(.., ref ty_params, ref trait_ref, ref typ, ref impl_items) => {
1382 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1384 Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1385 self.process_trait(item, generics, trait_refs, methods)
1388 self.process_mod(item);
1389 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1391 Ty(ref ty, ref ty_params) => {
1392 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1393 let value = ty_to_string(&ty);
1394 if !self.span.filter_generated(item.ident.span) {
1395 let span = self.span_from_span(item.ident.span);
1396 let id = id_from_node_id(item.id, &self.save_ctxt);
1398 self.dumper.dump_def(
1399 &access_from!(self.save_ctxt, item),
1401 kind: DefKind::Type,
1404 name: item.ident.to_string(),
1405 qualname: qualname.clone(),
1410 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1411 sig: sig::item_signature(item, &self.save_ctxt),
1412 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1418 self.process_generic_params(ty_params, &qualname, item.id);
1420 Existential(ref _bounds, ref ty_params) => {
1421 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1422 // FIXME do something with _bounds
1423 let value = String::new();
1424 if !self.span.filter_generated(item.ident.span) {
1425 let span = self.span_from_span(item.ident.span);
1426 let id = id_from_node_id(item.id, &self.save_ctxt);
1428 self.dumper.dump_def(
1429 &access_from!(self.save_ctxt, item),
1431 kind: DefKind::Type,
1434 name: item.ident.to_string(),
1435 qualname: qualname.clone(),
1440 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1441 sig: sig::item_signature(item, &self.save_ctxt),
1442 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1447 self.process_generic_params(ty_params, &qualname, item.id);
1450 _ => visit::walk_item(self, item),
1454 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1455 for param in &generics.params {
1457 ast::GenericParamKind::Lifetime { .. } => {}
1458 ast::GenericParamKind::Type { ref default, .. } => {
1459 self.process_bounds(¶m.bounds);
1460 if let Some(ref ty) = default {
1464 ast::GenericParamKind::Const { ref ty } => {
1465 self.process_bounds(¶m.bounds);
1470 for pred in &generics.where_clause.predicates {
1471 if let ast::WherePredicate::BoundPredicate(ref wbp) = *pred {
1472 self.process_bounds(&wbp.bounds);
1473 self.visit_ty(&wbp.bounded_ty);
1478 fn visit_ty(&mut self, t: &'l ast::Ty) {
1479 self.process_macro_use(t.span);
1481 ast::TyKind::Path(_, ref path) => {
1482 if generated_code(t.span) {
1486 if let Some(id) = self.lookup_def_id(t.id) {
1487 let sub_span = path.segments.last().unwrap().ident.span;
1488 let span = self.span_from_span(sub_span);
1489 self.dumper.dump_ref(Ref {
1490 kind: RefKind::Type,
1492 ref_id: id_from_def_id(id),
1496 self.write_sub_paths_truncated(path);
1497 visit::walk_path(self, path);
1499 ast::TyKind::Array(ref element, ref length) => {
1500 self.visit_ty(element);
1501 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1503 _ => visit::walk_ty(self, t),
1507 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1508 debug!("visit_expr {:?}", ex.node);
1509 self.process_macro_use(ex.span);
1511 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1512 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(ex.id);
1513 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1514 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1516 visit::walk_expr(self, ex);
1520 let def = self.save_ctxt.get_path_def(hir_expr.id);
1521 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1523 ast::ExprKind::MethodCall(ref seg, ref args) => self.process_method_call(ex, seg, args),
1524 ast::ExprKind::Field(ref sub_ex, _) => {
1525 self.visit_expr(&sub_ex);
1527 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1528 down_cast_data!(field_data, RefData, ex.span);
1529 if !generated_code(ex.span) {
1530 self.dumper.dump_ref(field_data);
1534 ast::ExprKind::Closure(_, _, _, ref decl, ref body, _fn_decl_span) => {
1535 let id = format!("${}", ex.id);
1537 // walk arg and return types
1538 for arg in &decl.inputs {
1539 self.visit_ty(&arg.ty);
1542 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1543 self.visit_ty(&ret_ty);
1547 self.nest_tables(ex.id, |v| {
1548 v.process_formals(&decl.inputs, &id);
1549 v.nest_scope(ex.id, |v| v.visit_expr(body))
1552 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1553 let value = self.span.snippet(subexpression.span);
1554 self.process_var_decl(pattern, value);
1555 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1556 self.visit_expr(subexpression);
1557 visit::walk_block(self, block);
1559 ast::ExprKind::WhileLet(ref pats, ref subexpression, ref block, _) => {
1560 self.process_var_decl_multi(pats);
1561 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1562 self.visit_expr(subexpression);
1563 visit::walk_block(self, block);
1565 ast::ExprKind::IfLet(ref pats, ref subexpression, ref block, ref opt_else) => {
1566 self.process_var_decl_multi(pats);
1567 self.visit_expr(subexpression);
1568 visit::walk_block(self, block);
1569 opt_else.as_ref().map(|el| self.visit_expr(el));
1571 ast::ExprKind::Repeat(ref element, ref count) => {
1572 self.visit_expr(element);
1573 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1575 // In particular, we take this branch for call and path expressions,
1576 // where we'll index the idents involved just by continuing to walk.
1577 _ => visit::walk_expr(self, ex),
1581 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1582 // These shouldn't exist in the AST at this point, log a span bug.
1585 "macro invocation should have been expanded out of AST"
1589 fn visit_pat(&mut self, p: &'l ast::Pat) {
1590 self.process_macro_use(p.span);
1591 self.process_pat(p);
1594 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1595 self.process_var_decl_multi(&arm.pats);
1597 Some(ast::Guard::If(ref expr)) => self.visit_expr(expr),
1600 self.visit_expr(&arm.body);
1603 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1604 self.process_path(id, p);
1607 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1608 self.process_macro_use(s.span);
1609 visit::walk_stmt(self, s)
1612 fn visit_local(&mut self, l: &'l ast::Local) {
1613 self.process_macro_use(l.span);
1616 .map(|i| self.span.snippet(i.span))
1617 .unwrap_or_default();
1618 self.process_var_decl(&l.pat, value);
1620 // Just walk the initialiser and type (don't want to walk the pattern again).
1621 walk_list!(self, visit_ty, &l.ty);
1622 walk_list!(self, visit_expr, &l.init);
1625 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1626 let access = access_from!(self.save_ctxt, item);
1629 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1630 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1631 down_cast_data!(fn_data, DefData, item.span);
1633 self.process_generic_params(generics, &fn_data.qualname, item.id);
1634 self.dumper.dump_def(&access, fn_data);
1637 for arg in &decl.inputs {
1638 self.visit_ty(&arg.ty);
1641 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1642 self.visit_ty(&ret_ty);
1645 ast::ForeignItemKind::Static(ref ty, _) => {
1646 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1647 down_cast_data!(var_data, DefData, item.span);
1648 self.dumper.dump_def(&access, var_data);
1653 ast::ForeignItemKind::Ty => {
1654 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1655 down_cast_data!(var_data, DefData, item.span);
1656 self.dumper.dump_def(&access, var_data);
1659 ast::ForeignItemKind::Macro(..) => {}