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 Def IDs to identify objects. The
5 //! tricky part is getting syntactic (span, source text) and semantic (reference
6 //! Def IDs) 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;
19 use rustc::ty::{self, TyCtxt};
20 use rustc_data_structures::fx::FxHashSet;
25 use syntax::ast::{self, Attribute, NodeId, PatKind, CRATE_NODE_ID};
26 use syntax::parse::token;
27 use syntax::visit::{self, Visitor};
28 use syntax::print::pprust::{
30 generic_params_to_string,
34 use syntax::source_map::{Spanned, DUMMY_SP, respan};
37 use {escape, generated_code, lower_attributes, PathCollector, SaveContext};
38 use json_dumper::{Access, DumpOutput, JsonDumper};
39 use span_utils::SpanUtils;
42 use rls_data::{CompilationOptions, CratePreludeData, Def, DefKind, GlobalCrateId, Import,
43 ImportKind, Ref, RefKind, Relation, RelationKind, SpanData};
45 macro_rules! down_cast_data {
46 ($id:ident, $kind:ident, $sp:expr) => {
47 let $id = if let super::Data::$kind(data) = $id {
50 span_bug!($sp, "unexpected data kind: {:?}", $id);
55 macro_rules! access_from {
56 ($save_ctxt:expr, $vis:expr, $id:expr) => {
58 public: $vis.node.is_pub(),
59 reachable: $save_ctxt.access_levels.is_reachable($id),
63 ($save_ctxt:expr, $item:expr) => {
65 public: $item.vis.node.is_pub(),
66 reachable: $save_ctxt.access_levels.is_reachable($item.id),
71 pub struct DumpVisitor<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> {
72 save_ctxt: SaveContext<'l, 'tcx>,
73 tcx: TyCtxt<'l, 'tcx, 'tcx>,
74 dumper: &'ll mut JsonDumper<O>,
80 // Set of macro definition (callee) spans, and the set
81 // of macro use (callsite) spans. We store these to ensure
82 // we only write one macro def per unique macro definition, and
83 // one macro use per unique callsite span.
84 // mac_defs: FxHashSet<Span>,
85 // macro_calls: FxHashSet<Span>,
88 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> {
90 save_ctxt: SaveContext<'l, 'tcx>,
91 dumper: &'ll mut JsonDumper<O>,
92 ) -> DumpVisitor<'l, 'tcx, 'll, O> {
93 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
99 cur_scope: CRATE_NODE_ID,
100 // mac_defs: FxHashSet::default(),
101 // macro_calls: FxHashSet::default(),
105 fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
107 F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
109 let parent_scope = self.cur_scope;
110 self.cur_scope = scope_id;
112 self.cur_scope = parent_scope;
115 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
117 F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
119 let item_def_id = self.tcx.hir().local_def_id(item_id);
120 if self.tcx.has_typeck_tables(item_def_id) {
121 let tables = self.tcx.typeck_tables_of(item_def_id);
122 let old_tables = self.save_ctxt.tables;
123 self.save_ctxt.tables = tables;
125 self.save_ctxt.tables = old_tables;
131 fn span_from_span(&self, span: Span) -> SpanData {
132 self.save_ctxt.span_from_span(span)
135 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
136 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
137 let crate_root = source_file.map(|source_file| {
138 let source_file = Path::new(source_file);
139 match source_file.file_name() {
140 Some(_) => source_file.parent().unwrap().display(),
141 None => source_file.display(),
145 let data = CratePreludeData {
146 crate_id: GlobalCrateId {
148 disambiguator: self.tcx
150 .local_crate_disambiguator()
154 crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
155 external_crates: self.save_ctxt.get_external_crates(),
156 span: self.span_from_span(krate.span),
159 self.dumper.crate_prelude(data);
162 pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
163 // Apply possible `remap-path-prefix` remapping to the input source file
164 // (and don't include remapping args anymore)
165 let (program, arguments) = {
166 let remap_arg_indices = {
167 let mut indices = FxHashSet::default();
168 // Args are guaranteed to be valid UTF-8 (checked early)
169 for (i, e) in env::args().enumerate() {
170 if e.starts_with("--remap-path-prefix=") {
172 } else if e == "--remap-path-prefix" {
174 indices.insert(i + 1);
180 let mut args = env::args()
182 .filter(|(i, _)| !remap_arg_indices.contains(i))
185 Input::File(ref path) if path == Path::new(&arg) => {
186 let mapped = &self.tcx.sess.local_crate_source_file;
197 (args.next().unwrap(), args.collect())
200 let data = CompilationOptions {
201 directory: self.tcx.sess.working_dir.0.clone(),
204 output: self.save_ctxt.compilation_output(crate_name),
207 self.dumper.compilation_opts(data);
210 fn write_sub_paths(&mut self, path: &ast::Path) {
211 for seg in &path.segments {
212 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
213 self.dumper.dump_ref(data);
218 // As write_sub_paths, but does not process the last ident in the path (assuming it
219 // will be processed elsewhere). See note on write_sub_paths about global.
220 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
221 for seg in &path.segments[..path.segments.len() - 1] {
222 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
223 self.dumper.dump_ref(data);
228 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
229 match self.save_ctxt.get_path_def(ref_id) {
230 HirDef::PrimTy(..) | HirDef::SelfTy(..) | HirDef::Err => None,
231 def => Some(def.def_id()),
235 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
237 self.visit_pat(&arg.pat);
238 let mut collector = PathCollector::new();
239 collector.visit_pat(&arg.pat);
241 for (id, ident, ..) in collector.collected_idents {
242 let hir_id = self.tcx.hir().node_to_hir_id(id);
243 let typ = match self.save_ctxt.tables.node_id_to_type_opt(hir_id) {
244 Some(s) => s.to_string(),
247 if !self.span.filter_generated(ident.span) {
248 let id = ::id_from_node_id(id, &self.save_ctxt);
249 let span = self.span_from_span(ident.span);
251 self.dumper.dump_def(
257 kind: DefKind::Local,
260 name: ident.to_string(),
261 qualname: format!("{}::{}", qualname, ident.to_string()),
278 sig: &'l ast::MethodSig,
279 body: Option<&'l ast::Block>,
282 generics: &'l ast::Generics,
283 vis: ast::Visibility,
286 debug!("process_method: {}:{}", id, ident);
288 if let Some(mut method_data) = self.save_ctxt.get_method_data(id, ident, span) {
289 let sig_str = ::make_signature(&sig.decl, &generics);
293 |v| v.process_formals(&sig.decl.inputs, &method_data.qualname),
297 self.process_generic_params(&generics, &method_data.qualname, id);
299 method_data.value = sig_str;
300 method_data.sig = sig::method_signature(id, ident, generics, sig, &self.save_ctxt);
301 self.dumper.dump_def(&access_from!(self.save_ctxt, vis, id), method_data);
304 // walk arg and return types
305 for arg in &sig.decl.inputs {
306 self.visit_ty(&arg.ty);
309 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
310 self.visit_ty(ret_ty);
314 if let Some(body) = body {
315 self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
319 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
320 let field_data = self.save_ctxt.get_field_data(field, parent_id);
321 if let Some(field_data) = field_data {
322 self.dumper.dump_def(&access_from!(self.save_ctxt, field), field_data);
326 // Dump generic params bindings, then visit_generics
327 fn process_generic_params(
329 generics: &'l ast::Generics,
333 for param in &generics.params {
335 ast::GenericParamKind::Lifetime { .. } => {}
336 ast::GenericParamKind::Type { .. } => {
337 let param_ss = param.ident.span;
338 let name = escape(self.span.snippet(param_ss));
339 // Append $id to name to make sure each one is unique.
340 let qualname = format!("{}::{}${}", prefix, name, id);
341 if !self.span.filter_generated(param_ss) {
342 let id = ::id_from_node_id(param.id, &self.save_ctxt);
343 let span = self.span_from_span(param_ss);
345 self.dumper.dump_def(
356 value: String::new(),
369 self.visit_generics(generics);
375 decl: &'l ast::FnDecl,
376 ty_params: &'l ast::Generics,
377 body: &'l ast::Block,
379 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
380 down_cast_data!(fn_data, DefData, item.span);
383 |v| v.process_formals(&decl.inputs, &fn_data.qualname),
385 self.process_generic_params(ty_params, &fn_data.qualname, item.id);
386 self.dumper.dump_def(&access_from!(self.save_ctxt, item), fn_data);
389 for arg in &decl.inputs {
390 self.visit_ty(&arg.ty);
393 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
394 self.visit_ty(&ret_ty);
397 self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
400 fn process_static_or_const_item(
406 self.nest_tables(item.id, |v| {
407 if let Some(var_data) = v.save_ctxt.get_item_data(item) {
408 down_cast_data!(var_data, DefData, item.span);
409 v.dumper.dump_def(&access_from!(v.save_ctxt, item), var_data);
416 fn process_assoc_const(
421 expr: Option<&'l ast::Expr>,
423 vis: ast::Visibility,
424 attrs: &'l [Attribute],
426 let qualname = format!("::{}", self.tcx.node_path_str(id));
428 if !self.span.filter_generated(ident.span) {
429 let sig = sig::assoc_const_signature(id, ident.name, typ, expr, &self.save_ctxt);
430 let span = self.span_from_span(ident.span);
432 self.dumper.dump_def(
433 &access_from!(self.save_ctxt, vis, id),
435 kind: DefKind::Const,
436 id: ::id_from_node_id(id, &self.save_ctxt),
438 name: ident.name.to_string(),
440 value: ty_to_string(&typ),
441 parent: Some(::id_from_def_id(parent_id)),
444 docs: self.save_ctxt.docs_for_attrs(attrs),
446 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
451 // walk type and init value
453 if let Some(expr) = expr {
454 self.visit_expr(expr);
458 // FIXME tuple structs should generate tuple-specific data.
462 def: &'l ast::VariantData,
463 ty_params: &'l ast::Generics,
465 debug!("process_struct {:?} {:?}", item, item.span);
466 let name = item.ident.to_string();
467 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
469 let kind = match item.node {
470 ast::ItemKind::Struct(_, _) => DefKind::Struct,
471 ast::ItemKind::Union(_, _) => DefKind::Union,
475 let (value, fields) = match item.node {
476 ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, _), _) |
477 ast::ItemKind::Union(ast::VariantData::Struct(ref fields, _), _) => {
478 let include_priv_fields = !self.save_ctxt.config.pub_only;
479 let fields_str = fields
482 .filter_map(|(i, f)| {
483 if include_priv_fields || f.vis.node.is_pub() {
485 .map(|i| i.to_string())
486 .or_else(|| Some(i.to_string()))
493 let value = format!("{} {{ {} }}", name, fields_str);
498 .map(|f| ::id_from_node_id(f.id, &self.save_ctxt))
502 _ => (String::new(), vec![]),
505 if !self.span.filter_generated(item.ident.span) {
506 let span = self.span_from_span(item.ident.span);
507 self.dumper.dump_def(
508 &access_from!(self.save_ctxt, item),
511 id: ::id_from_node_id(item.id, &self.save_ctxt),
514 qualname: qualname.clone(),
519 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
520 sig: sig::item_signature(item, &self.save_ctxt),
521 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
526 for field in def.fields() {
527 self.process_struct_field_def(field, item.id);
528 self.visit_ty(&field.ty);
531 self.process_generic_params(ty_params, &qualname, item.id);
537 enum_definition: &'l ast::EnumDef,
538 ty_params: &'l ast::Generics,
540 let enum_data = self.save_ctxt.get_item_data(item);
541 let enum_data = match enum_data {
545 down_cast_data!(enum_data, DefData, item.span);
547 let access = access_from!(self.save_ctxt, item);
549 for variant in &enum_definition.variants {
550 let name = variant.node.ident.name.to_string();
551 let qualname = format!("{}::{}", enum_data.qualname, name);
552 let name_span = variant.node.ident.span;
554 match variant.node.data {
555 ast::VariantData::Struct(ref fields, _) => {
556 let fields_str = fields
560 f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
564 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
565 if !self.span.filter_generated(name_span) {
566 let span = self.span_from_span(name_span);
567 let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
568 let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
570 self.dumper.dump_def(
573 kind: DefKind::StructVariant,
582 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
583 sig: sig::variant_signature(variant, &self.save_ctxt),
584 attributes: lower_attributes(
585 variant.node.attrs.clone(),
593 let mut value = format!("{}::{}", enum_data.name, name);
594 if let &ast::VariantData::Tuple(ref fields, _) = v {
596 value.push_str(&fields
598 .map(|f| ty_to_string(&f.ty))
603 if !self.span.filter_generated(name_span) {
604 let span = self.span_from_span(name_span);
605 let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
606 let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
608 self.dumper.dump_def(
611 kind: DefKind::TupleVariant,
620 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
621 sig: sig::variant_signature(variant, &self.save_ctxt),
622 attributes: lower_attributes(
623 variant.node.attrs.clone(),
633 for field in variant.node.data.fields() {
634 self.process_struct_field_def(field, variant.node.data.id());
635 self.visit_ty(&field.ty);
638 self.process_generic_params(ty_params, &enum_data.qualname, item.id);
639 self.dumper.dump_def(&access, enum_data);
645 type_parameters: &'l ast::Generics,
646 trait_ref: &'l Option<ast::TraitRef>,
648 impl_items: &'l [ast::ImplItem],
650 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
651 if !self.span.filter_generated(item.span) {
652 if let super::Data::RelationData(rel, imp) = impl_data {
653 self.dumper.dump_relation(rel);
654 self.dumper.dump_impl(imp);
656 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
661 if let &Some(ref trait_ref) = trait_ref {
662 self.process_path(trait_ref.ref_id, &trait_ref.path);
664 self.process_generic_params(type_parameters, "", item.id);
665 for impl_item in impl_items {
666 let map = &self.tcx.hir();
667 self.process_impl_item(impl_item, map.local_def_id(item.id));
674 generics: &'l ast::Generics,
675 trait_refs: &'l ast::GenericBounds,
676 methods: &'l [ast::TraitItem],
678 let name = item.ident.to_string();
679 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
680 let mut val = name.clone();
681 if !generics.params.is_empty() {
682 val.push_str(&generic_params_to_string(&generics.params));
684 if !trait_refs.is_empty() {
686 val.push_str(&bounds_to_string(trait_refs));
688 if !self.span.filter_generated(item.ident.span) {
689 let id = ::id_from_node_id(item.id, &self.save_ctxt);
690 let span = self.span_from_span(item.ident.span);
691 let children = methods
693 .map(|i| ::id_from_node_id(i.id, &self.save_ctxt))
695 self.dumper.dump_def(
696 &access_from!(self.save_ctxt, item),
698 kind: DefKind::Trait,
702 qualname: qualname.clone(),
707 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
708 sig: sig::item_signature(item, &self.save_ctxt),
709 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
715 for super_bound in trait_refs.iter() {
716 let trait_ref = match *super_bound {
717 ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
718 ast::GenericBound::Outlives(..) => continue,
721 let trait_ref = &trait_ref.trait_ref;
722 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
723 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
724 if !self.span.filter_generated(sub_span) {
725 let span = self.span_from_span(sub_span);
726 self.dumper.dump_ref(Ref {
729 ref_id: ::id_from_def_id(id),
732 self.dumper.dump_relation(Relation {
733 kind: RelationKind::SuperTrait,
735 from: ::id_from_def_id(id),
736 to: ::id_from_node_id(item.id, &self.save_ctxt),
742 // walk generics and methods
743 self.process_generic_params(generics, &qualname, item.id);
744 for method in methods {
745 let map = &self.tcx.hir();
746 self.process_trait_item(method, map.local_def_id(item.id))
750 // `item` is the module in question, represented as an item.
751 fn process_mod(&mut self, item: &ast::Item) {
752 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
753 down_cast_data!(mod_data, DefData, item.span);
754 self.dumper.dump_def(&access_from!(self.save_ctxt, item), mod_data);
758 fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
759 let path_data = self.save_ctxt.get_path_data(id, path);
760 if let Some(path_data) = path_data {
761 self.dumper.dump_ref(path_data);
765 fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
766 if self.span.filter_generated(path.span) {
769 self.dump_path_ref(id, path);
772 for seg in &path.segments {
773 if let Some(ref generic_args) = seg.args {
774 match **generic_args {
775 ast::GenericArgs::AngleBracketed(ref data) => {
776 for arg in &data.args {
778 ast::GenericArg::Type(ty) => self.visit_ty(ty),
783 ast::GenericArgs::Parenthesized(ref data) => {
784 for t in &data.inputs {
787 if let Some(ref t) = data.output {
795 self.write_sub_paths_truncated(path);
798 fn process_struct_lit(
802 fields: &'l [ast::Field],
803 variant: &'l ty::VariantDef,
804 base: &'l Option<P<ast::Expr>>,
806 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
807 self.write_sub_paths_truncated(path);
808 down_cast_data!(struct_lit_data, RefData, ex.span);
809 if !generated_code(ex.span) {
810 self.dumper.dump_ref(struct_lit_data);
813 for field in fields {
814 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
815 self.dumper.dump_ref(field_data);
818 self.visit_expr(&field.expr)
822 walk_list!(self, visit_expr, base);
825 fn process_method_call(
828 seg: &'l ast::PathSegment,
829 args: &'l [P<ast::Expr>],
831 debug!("process_method_call {:?} {:?}", ex, ex.span);
832 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
833 down_cast_data!(mcd, RefData, ex.span);
834 if !generated_code(ex.span) {
835 self.dumper.dump_ref(mcd);
839 // Explicit types in the turbo-fish.
840 if let Some(ref generic_args) = seg.args {
841 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
842 for arg in &data.args {
844 ast::GenericArg::Type(ty) => self.visit_ty(ty),
851 // walk receiver and args
852 walk_list!(self, visit_expr, args);
855 fn process_pat(&mut self, p: &'l ast::Pat) {
857 PatKind::Struct(ref _path, ref fields, _) => {
858 // FIXME do something with _path?
859 let hir_id = self.tcx.hir().node_to_hir_id(p.id);
860 let adt = match self.save_ctxt.tables.node_id_to_type_opt(hir_id) {
861 Some(ty) => ty.ty_adt_def().unwrap(),
863 visit::walk_pat(self, p);
867 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
869 for &Spanned { node: ref field, .. } in fields {
870 if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
871 if !self.span.filter_generated(field.ident.span) {
872 let span = self.span_from_span(field.ident.span);
873 self.dumper.dump_ref(Ref {
874 kind: RefKind::Variable,
876 ref_id: ::id_from_def_id(variant.fields[index].did),
880 self.visit_pat(&field.pat);
883 _ => visit::walk_pat(self, p),
887 fn process_var_decl_multi(&mut self, pats: &'l [P<ast::Pat>]) {
888 let mut collector = PathCollector::new();
889 for pattern in pats {
890 // collect paths from the arm's patterns
891 collector.visit_pat(&pattern);
892 self.visit_pat(&pattern);
895 // process collected paths
896 for (id, ident, immut) in collector.collected_idents {
897 match self.save_ctxt.get_path_def(id) {
898 HirDef::Local(id) => {
899 let mut value = if immut == ast::Mutability::Immutable {
900 self.span.snippet(ident.span)
902 "<mutable>".to_owned()
904 let hir_id = self.tcx.hir().node_to_hir_id(id);
905 let typ = self.save_ctxt
907 .node_id_to_type_opt(hir_id)
908 .map(|t| t.to_string())
909 .unwrap_or_default();
910 value.push_str(": ");
911 value.push_str(&typ);
913 if !self.span.filter_generated(ident.span) {
914 let qualname = format!("{}${}", ident.to_string(), id);
915 let id = ::id_from_node_id(id, &self.save_ctxt);
916 let span = self.span_from_span(ident.span);
918 self.dumper.dump_def(
924 kind: DefKind::Local,
927 name: ident.to_string(),
940 HirDef::StructCtor(..) |
941 HirDef::VariantCtor(..) |
943 HirDef::AssociatedConst(..) |
945 HirDef::Variant(..) |
946 HirDef::TyAlias(..) |
947 HirDef::AssociatedTy(..) |
948 HirDef::SelfTy(..) => {
949 self.dump_path_ref(id, &ast::Path::from_ident(ident));
952 "unexpected definition kind when processing collected idents: {:?}",
958 for (id, ref path) in collector.collected_paths {
959 self.process_path(id, path);
963 fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
964 // The local could declare multiple new vars, we must walk the
965 // pattern and collect them all.
966 let mut collector = PathCollector::new();
967 collector.visit_pat(&p);
970 for (id, ident, immut) in collector.collected_idents {
971 let mut value = match immut {
972 ast::Mutability::Immutable => value.to_string(),
975 let hir_id = self.tcx.hir().node_to_hir_id(id);
976 let typ = match self.save_ctxt.tables.node_id_to_type_opt(hir_id) {
978 let typ = typ.to_string();
979 if !value.is_empty() {
980 value.push_str(": ");
982 value.push_str(&typ);
985 None => String::new(),
988 // Rust uses the id of the pattern for var lookups, so we'll use it too.
989 if !self.span.filter_generated(ident.span) {
990 let qualname = format!("{}${}", ident.to_string(), id);
991 let id = ::id_from_node_id(id, &self.save_ctxt);
992 let span = self.span_from_span(ident.span);
994 self.dumper.dump_def(
1000 kind: DefKind::Local,
1003 name: ident.to_string(),
1009 docs: String::new(),
1018 /// Extract macro use and definition information from the AST node defined
1019 /// by the given NodeId, using the expansion information from the node's
1022 /// If the span is not macro-generated, do nothing, else use callee and
1023 /// callsite spans to record macro definition and use data, using the
1024 /// mac_uses and mac_defs sets to prevent multiples.
1025 fn process_macro_use(&mut self, _span: Span) {
1026 // FIXME if we're not dumping the defs (see below), there is no point
1027 // dumping refs either.
1028 // let source_span = span.source_callsite();
1029 // if !self.macro_calls.insert(source_span) {
1033 // let data = match self.save_ctxt.get_macro_use_data(span) {
1035 // Some(data) => data,
1038 // self.dumper.macro_use(data);
1040 // FIXME write the macro def
1041 // let mut hasher = DefaultHasher::new();
1042 // data.callee_span.hash(&mut hasher);
1043 // let hash = hasher.finish();
1044 // let qualname = format!("{}::{}", data.name, hash);
1045 // Don't write macro definition for imported macros
1046 // if !self.mac_defs.contains(&data.callee_span)
1047 // && !data.imported {
1048 // self.mac_defs.insert(data.callee_span);
1049 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1050 // self.dumper.macro_data(MacroData {
1052 // name: data.name.clone(),
1053 // qualname: qualname.clone(),
1054 // // FIXME where do macro docs come from?
1055 // docs: String::new(),
1056 // }.lower(self.tcx));
1061 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1062 self.process_macro_use(trait_item.span);
1063 let vis_span = trait_item.span.shrink_to_lo();
1064 match trait_item.node {
1065 ast::TraitItemKind::Const(ref ty, ref expr) => {
1066 self.process_assoc_const(
1070 expr.as_ref().map(|e| &**e),
1072 respan(vis_span, ast::VisibilityKind::Public),
1076 ast::TraitItemKind::Method(ref sig, ref body) => {
1077 self.process_method(
1079 body.as_ref().map(|x| &**x),
1082 &trait_item.generics,
1083 respan(vis_span, ast::VisibilityKind::Public),
1087 ast::TraitItemKind::Type(ref bounds, ref default_ty) => {
1088 // FIXME do something with _bounds (for type refs)
1089 let name = trait_item.ident.name.to_string();
1090 let qualname = format!("::{}", self.tcx.node_path_str(trait_item.id));
1092 if !self.span.filter_generated(trait_item.ident.span) {
1093 let span = self.span_from_span(trait_item.ident.span);
1094 let id = ::id_from_node_id(trait_item.id, &self.save_ctxt);
1096 self.dumper.dump_def(
1102 kind: DefKind::Type,
1107 value: self.span.snippet(trait_item.span),
1108 parent: Some(::id_from_def_id(trait_id)),
1111 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1112 sig: sig::assoc_type_signature(
1116 default_ty.as_ref().map(|ty| &**ty),
1119 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1124 if let &Some(ref default_ty) = default_ty {
1125 self.visit_ty(default_ty)
1128 ast::TraitItemKind::Macro(_) => {}
1132 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1133 self.process_macro_use(impl_item.span);
1134 match impl_item.node {
1135 ast::ImplItemKind::Const(ref ty, ref expr) => {
1136 self.process_assoc_const(
1142 impl_item.vis.clone(),
1146 ast::ImplItemKind::Method(ref sig, ref body) => {
1147 self.process_method(
1152 &impl_item.generics,
1153 impl_item.vis.clone(),
1157 ast::ImplItemKind::Type(ref ty) => {
1158 // FIXME uses of the assoc type should ideally point to this
1159 // 'def' and the name here should be a ref to the def in the
1163 ast::ImplItemKind::Existential(ref bounds) => {
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
1167 for bound in bounds.iter() {
1168 if let ast::GenericBound::Trait(trait_ref, _) = bound {
1169 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1173 ast::ImplItemKind::Macro(_) => {}
1177 /// Dumps imports in a use tree recursively.
1179 /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1180 /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1181 /// id and path. `root_item` is the topmost use tree in the hierarchy.
1183 /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1184 /// each child use tree is dumped recursively.
1185 fn process_use_tree(&mut self,
1186 use_tree: &'l ast::UseTree,
1188 root_item: &'l ast::Item,
1189 prefix: &ast::Path) {
1190 let path = &use_tree.prefix;
1192 // The access is calculated using the current tree ID, but with the root tree's visibility
1193 // (since nested trees don't have their own visibility).
1194 let access = access_from!(self.save_ctxt, root_item.vis, id);
1196 // The parent def id of a given use tree is always the enclosing item.
1197 let parent = self.save_ctxt.tcx.hir().opt_local_def_id(id)
1198 .and_then(|id| self.save_ctxt.tcx.parent_def_id(id))
1199 .map(::id_from_def_id);
1201 match use_tree.kind {
1202 ast::UseTreeKind::Simple(alias, ..) => {
1203 let ident = use_tree.ident();
1204 let path = ast::Path {
1205 segments: prefix.segments
1207 .chain(path.segments.iter())
1213 let sub_span = path.segments.last().unwrap().ident.span;
1214 if !self.span.filter_generated(sub_span) {
1215 let ref_id = self.lookup_def_id(id).map(|id| ::id_from_def_id(id));
1216 let alias_span = alias.map(|i| self.span_from_span(i.span));
1217 let span = self.span_from_span(sub_span);
1218 self.dumper.import(&access, Import {
1219 kind: ImportKind::Use,
1223 name: ident.to_string(),
1224 value: String::new(),
1227 self.write_sub_paths_truncated(&path);
1230 ast::UseTreeKind::Glob => {
1231 let path = ast::Path {
1232 segments: prefix.segments
1234 .chain(path.segments.iter())
1240 // Make a comma-separated list of names of imported modules.
1241 let def_id = self.tcx.hir().local_def_id(id);
1242 let names = self.tcx.names_imported_by_glob_use(def_id);
1243 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1245 // Otherwise it's a span with wrong macro expansion info, which
1246 // we don't want to track anyway, since it's probably macro-internal `use`
1247 if let Some(sub_span) =
1248 self.span.sub_span_of_token(use_tree.span, token::BinOp(token::Star))
1250 if !self.span.filter_generated(use_tree.span) {
1251 let span = self.span_from_span(sub_span);
1253 self.dumper.import(&access, Import {
1254 kind: ImportKind::GlobUse,
1258 name: "*".to_owned(),
1259 value: names.join(", "),
1262 self.write_sub_paths(&path);
1266 ast::UseTreeKind::Nested(ref nested_items) => {
1267 let prefix = ast::Path {
1268 segments: prefix.segments
1270 .chain(path.segments.iter())
1275 for &(ref tree, id) in nested_items {
1276 self.process_use_tree(tree, id, root_item, &prefix);
1282 fn process_bounds(&mut self, bounds: &'l ast::GenericBounds) {
1283 for bound in bounds {
1284 if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1285 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1291 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, O> {
1292 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1293 // Since we handle explicit modules ourselves in visit_item, this should
1294 // only get called for the root module of a crate.
1295 assert_eq!(id, ast::CRATE_NODE_ID);
1297 let qualname = format!("::{}", self.tcx.node_path_str(id));
1299 let cm = self.tcx.sess.source_map();
1300 let filename = cm.span_to_filename(span);
1301 let data_id = ::id_from_node_id(id, &self.save_ctxt);
1302 let children = m.items
1304 .map(|i| ::id_from_node_id(i.id, &self.save_ctxt))
1306 let span = self.span_from_span(span);
1308 self.dumper.dump_def(
1316 name: String::new(),
1319 value: filename.to_string(),
1323 docs: self.save_ctxt.docs_for_attrs(attrs),
1325 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1328 self.nest_scope(id, |v| visit::walk_mod(v, m));
1331 fn visit_item(&mut self, item: &'l ast::Item) {
1332 use syntax::ast::ItemKind::*;
1333 self.process_macro_use(item.span);
1335 Use(ref use_tree) => {
1336 let prefix = ast::Path {
1340 self.process_use_tree(use_tree, item.id, item, &prefix);
1343 let name_span = item.ident.span;
1344 if !self.span.filter_generated(name_span) {
1345 let span = self.span_from_span(name_span);
1346 let parent = self.save_ctxt.tcx.hir().opt_local_def_id(item.id)
1347 .and_then(|id| self.save_ctxt.tcx.parent_def_id(id))
1348 .map(::id_from_def_id);
1355 kind: ImportKind::ExternCrate,
1359 name: item.ident.to_string(),
1360 value: String::new(),
1366 Fn(ref decl, .., ref ty_params, ref body) => {
1367 self.process_fn(item, &decl, ty_params, &body)
1369 Static(ref typ, _, ref expr) => self.process_static_or_const_item(item, typ, expr),
1370 Const(ref typ, ref expr) => self.process_static_or_const_item(item, &typ, &expr),
1371 Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1372 self.process_struct(item, def, ty_params)
1374 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1375 Impl(.., ref ty_params, ref trait_ref, ref typ, ref impl_items) => {
1376 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1378 Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1379 self.process_trait(item, generics, trait_refs, methods)
1382 self.process_mod(item);
1383 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1385 Ty(ref ty, ref ty_params) => {
1386 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1387 let value = ty_to_string(&ty);
1388 if !self.span.filter_generated(item.ident.span) {
1389 let span = self.span_from_span(item.ident.span);
1390 let id = ::id_from_node_id(item.id, &self.save_ctxt);
1392 self.dumper.dump_def(
1393 &access_from!(self.save_ctxt, item),
1395 kind: DefKind::Type,
1398 name: item.ident.to_string(),
1399 qualname: qualname.clone(),
1404 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1405 sig: sig::item_signature(item, &self.save_ctxt),
1406 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1412 self.process_generic_params(ty_params, &qualname, item.id);
1414 Existential(ref _bounds, ref ty_params) => {
1415 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1416 // FIXME do something with _bounds
1417 let value = String::new();
1418 if !self.span.filter_generated(item.ident.span) {
1419 let span = self.span_from_span(item.ident.span);
1420 let id = ::id_from_node_id(item.id, &self.save_ctxt);
1422 self.dumper.dump_def(
1423 &access_from!(self.save_ctxt, item),
1425 kind: DefKind::Type,
1428 name: item.ident.to_string(),
1429 qualname: qualname.clone(),
1434 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1435 sig: sig::item_signature(item, &self.save_ctxt),
1436 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1441 self.process_generic_params(ty_params, &qualname, item.id);
1444 _ => visit::walk_item(self, item),
1448 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1449 for param in &generics.params {
1450 if let ast::GenericParamKind::Type { ref default, .. } = param.kind {
1451 self.process_bounds(¶m.bounds);
1452 if let Some(ref ty) = default {
1457 for pred in &generics.where_clause.predicates {
1458 if let ast::WherePredicate::BoundPredicate(ref wbp) = *pred {
1459 self.process_bounds(&wbp.bounds);
1460 self.visit_ty(&wbp.bounded_ty);
1465 fn visit_ty(&mut self, t: &'l ast::Ty) {
1466 self.process_macro_use(t.span);
1468 ast::TyKind::Path(_, ref path) => {
1469 if generated_code(t.span) {
1473 if let Some(id) = self.lookup_def_id(t.id) {
1474 let sub_span = path.segments.last().unwrap().ident.span;
1475 let span = self.span_from_span(sub_span);
1476 self.dumper.dump_ref(Ref {
1477 kind: RefKind::Type,
1479 ref_id: ::id_from_def_id(id),
1483 self.write_sub_paths_truncated(path);
1484 visit::walk_path(self, path);
1486 ast::TyKind::Array(ref element, ref length) => {
1487 self.visit_ty(element);
1488 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1490 _ => visit::walk_ty(self, t),
1494 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1495 debug!("visit_expr {:?}", ex.node);
1496 self.process_macro_use(ex.span);
1498 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1499 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(ex.id);
1500 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1501 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1503 visit::walk_expr(self, ex);
1507 let def = self.save_ctxt.get_path_def(hir_expr.id);
1508 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1510 ast::ExprKind::MethodCall(ref seg, ref args) => self.process_method_call(ex, seg, args),
1511 ast::ExprKind::Field(ref sub_ex, _) => {
1512 self.visit_expr(&sub_ex);
1514 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1515 down_cast_data!(field_data, RefData, ex.span);
1516 if !generated_code(ex.span) {
1517 self.dumper.dump_ref(field_data);
1521 ast::ExprKind::Closure(_, _, _, ref decl, ref body, _fn_decl_span) => {
1522 let id = format!("${}", ex.id);
1524 // walk arg and return types
1525 for arg in &decl.inputs {
1526 self.visit_ty(&arg.ty);
1529 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1530 self.visit_ty(&ret_ty);
1534 self.nest_tables(ex.id, |v| {
1535 v.process_formals(&decl.inputs, &id);
1536 v.nest_scope(ex.id, |v| v.visit_expr(body))
1539 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1540 let value = self.span.snippet(subexpression.span);
1541 self.process_var_decl(pattern, value);
1542 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1543 self.visit_expr(subexpression);
1544 visit::walk_block(self, block);
1546 ast::ExprKind::WhileLet(ref pats, ref subexpression, ref block, _) => {
1547 self.process_var_decl_multi(pats);
1548 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1549 self.visit_expr(subexpression);
1550 visit::walk_block(self, block);
1552 ast::ExprKind::IfLet(ref pats, ref subexpression, ref block, ref opt_else) => {
1553 self.process_var_decl_multi(pats);
1554 self.visit_expr(subexpression);
1555 visit::walk_block(self, block);
1556 opt_else.as_ref().map(|el| self.visit_expr(el));
1558 ast::ExprKind::Repeat(ref element, ref count) => {
1559 self.visit_expr(element);
1560 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1562 // In particular, we take this branch for call and path expressions,
1563 // where we'll index the idents involved just by continuing to walk.
1564 _ => visit::walk_expr(self, ex),
1568 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1569 // These shouldn't exist in the AST at this point, log a span bug.
1572 "macro invocation should have been expanded out of AST"
1576 fn visit_pat(&mut self, p: &'l ast::Pat) {
1577 self.process_macro_use(p.span);
1578 self.process_pat(p);
1581 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1582 self.process_var_decl_multi(&arm.pats);
1584 Some(ast::Guard::If(ref expr)) => self.visit_expr(expr),
1587 self.visit_expr(&arm.body);
1590 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1591 self.process_path(id, p);
1594 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1595 self.process_macro_use(s.span);
1596 visit::walk_stmt(self, s)
1599 fn visit_local(&mut self, l: &'l ast::Local) {
1600 self.process_macro_use(l.span);
1603 .map(|i| self.span.snippet(i.span))
1604 .unwrap_or_default();
1605 self.process_var_decl(&l.pat, value);
1607 // Just walk the initialiser and type (don't want to walk the pattern again).
1608 walk_list!(self, visit_ty, &l.ty);
1609 walk_list!(self, visit_expr, &l.init);
1612 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1613 let access = access_from!(self.save_ctxt, item);
1616 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1617 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1618 down_cast_data!(fn_data, DefData, item.span);
1620 self.process_generic_params(generics, &fn_data.qualname, item.id);
1621 self.dumper.dump_def(&access, fn_data);
1624 for arg in &decl.inputs {
1625 self.visit_ty(&arg.ty);
1628 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1629 self.visit_ty(&ret_ty);
1632 ast::ForeignItemKind::Static(ref ty, _) => {
1633 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1634 down_cast_data!(var_data, DefData, item.span);
1635 self.dumper.dump_def(&access, var_data);
1640 ast::ForeignItemKind::Ty => {
1641 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1642 down_cast_data!(var_data, DefData, item.span);
1643 self.dumper.dump_def(&access, var_data);
1646 ast::ForeignItemKind::Macro(..) => {}