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);
119 let tables = if self.tcx.has_typeck_tables(item_def_id) {
120 self.tcx.typeck_tables_of(item_def_id)
122 self.save_ctxt.empty_tables
125 let old_tables = self.save_ctxt.tables;
126 self.save_ctxt.tables = tables;
128 self.save_ctxt.tables = old_tables;
131 fn span_from_span(&self, span: Span) -> SpanData {
132 self.save_ctxt.span_from_span(span)
135 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
136 self.save_ctxt.lookup_def_id(ref_id)
139 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
140 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
141 let crate_root = source_file.map(|source_file| {
142 let source_file = Path::new(source_file);
143 match source_file.file_name() {
144 Some(_) => source_file.parent().unwrap().display(),
145 None => source_file.display(),
149 let data = CratePreludeData {
150 crate_id: GlobalCrateId {
152 disambiguator: self.tcx
154 .local_crate_disambiguator()
158 crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
159 external_crates: self.save_ctxt.get_external_crates(),
160 span: self.span_from_span(krate.span),
163 self.dumper.crate_prelude(data);
166 pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
167 // Apply possible `remap-path-prefix` remapping to the input source file
168 // (and don't include remapping args anymore)
169 let (program, arguments) = {
170 let remap_arg_indices = {
171 let mut indices = FxHashSet::default();
172 // Args are guaranteed to be valid UTF-8 (checked early)
173 for (i, e) in env::args().enumerate() {
174 if e.starts_with("--remap-path-prefix=") {
176 } else if e == "--remap-path-prefix" {
178 indices.insert(i + 1);
184 let mut args = env::args()
186 .filter(|(i, _)| !remap_arg_indices.contains(i))
189 Input::File(ref path) if path == Path::new(&arg) => {
190 let mapped = &self.tcx.sess.local_crate_source_file;
201 (args.next().unwrap(), args.collect())
204 let data = CompilationOptions {
205 directory: self.tcx.sess.working_dir.0.clone(),
208 output: self.save_ctxt.compilation_output(crate_name),
211 self.dumper.compilation_opts(data);
214 fn write_sub_paths(&mut self, path: &ast::Path) {
215 for seg in &path.segments {
216 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
217 self.dumper.dump_ref(data);
222 // As write_sub_paths, but does not process the last ident in the path (assuming it
223 // will be processed elsewhere). See note on write_sub_paths about global.
224 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
225 for seg in &path.segments[..path.segments.len() - 1] {
226 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
227 self.dumper.dump_ref(data);
232 fn process_formals(&mut self, formals: &'l [ast::Param], qualname: &str) {
234 self.visit_pat(&arg.pat);
235 let mut collector = PathCollector::new();
236 collector.visit_pat(&arg.pat);
238 for (id, ident, ..) in collector.collected_idents {
239 let hir_id = self.tcx.hir().node_to_hir_id(id);
240 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
241 Some(s) => s.to_string(),
244 if !self.span.filter_generated(ident.span) {
245 let id = id_from_node_id(id, &self.save_ctxt);
246 let span = self.span_from_span(ident.span);
248 self.dumper.dump_def(
254 kind: DefKind::Local,
257 name: ident.to_string(),
258 qualname: format!("{}::{}", qualname, ident.to_string()),
275 sig: &'l ast::MethodSig,
276 body: Option<&'l ast::Block>,
279 generics: &'l ast::Generics,
280 vis: ast::Visibility,
283 debug!("process_method: {}:{}", id, ident);
285 let hir_id = self.tcx.hir().node_to_hir_id(id);
286 self.nest_tables(id, |v| {
287 if let Some(mut method_data) = v.save_ctxt.get_method_data(id, ident, span) {
288 v.process_formals(&sig.decl.inputs, &method_data.qualname);
289 v.process_generic_params(&generics, &method_data.qualname, id);
291 method_data.value = crate::make_signature(&sig.decl, &generics);
292 method_data.sig = sig::method_signature(id, ident, generics, sig, &v.save_ctxt);
294 v.dumper.dump_def(&access_from_vis!(v.save_ctxt, vis, hir_id), method_data);
297 // walk arg and return types
298 for arg in &sig.decl.inputs {
302 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
307 if let Some(body) = body {
313 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
314 let field_data = self.save_ctxt.get_field_data(field, parent_id);
315 if let Some(field_data) = field_data {
316 let hir_id = self.tcx.hir().node_to_hir_id(field.id);
317 self.dumper.dump_def(&access_from!(self.save_ctxt, field, hir_id), field_data);
321 // Dump generic params bindings, then visit_generics
322 fn process_generic_params(
324 generics: &'l ast::Generics,
328 for param in &generics.params {
330 ast::GenericParamKind::Lifetime { .. } => {}
331 ast::GenericParamKind::Type { .. } => {
332 let param_ss = param.ident.span;
333 let name = escape(self.span.snippet(param_ss));
334 // Append $id to name to make sure each one is unique.
335 let qualname = format!("{}::{}${}", prefix, name, id);
336 if !self.span.filter_generated(param_ss) {
337 let id = id_from_node_id(param.id, &self.save_ctxt);
338 let span = self.span_from_span(param_ss);
340 self.dumper.dump_def(
351 value: String::new(),
362 ast::GenericParamKind::Const { .. } => {}
365 self.visit_generics(generics);
371 decl: &'l ast::FnDecl,
372 ty_params: &'l ast::Generics,
373 body: &'l ast::Block,
375 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
376 self.nest_tables(item.id, |v| {
377 if let Some(fn_data) = v.save_ctxt.get_item_data(item) {
378 down_cast_data!(fn_data, DefData, item.span);
379 v.process_formals(&decl.inputs, &fn_data.qualname);
380 v.process_generic_params(ty_params, &fn_data.qualname, item.id);
382 v.dumper.dump_def(&access_from!(v.save_ctxt, item, hir_id), fn_data);
385 for arg in &decl.inputs {
389 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
390 if let ast::TyKind::ImplTrait(..) = ret_ty.kind {
391 // FIXME: Opaque type desugaring prevents us from easily
392 // processing trait bounds. See `visit_ty` for more details.
398 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.kind {
478 ast::ItemKind::Struct(_, _) => DefKind::Struct,
479 ast::ItemKind::Union(_, _) => DefKind::Union,
483 let (value, fields) = match item.kind {
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 self.nest_tables(item.id, |v| {
536 for field in def.fields() {
537 v.process_struct_field_def(field, item.id);
538 v.visit_ty(&field.ty);
541 v.process_generic_params(ty_params, &qualname, item.id);
548 enum_definition: &'l ast::EnumDef,
549 ty_params: &'l ast::Generics,
551 let enum_data = self.save_ctxt.get_item_data(item);
552 let enum_data = match enum_data {
556 down_cast_data!(enum_data, DefData, item.span);
558 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
559 let access = access_from!(self.save_ctxt, item, hir_id);
561 for variant in &enum_definition.variants {
562 let name = variant.ident.name.to_string();
563 let qualname = format!("{}::{}", enum_data.qualname, name);
564 let name_span = variant.ident.span;
567 ast::VariantData::Struct(ref fields, ..) => {
568 let fields_str = fields
572 f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
576 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
577 if !self.span.filter_generated(name_span) {
578 let span = self.span_from_span(name_span);
579 let id = id_from_node_id(variant.id, &self.save_ctxt);
580 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
582 self.dumper.dump_def(
585 kind: DefKind::StructVariant,
594 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
595 sig: sig::variant_signature(variant, &self.save_ctxt),
596 attributes: lower_attributes(
597 variant.attrs.clone(),
605 let mut value = format!("{}::{}", enum_data.name, name);
606 if let &ast::VariantData::Tuple(ref fields, _) = v {
608 value.push_str(&fields
610 .map(|f| ty_to_string(&f.ty))
615 if !self.span.filter_generated(name_span) {
616 let span = self.span_from_span(name_span);
617 let id = id_from_node_id(variant.id, &self.save_ctxt);
618 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
620 self.dumper.dump_def(
623 kind: DefKind::TupleVariant,
632 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
633 sig: sig::variant_signature(variant, &self.save_ctxt),
634 attributes: lower_attributes(
635 variant.attrs.clone(),
645 for field in variant.data.fields() {
646 self.process_struct_field_def(field, variant.id);
647 self.visit_ty(&field.ty);
650 self.process_generic_params(ty_params, &enum_data.qualname, item.id);
651 self.dumper.dump_def(&access, enum_data);
657 generics: &'l ast::Generics,
658 trait_ref: &'l Option<ast::TraitRef>,
660 impl_items: &'l [ast::ImplItem],
662 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
663 if !self.span.filter_generated(item.span) {
664 if let super::Data::RelationData(rel, imp) = impl_data {
665 self.dumper.dump_relation(rel);
666 self.dumper.dump_impl(imp);
668 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
673 let map = &self.tcx.hir();
674 self.nest_tables(item.id, |v| {
676 if let &Some(ref trait_ref) = trait_ref {
677 v.process_path(trait_ref.ref_id, &trait_ref.path);
679 v.process_generic_params(generics, "", item.id);
680 for impl_item in impl_items {
681 v.process_impl_item(impl_item, map.local_def_id_from_node_id(item.id));
689 generics: &'l ast::Generics,
690 trait_refs: &'l ast::GenericBounds,
691 methods: &'l [ast::TraitItem],
693 let name = item.ident.to_string();
694 let qualname = format!("::{}",
695 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
696 let mut val = name.clone();
697 if !generics.params.is_empty() {
698 val.push_str(&generic_params_to_string(&generics.params));
700 if !trait_refs.is_empty() {
702 val.push_str(&bounds_to_string(trait_refs));
704 if !self.span.filter_generated(item.ident.span) {
705 let id = id_from_node_id(item.id, &self.save_ctxt);
706 let span = self.span_from_span(item.ident.span);
707 let children = methods
709 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
711 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
712 self.dumper.dump_def(
713 &access_from!(self.save_ctxt, item, hir_id),
715 kind: DefKind::Trait,
719 qualname: qualname.clone(),
724 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
725 sig: sig::item_signature(item, &self.save_ctxt),
726 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
732 for super_bound in trait_refs.iter() {
733 let trait_ref = match *super_bound {
734 ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
735 ast::GenericBound::Outlives(..) => continue,
738 let trait_ref = &trait_ref.trait_ref;
739 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
740 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
741 if !self.span.filter_generated(sub_span) {
742 let span = self.span_from_span(sub_span);
743 self.dumper.dump_ref(Ref {
746 ref_id: id_from_def_id(id),
749 self.dumper.dump_relation(Relation {
750 kind: RelationKind::SuperTrait,
752 from: id_from_def_id(id),
753 to: id_from_node_id(item.id, &self.save_ctxt),
759 // walk generics and methods
760 self.process_generic_params(generics, &qualname, item.id);
761 for method in methods {
762 let map = &self.tcx.hir();
763 self.process_trait_item(method, map.local_def_id_from_node_id(item.id))
767 // `item` is the module in question, represented as an item.
768 fn process_mod(&mut self, item: &ast::Item) {
769 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
770 down_cast_data!(mod_data, DefData, item.span);
771 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
772 self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), mod_data);
776 fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
777 let path_data = self.save_ctxt.get_path_data(id, path);
778 if let Some(path_data) = path_data {
779 self.dumper.dump_ref(path_data);
783 fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
784 if self.span.filter_generated(path.span) {
787 self.dump_path_ref(id, path);
790 for seg in &path.segments {
791 if let Some(ref generic_args) = seg.args {
792 match **generic_args {
793 ast::GenericArgs::AngleBracketed(ref data) => {
794 for arg in &data.args {
796 ast::GenericArg::Type(ty) => self.visit_ty(ty),
801 ast::GenericArgs::Parenthesized(ref data) => {
802 for t in &data.inputs {
805 if let Some(ref t) = data.output {
813 self.write_sub_paths_truncated(path);
816 fn process_struct_lit(
820 fields: &'l [ast::Field],
821 variant: &'l ty::VariantDef,
822 base: &'l Option<P<ast::Expr>>,
824 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
825 self.write_sub_paths_truncated(path);
826 down_cast_data!(struct_lit_data, RefData, ex.span);
827 if !generated_code(ex.span) {
828 self.dumper.dump_ref(struct_lit_data);
831 for field in fields {
832 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
833 self.dumper.dump_ref(field_data);
836 self.visit_expr(&field.expr)
840 walk_list!(self, visit_expr, base);
843 fn process_method_call(
846 seg: &'l ast::PathSegment,
847 args: &'l [P<ast::Expr>],
849 debug!("process_method_call {:?} {:?}", ex, ex.span);
850 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
851 down_cast_data!(mcd, RefData, ex.span);
852 if !generated_code(ex.span) {
853 self.dumper.dump_ref(mcd);
857 // Explicit types in the turbo-fish.
858 if let Some(ref generic_args) = seg.args {
859 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
860 for arg in &data.args {
862 ast::GenericArg::Type(ty) => self.visit_ty(ty),
869 // walk receiver and args
870 walk_list!(self, visit_expr, args);
873 fn process_pat(&mut self, p: &'l ast::Pat) {
875 PatKind::Struct(ref _path, ref fields, _) => {
876 // FIXME do something with _path?
877 let hir_id = self.tcx.hir().node_to_hir_id(p.id);
878 let adt = match self.save_ctxt.tables.node_type_opt(hir_id) {
879 Some(ty) => ty.ty_adt_def().unwrap(),
881 visit::walk_pat(self, p);
885 let variant = adt.variant_of_res(self.save_ctxt.get_path_res(p.id));
887 for field in fields {
888 if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
889 if !self.span.filter_generated(field.ident.span) {
890 let span = self.span_from_span(field.ident.span);
891 self.dumper.dump_ref(Ref {
892 kind: RefKind::Variable,
894 ref_id: id_from_def_id(variant.fields[index].did),
898 self.visit_pat(&field.pat);
901 _ => visit::walk_pat(self, p),
905 fn process_var_decl(&mut self, pat: &'l ast::Pat) {
906 // The pattern could declare multiple new vars,
907 // we must walk the pattern and collect them all.
908 let mut collector = PathCollector::new();
909 collector.visit_pat(&pat);
910 self.visit_pat(&pat);
912 // Process collected paths.
913 for (id, ident, _) in collector.collected_idents {
914 match self.save_ctxt.get_path_res(id) {
915 Res::Local(hir_id) => {
916 let id = self.tcx.hir().hir_to_node_id(hir_id);
917 let typ = self.save_ctxt.tables.node_type_opt(hir_id)
918 .map(|t| t.to_string())
919 .unwrap_or_default();
921 // Rust uses the id of the pattern for var lookups, so we'll use it too.
922 if !self.span.filter_generated(ident.span) {
923 let qualname = format!("{}${}", ident.to_string(), id);
924 let id = id_from_node_id(id, &self.save_ctxt);
925 let span = self.span_from_span(ident.span);
927 self.dumper.dump_def(
933 kind: DefKind::Local,
936 name: ident.to_string(),
949 Res::Def(HirDefKind::Ctor(..), _) |
950 Res::Def(HirDefKind::Const, _) |
951 Res::Def(HirDefKind::AssocConst, _) |
952 Res::Def(HirDefKind::Struct, _) |
953 Res::Def(HirDefKind::Variant, _) |
954 Res::Def(HirDefKind::TyAlias, _) |
955 Res::Def(HirDefKind::AssocTy, _) |
957 self.dump_path_ref(id, &ast::Path::from_ident(ident));
960 "unexpected definition kind when processing collected idents: {:?}",
966 for (id, ref path) in collector.collected_paths {
967 self.process_path(id, path);
971 /// Extracts macro use and definition information from the AST node defined
972 /// by the given NodeId, using the expansion information from the node's
975 /// If the span is not macro-generated, do nothing, else use callee and
976 /// callsite spans to record macro definition and use data, using the
977 /// mac_uses and mac_defs sets to prevent multiples.
978 fn process_macro_use(&mut self, _span: Span) {
979 // FIXME if we're not dumping the defs (see below), there is no point
980 // dumping refs either.
981 // let source_span = span.source_callsite();
982 // if !self.macro_calls.insert(source_span) {
986 // let data = match self.save_ctxt.get_macro_use_data(span) {
988 // Some(data) => data,
991 // self.dumper.macro_use(data);
993 // FIXME write the macro def
994 // let mut hasher = DefaultHasher::new();
995 // data.callee_span.hash(&mut hasher);
996 // let hash = hasher.finish();
997 // let qualname = format!("{}::{}", data.name, hash);
998 // Don't write macro definition for imported macros
999 // if !self.mac_defs.contains(&data.callee_span)
1000 // && !data.imported {
1001 // self.mac_defs.insert(data.callee_span);
1002 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1003 // self.dumper.macro_data(MacroData {
1005 // name: data.name.clone(),
1006 // qualname: qualname.clone(),
1007 // // FIXME where do macro docs come from?
1008 // docs: String::new(),
1009 // }.lower(self.tcx));
1014 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1015 self.process_macro_use(trait_item.span);
1016 let vis_span = trait_item.span.shrink_to_lo();
1017 match trait_item.kind {
1018 ast::TraitItemKind::Const(ref ty, ref expr) => {
1019 self.process_assoc_const(
1023 expr.as_ref().map(|e| &**e),
1025 respan(vis_span, ast::VisibilityKind::Public),
1029 ast::TraitItemKind::Method(ref sig, ref body) => {
1030 self.process_method(
1032 body.as_ref().map(|x| &**x),
1035 &trait_item.generics,
1036 respan(vis_span, ast::VisibilityKind::Public),
1040 ast::TraitItemKind::Type(ref bounds, ref default_ty) => {
1041 // FIXME do something with _bounds (for type refs)
1042 let name = trait_item.ident.name.to_string();
1043 let qualname = format!("::{}",
1044 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(trait_item.id)));
1046 if !self.span.filter_generated(trait_item.ident.span) {
1047 let span = self.span_from_span(trait_item.ident.span);
1048 let id = id_from_node_id(trait_item.id, &self.save_ctxt);
1050 self.dumper.dump_def(
1056 kind: DefKind::Type,
1061 value: self.span.snippet(trait_item.span),
1062 parent: Some(id_from_def_id(trait_id)),
1065 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1066 sig: sig::assoc_type_signature(
1070 default_ty.as_ref().map(|ty| &**ty),
1073 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1078 if let &Some(ref default_ty) = default_ty {
1079 self.visit_ty(default_ty)
1082 ast::TraitItemKind::Macro(_) => {}
1086 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1087 self.process_macro_use(impl_item.span);
1088 match impl_item.kind {
1089 ast::ImplItemKind::Const(ref ty, ref expr) => {
1090 self.process_assoc_const(
1096 impl_item.vis.clone(),
1100 ast::ImplItemKind::Method(ref sig, ref body) => {
1101 self.process_method(
1106 &impl_item.generics,
1107 impl_item.vis.clone(),
1111 ast::ImplItemKind::TyAlias(ref ty) => {
1112 // FIXME: uses of the assoc type should ideally point to this
1113 // 'def' and the name here should be a ref to the def in the
1117 ast::ImplItemKind::OpaqueTy(ref bounds) => {
1118 // FIXME: uses of the assoc type should ideally point to this
1119 // 'def' and the name here should be a ref to the def in the
1121 self.process_bounds(&bounds);
1123 ast::ImplItemKind::Macro(_) => {}
1127 /// Dumps imports in a use tree recursively.
1129 /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1130 /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1131 /// ID and path. `root_item` is the topmost use tree in the hierarchy.
1133 /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1134 /// each child use tree is dumped recursively.
1135 fn process_use_tree(&mut self,
1136 use_tree: &'l ast::UseTree,
1138 root_item: &'l ast::Item,
1139 prefix: &ast::Path) {
1140 let path = &use_tree.prefix;
1142 // The access is calculated using the current tree ID, but with the root tree's visibility
1143 // (since nested trees don't have their own visibility).
1144 let hir_id = self.tcx.hir().node_to_hir_id(id);
1145 let access = access_from!(self.save_ctxt, root_item, hir_id);
1147 // The parent `DefId` of a given use tree is always the enclosing item.
1148 let parent = self.save_ctxt.tcx.hir().opt_local_def_id_from_node_id(id)
1149 .and_then(|id| self.save_ctxt.tcx.parent(id))
1150 .map(id_from_def_id);
1152 match use_tree.kind {
1153 ast::UseTreeKind::Simple(alias, ..) => {
1154 let ident = use_tree.ident();
1155 let path = ast::Path {
1156 segments: prefix.segments
1158 .chain(path.segments.iter())
1164 let sub_span = path.segments.last().unwrap().ident.span;
1165 if !self.span.filter_generated(sub_span) {
1166 let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id));
1167 let alias_span = alias.map(|i| self.span_from_span(i.span));
1168 let span = self.span_from_span(sub_span);
1169 self.dumper.import(&access, Import {
1170 kind: ImportKind::Use,
1174 name: ident.to_string(),
1175 value: String::new(),
1178 self.write_sub_paths_truncated(&path);
1181 ast::UseTreeKind::Glob => {
1182 let path = ast::Path {
1183 segments: prefix.segments
1185 .chain(path.segments.iter())
1191 // Make a comma-separated list of names of imported modules.
1192 let def_id = self.tcx.hir().local_def_id_from_node_id(id);
1193 let names = self.tcx.names_imported_by_glob_use(def_id);
1194 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1196 // Otherwise it's a span with wrong macro expansion info, which
1197 // we don't want to track anyway, since it's probably macro-internal `use`
1198 if let Some(sub_span) =
1199 self.span.sub_span_of_token(use_tree.span, token::BinOp(token::Star))
1201 if !self.span.filter_generated(use_tree.span) {
1202 let span = self.span_from_span(sub_span);
1204 self.dumper.import(&access, Import {
1205 kind: ImportKind::GlobUse,
1209 name: "*".to_owned(),
1210 value: names.join(", "),
1213 self.write_sub_paths(&path);
1217 ast::UseTreeKind::Nested(ref nested_items) => {
1218 let prefix = ast::Path {
1219 segments: prefix.segments
1221 .chain(path.segments.iter())
1226 for &(ref tree, id) in nested_items {
1227 self.process_use_tree(tree, id, root_item, &prefix);
1233 fn process_bounds(&mut self, bounds: &'l ast::GenericBounds) {
1234 for bound in bounds {
1235 if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1236 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1242 impl<'l, 'tcx> Visitor<'l> for DumpVisitor<'l, 'tcx> {
1243 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1244 // Since we handle explicit modules ourselves in visit_item, this should
1245 // only get called for the root module of a crate.
1246 assert_eq!(id, ast::CRATE_NODE_ID);
1248 let qualname = format!("::{}",
1249 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
1251 let cm = self.tcx.sess.source_map();
1252 let filename = cm.span_to_filename(span);
1253 let data_id = id_from_node_id(id, &self.save_ctxt);
1254 let children = m.items
1256 .map(|i| id_from_node_id(i.id, &self.save_ctxt))
1258 let span = self.span_from_span(span);
1260 self.dumper.dump_def(
1268 name: String::new(),
1271 value: filename.to_string(),
1275 docs: self.save_ctxt.docs_for_attrs(attrs),
1277 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1280 visit::walk_mod(self, m);
1283 fn visit_item(&mut self, item: &'l ast::Item) {
1284 use syntax::ast::ItemKind::*;
1285 self.process_macro_use(item.span);
1287 Use(ref use_tree) => {
1288 let prefix = ast::Path {
1292 self.process_use_tree(use_tree, item.id, item, &prefix);
1295 let name_span = item.ident.span;
1296 if !self.span.filter_generated(name_span) {
1297 let span = self.span_from_span(name_span);
1298 let parent = self.save_ctxt.tcx.hir().opt_local_def_id_from_node_id(item.id)
1299 .and_then(|id| self.save_ctxt.tcx.parent(id))
1300 .map(id_from_def_id);
1307 kind: ImportKind::ExternCrate,
1311 name: item.ident.to_string(),
1312 value: String::new(),
1318 Fn(ref decl, .., ref ty_params, ref body) => {
1319 self.process_fn(item, &decl, ty_params, &body)
1321 Static(ref typ, _, ref expr) => self.process_static_or_const_item(item, typ, expr),
1322 Const(ref typ, ref expr) => self.process_static_or_const_item(item, &typ, &expr),
1323 Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1324 self.process_struct(item, def, ty_params)
1326 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1327 Impl(.., ref ty_params, ref trait_ref, ref typ, ref impl_items) => {
1328 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1330 Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1331 self.process_trait(item, generics, trait_refs, methods)
1334 self.process_mod(item);
1335 visit::walk_mod(self, m);
1337 TyAlias(ref ty, ref ty_params) => {
1338 let qualname = format!("::{}",
1339 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
1340 let value = ty_to_string(&ty);
1341 if !self.span.filter_generated(item.ident.span) {
1342 let span = self.span_from_span(item.ident.span);
1343 let id = id_from_node_id(item.id, &self.save_ctxt);
1344 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1346 self.dumper.dump_def(
1347 &access_from!(self.save_ctxt, item, hir_id),
1349 kind: DefKind::Type,
1352 name: item.ident.to_string(),
1353 qualname: qualname.clone(),
1358 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1359 sig: sig::item_signature(item, &self.save_ctxt),
1360 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1366 self.process_generic_params(ty_params, &qualname, item.id);
1368 OpaqueTy(ref bounds, ref ty_params) => {
1369 let qualname = format!("::{}",
1370 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
1372 let value = String::new();
1373 if !self.span.filter_generated(item.ident.span) {
1374 let span = self.span_from_span(item.ident.span);
1375 let id = id_from_node_id(item.id, &self.save_ctxt);
1376 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1378 self.dumper.dump_def(
1379 &access_from!(self.save_ctxt, item, hir_id),
1381 kind: DefKind::Type,
1384 name: item.ident.to_string(),
1385 qualname: qualname.clone(),
1390 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1391 sig: sig::item_signature(item, &self.save_ctxt),
1392 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1397 self.process_bounds(bounds);
1398 self.process_generic_params(ty_params, &qualname, item.id);
1401 _ => visit::walk_item(self, item),
1405 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1406 for param in &generics.params {
1408 ast::GenericParamKind::Lifetime { .. } => {}
1409 ast::GenericParamKind::Type { ref default, .. } => {
1410 self.process_bounds(¶m.bounds);
1411 if let Some(ref ty) = default {
1415 ast::GenericParamKind::Const { ref ty } => {
1416 self.process_bounds(¶m.bounds);
1421 for pred in &generics.where_clause.predicates {
1422 if let ast::WherePredicate::BoundPredicate(ref wbp) = *pred {
1423 self.process_bounds(&wbp.bounds);
1424 self.visit_ty(&wbp.bounded_ty);
1429 fn visit_ty(&mut self, t: &'l ast::Ty) {
1430 self.process_macro_use(t.span);
1432 ast::TyKind::Path(_, ref path) => {
1433 if generated_code(t.span) {
1437 if let Some(id) = self.lookup_def_id(t.id) {
1438 let sub_span = path.segments.last().unwrap().ident.span;
1439 let span = self.span_from_span(sub_span);
1440 self.dumper.dump_ref(Ref {
1441 kind: RefKind::Type,
1443 ref_id: id_from_def_id(id),
1447 self.write_sub_paths_truncated(path);
1448 visit::walk_path(self, path);
1450 ast::TyKind::Array(ref element, ref length) => {
1451 self.visit_ty(element);
1452 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1454 ast::TyKind::ImplTrait(id, ref bounds) => {
1455 // FIXME: As of writing, the opaque type lowering introduces
1456 // another DefPath scope/segment (used to declare the resulting
1457 // opaque type item).
1458 // However, the synthetic scope does *not* have associated
1459 // typeck tables, which means we can't nest it and we fire an
1460 // assertion when resolving the qualified type paths in trait
1462 // This will panic if called on return type `impl Trait`, which
1463 // we guard against in `process_fn`.
1464 self.nest_tables(id, |v| v.process_bounds(bounds));
1466 _ => visit::walk_ty(self, t),
1470 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1471 debug!("visit_expr {:?}", ex.kind);
1472 self.process_macro_use(ex.span);
1474 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1475 let expr_hir_id = self.save_ctxt.tcx.hir().node_to_hir_id(ex.id);
1476 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(expr_hir_id);
1477 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1478 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1480 visit::walk_expr(self, ex);
1484 let node_id = self.save_ctxt.tcx.hir().hir_to_node_id(hir_expr.hir_id);
1485 let res = self.save_ctxt.get_path_res(node_id);
1486 self.process_struct_lit(ex, path, fields, adt.variant_of_res(res), base)
1488 ast::ExprKind::MethodCall(ref seg, ref args) => self.process_method_call(ex, seg, args),
1489 ast::ExprKind::Field(ref sub_ex, _) => {
1490 self.visit_expr(&sub_ex);
1492 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1493 down_cast_data!(field_data, RefData, ex.span);
1494 if !generated_code(ex.span) {
1495 self.dumper.dump_ref(field_data);
1499 ast::ExprKind::Closure(_, _, _, ref decl, ref body, _fn_decl_span) => {
1500 let id = format!("${}", ex.id);
1502 // walk arg and return types
1503 for arg in &decl.inputs {
1504 self.visit_ty(&arg.ty);
1507 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1508 self.visit_ty(&ret_ty);
1512 self.nest_tables(ex.id, |v| {
1513 v.process_formals(&decl.inputs, &id);
1517 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1518 self.process_var_decl(pattern);
1519 debug!("for loop, walk sub-expr: {:?}", subexpression.kind);
1520 self.visit_expr(subexpression);
1521 visit::walk_block(self, block);
1523 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1524 self.process_var_decl(pat);
1525 self.visit_expr(scrutinee);
1527 ast::ExprKind::Repeat(ref element, ref count) => {
1528 self.visit_expr(element);
1529 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1531 // In particular, we take this branch for call and path expressions,
1532 // where we'll index the idents involved just by continuing to walk.
1533 _ => visit::walk_expr(self, ex),
1537 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1538 // These shouldn't exist in the AST at this point, log a span bug.
1541 "macro invocation should have been expanded out of AST"
1545 fn visit_pat(&mut self, p: &'l ast::Pat) {
1546 self.process_macro_use(p.span);
1547 self.process_pat(p);
1550 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1551 self.process_var_decl(&arm.pat);
1552 if let Some(expr) = &arm.guard {
1553 self.visit_expr(expr);
1555 self.visit_expr(&arm.body);
1558 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1559 self.process_path(id, p);
1562 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1563 self.process_macro_use(s.span);
1564 visit::walk_stmt(self, s)
1567 fn visit_local(&mut self, l: &'l ast::Local) {
1568 self.process_macro_use(l.span);
1569 self.process_var_decl(&l.pat);
1571 // Just walk the initialiser and type (don't want to walk the pattern again).
1572 walk_list!(self, visit_ty, &l.ty);
1573 walk_list!(self, visit_expr, &l.init);
1576 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1577 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1578 let access = access_from!(self.save_ctxt, item, hir_id);
1581 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1582 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1583 down_cast_data!(fn_data, DefData, item.span);
1585 self.process_generic_params(generics, &fn_data.qualname, item.id);
1586 self.dumper.dump_def(&access, fn_data);
1589 for arg in &decl.inputs {
1590 self.visit_ty(&arg.ty);
1593 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1594 self.visit_ty(&ret_ty);
1597 ast::ForeignItemKind::Static(ref ty, _) => {
1598 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1599 down_cast_data!(var_data, DefData, item.span);
1600 self.dumper.dump_def(&access, var_data);
1605 ast::ForeignItemKind::Ty => {
1606 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1607 down_cast_data!(var_data, DefData, item.span);
1608 self.dumper.dump_def(&access, var_data);
1611 ast::ForeignItemKind::Macro(..) => {}