1 //! Write the output of rustc's analysis to an implementor of Dump.
3 //! Dumping the analysis is implemented by walking the AST and getting a bunch of
4 //! info out from all over the place. We use `DefId`s to identify objects. The
5 //! tricky part is getting syntactic (span, source text) and semantic (reference
6 //! `DefId`s) information for parts of expressions which the compiler has discarded.
7 //! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
8 //! path and a reference to `baz`, but we want spans and references for all three
11 //! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
12 //! from spans (e.g., the span for `bar` from the above example path).
13 //! DumpVisitor walks the AST and processes it, and Dumper is used for
14 //! recording the output.
16 use rustc::hir::def::{Res, DefKind as HirDefKind};
17 use rustc::hir::def_id::DefId;
18 use rustc::session::config::Input;
20 use rustc::ty::{self, DefIdTree, TyCtxt};
21 use rustc_data_structures::fx::FxHashSet;
26 use syntax::ast::{self, Attribute, NodeId, PatKind};
27 use syntax::parse::token;
28 use syntax::visit::{self, Visitor};
29 use syntax::print::pprust::{
31 generic_params_to_string,
35 use syntax::source_map::{DUMMY_SP, respan};
36 use syntax::walk_list;
39 use crate::{escape, generated_code, id_from_def_id, id_from_node_id, lower_attributes,
40 PathCollector, SaveContext};
41 use crate::dumper::{Access, Dumper};
42 use crate::span_utils::SpanUtils;
45 use rls_data::{CompilationOptions, CratePreludeData, Def, DefKind, GlobalCrateId, Import,
46 ImportKind, Ref, RefKind, Relation, RelationKind, SpanData};
48 use log::{debug, error};
50 macro_rules! down_cast_data {
51 ($id:ident, $kind:ident, $sp:expr) => {
52 let $id = if let super::Data::$kind(data) = $id {
55 span_bug!($sp, "unexpected data kind: {:?}", $id);
60 macro_rules! access_from {
61 ($save_ctxt:expr, $item:expr, $id:expr) => {
63 public: $item.vis.node.is_pub(),
64 reachable: $save_ctxt.access_levels.is_reachable($id),
69 macro_rules! access_from_vis {
70 ($save_ctxt:expr, $vis:expr, $id:expr) => {
72 public: $vis.node.is_pub(),
73 reachable: $save_ctxt.access_levels.is_reachable($id),
78 pub struct DumpVisitor<'l, 'tcx> {
79 pub save_ctxt: SaveContext<'l, 'tcx>,
85 // Set of macro definition (callee) spans, and the set
86 // of macro use (callsite) spans. We store these to ensure
87 // we only write one macro def per unique macro definition, and
88 // one macro use per unique callsite span.
89 // mac_defs: FxHashSet<Span>,
90 // macro_calls: FxHashSet<Span>,
93 impl<'l, 'tcx> DumpVisitor<'l, 'tcx> {
95 save_ctxt: SaveContext<'l, 'tcx>,
96 ) -> DumpVisitor<'l, 'tcx> {
97 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
98 let dumper = Dumper::new(save_ctxt.config.clone());
104 // mac_defs: FxHashSet::default(),
105 // macro_calls: FxHashSet::default(),
109 pub fn analysis(&self) -> &rls_data::Analysis {
110 self.dumper.analysis()
113 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
115 F: FnOnce(&mut Self),
117 let item_def_id = self.tcx.hir().local_def_id_from_node_id(item_id);
118 if self.tcx.has_typeck_tables(item_def_id) {
119 let tables = self.tcx.typeck_tables_of(item_def_id);
120 let old_tables = self.save_ctxt.tables;
121 self.save_ctxt.tables = tables;
123 self.save_ctxt.tables = old_tables;
129 fn span_from_span(&self, span: Span) -> SpanData {
130 self.save_ctxt.span_from_span(span)
133 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
134 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
135 let crate_root = source_file.map(|source_file| {
136 let source_file = Path::new(source_file);
137 match source_file.file_name() {
138 Some(_) => source_file.parent().unwrap().display(),
139 None => source_file.display(),
143 let data = CratePreludeData {
144 crate_id: GlobalCrateId {
146 disambiguator: self.tcx
148 .local_crate_disambiguator()
152 crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
153 external_crates: self.save_ctxt.get_external_crates(),
154 span: self.span_from_span(krate.span),
157 self.dumper.crate_prelude(data);
160 pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
161 // Apply possible `remap-path-prefix` remapping to the input source file
162 // (and don't include remapping args anymore)
163 let (program, arguments) = {
164 let remap_arg_indices = {
165 let mut indices = FxHashSet::default();
166 // Args are guaranteed to be valid UTF-8 (checked early)
167 for (i, e) in env::args().enumerate() {
168 if e.starts_with("--remap-path-prefix=") {
170 } else if e == "--remap-path-prefix" {
172 indices.insert(i + 1);
178 let mut args = env::args()
180 .filter(|(i, _)| !remap_arg_indices.contains(i))
183 Input::File(ref path) if path == Path::new(&arg) => {
184 let mapped = &self.tcx.sess.local_crate_source_file;
195 (args.next().unwrap(), args.collect())
198 let data = CompilationOptions {
199 directory: self.tcx.sess.working_dir.0.clone(),
202 output: self.save_ctxt.compilation_output(crate_name),
205 self.dumper.compilation_opts(data);
208 fn write_sub_paths(&mut self, path: &ast::Path) {
209 for seg in &path.segments {
210 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
211 self.dumper.dump_ref(data);
216 // As write_sub_paths, but does not process the last ident in the path (assuming it
217 // will be processed elsewhere). See note on write_sub_paths about global.
218 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
219 for seg in &path.segments[..path.segments.len() - 1] {
220 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
221 self.dumper.dump_ref(data);
226 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
227 match self.save_ctxt.get_path_res(ref_id) {
228 Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => None,
229 def => Some(def.def_id()),
233 fn process_formals(&mut self, formals: &'l [ast::Param], qualname: &str) {
235 self.visit_pat(&arg.pat);
236 let mut collector = PathCollector::new();
237 collector.visit_pat(&arg.pat);
239 for (id, ident, ..) in collector.collected_idents {
240 let hir_id = self.tcx.hir().node_to_hir_id(id);
241 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
242 Some(s) => s.to_string(),
245 if !self.span.filter_generated(ident.span) {
246 let id = id_from_node_id(id, &self.save_ctxt);
247 let span = self.span_from_span(ident.span);
249 self.dumper.dump_def(
255 kind: DefKind::Local,
258 name: ident.to_string(),
259 qualname: format!("{}::{}", qualname, ident.to_string()),
276 sig: &'l ast::MethodSig,
277 body: Option<&'l ast::Block>,
280 generics: &'l ast::Generics,
281 vis: ast::Visibility,
284 debug!("process_method: {}:{}", id, ident);
286 if let Some(mut method_data) = self.save_ctxt.get_method_data(id, ident, span) {
287 let sig_str = crate::make_signature(&sig.decl, &generics);
291 |v| v.process_formals(&sig.decl.inputs, &method_data.qualname),
295 self.process_generic_params(&generics, &method_data.qualname, id);
297 method_data.value = sig_str;
298 method_data.sig = sig::method_signature(id, ident, generics, sig, &self.save_ctxt);
299 let hir_id = self.tcx.hir().node_to_hir_id(id);
300 self.dumper.dump_def(&access_from_vis!(self.save_ctxt, vis, hir_id), method_data);
303 // walk arg and return types
304 for arg in &sig.decl.inputs {
305 self.visit_ty(&arg.ty);
308 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
309 self.visit_ty(ret_ty);
313 if let Some(body) = body {
314 self.nest_tables(id, |v| v.visit_block(body));
318 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
319 let field_data = self.save_ctxt.get_field_data(field, parent_id);
320 if let Some(field_data) = field_data {
321 let hir_id = self.tcx.hir().node_to_hir_id(field.id);
322 self.dumper.dump_def(&access_from!(self.save_ctxt, field, hir_id), field_data);
326 // Dump generic params bindings, then visit_generics
327 fn process_generic_params(
329 generics: &'l ast::Generics,
333 for param in &generics.params {
335 ast::GenericParamKind::Lifetime { .. } => {}
336 ast::GenericParamKind::Type { .. } => {
337 let param_ss = param.ident.span;
338 let name = escape(self.span.snippet(param_ss));
339 // Append $id to name to make sure each one is unique.
340 let qualname = format!("{}::{}${}", prefix, name, id);
341 if !self.span.filter_generated(param_ss) {
342 let id = id_from_node_id(param.id, &self.save_ctxt);
343 let span = self.span_from_span(param_ss);
345 self.dumper.dump_def(
356 value: String::new(),
367 ast::GenericParamKind::Const { .. } => {}
370 self.visit_generics(generics);
376 decl: &'l ast::FnDecl,
377 ty_params: &'l ast::Generics,
378 body: &'l ast::Block,
380 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
381 down_cast_data!(fn_data, DefData, item.span);
384 |v| v.process_formals(&decl.inputs, &fn_data.qualname),
386 self.process_generic_params(ty_params, &fn_data.qualname, item.id);
387 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
388 self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), fn_data);
391 for arg in &decl.inputs {
392 self.visit_ty(&arg.ty);
395 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
396 self.visit_ty(&ret_ty);
399 self.nest_tables(item.id, |v| v.visit_block(&body));
402 fn process_static_or_const_item(
408 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
409 self.nest_tables(item.id, |v| {
410 if let Some(var_data) = v.save_ctxt.get_item_data(item) {
411 down_cast_data!(var_data, DefData, item.span);
412 v.dumper.dump_def(&access_from!(v.save_ctxt, item, hir_id), var_data);
419 fn process_assoc_const(
424 expr: Option<&'l ast::Expr>,
426 vis: ast::Visibility,
427 attrs: &'l [Attribute],
429 let qualname = format!("::{}",
430 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
432 if !self.span.filter_generated(ident.span) {
433 let sig = sig::assoc_const_signature(id, ident.name, typ, expr, &self.save_ctxt);
434 let span = self.span_from_span(ident.span);
435 let hir_id = self.tcx.hir().node_to_hir_id(id);
437 self.dumper.dump_def(
438 &access_from_vis!(self.save_ctxt, vis, hir_id),
440 kind: DefKind::Const,
441 id: id_from_node_id(id, &self.save_ctxt),
443 name: ident.name.to_string(),
445 value: ty_to_string(&typ),
446 parent: Some(id_from_def_id(parent_id)),
449 docs: self.save_ctxt.docs_for_attrs(attrs),
451 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
456 // walk type and init value
457 self.nest_tables(id, |v| {
459 if let Some(expr) = expr {
465 // FIXME tuple structs should generate tuple-specific data.
469 def: &'l ast::VariantData,
470 ty_params: &'l ast::Generics,
472 debug!("process_struct {:?} {:?}", item, item.span);
473 let name = item.ident.to_string();
474 let qualname = format!("::{}",
475 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
477 let kind = match item.node {
478 ast::ItemKind::Struct(_, _) => DefKind::Struct,
479 ast::ItemKind::Union(_, _) => DefKind::Union,
483 let (value, fields) = match item.node {
484 ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, ..), ..) |
485 ast::ItemKind::Union(ast::VariantData::Struct(ref fields, ..), ..) => {
486 let include_priv_fields = !self.save_ctxt.config.pub_only;
487 let fields_str = fields
490 .filter_map(|(i, f)| {
491 if include_priv_fields || f.vis.node.is_pub() {
493 .map(|i| i.to_string())
494 .or_else(|| Some(i.to_string()))
501 let value = format!("{} {{ {} }}", name, fields_str);
506 .map(|f| id_from_node_id(f.id, &self.save_ctxt))
510 _ => (String::new(), vec![]),
513 if !self.span.filter_generated(item.ident.span) {
514 let span = self.span_from_span(item.ident.span);
515 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
516 self.dumper.dump_def(
517 &access_from!(self.save_ctxt, item, hir_id),
520 id: id_from_node_id(item.id, &self.save_ctxt),
523 qualname: qualname.clone(),
528 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
529 sig: sig::item_signature(item, &self.save_ctxt),
530 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
535 for field in def.fields() {
536 self.process_struct_field_def(field, item.id);
537 self.visit_ty(&field.ty);
540 self.process_generic_params(ty_params, &qualname, item.id);
546 enum_definition: &'l ast::EnumDef,
547 ty_params: &'l ast::Generics,
549 let enum_data = self.save_ctxt.get_item_data(item);
550 let enum_data = match enum_data {
554 down_cast_data!(enum_data, DefData, item.span);
556 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
557 let access = access_from!(self.save_ctxt, item, hir_id);
559 for variant in &enum_definition.variants {
560 let name = variant.ident.name.to_string();
561 let qualname = format!("{}::{}", enum_data.qualname, name);
562 let name_span = variant.ident.span;
565 ast::VariantData::Struct(ref fields, ..) => {
566 let fields_str = fields
570 f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
574 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
575 if !self.span.filter_generated(name_span) {
576 let span = self.span_from_span(name_span);
577 let id = id_from_node_id(variant.id, &self.save_ctxt);
578 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
580 self.dumper.dump_def(
583 kind: DefKind::StructVariant,
592 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
593 sig: sig::variant_signature(variant, &self.save_ctxt),
594 attributes: lower_attributes(
595 variant.attrs.clone(),
603 let mut value = format!("{}::{}", enum_data.name, name);
604 if let &ast::VariantData::Tuple(ref fields, _) = v {
606 value.push_str(&fields
608 .map(|f| ty_to_string(&f.ty))
613 if !self.span.filter_generated(name_span) {
614 let span = self.span_from_span(name_span);
615 let id = id_from_node_id(variant.id, &self.save_ctxt);
616 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
618 self.dumper.dump_def(
621 kind: DefKind::TupleVariant,
630 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
631 sig: sig::variant_signature(variant, &self.save_ctxt),
632 attributes: lower_attributes(
633 variant.attrs.clone(),
643 for field in variant.data.fields() {
644 self.process_struct_field_def(field, variant.id);
645 self.visit_ty(&field.ty);
648 self.process_generic_params(ty_params, &enum_data.qualname, item.id);
649 self.dumper.dump_def(&access, enum_data);
655 generics: &'l ast::Generics,
656 trait_ref: &'l Option<ast::TraitRef>,
658 impl_items: &'l [ast::ImplItem],
660 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
661 if !self.span.filter_generated(item.span) {
662 if let super::Data::RelationData(rel, imp) = impl_data {
663 self.dumper.dump_relation(rel);
664 self.dumper.dump_impl(imp);
666 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
671 if let &Some(ref trait_ref) = trait_ref {
672 self.process_path(trait_ref.ref_id, &trait_ref.path);
674 self.process_generic_params(generics, "", item.id);
675 for impl_item in impl_items {
676 let map = &self.tcx.hir();
677 self.process_impl_item(impl_item, map.local_def_id_from_node_id(item.id));
684 generics: &'l ast::Generics,
685 trait_refs: &'l ast::GenericBounds,
686 methods: &'l [ast::TraitItem],
688 let name = item.ident.to_string();
689 let qualname = format!("::{}",
690 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
691 let mut val = name.clone();
692 if !generics.params.is_empty() {
693 val.push_str(&generic_params_to_string(&generics.params));
695 if !trait_refs.is_empty() {
697 val.push_str(&bounds_to_string(trait_refs));
699 if !self.span.filter_generated(item.ident.span) {
700 let id = id_from_node_id(item.id, &self.save_ctxt);
701 let span = self.span_from_span(item.ident.span);
702 let children = methods
704 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
706 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
707 self.dumper.dump_def(
708 &access_from!(self.save_ctxt, item, hir_id),
710 kind: DefKind::Trait,
714 qualname: qualname.clone(),
719 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
720 sig: sig::item_signature(item, &self.save_ctxt),
721 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
727 for super_bound in trait_refs.iter() {
728 let trait_ref = match *super_bound {
729 ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
730 ast::GenericBound::Outlives(..) => continue,
733 let trait_ref = &trait_ref.trait_ref;
734 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
735 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
736 if !self.span.filter_generated(sub_span) {
737 let span = self.span_from_span(sub_span);
738 self.dumper.dump_ref(Ref {
741 ref_id: id_from_def_id(id),
744 self.dumper.dump_relation(Relation {
745 kind: RelationKind::SuperTrait,
747 from: id_from_def_id(id),
748 to: id_from_node_id(item.id, &self.save_ctxt),
754 // walk generics and methods
755 self.process_generic_params(generics, &qualname, item.id);
756 for method in methods {
757 let map = &self.tcx.hir();
758 self.process_trait_item(method, map.local_def_id_from_node_id(item.id))
762 // `item` is the module in question, represented as an item.
763 fn process_mod(&mut self, item: &ast::Item) {
764 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
765 down_cast_data!(mod_data, DefData, item.span);
766 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
767 self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), mod_data);
771 fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
772 let path_data = self.save_ctxt.get_path_data(id, path);
773 if let Some(path_data) = path_data {
774 self.dumper.dump_ref(path_data);
778 fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
779 if self.span.filter_generated(path.span) {
782 self.dump_path_ref(id, path);
785 for seg in &path.segments {
786 if let Some(ref generic_args) = seg.args {
787 match **generic_args {
788 ast::GenericArgs::AngleBracketed(ref data) => {
789 for arg in &data.args {
791 ast::GenericArg::Type(ty) => self.visit_ty(ty),
796 ast::GenericArgs::Parenthesized(ref data) => {
797 for t in &data.inputs {
800 if let Some(ref t) = data.output {
808 self.write_sub_paths_truncated(path);
811 fn process_struct_lit(
815 fields: &'l [ast::Field],
816 variant: &'l ty::VariantDef,
817 base: &'l Option<P<ast::Expr>>,
819 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
820 self.write_sub_paths_truncated(path);
821 down_cast_data!(struct_lit_data, RefData, ex.span);
822 if !generated_code(ex.span) {
823 self.dumper.dump_ref(struct_lit_data);
826 for field in fields {
827 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
828 self.dumper.dump_ref(field_data);
831 self.visit_expr(&field.expr)
835 walk_list!(self, visit_expr, base);
838 fn process_method_call(
841 seg: &'l ast::PathSegment,
842 args: &'l [P<ast::Expr>],
844 debug!("process_method_call {:?} {:?}", ex, ex.span);
845 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
846 down_cast_data!(mcd, RefData, ex.span);
847 if !generated_code(ex.span) {
848 self.dumper.dump_ref(mcd);
852 // Explicit types in the turbo-fish.
853 if let Some(ref generic_args) = seg.args {
854 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
855 for arg in &data.args {
857 ast::GenericArg::Type(ty) => self.visit_ty(ty),
864 // walk receiver and args
865 walk_list!(self, visit_expr, args);
868 fn process_pat(&mut self, p: &'l ast::Pat) {
870 PatKind::Struct(ref _path, ref fields, _) => {
871 // FIXME do something with _path?
872 let hir_id = self.tcx.hir().node_to_hir_id(p.id);
873 let adt = match self.save_ctxt.tables.node_type_opt(hir_id) {
874 Some(ty) => ty.ty_adt_def().unwrap(),
876 visit::walk_pat(self, p);
880 let variant = adt.variant_of_res(self.save_ctxt.get_path_res(p.id));
882 for field in fields {
883 if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
884 if !self.span.filter_generated(field.ident.span) {
885 let span = self.span_from_span(field.ident.span);
886 self.dumper.dump_ref(Ref {
887 kind: RefKind::Variable,
889 ref_id: id_from_def_id(variant.fields[index].did),
893 self.visit_pat(&field.pat);
896 _ => visit::walk_pat(self, p),
900 fn process_var_decl(&mut self, pat: &'l ast::Pat) {
901 // The pattern could declare multiple new vars,
902 // we must walk the pattern and collect them all.
903 let mut collector = PathCollector::new();
904 collector.visit_pat(&pat);
905 self.visit_pat(&pat);
907 // Process collected paths.
908 for (id, ident, _) in collector.collected_idents {
909 match self.save_ctxt.get_path_res(id) {
910 Res::Local(hir_id) => {
911 let id = self.tcx.hir().hir_to_node_id(hir_id);
912 let typ = self.save_ctxt.tables.node_type_opt(hir_id)
913 .map(|t| t.to_string())
914 .unwrap_or_default();
916 // Rust uses the id of the pattern for var lookups, so we'll use it too.
917 if !self.span.filter_generated(ident.span) {
918 let qualname = format!("{}${}", ident.to_string(), id);
919 let id = id_from_node_id(id, &self.save_ctxt);
920 let span = self.span_from_span(ident.span);
922 self.dumper.dump_def(
928 kind: DefKind::Local,
931 name: ident.to_string(),
944 Res::Def(HirDefKind::Ctor(..), _) |
945 Res::Def(HirDefKind::Const, _) |
946 Res::Def(HirDefKind::AssocConst, _) |
947 Res::Def(HirDefKind::Struct, _) |
948 Res::Def(HirDefKind::Variant, _) |
949 Res::Def(HirDefKind::TyAlias, _) |
950 Res::Def(HirDefKind::AssocTy, _) |
952 self.dump_path_ref(id, &ast::Path::from_ident(ident));
955 "unexpected definition kind when processing collected idents: {:?}",
961 for (id, ref path) in collector.collected_paths {
962 self.process_path(id, path);
966 /// Extracts macro use and definition information from the AST node defined
967 /// by the given NodeId, using the expansion information from the node's
970 /// If the span is not macro-generated, do nothing, else use callee and
971 /// callsite spans to record macro definition and use data, using the
972 /// mac_uses and mac_defs sets to prevent multiples.
973 fn process_macro_use(&mut self, _span: Span) {
974 // FIXME if we're not dumping the defs (see below), there is no point
975 // dumping refs either.
976 // let source_span = span.source_callsite();
977 // if !self.macro_calls.insert(source_span) {
981 // let data = match self.save_ctxt.get_macro_use_data(span) {
983 // Some(data) => data,
986 // self.dumper.macro_use(data);
988 // FIXME write the macro def
989 // let mut hasher = DefaultHasher::new();
990 // data.callee_span.hash(&mut hasher);
991 // let hash = hasher.finish();
992 // let qualname = format!("{}::{}", data.name, hash);
993 // Don't write macro definition for imported macros
994 // if !self.mac_defs.contains(&data.callee_span)
995 // && !data.imported {
996 // self.mac_defs.insert(data.callee_span);
997 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
998 // self.dumper.macro_data(MacroData {
1000 // name: data.name.clone(),
1001 // qualname: qualname.clone(),
1002 // // FIXME where do macro docs come from?
1003 // docs: String::new(),
1004 // }.lower(self.tcx));
1009 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1010 self.process_macro_use(trait_item.span);
1011 let vis_span = trait_item.span.shrink_to_lo();
1012 match trait_item.node {
1013 ast::TraitItemKind::Const(ref ty, ref expr) => {
1014 self.process_assoc_const(
1018 expr.as_ref().map(|e| &**e),
1020 respan(vis_span, ast::VisibilityKind::Public),
1024 ast::TraitItemKind::Method(ref sig, ref body) => {
1025 self.process_method(
1027 body.as_ref().map(|x| &**x),
1030 &trait_item.generics,
1031 respan(vis_span, ast::VisibilityKind::Public),
1035 ast::TraitItemKind::Type(ref bounds, ref default_ty) => {
1036 // FIXME do something with _bounds (for type refs)
1037 let name = trait_item.ident.name.to_string();
1038 let qualname = format!("::{}",
1039 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(trait_item.id)));
1041 if !self.span.filter_generated(trait_item.ident.span) {
1042 let span = self.span_from_span(trait_item.ident.span);
1043 let id = id_from_node_id(trait_item.id, &self.save_ctxt);
1045 self.dumper.dump_def(
1051 kind: DefKind::Type,
1056 value: self.span.snippet(trait_item.span),
1057 parent: Some(id_from_def_id(trait_id)),
1060 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1061 sig: sig::assoc_type_signature(
1065 default_ty.as_ref().map(|ty| &**ty),
1068 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1073 if let &Some(ref default_ty) = default_ty {
1074 self.visit_ty(default_ty)
1077 ast::TraitItemKind::Macro(_) => {}
1081 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1082 self.process_macro_use(impl_item.span);
1083 match impl_item.node {
1084 ast::ImplItemKind::Const(ref ty, ref expr) => {
1085 self.process_assoc_const(
1091 impl_item.vis.clone(),
1095 ast::ImplItemKind::Method(ref sig, ref body) => {
1096 self.process_method(
1101 &impl_item.generics,
1102 impl_item.vis.clone(),
1106 ast::ImplItemKind::TyAlias(ref ty) => {
1107 // FIXME: uses of the assoc type should ideally point to this
1108 // 'def' and the name here should be a ref to the def in the
1112 ast::ImplItemKind::OpaqueTy(ref bounds) => {
1113 // FIXME: uses of the assoc type should ideally point to this
1114 // 'def' and the name here should be a ref to the def in the
1116 for bound in bounds.iter() {
1117 if let ast::GenericBound::Trait(trait_ref, _) = bound {
1118 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1122 ast::ImplItemKind::Macro(_) => {}
1126 /// Dumps imports in a use tree recursively.
1128 /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1129 /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1130 /// ID and path. `root_item` is the topmost use tree in the hierarchy.
1132 /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1133 /// each child use tree is dumped recursively.
1134 fn process_use_tree(&mut self,
1135 use_tree: &'l ast::UseTree,
1137 root_item: &'l ast::Item,
1138 prefix: &ast::Path) {
1139 let path = &use_tree.prefix;
1141 // The access is calculated using the current tree ID, but with the root tree's visibility
1142 // (since nested trees don't have their own visibility).
1143 let hir_id = self.tcx.hir().node_to_hir_id(id);
1144 let access = access_from!(self.save_ctxt, root_item, hir_id);
1146 // The parent `DefId` of a given use tree is always the enclosing item.
1147 let parent = self.save_ctxt.tcx.hir().opt_local_def_id_from_node_id(id)
1148 .and_then(|id| self.save_ctxt.tcx.parent(id))
1149 .map(id_from_def_id);
1151 match use_tree.kind {
1152 ast::UseTreeKind::Simple(alias, ..) => {
1153 let ident = use_tree.ident();
1154 let path = ast::Path {
1155 segments: prefix.segments
1157 .chain(path.segments.iter())
1163 let sub_span = path.segments.last().unwrap().ident.span;
1164 if !self.span.filter_generated(sub_span) {
1165 let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id));
1166 let alias_span = alias.map(|i| self.span_from_span(i.span));
1167 let span = self.span_from_span(sub_span);
1168 self.dumper.import(&access, Import {
1169 kind: ImportKind::Use,
1173 name: ident.to_string(),
1174 value: String::new(),
1177 self.write_sub_paths_truncated(&path);
1180 ast::UseTreeKind::Glob => {
1181 let path = ast::Path {
1182 segments: prefix.segments
1184 .chain(path.segments.iter())
1190 // Make a comma-separated list of names of imported modules.
1191 let def_id = self.tcx.hir().local_def_id_from_node_id(id);
1192 let names = self.tcx.names_imported_by_glob_use(def_id);
1193 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1195 // Otherwise it's a span with wrong macro expansion info, which
1196 // we don't want to track anyway, since it's probably macro-internal `use`
1197 if let Some(sub_span) =
1198 self.span.sub_span_of_token(use_tree.span, token::BinOp(token::Star))
1200 if !self.span.filter_generated(use_tree.span) {
1201 let span = self.span_from_span(sub_span);
1203 self.dumper.import(&access, Import {
1204 kind: ImportKind::GlobUse,
1208 name: "*".to_owned(),
1209 value: names.join(", "),
1212 self.write_sub_paths(&path);
1216 ast::UseTreeKind::Nested(ref nested_items) => {
1217 let prefix = ast::Path {
1218 segments: prefix.segments
1220 .chain(path.segments.iter())
1225 for &(ref tree, id) in nested_items {
1226 self.process_use_tree(tree, id, root_item, &prefix);
1232 fn process_bounds(&mut self, bounds: &'l ast::GenericBounds) {
1233 for bound in bounds {
1234 if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1235 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1241 impl<'l, 'tcx> Visitor<'l> for DumpVisitor<'l, 'tcx> {
1242 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1243 // Since we handle explicit modules ourselves in visit_item, this should
1244 // only get called for the root module of a crate.
1245 assert_eq!(id, ast::CRATE_NODE_ID);
1247 let qualname = format!("::{}",
1248 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
1250 let cm = self.tcx.sess.source_map();
1251 let filename = cm.span_to_filename(span);
1252 let data_id = id_from_node_id(id, &self.save_ctxt);
1253 let children = m.items
1255 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
1257 let span = self.span_from_span(span);
1259 self.dumper.dump_def(
1267 name: String::new(),
1270 value: filename.to_string(),
1274 docs: self.save_ctxt.docs_for_attrs(attrs),
1276 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1279 visit::walk_mod(self, m);
1282 fn visit_item(&mut self, item: &'l ast::Item) {
1283 use syntax::ast::ItemKind::*;
1284 self.process_macro_use(item.span);
1286 Use(ref use_tree) => {
1287 let prefix = ast::Path {
1291 self.process_use_tree(use_tree, item.id, item, &prefix);
1294 let name_span = item.ident.span;
1295 if !self.span.filter_generated(name_span) {
1296 let span = self.span_from_span(name_span);
1297 let parent = self.save_ctxt.tcx.hir().opt_local_def_id_from_node_id(item.id)
1298 .and_then(|id| self.save_ctxt.tcx.parent(id))
1299 .map(id_from_def_id);
1306 kind: ImportKind::ExternCrate,
1310 name: item.ident.to_string(),
1311 value: String::new(),
1317 Fn(ref decl, .., ref ty_params, ref body) => {
1318 self.process_fn(item, &decl, ty_params, &body)
1320 Static(ref typ, _, ref expr) => self.process_static_or_const_item(item, typ, expr),
1321 Const(ref typ, ref expr) => self.process_static_or_const_item(item, &typ, &expr),
1322 Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1323 self.process_struct(item, def, ty_params)
1325 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1326 Impl(.., ref ty_params, ref trait_ref, ref typ, ref impl_items) => {
1327 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1329 Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1330 self.process_trait(item, generics, trait_refs, methods)
1333 self.process_mod(item);
1334 visit::walk_mod(self, m);
1336 TyAlias(ref ty, ref ty_params) => {
1337 let qualname = format!("::{}",
1338 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
1339 let value = ty_to_string(&ty);
1340 if !self.span.filter_generated(item.ident.span) {
1341 let span = self.span_from_span(item.ident.span);
1342 let id = id_from_node_id(item.id, &self.save_ctxt);
1343 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1345 self.dumper.dump_def(
1346 &access_from!(self.save_ctxt, item, hir_id),
1348 kind: DefKind::Type,
1351 name: item.ident.to_string(),
1352 qualname: qualname.clone(),
1357 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1358 sig: sig::item_signature(item, &self.save_ctxt),
1359 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1365 self.process_generic_params(ty_params, &qualname, item.id);
1367 OpaqueTy(ref _bounds, ref ty_params) => {
1368 let qualname = format!("::{}",
1369 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
1370 // FIXME do something with _bounds
1371 let value = String::new();
1372 if !self.span.filter_generated(item.ident.span) {
1373 let span = self.span_from_span(item.ident.span);
1374 let id = id_from_node_id(item.id, &self.save_ctxt);
1375 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1377 self.dumper.dump_def(
1378 &access_from!(self.save_ctxt, item, hir_id),
1380 kind: DefKind::Type,
1383 name: item.ident.to_string(),
1384 qualname: qualname.clone(),
1389 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1390 sig: sig::item_signature(item, &self.save_ctxt),
1391 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1396 self.process_generic_params(ty_params, &qualname, item.id);
1399 _ => visit::walk_item(self, item),
1403 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1404 for param in &generics.params {
1406 ast::GenericParamKind::Lifetime { .. } => {}
1407 ast::GenericParamKind::Type { ref default, .. } => {
1408 self.process_bounds(¶m.bounds);
1409 if let Some(ref ty) = default {
1413 ast::GenericParamKind::Const { ref ty } => {
1414 self.process_bounds(¶m.bounds);
1419 for pred in &generics.where_clause.predicates {
1420 if let ast::WherePredicate::BoundPredicate(ref wbp) = *pred {
1421 self.process_bounds(&wbp.bounds);
1422 self.visit_ty(&wbp.bounded_ty);
1427 fn visit_ty(&mut self, t: &'l ast::Ty) {
1428 self.process_macro_use(t.span);
1430 ast::TyKind::Path(_, ref path) => {
1431 if generated_code(t.span) {
1435 if let Some(id) = self.lookup_def_id(t.id) {
1436 let sub_span = path.segments.last().unwrap().ident.span;
1437 let span = self.span_from_span(sub_span);
1438 self.dumper.dump_ref(Ref {
1439 kind: RefKind::Type,
1441 ref_id: id_from_def_id(id),
1445 self.write_sub_paths_truncated(path);
1446 visit::walk_path(self, path);
1448 ast::TyKind::Array(ref element, ref length) => {
1449 self.visit_ty(element);
1450 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1452 _ => visit::walk_ty(self, t),
1456 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1457 debug!("visit_expr {:?}", ex.node);
1458 self.process_macro_use(ex.span);
1460 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1461 let expr_hir_id = self.save_ctxt.tcx.hir().node_to_hir_id(ex.id);
1462 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(expr_hir_id);
1463 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1464 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1466 visit::walk_expr(self, ex);
1470 let node_id = self.save_ctxt.tcx.hir().hir_to_node_id(hir_expr.hir_id);
1471 let res = self.save_ctxt.get_path_res(node_id);
1472 self.process_struct_lit(ex, path, fields, adt.variant_of_res(res), base)
1474 ast::ExprKind::MethodCall(ref seg, ref args) => self.process_method_call(ex, seg, args),
1475 ast::ExprKind::Field(ref sub_ex, _) => {
1476 self.visit_expr(&sub_ex);
1478 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1479 down_cast_data!(field_data, RefData, ex.span);
1480 if !generated_code(ex.span) {
1481 self.dumper.dump_ref(field_data);
1485 ast::ExprKind::Closure(_, _, _, ref decl, ref body, _fn_decl_span) => {
1486 let id = format!("${}", ex.id);
1488 // walk arg and return types
1489 for arg in &decl.inputs {
1490 self.visit_ty(&arg.ty);
1493 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1494 self.visit_ty(&ret_ty);
1498 self.nest_tables(ex.id, |v| {
1499 v.process_formals(&decl.inputs, &id);
1503 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1504 self.process_var_decl(pattern);
1505 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1506 self.visit_expr(subexpression);
1507 visit::walk_block(self, block);
1509 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1510 self.process_var_decl(pat);
1511 self.visit_expr(scrutinee);
1513 ast::ExprKind::Repeat(ref element, ref count) => {
1514 self.visit_expr(element);
1515 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1517 // In particular, we take this branch for call and path expressions,
1518 // where we'll index the idents involved just by continuing to walk.
1519 _ => visit::walk_expr(self, ex),
1523 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1524 // These shouldn't exist in the AST at this point, log a span bug.
1527 "macro invocation should have been expanded out of AST"
1531 fn visit_pat(&mut self, p: &'l ast::Pat) {
1532 self.process_macro_use(p.span);
1533 self.process_pat(p);
1536 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1537 self.process_var_decl(&arm.pat);
1538 if let Some(expr) = &arm.guard {
1539 self.visit_expr(expr);
1541 self.visit_expr(&arm.body);
1544 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1545 self.process_path(id, p);
1548 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1549 self.process_macro_use(s.span);
1550 visit::walk_stmt(self, s)
1553 fn visit_local(&mut self, l: &'l ast::Local) {
1554 self.process_macro_use(l.span);
1555 self.process_var_decl(&l.pat);
1557 // Just walk the initialiser and type (don't want to walk the pattern again).
1558 walk_list!(self, visit_ty, &l.ty);
1559 walk_list!(self, visit_expr, &l.init);
1562 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1563 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1564 let access = access_from!(self.save_ctxt, item, hir_id);
1567 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1568 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1569 down_cast_data!(fn_data, DefData, item.span);
1571 self.process_generic_params(generics, &fn_data.qualname, item.id);
1572 self.dumper.dump_def(&access, fn_data);
1575 for arg in &decl.inputs {
1576 self.visit_ty(&arg.ty);
1579 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1580 self.visit_ty(&ret_ty);
1583 ast::ForeignItemKind::Static(ref ty, _) => {
1584 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1585 down_cast_data!(var_data, DefData, item.span);
1586 self.dumper.dump_def(&access, var_data);
1591 ast::ForeignItemKind::Ty => {
1592 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1593 down_cast_data!(var_data, DefData, item.span);
1594 self.dumper.dump_def(&access, var_data);
1597 ast::ForeignItemKind::Macro(..) => {}