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, DefIdTree, TyCtxt};
21 use rustc_data_structures::fx::FxHashSet;
26 use syntax::ast::{self, Attribute, NodeId, PatKind, CRATE_NODE_ID};
27 use syntax::parse::token;
28 use syntax::visit::{self, Visitor};
29 use syntax::print::pprust::{
31 generic_params_to_string,
35 use syntax::source_map::{Spanned, DUMMY_SP, respan};
36 use syntax::walk_list;
39 use crate::{escape, generated_code, id_from_def_id, id_from_node_id, lower_attributes,
40 PathCollector, SaveContext};
41 use crate::json_dumper::{Access, DumpOutput, JsonDumper};
42 use crate::span_utils::SpanUtils;
45 use rls_data::{CompilationOptions, CratePreludeData, Def, DefKind, GlobalCrateId, Import,
46 ImportKind, Ref, RefKind, Relation, RelationKind, SpanData};
48 use log::{debug, error};
50 macro_rules! down_cast_data {
51 ($id:ident, $kind:ident, $sp:expr) => {
52 let $id = if let super::Data::$kind(data) = $id {
55 span_bug!($sp, "unexpected data kind: {:?}", $id);
60 macro_rules! access_from {
61 ($save_ctxt:expr, $item:expr, $id:expr) => {
63 public: $item.vis.node.is_pub(),
64 reachable: $save_ctxt.access_levels.is_reachable($id),
69 macro_rules! access_from_vis {
70 ($save_ctxt:expr, $vis:expr, $id:expr) => {
72 public: $vis.node.is_pub(),
73 reachable: $save_ctxt.access_levels.is_reachable($id),
78 pub struct DumpVisitor<'l, 'tcx: 'l, 'll, O: DumpOutput> {
79 save_ctxt: SaveContext<'l, 'tcx>,
80 tcx: TyCtxt<'l, 'tcx, 'tcx>,
81 dumper: &'ll mut JsonDumper<O>,
87 // Set of macro definition (callee) spans, and the set
88 // of macro use (callsite) spans. We store these to ensure
89 // we only write one macro def per unique macro definition, and
90 // one macro use per unique callsite span.
91 // mac_defs: FxHashSet<Span>,
92 // macro_calls: FxHashSet<Span>,
95 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> {
97 save_ctxt: SaveContext<'l, 'tcx>,
98 dumper: &'ll mut JsonDumper<O>,
99 ) -> DumpVisitor<'l, 'tcx, 'll, O> {
100 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
106 cur_scope: CRATE_NODE_ID,
107 // mac_defs: FxHashSet::default(),
108 // macro_calls: FxHashSet::default(),
112 fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
114 F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
116 let parent_scope = self.cur_scope;
117 self.cur_scope = scope_id;
119 self.cur_scope = parent_scope;
122 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
124 F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
126 let item_def_id = self.tcx.hir().local_def_id(item_id);
127 if self.tcx.has_typeck_tables(item_def_id) {
128 let tables = self.tcx.typeck_tables_of(item_def_id);
129 let old_tables = self.save_ctxt.tables;
130 self.save_ctxt.tables = tables;
132 self.save_ctxt.tables = old_tables;
138 fn span_from_span(&self, span: Span) -> SpanData {
139 self.save_ctxt.span_from_span(span)
142 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
143 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
144 let crate_root = source_file.map(|source_file| {
145 let source_file = Path::new(source_file);
146 match source_file.file_name() {
147 Some(_) => source_file.parent().unwrap().display(),
148 None => source_file.display(),
152 let data = CratePreludeData {
153 crate_id: GlobalCrateId {
155 disambiguator: self.tcx
157 .local_crate_disambiguator()
161 crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
162 external_crates: self.save_ctxt.get_external_crates(),
163 span: self.span_from_span(krate.span),
166 self.dumper.crate_prelude(data);
169 pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
170 // Apply possible `remap-path-prefix` remapping to the input source file
171 // (and don't include remapping args anymore)
172 let (program, arguments) = {
173 let remap_arg_indices = {
174 let mut indices = FxHashSet::default();
175 // Args are guaranteed to be valid UTF-8 (checked early)
176 for (i, e) in env::args().enumerate() {
177 if e.starts_with("--remap-path-prefix=") {
179 } else if e == "--remap-path-prefix" {
181 indices.insert(i + 1);
187 let mut args = env::args()
189 .filter(|(i, _)| !remap_arg_indices.contains(i))
192 Input::File(ref path) if path == Path::new(&arg) => {
193 let mapped = &self.tcx.sess.local_crate_source_file;
204 (args.next().unwrap(), args.collect())
207 let data = CompilationOptions {
208 directory: self.tcx.sess.working_dir.0.clone(),
211 output: self.save_ctxt.compilation_output(crate_name),
214 self.dumper.compilation_opts(data);
217 fn write_sub_paths(&mut self, path: &ast::Path) {
218 for seg in &path.segments {
219 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
220 self.dumper.dump_ref(data);
225 // As write_sub_paths, but does not process the last ident in the path (assuming it
226 // will be processed elsewhere). See note on write_sub_paths about global.
227 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
228 for seg in &path.segments[..path.segments.len() - 1] {
229 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
230 self.dumper.dump_ref(data);
235 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
236 match self.save_ctxt.get_path_def(ref_id) {
237 HirDef::PrimTy(..) | HirDef::SelfTy(..) | HirDef::Err => None,
238 def => Some(def.def_id()),
242 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
244 self.visit_pat(&arg.pat);
245 let mut collector = PathCollector::new();
246 collector.visit_pat(&arg.pat);
248 for (id, ident, ..) in collector.collected_idents {
249 let hir_id = self.tcx.hir().node_to_hir_id(id);
250 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
251 Some(s) => s.to_string(),
254 if !self.span.filter_generated(ident.span) {
255 let id = id_from_node_id(id, &self.save_ctxt);
256 let span = self.span_from_span(ident.span);
258 self.dumper.dump_def(
264 kind: DefKind::Local,
267 name: ident.to_string(),
268 qualname: format!("{}::{}", qualname, ident.to_string()),
285 sig: &'l ast::MethodSig,
286 body: Option<&'l ast::Block>,
289 generics: &'l ast::Generics,
290 vis: ast::Visibility,
293 debug!("process_method: {}:{}", id, ident);
295 if let Some(mut method_data) = self.save_ctxt.get_method_data(id, ident, span) {
296 let sig_str = crate::make_signature(&sig.decl, &generics);
300 |v| v.process_formals(&sig.decl.inputs, &method_data.qualname),
304 self.process_generic_params(&generics, &method_data.qualname, id);
306 method_data.value = sig_str;
307 method_data.sig = sig::method_signature(id, ident, generics, sig, &self.save_ctxt);
308 let hir_id = self.tcx.hir().node_to_hir_id(id);
309 self.dumper.dump_def(&access_from_vis!(self.save_ctxt, vis, hir_id), method_data);
312 // walk arg and return types
313 for arg in &sig.decl.inputs {
314 self.visit_ty(&arg.ty);
317 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
318 self.visit_ty(ret_ty);
322 if let Some(body) = body {
323 self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
327 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
328 let field_data = self.save_ctxt.get_field_data(field, parent_id);
329 if let Some(field_data) = field_data {
330 let hir_id = self.tcx.hir().node_to_hir_id(field.id);
331 self.dumper.dump_def(&access_from!(self.save_ctxt, field, hir_id), field_data);
335 // Dump generic params bindings, then visit_generics
336 fn process_generic_params(
338 generics: &'l ast::Generics,
342 for param in &generics.params {
344 ast::GenericParamKind::Lifetime { .. } => {}
345 ast::GenericParamKind::Type { .. } => {
346 let param_ss = param.ident.span;
347 let name = escape(self.span.snippet(param_ss));
348 // Append $id to name to make sure each one is unique.
349 let qualname = format!("{}::{}${}", prefix, name, id);
350 if !self.span.filter_generated(param_ss) {
351 let id = id_from_node_id(param.id, &self.save_ctxt);
352 let span = self.span_from_span(param_ss);
354 self.dumper.dump_def(
365 value: String::new(),
376 ast::GenericParamKind::Const { .. } => {}
379 self.visit_generics(generics);
385 decl: &'l ast::FnDecl,
386 ty_params: &'l ast::Generics,
387 body: &'l ast::Block,
389 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
390 down_cast_data!(fn_data, DefData, item.span);
393 |v| v.process_formals(&decl.inputs, &fn_data.qualname),
395 self.process_generic_params(ty_params, &fn_data.qualname, item.id);
396 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
397 self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), fn_data);
400 for arg in &decl.inputs {
401 self.visit_ty(&arg.ty);
404 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
405 self.visit_ty(&ret_ty);
408 self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
411 fn process_static_or_const_item(
417 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
418 self.nest_tables(item.id, |v| {
419 if let Some(var_data) = v.save_ctxt.get_item_data(item) {
420 down_cast_data!(var_data, DefData, item.span);
421 v.dumper.dump_def(&access_from!(v.save_ctxt, item, hir_id), var_data);
428 fn process_assoc_const(
433 expr: Option<&'l ast::Expr>,
435 vis: ast::Visibility,
436 attrs: &'l [Attribute],
438 let qualname = format!("::{}",
439 self.tcx.def_path_str(self.tcx.hir().local_def_id(id)));
441 if !self.span.filter_generated(ident.span) {
442 let sig = sig::assoc_const_signature(id, ident.name, typ, expr, &self.save_ctxt);
443 let span = self.span_from_span(ident.span);
444 let hir_id = self.tcx.hir().node_to_hir_id(id);
446 self.dumper.dump_def(
447 &access_from_vis!(self.save_ctxt, vis, hir_id),
449 kind: DefKind::Const,
450 id: id_from_node_id(id, &self.save_ctxt),
452 name: ident.name.to_string(),
454 value: ty_to_string(&typ),
455 parent: Some(id_from_def_id(parent_id)),
458 docs: self.save_ctxt.docs_for_attrs(attrs),
460 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
465 // walk type and init value
467 if let Some(expr) = expr {
468 self.visit_expr(expr);
472 // FIXME tuple structs should generate tuple-specific data.
476 def: &'l ast::VariantData,
477 ty_params: &'l ast::Generics,
479 debug!("process_struct {:?} {:?}", item, item.span);
480 let name = item.ident.to_string();
481 let qualname = format!("::{}",
482 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
484 let kind = match item.node {
485 ast::ItemKind::Struct(_, _) => DefKind::Struct,
486 ast::ItemKind::Union(_, _) => DefKind::Union,
490 let (value, fields) = match item.node {
491 ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, ..), _) |
492 ast::ItemKind::Union(ast::VariantData::Struct(ref fields, ..), _) => {
493 let include_priv_fields = !self.save_ctxt.config.pub_only;
494 let fields_str = fields
497 .filter_map(|(i, f)| {
498 if include_priv_fields || f.vis.node.is_pub() {
500 .map(|i| i.to_string())
501 .or_else(|| Some(i.to_string()))
508 let value = format!("{} {{ {} }}", name, fields_str);
513 .map(|f| id_from_node_id(f.id, &self.save_ctxt))
517 _ => (String::new(), vec![]),
520 if !self.span.filter_generated(item.ident.span) {
521 let span = self.span_from_span(item.ident.span);
522 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
523 self.dumper.dump_def(
524 &access_from!(self.save_ctxt, item, hir_id),
527 id: id_from_node_id(item.id, &self.save_ctxt),
530 qualname: qualname.clone(),
535 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
536 sig: sig::item_signature(item, &self.save_ctxt),
537 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
542 for field in def.fields() {
543 self.process_struct_field_def(field, item.id);
544 self.visit_ty(&field.ty);
547 self.process_generic_params(ty_params, &qualname, item.id);
553 enum_definition: &'l ast::EnumDef,
554 ty_params: &'l ast::Generics,
556 let enum_data = self.save_ctxt.get_item_data(item);
557 let enum_data = match enum_data {
561 down_cast_data!(enum_data, DefData, item.span);
563 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
564 let access = access_from!(self.save_ctxt, item, hir_id);
566 for variant in &enum_definition.variants {
567 let name = variant.node.ident.name.to_string();
568 let qualname = format!("{}::{}", enum_data.qualname, name);
569 let name_span = variant.node.ident.span;
571 match variant.node.data {
572 ast::VariantData::Struct(ref fields, ..) => {
573 let fields_str = fields
577 f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
581 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
582 if !self.span.filter_generated(name_span) {
583 let span = self.span_from_span(name_span);
584 let id = id_from_node_id(variant.node.data.id(), &self.save_ctxt);
585 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
587 self.dumper.dump_def(
590 kind: DefKind::StructVariant,
599 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
600 sig: sig::variant_signature(variant, &self.save_ctxt),
601 attributes: lower_attributes(
602 variant.node.attrs.clone(),
610 let mut value = format!("{}::{}", enum_data.name, name);
611 if let &ast::VariantData::Tuple(ref fields, _) = v {
613 value.push_str(&fields
615 .map(|f| ty_to_string(&f.ty))
620 if !self.span.filter_generated(name_span) {
621 let span = self.span_from_span(name_span);
622 let id = id_from_node_id(variant.node.data.id(), &self.save_ctxt);
623 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
625 self.dumper.dump_def(
628 kind: DefKind::TupleVariant,
637 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
638 sig: sig::variant_signature(variant, &self.save_ctxt),
639 attributes: lower_attributes(
640 variant.node.attrs.clone(),
650 for field in variant.node.data.fields() {
651 self.process_struct_field_def(field, variant.node.data.id());
652 self.visit_ty(&field.ty);
655 self.process_generic_params(ty_params, &enum_data.qualname, item.id);
656 self.dumper.dump_def(&access, enum_data);
662 type_parameters: &'l ast::Generics,
663 trait_ref: &'l Option<ast::TraitRef>,
665 impl_items: &'l [ast::ImplItem],
667 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
668 if !self.span.filter_generated(item.span) {
669 if let super::Data::RelationData(rel, imp) = impl_data {
670 self.dumper.dump_relation(rel);
671 self.dumper.dump_impl(imp);
673 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
678 if let &Some(ref trait_ref) = trait_ref {
679 self.process_path(trait_ref.ref_id, &trait_ref.path);
681 self.process_generic_params(type_parameters, "", item.id);
682 for impl_item in impl_items {
683 let map = &self.tcx.hir();
684 self.process_impl_item(impl_item, map.local_def_id(item.id));
691 generics: &'l ast::Generics,
692 trait_refs: &'l ast::GenericBounds,
693 methods: &'l [ast::TraitItem],
695 let name = item.ident.to_string();
696 let qualname = format!("::{}",
697 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
698 let mut val = name.clone();
699 if !generics.params.is_empty() {
700 val.push_str(&generic_params_to_string(&generics.params));
702 if !trait_refs.is_empty() {
704 val.push_str(&bounds_to_string(trait_refs));
706 if !self.span.filter_generated(item.ident.span) {
707 let id = id_from_node_id(item.id, &self.save_ctxt);
708 let span = self.span_from_span(item.ident.span);
709 let children = methods
711 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
713 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
714 self.dumper.dump_def(
715 &access_from!(self.save_ctxt, item, hir_id),
717 kind: DefKind::Trait,
721 qualname: qualname.clone(),
726 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
727 sig: sig::item_signature(item, &self.save_ctxt),
728 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
734 for super_bound in trait_refs.iter() {
735 let trait_ref = match *super_bound {
736 ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
737 ast::GenericBound::Outlives(..) => continue,
740 let trait_ref = &trait_ref.trait_ref;
741 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
742 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
743 if !self.span.filter_generated(sub_span) {
744 let span = self.span_from_span(sub_span);
745 self.dumper.dump_ref(Ref {
748 ref_id: id_from_def_id(id),
751 self.dumper.dump_relation(Relation {
752 kind: RelationKind::SuperTrait,
754 from: id_from_def_id(id),
755 to: id_from_node_id(item.id, &self.save_ctxt),
761 // walk generics and methods
762 self.process_generic_params(generics, &qualname, item.id);
763 for method in methods {
764 let map = &self.tcx.hir();
765 self.process_trait_item(method, map.local_def_id(item.id))
769 // `item` is the module in question, represented as an item.
770 fn process_mod(&mut self, item: &ast::Item) {
771 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
772 down_cast_data!(mod_data, DefData, item.span);
773 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
774 self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), mod_data);
778 fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
779 let path_data = self.save_ctxt.get_path_data(id, path);
780 if let Some(path_data) = path_data {
781 self.dumper.dump_ref(path_data);
785 fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
786 if self.span.filter_generated(path.span) {
789 self.dump_path_ref(id, path);
792 for seg in &path.segments {
793 if let Some(ref generic_args) = seg.args {
794 match **generic_args {
795 ast::GenericArgs::AngleBracketed(ref data) => {
796 for arg in &data.args {
798 ast::GenericArg::Type(ty) => self.visit_ty(ty),
803 ast::GenericArgs::Parenthesized(ref data) => {
804 for t in &data.inputs {
807 if let Some(ref t) = data.output {
815 self.write_sub_paths_truncated(path);
818 fn process_struct_lit(
822 fields: &'l [ast::Field],
823 variant: &'l ty::VariantDef,
824 base: &'l Option<P<ast::Expr>>,
826 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
827 self.write_sub_paths_truncated(path);
828 down_cast_data!(struct_lit_data, RefData, ex.span);
829 if !generated_code(ex.span) {
830 self.dumper.dump_ref(struct_lit_data);
833 for field in fields {
834 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
835 self.dumper.dump_ref(field_data);
838 self.visit_expr(&field.expr)
842 walk_list!(self, visit_expr, base);
845 fn process_method_call(
848 seg: &'l ast::PathSegment,
849 args: &'l [P<ast::Expr>],
851 debug!("process_method_call {:?} {:?}", ex, ex.span);
852 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
853 down_cast_data!(mcd, RefData, ex.span);
854 if !generated_code(ex.span) {
855 self.dumper.dump_ref(mcd);
859 // Explicit types in the turbo-fish.
860 if let Some(ref generic_args) = seg.args {
861 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
862 for arg in &data.args {
864 ast::GenericArg::Type(ty) => self.visit_ty(ty),
871 // walk receiver and args
872 walk_list!(self, visit_expr, args);
875 fn process_pat(&mut self, p: &'l ast::Pat) {
877 PatKind::Struct(ref _path, ref fields, _) => {
878 // FIXME do something with _path?
879 let hir_id = self.tcx.hir().node_to_hir_id(p.id);
880 let adt = match self.save_ctxt.tables.node_type_opt(hir_id) {
881 Some(ty) => ty.ty_adt_def().unwrap(),
883 visit::walk_pat(self, p);
887 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
889 for &Spanned { node: ref field, .. } in fields {
890 if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
891 if !self.span.filter_generated(field.ident.span) {
892 let span = self.span_from_span(field.ident.span);
893 self.dumper.dump_ref(Ref {
894 kind: RefKind::Variable,
896 ref_id: id_from_def_id(variant.fields[index].did),
900 self.visit_pat(&field.pat);
903 _ => visit::walk_pat(self, p),
907 fn process_var_decl_multi(&mut self, pats: &'l [P<ast::Pat>]) {
908 let mut collector = PathCollector::new();
909 for pattern in pats {
910 // collect paths from the arm's patterns
911 collector.visit_pat(&pattern);
912 self.visit_pat(&pattern);
915 // process collected paths
916 for (id, ident, immut) in collector.collected_idents {
917 match self.save_ctxt.get_path_def(id) {
918 HirDef::Local(id) => {
919 let mut value = if immut == ast::Mutability::Immutable {
920 self.span.snippet(ident.span)
922 "<mutable>".to_owned()
924 let hir_id = self.tcx.hir().node_to_hir_id(id);
925 let typ = self.save_ctxt
927 .node_type_opt(hir_id)
928 .map(|t| t.to_string())
929 .unwrap_or_default();
930 value.push_str(": ");
931 value.push_str(&typ);
933 if !self.span.filter_generated(ident.span) {
934 let qualname = format!("{}${}", ident.to_string(), id);
935 let id = id_from_node_id(id, &self.save_ctxt);
936 let span = self.span_from_span(ident.span);
938 self.dumper.dump_def(
944 kind: DefKind::Local,
947 name: ident.to_string(),
960 HirDef::StructCtor(..) |
961 HirDef::VariantCtor(..) |
963 HirDef::AssociatedConst(..) |
965 HirDef::Variant(..) |
966 HirDef::TyAlias(..) |
967 HirDef::AssociatedTy(..) |
968 HirDef::SelfTy(..) => {
969 self.dump_path_ref(id, &ast::Path::from_ident(ident));
972 "unexpected definition kind when processing collected idents: {:?}",
978 for (id, ref path) in collector.collected_paths {
979 self.process_path(id, path);
983 fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
984 // The local could declare multiple new vars, we must walk the
985 // pattern and collect them all.
986 let mut collector = PathCollector::new();
987 collector.visit_pat(&p);
990 for (id, ident, immut) in collector.collected_idents {
991 let mut value = match immut {
992 ast::Mutability::Immutable => value.to_string(),
995 let hir_id = self.tcx.hir().node_to_hir_id(id);
996 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
998 let typ = typ.to_string();
999 if !value.is_empty() {
1000 value.push_str(": ");
1002 value.push_str(&typ);
1005 None => String::new(),
1008 // Rust uses the id of the pattern for var lookups, so we'll use it too.
1009 if !self.span.filter_generated(ident.span) {
1010 let qualname = format!("{}${}", ident.to_string(), id);
1011 let id = id_from_node_id(id, &self.save_ctxt);
1012 let span = self.span_from_span(ident.span);
1014 self.dumper.dump_def(
1020 kind: DefKind::Local,
1023 name: ident.to_string(),
1029 docs: String::new(),
1038 /// Extracts macro use and definition information from the AST node defined
1039 /// by the given NodeId, using the expansion information from the node's
1042 /// If the span is not macro-generated, do nothing, else use callee and
1043 /// callsite spans to record macro definition and use data, using the
1044 /// mac_uses and mac_defs sets to prevent multiples.
1045 fn process_macro_use(&mut self, _span: Span) {
1046 // FIXME if we're not dumping the defs (see below), there is no point
1047 // dumping refs either.
1048 // let source_span = span.source_callsite();
1049 // if !self.macro_calls.insert(source_span) {
1053 // let data = match self.save_ctxt.get_macro_use_data(span) {
1055 // Some(data) => data,
1058 // self.dumper.macro_use(data);
1060 // FIXME write the macro def
1061 // let mut hasher = DefaultHasher::new();
1062 // data.callee_span.hash(&mut hasher);
1063 // let hash = hasher.finish();
1064 // let qualname = format!("{}::{}", data.name, hash);
1065 // Don't write macro definition for imported macros
1066 // if !self.mac_defs.contains(&data.callee_span)
1067 // && !data.imported {
1068 // self.mac_defs.insert(data.callee_span);
1069 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1070 // self.dumper.macro_data(MacroData {
1072 // name: data.name.clone(),
1073 // qualname: qualname.clone(),
1074 // // FIXME where do macro docs come from?
1075 // docs: String::new(),
1076 // }.lower(self.tcx));
1081 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1082 self.process_macro_use(trait_item.span);
1083 let vis_span = trait_item.span.shrink_to_lo();
1084 match trait_item.node {
1085 ast::TraitItemKind::Const(ref ty, ref expr) => {
1086 self.process_assoc_const(
1090 expr.as_ref().map(|e| &**e),
1092 respan(vis_span, ast::VisibilityKind::Public),
1096 ast::TraitItemKind::Method(ref sig, ref body) => {
1097 self.process_method(
1099 body.as_ref().map(|x| &**x),
1102 &trait_item.generics,
1103 respan(vis_span, ast::VisibilityKind::Public),
1107 ast::TraitItemKind::Type(ref bounds, ref default_ty) => {
1108 // FIXME do something with _bounds (for type refs)
1109 let name = trait_item.ident.name.to_string();
1110 let qualname = format!("::{}",
1111 self.tcx.def_path_str(self.tcx.hir().local_def_id(trait_item.id)));
1113 if !self.span.filter_generated(trait_item.ident.span) {
1114 let span = self.span_from_span(trait_item.ident.span);
1115 let id = id_from_node_id(trait_item.id, &self.save_ctxt);
1117 self.dumper.dump_def(
1123 kind: DefKind::Type,
1128 value: self.span.snippet(trait_item.span),
1129 parent: Some(id_from_def_id(trait_id)),
1132 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1133 sig: sig::assoc_type_signature(
1137 default_ty.as_ref().map(|ty| &**ty),
1140 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1145 if let &Some(ref default_ty) = default_ty {
1146 self.visit_ty(default_ty)
1149 ast::TraitItemKind::Macro(_) => {}
1153 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1154 self.process_macro_use(impl_item.span);
1155 match impl_item.node {
1156 ast::ImplItemKind::Const(ref ty, ref expr) => {
1157 self.process_assoc_const(
1163 impl_item.vis.clone(),
1167 ast::ImplItemKind::Method(ref sig, ref body) => {
1168 self.process_method(
1173 &impl_item.generics,
1174 impl_item.vis.clone(),
1178 ast::ImplItemKind::Type(ref ty) => {
1179 // FIXME uses of the assoc type should ideally point to this
1180 // 'def' and the name here should be a ref to the def in the
1184 ast::ImplItemKind::Existential(ref bounds) => {
1185 // FIXME uses of the assoc type should ideally point to this
1186 // 'def' and the name here should be a ref to the def in the
1188 for bound in bounds.iter() {
1189 if let ast::GenericBound::Trait(trait_ref, _) = bound {
1190 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1194 ast::ImplItemKind::Macro(_) => {}
1198 /// Dumps imports in a use tree recursively.
1200 /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1201 /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1202 /// ID and path. `root_item` is the topmost use tree in the hierarchy.
1204 /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1205 /// each child use tree is dumped recursively.
1206 fn process_use_tree(&mut self,
1207 use_tree: &'l ast::UseTree,
1209 root_item: &'l ast::Item,
1210 prefix: &ast::Path) {
1211 let path = &use_tree.prefix;
1213 // The access is calculated using the current tree ID, but with the root tree's visibility
1214 // (since nested trees don't have their own visibility).
1215 let hir_id = self.tcx.hir().node_to_hir_id(id);
1216 let access = access_from!(self.save_ctxt, root_item, hir_id);
1218 // The parent def id of a given use tree is always the enclosing item.
1219 let parent = self.save_ctxt.tcx.hir().opt_local_def_id(id)
1220 .and_then(|id| self.save_ctxt.tcx.parent(id))
1221 .map(id_from_def_id);
1223 match use_tree.kind {
1224 ast::UseTreeKind::Simple(alias, ..) => {
1225 let ident = use_tree.ident();
1226 let path = ast::Path {
1227 segments: prefix.segments
1229 .chain(path.segments.iter())
1235 let sub_span = path.segments.last().unwrap().ident.span;
1236 if !self.span.filter_generated(sub_span) {
1237 let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id));
1238 let alias_span = alias.map(|i| self.span_from_span(i.span));
1239 let span = self.span_from_span(sub_span);
1240 self.dumper.import(&access, Import {
1241 kind: ImportKind::Use,
1245 name: ident.to_string(),
1246 value: String::new(),
1249 self.write_sub_paths_truncated(&path);
1252 ast::UseTreeKind::Glob => {
1253 let path = ast::Path {
1254 segments: prefix.segments
1256 .chain(path.segments.iter())
1262 // Make a comma-separated list of names of imported modules.
1263 let def_id = self.tcx.hir().local_def_id(id);
1264 let names = self.tcx.names_imported_by_glob_use(def_id);
1265 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1267 // Otherwise it's a span with wrong macro expansion info, which
1268 // we don't want to track anyway, since it's probably macro-internal `use`
1269 if let Some(sub_span) =
1270 self.span.sub_span_of_token(use_tree.span, token::BinOp(token::Star))
1272 if !self.span.filter_generated(use_tree.span) {
1273 let span = self.span_from_span(sub_span);
1275 self.dumper.import(&access, Import {
1276 kind: ImportKind::GlobUse,
1280 name: "*".to_owned(),
1281 value: names.join(", "),
1284 self.write_sub_paths(&path);
1288 ast::UseTreeKind::Nested(ref nested_items) => {
1289 let prefix = ast::Path {
1290 segments: prefix.segments
1292 .chain(path.segments.iter())
1297 for &(ref tree, id) in nested_items {
1298 self.process_use_tree(tree, id, root_item, &prefix);
1304 fn process_bounds(&mut self, bounds: &'l ast::GenericBounds) {
1305 for bound in bounds {
1306 if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1307 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1313 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, O> {
1314 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1315 // Since we handle explicit modules ourselves in visit_item, this should
1316 // only get called for the root module of a crate.
1317 assert_eq!(id, ast::CRATE_NODE_ID);
1319 let qualname = format!("::{}",
1320 self.tcx.def_path_str(self.tcx.hir().local_def_id(id)));
1322 let cm = self.tcx.sess.source_map();
1323 let filename = cm.span_to_filename(span);
1324 let data_id = id_from_node_id(id, &self.save_ctxt);
1325 let children = m.items
1327 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
1329 let span = self.span_from_span(span);
1331 self.dumper.dump_def(
1339 name: String::new(),
1342 value: filename.to_string(),
1346 docs: self.save_ctxt.docs_for_attrs(attrs),
1348 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1351 self.nest_scope(id, |v| visit::walk_mod(v, m));
1354 fn visit_item(&mut self, item: &'l ast::Item) {
1355 use syntax::ast::ItemKind::*;
1356 self.process_macro_use(item.span);
1358 Use(ref use_tree) => {
1359 let prefix = ast::Path {
1363 self.process_use_tree(use_tree, item.id, item, &prefix);
1366 let name_span = item.ident.span;
1367 if !self.span.filter_generated(name_span) {
1368 let span = self.span_from_span(name_span);
1369 let parent = self.save_ctxt.tcx.hir().opt_local_def_id(item.id)
1370 .and_then(|id| self.save_ctxt.tcx.parent(id))
1371 .map(id_from_def_id);
1378 kind: ImportKind::ExternCrate,
1382 name: item.ident.to_string(),
1383 value: String::new(),
1389 Fn(ref decl, .., ref ty_params, ref body) => {
1390 self.process_fn(item, &decl, ty_params, &body)
1392 Static(ref typ, _, ref expr) => self.process_static_or_const_item(item, typ, expr),
1393 Const(ref typ, ref expr) => self.process_static_or_const_item(item, &typ, &expr),
1394 Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1395 self.process_struct(item, def, ty_params)
1397 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1398 Impl(.., ref ty_params, ref trait_ref, ref typ, ref impl_items) => {
1399 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1401 Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1402 self.process_trait(item, generics, trait_refs, methods)
1405 self.process_mod(item);
1406 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1408 Ty(ref ty, ref ty_params) => {
1409 let qualname = format!("::{}",
1410 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
1411 let value = ty_to_string(&ty);
1412 if !self.span.filter_generated(item.ident.span) {
1413 let span = self.span_from_span(item.ident.span);
1414 let id = id_from_node_id(item.id, &self.save_ctxt);
1415 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1417 self.dumper.dump_def(
1418 &access_from!(self.save_ctxt, item, hir_id),
1420 kind: DefKind::Type,
1423 name: item.ident.to_string(),
1424 qualname: qualname.clone(),
1429 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1430 sig: sig::item_signature(item, &self.save_ctxt),
1431 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1437 self.process_generic_params(ty_params, &qualname, item.id);
1439 Existential(ref _bounds, ref ty_params) => {
1440 let qualname = format!("::{}",
1441 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
1442 // FIXME do something with _bounds
1443 let value = String::new();
1444 if !self.span.filter_generated(item.ident.span) {
1445 let span = self.span_from_span(item.ident.span);
1446 let id = id_from_node_id(item.id, &self.save_ctxt);
1447 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1449 self.dumper.dump_def(
1450 &access_from!(self.save_ctxt, item, hir_id),
1452 kind: DefKind::Type,
1455 name: item.ident.to_string(),
1456 qualname: qualname.clone(),
1461 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1462 sig: sig::item_signature(item, &self.save_ctxt),
1463 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1468 self.process_generic_params(ty_params, &qualname, item.id);
1471 _ => visit::walk_item(self, item),
1475 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1476 for param in &generics.params {
1478 ast::GenericParamKind::Lifetime { .. } => {}
1479 ast::GenericParamKind::Type { ref default, .. } => {
1480 self.process_bounds(¶m.bounds);
1481 if let Some(ref ty) = default {
1485 ast::GenericParamKind::Const { ref ty } => {
1486 self.process_bounds(¶m.bounds);
1491 for pred in &generics.where_clause.predicates {
1492 if let ast::WherePredicate::BoundPredicate(ref wbp) = *pred {
1493 self.process_bounds(&wbp.bounds);
1494 self.visit_ty(&wbp.bounded_ty);
1499 fn visit_ty(&mut self, t: &'l ast::Ty) {
1500 self.process_macro_use(t.span);
1502 ast::TyKind::Path(_, ref path) => {
1503 if generated_code(t.span) {
1507 if let Some(id) = self.lookup_def_id(t.id) {
1508 let sub_span = path.segments.last().unwrap().ident.span;
1509 let span = self.span_from_span(sub_span);
1510 self.dumper.dump_ref(Ref {
1511 kind: RefKind::Type,
1513 ref_id: id_from_def_id(id),
1517 self.write_sub_paths_truncated(path);
1518 visit::walk_path(self, path);
1520 ast::TyKind::Array(ref element, ref length) => {
1521 self.visit_ty(element);
1522 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1524 _ => visit::walk_ty(self, t),
1528 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1529 debug!("visit_expr {:?}", ex.node);
1530 self.process_macro_use(ex.span);
1532 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1533 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(ex.id);
1534 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1535 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1537 visit::walk_expr(self, ex);
1541 let node_id = self.save_ctxt.tcx.hir().hir_to_node_id(hir_expr.hir_id);
1542 let def = self.save_ctxt.get_path_def(node_id);
1543 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1545 ast::ExprKind::MethodCall(ref seg, ref args) => self.process_method_call(ex, seg, args),
1546 ast::ExprKind::Field(ref sub_ex, _) => {
1547 self.visit_expr(&sub_ex);
1549 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1550 down_cast_data!(field_data, RefData, ex.span);
1551 if !generated_code(ex.span) {
1552 self.dumper.dump_ref(field_data);
1556 ast::ExprKind::Closure(_, _, _, ref decl, ref body, _fn_decl_span) => {
1557 let id = format!("${}", ex.id);
1559 // walk arg and return types
1560 for arg in &decl.inputs {
1561 self.visit_ty(&arg.ty);
1564 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1565 self.visit_ty(&ret_ty);
1569 self.nest_tables(ex.id, |v| {
1570 v.process_formals(&decl.inputs, &id);
1571 v.nest_scope(ex.id, |v| v.visit_expr(body))
1574 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1575 let value = self.span.snippet(subexpression.span);
1576 self.process_var_decl(pattern, value);
1577 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1578 self.visit_expr(subexpression);
1579 visit::walk_block(self, block);
1581 ast::ExprKind::WhileLet(ref pats, ref subexpression, ref block, _) => {
1582 self.process_var_decl_multi(pats);
1583 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1584 self.visit_expr(subexpression);
1585 visit::walk_block(self, block);
1587 ast::ExprKind::IfLet(ref pats, ref subexpression, ref block, ref opt_else) => {
1588 self.process_var_decl_multi(pats);
1589 self.visit_expr(subexpression);
1590 visit::walk_block(self, block);
1591 opt_else.as_ref().map(|el| self.visit_expr(el));
1593 ast::ExprKind::Repeat(ref element, ref count) => {
1594 self.visit_expr(element);
1595 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1597 // In particular, we take this branch for call and path expressions,
1598 // where we'll index the idents involved just by continuing to walk.
1599 _ => visit::walk_expr(self, ex),
1603 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1604 // These shouldn't exist in the AST at this point, log a span bug.
1607 "macro invocation should have been expanded out of AST"
1611 fn visit_pat(&mut self, p: &'l ast::Pat) {
1612 self.process_macro_use(p.span);
1613 self.process_pat(p);
1616 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1617 self.process_var_decl_multi(&arm.pats);
1619 Some(ast::Guard::If(ref expr)) => self.visit_expr(expr),
1622 self.visit_expr(&arm.body);
1625 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1626 self.process_path(id, p);
1629 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1630 self.process_macro_use(s.span);
1631 visit::walk_stmt(self, s)
1634 fn visit_local(&mut self, l: &'l ast::Local) {
1635 self.process_macro_use(l.span);
1638 .map(|i| self.span.snippet(i.span))
1639 .unwrap_or_default();
1640 self.process_var_decl(&l.pat, value);
1642 // Just walk the initialiser and type (don't want to walk the pattern again).
1643 walk_list!(self, visit_ty, &l.ty);
1644 walk_list!(self, visit_expr, &l.init);
1647 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1648 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1649 let access = access_from!(self.save_ctxt, item, hir_id);
1652 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1653 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1654 down_cast_data!(fn_data, DefData, item.span);
1656 self.process_generic_params(generics, &fn_data.qualname, item.id);
1657 self.dumper.dump_def(&access, fn_data);
1660 for arg in &decl.inputs {
1661 self.visit_ty(&arg.ty);
1664 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1665 self.visit_ty(&ret_ty);
1668 ast::ForeignItemKind::Static(ref ty, _) => {
1669 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1670 down_cast_data!(var_data, DefData, item.span);
1671 self.dumper.dump_def(&access, var_data);
1676 ast::ForeignItemKind::Ty => {
1677 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1678 down_cast_data!(var_data, DefData, item.span);
1679 self.dumper.dump_def(&access, var_data);
1682 ast::ForeignItemKind::Macro(..) => {}