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::session::config::Input;
18 use rustc::ty::{self, DefIdTree, TyCtxt};
19 use rustc_ast_pretty::pprust::{bounds_to_string, generic_params_to_string, ty_to_string};
20 use rustc_data_structures::fx::FxHashSet;
21 use rustc_hir::def::{DefKind as HirDefKind, Res};
22 use rustc_hir::def_id::DefId;
23 use rustc_span::source_map::{respan, DUMMY_SP};
25 use syntax::ast::{self, Attribute, NodeId, PatKind};
28 use syntax::visit::{self, Visitor};
29 use syntax::walk_list;
34 use crate::dumper::{Access, Dumper};
36 use crate::span_utils::SpanUtils;
38 escape, generated_code, id_from_def_id, id_from_node_id, lower_attributes, PathCollector,
43 CompilationOptions, CratePreludeData, Def, DefKind, GlobalCrateId, Import, ImportKind, Ref,
44 RefKind, Relation, RelationKind, SpanData,
47 use log::{debug, error};
49 macro_rules! down_cast_data {
50 ($id:ident, $kind:ident, $sp:expr) => {
51 let $id = if let super::Data::$kind(data) = $id {
54 span_bug!($sp, "unexpected data kind: {:?}", $id);
59 macro_rules! access_from {
60 ($save_ctxt:expr, $item:expr, $id:expr) => {
62 public: $item.vis.node.is_pub(),
63 reachable: $save_ctxt.access_levels.is_reachable($id),
68 macro_rules! access_from_vis {
69 ($save_ctxt:expr, $vis:expr, $id:expr) => {
70 Access { public: $vis.node.is_pub(), reachable: $save_ctxt.access_levels.is_reachable($id) }
74 pub struct DumpVisitor<'l, 'tcx> {
75 pub save_ctxt: SaveContext<'l, 'tcx>,
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> DumpVisitor<'l, 'tcx> {
89 pub fn new(save_ctxt: SaveContext<'l, 'tcx>) -> DumpVisitor<'l, 'tcx> {
90 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
91 let dumper = Dumper::new(save_ctxt.config.clone());
97 // mac_defs: FxHashSet::default(),
98 // macro_calls: FxHashSet::default(),
102 pub fn analysis(&self) -> &rls_data::Analysis {
103 self.dumper.analysis()
106 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
108 F: FnOnce(&mut Self),
110 let item_def_id = self.tcx.hir().local_def_id_from_node_id(item_id);
112 let tables = if self.tcx.has_typeck_tables(item_def_id) {
113 self.tcx.typeck_tables_of(item_def_id)
115 self.save_ctxt.empty_tables
118 let old_tables = self.save_ctxt.tables;
119 self.save_ctxt.tables = tables;
121 self.save_ctxt.tables = old_tables;
124 fn span_from_span(&self, span: Span) -> SpanData {
125 self.save_ctxt.span_from_span(span)
128 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
129 self.save_ctxt.lookup_def_id(ref_id)
132 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
133 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
134 let crate_root = source_file.map(|source_file| {
135 let source_file = Path::new(source_file);
136 match source_file.file_name() {
137 Some(_) => source_file.parent().unwrap().display(),
138 None => source_file.display(),
143 let data = CratePreludeData {
144 crate_id: GlobalCrateId {
149 .local_crate_disambiguator()
153 crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
154 external_crates: self.save_ctxt.get_external_crates(),
155 span: self.span_from_span(krate.span),
158 self.dumper.crate_prelude(data);
161 pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
162 // Apply possible `remap-path-prefix` remapping to the input source file
163 // (and don't include remapping args anymore)
164 let (program, arguments) = {
165 let remap_arg_indices = {
166 let mut indices = FxHashSet::default();
167 // Args are guaranteed to be valid UTF-8 (checked early)
168 for (i, e) in env::args().enumerate() {
169 if e.starts_with("--remap-path-prefix=") {
171 } else if e == "--remap-path-prefix" {
173 indices.insert(i + 1);
179 let mut args = env::args()
181 .filter(|(i, _)| !remap_arg_indices.contains(i))
182 .map(|(_, arg)| match input {
183 Input::File(ref path) if path == Path::new(&arg) => {
184 let mapped = &self.tcx.sess.local_crate_source_file;
185 mapped.as_ref().unwrap().to_string_lossy().into()
190 (args.next().unwrap(), args.collect())
193 let data = CompilationOptions {
194 directory: self.tcx.sess.working_dir.0.clone(),
197 output: self.save_ctxt.compilation_output(crate_name),
200 self.dumper.compilation_opts(data);
203 fn write_sub_paths(&mut self, path: &ast::Path) {
204 for seg in &path.segments {
205 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
206 self.dumper.dump_ref(data);
211 // As write_sub_paths, but does not process the last ident in the path (assuming it
212 // will be processed elsewhere). See note on write_sub_paths about global.
213 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
214 for seg in &path.segments[..path.segments.len() - 1] {
215 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
216 self.dumper.dump_ref(data);
221 fn process_formals(&mut self, formals: &'l [ast::Param], qualname: &str) {
223 self.visit_pat(&arg.pat);
224 let mut collector = PathCollector::new();
225 collector.visit_pat(&arg.pat);
227 for (id, ident, ..) in collector.collected_idents {
228 let hir_id = self.tcx.hir().node_to_hir_id(id);
229 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
230 Some(s) => s.to_string(),
233 if !self.span.filter_generated(ident.span) {
234 let id = id_from_node_id(id, &self.save_ctxt);
235 let span = self.span_from_span(ident.span);
237 self.dumper.dump_def(
238 &Access { public: false, reachable: false },
240 kind: DefKind::Local,
243 name: ident.to_string(),
244 qualname: format!("{}::{}", qualname, ident.to_string()),
262 body: Option<&'l ast::Block>,
265 generics: &'l ast::Generics,
266 vis: ast::Visibility,
269 debug!("process_method: {}:{}", id, ident);
271 let hir_id = self.tcx.hir().node_to_hir_id(id);
272 self.nest_tables(id, |v| {
273 if let Some(mut method_data) = v.save_ctxt.get_method_data(id, ident, span) {
274 v.process_formals(&sig.decl.inputs, &method_data.qualname);
275 v.process_generic_params(&generics, &method_data.qualname, id);
277 method_data.value = crate::make_signature(&sig.decl, &generics);
278 method_data.sig = sig::method_signature(id, ident, generics, sig, &v.save_ctxt);
280 v.dumper.dump_def(&access_from_vis!(v.save_ctxt, vis, hir_id), method_data);
283 // walk arg and return types
284 for arg in &sig.decl.inputs {
288 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
289 // In async functions, return types are desugared and redefined
290 // as an `impl Trait` existential type. Because of this, to match
291 // the definition paths when resolving nested types we need to
292 // start walking from the newly-created definition.
293 match sig.header.asyncness {
294 ast::Async::Yes { return_impl_trait_id, .. } => {
295 v.nest_tables(return_impl_trait_id, |v| v.visit_ty(ret_ty))
297 _ => v.visit_ty(ret_ty),
302 if let Some(body) = body {
308 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
309 let field_data = self.save_ctxt.get_field_data(field, parent_id);
310 if let Some(field_data) = field_data {
311 let hir_id = self.tcx.hir().node_to_hir_id(field.id);
312 self.dumper.dump_def(&access_from!(self.save_ctxt, field, hir_id), field_data);
316 // Dump generic params bindings, then visit_generics
317 fn process_generic_params(&mut self, generics: &'l ast::Generics, prefix: &str, id: NodeId) {
318 for param in &generics.params {
320 ast::GenericParamKind::Lifetime { .. } => {}
321 ast::GenericParamKind::Type { .. } => {
322 let param_ss = param.ident.span;
323 let name = escape(self.span.snippet(param_ss));
324 // Append $id to name to make sure each one is unique.
325 let qualname = format!("{}::{}${}", prefix, name, id);
326 if !self.span.filter_generated(param_ss) {
327 let id = id_from_node_id(param.id, &self.save_ctxt);
328 let span = self.span_from_span(param_ss);
330 self.dumper.dump_def(
331 &Access { public: false, reachable: false },
338 value: String::new(),
349 ast::GenericParamKind::Const { .. } => {}
352 self.visit_generics(generics);
358 decl: &'l ast::FnDecl,
359 header: &'l ast::FnHeader,
360 ty_params: &'l ast::Generics,
361 body: Option<&'l ast::Block>,
363 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
364 self.nest_tables(item.id, |v| {
365 if let Some(fn_data) = v.save_ctxt.get_item_data(item) {
366 down_cast_data!(fn_data, DefData, item.span);
367 v.process_formals(&decl.inputs, &fn_data.qualname);
368 v.process_generic_params(ty_params, &fn_data.qualname, item.id);
370 v.dumper.dump_def(&access_from!(v.save_ctxt, item, hir_id), fn_data);
373 for arg in &decl.inputs {
377 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
378 if let ast::TyKind::ImplTrait(..) = ret_ty.kind {
379 // FIXME: Opaque type desugaring prevents us from easily
380 // processing trait bounds. See `visit_ty` for more details.
382 // In async functions, return types are desugared and redefined
383 // as an `impl Trait` existential type. Because of this, to match
384 // the definition paths when resolving nested types we need to
385 // start walking from the newly-created definition.
386 match header.asyncness {
387 ast::Async::Yes { return_impl_trait_id, .. } => {
388 v.nest_tables(return_impl_trait_id, |v| v.visit_ty(ret_ty))
390 _ => v.visit_ty(ret_ty),
395 walk_list!(v, visit_block, body);
399 fn process_static_or_const_item(
405 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
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, hir_id), var_data);
416 fn process_assoc_const(
421 expr: Option<&'l ast::Expr>,
423 vis: ast::Visibility,
424 attrs: &'l [Attribute],
427 format!("::{}", self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
429 if !self.span.filter_generated(ident.span) {
430 let sig = sig::assoc_const_signature(id, ident.name, typ, expr, &self.save_ctxt);
431 let span = self.span_from_span(ident.span);
432 let hir_id = self.tcx.hir().node_to_hir_id(id);
434 self.dumper.dump_def(
435 &access_from_vis!(self.save_ctxt, vis, hir_id),
437 kind: DefKind::Const,
438 id: id_from_node_id(id, &self.save_ctxt),
440 name: ident.name.to_string(),
442 value: ty_to_string(&typ),
443 parent: Some(id_from_def_id(parent_id)),
446 docs: self.save_ctxt.docs_for_attrs(attrs),
448 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
453 // walk type and init value
454 self.nest_tables(id, |v| {
456 if let Some(expr) = expr {
462 // FIXME tuple structs should generate tuple-specific data.
466 def: &'l ast::VariantData,
467 ty_params: &'l ast::Generics,
469 debug!("process_struct {:?} {:?}", item, item.span);
470 let name = item.ident.to_string();
471 let qualname = format!(
473 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id))
476 let kind = match item.kind {
477 ast::ItemKind::Struct(_, _) => DefKind::Struct,
478 ast::ItemKind::Union(_, _) => DefKind::Union,
482 let (value, fields) = match item.kind {
483 ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, ..), ..)
484 | ast::ItemKind::Union(ast::VariantData::Struct(ref fields, ..), ..) => {
485 let include_priv_fields = !self.save_ctxt.config.pub_only;
486 let fields_str = fields
489 .filter_map(|(i, f)| {
490 if include_priv_fields || f.vis.node.is_pub() {
491 f.ident.map(|i| i.to_string()).or_else(|| Some(i.to_string()))
498 let value = format!("{} {{ {} }}", name, fields_str);
499 (value, fields.iter().map(|f| id_from_node_id(f.id, &self.save_ctxt)).collect())
501 _ => (String::new(), vec![]),
504 if !self.span.filter_generated(item.ident.span) {
505 let span = self.span_from_span(item.ident.span);
506 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
507 self.dumper.dump_def(
508 &access_from!(self.save_ctxt, item, hir_id),
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 self.nest_tables(item.id, |v| {
527 for field in def.fields() {
528 v.process_struct_field_def(field, item.id);
529 v.visit_ty(&field.ty);
532 v.process_generic_params(ty_params, &qualname, item.id);
539 enum_definition: &'l ast::EnumDef,
540 ty_params: &'l ast::Generics,
542 let enum_data = self.save_ctxt.get_item_data(item);
543 let enum_data = match enum_data {
547 down_cast_data!(enum_data, DefData, item.span);
549 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
550 let access = access_from!(self.save_ctxt, item, hir_id);
552 for variant in &enum_definition.variants {
553 let name = variant.ident.name.to_string();
554 let qualname = format!("{}::{}", enum_data.qualname, name);
555 let name_span = variant.ident.span;
558 ast::VariantData::Struct(ref fields, ..) => {
559 let fields_str = fields
563 f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
567 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
568 if !self.span.filter_generated(name_span) {
569 let span = self.span_from_span(name_span);
570 let id = id_from_node_id(variant.id, &self.save_ctxt);
571 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
573 self.dumper.dump_def(
576 kind: DefKind::StructVariant,
585 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
586 sig: sig::variant_signature(variant, &self.save_ctxt),
587 attributes: lower_attributes(
588 variant.attrs.clone(),
596 let mut value = format!("{}::{}", enum_data.name, name);
597 if let &ast::VariantData::Tuple(ref fields, _) = v {
602 .map(|f| ty_to_string(&f.ty))
608 if !self.span.filter_generated(name_span) {
609 let span = self.span_from_span(name_span);
610 let id = id_from_node_id(variant.id, &self.save_ctxt);
611 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
613 self.dumper.dump_def(
616 kind: DefKind::TupleVariant,
625 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
626 sig: sig::variant_signature(variant, &self.save_ctxt),
627 attributes: lower_attributes(
628 variant.attrs.clone(),
637 for field in variant.data.fields() {
638 self.process_struct_field_def(field, variant.id);
639 self.visit_ty(&field.ty);
642 self.process_generic_params(ty_params, &enum_data.qualname, item.id);
643 self.dumper.dump_def(&access, enum_data);
649 generics: &'l ast::Generics,
650 trait_ref: &'l Option<ast::TraitRef>,
652 impl_items: &'l [P<ast::AssocItem>],
654 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
655 if !self.span.filter_generated(item.span) {
656 if let super::Data::RelationData(rel, imp) = impl_data {
657 self.dumper.dump_relation(rel);
658 self.dumper.dump_impl(imp);
660 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
665 let map = &self.tcx.hir();
666 self.nest_tables(item.id, |v| {
668 if let &Some(ref trait_ref) = trait_ref {
669 v.process_path(trait_ref.ref_id, &trait_ref.path);
671 v.process_generic_params(generics, "", item.id);
672 for impl_item in impl_items {
673 v.process_impl_item(impl_item, map.local_def_id_from_node_id(item.id));
681 generics: &'l ast::Generics,
682 trait_refs: &'l ast::GenericBounds,
683 methods: &'l [P<ast::AssocItem>],
685 let name = item.ident.to_string();
686 let qualname = format!(
688 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id))
690 let mut val = name.clone();
691 if !generics.params.is_empty() {
692 val.push_str(&generic_params_to_string(&generics.params));
694 if !trait_refs.is_empty() {
696 val.push_str(&bounds_to_string(trait_refs));
698 if !self.span.filter_generated(item.ident.span) {
699 let id = id_from_node_id(item.id, &self.save_ctxt);
700 let span = self.span_from_span(item.ident.span);
701 let children = methods.iter().map(|i| id_from_node_id(i.id, &self.save_ctxt)).collect();
702 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
703 self.dumper.dump_def(
704 &access_from!(self.save_ctxt, item, hir_id),
706 kind: DefKind::Trait,
710 qualname: qualname.clone(),
715 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
716 sig: sig::item_signature(item, &self.save_ctxt),
717 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
723 for super_bound in trait_refs.iter() {
724 let trait_ref = match *super_bound {
725 ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
726 ast::GenericBound::Outlives(..) => continue,
729 let trait_ref = &trait_ref.trait_ref;
730 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
731 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
732 if !self.span.filter_generated(sub_span) {
733 let span = self.span_from_span(sub_span);
734 self.dumper.dump_ref(Ref {
737 ref_id: id_from_def_id(id),
740 self.dumper.dump_relation(Relation {
741 kind: RelationKind::SuperTrait,
743 from: id_from_def_id(id),
744 to: id_from_node_id(item.id, &self.save_ctxt),
750 // walk generics and methods
751 self.process_generic_params(generics, &qualname, item.id);
752 for method in methods {
753 let map = &self.tcx.hir();
754 self.process_trait_item(method, map.local_def_id_from_node_id(item.id))
758 // `item` is the module in question, represented as an item.
759 fn process_mod(&mut self, item: &ast::Item) {
760 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
761 down_cast_data!(mod_data, DefData, item.span);
762 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
763 self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), mod_data);
767 fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
768 let path_data = self.save_ctxt.get_path_data(id, path);
769 if let Some(path_data) = path_data {
770 self.dumper.dump_ref(path_data);
774 fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
775 if self.span.filter_generated(path.span) {
778 self.dump_path_ref(id, path);
781 for seg in &path.segments {
782 if let Some(ref generic_args) = seg.args {
783 match **generic_args {
784 ast::GenericArgs::AngleBracketed(ref data) => {
785 for arg in &data.args {
786 if let ast::GenericArg::Type(ty) = arg {
791 ast::GenericArgs::Parenthesized(ref data) => {
792 for t in &data.inputs {
795 if let ast::FunctionRetTy::Ty(ty) = &data.output {
803 self.write_sub_paths_truncated(path);
806 fn process_struct_lit(
810 fields: &'l [ast::Field],
811 variant: &'l ty::VariantDef,
812 base: &'l Option<P<ast::Expr>>,
814 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
815 self.write_sub_paths_truncated(path);
816 down_cast_data!(struct_lit_data, RefData, ex.span);
817 if !generated_code(ex.span) {
818 self.dumper.dump_ref(struct_lit_data);
821 for field in fields {
822 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
823 self.dumper.dump_ref(field_data);
826 self.visit_expr(&field.expr)
830 walk_list!(self, visit_expr, base);
833 fn process_method_call(
836 seg: &'l ast::PathSegment,
837 args: &'l [P<ast::Expr>],
839 debug!("process_method_call {:?} {:?}", ex, ex.span);
840 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
841 down_cast_data!(mcd, RefData, ex.span);
842 if !generated_code(ex.span) {
843 self.dumper.dump_ref(mcd);
847 // Explicit types in the turbo-fish.
848 if let Some(ref generic_args) = seg.args {
849 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
850 for arg in &data.args {
852 ast::GenericArg::Type(ty) => self.visit_ty(ty),
859 // walk receiver and args
860 walk_list!(self, visit_expr, args);
863 fn process_pat(&mut self, p: &'l ast::Pat) {
865 PatKind::Struct(ref _path, ref fields, _) => {
866 // FIXME do something with _path?
867 let hir_id = self.tcx.hir().node_to_hir_id(p.id);
868 let adt = match self.save_ctxt.tables.node_type_opt(hir_id) {
869 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
871 visit::walk_pat(self, p);
875 let variant = adt.variant_of_res(self.save_ctxt.get_path_res(p.id));
877 for field in fields {
878 if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
879 if !self.span.filter_generated(field.ident.span) {
880 let span = self.span_from_span(field.ident.span);
881 self.dumper.dump_ref(Ref {
882 kind: RefKind::Variable,
884 ref_id: id_from_def_id(variant.fields[index].did),
888 self.visit_pat(&field.pat);
891 _ => visit::walk_pat(self, p),
895 fn process_var_decl(&mut self, pat: &'l ast::Pat) {
896 // The pattern could declare multiple new vars,
897 // we must walk the pattern and collect them all.
898 let mut collector = PathCollector::new();
899 collector.visit_pat(&pat);
900 self.visit_pat(&pat);
902 // Process collected paths.
903 for (id, ident, _) in collector.collected_idents {
904 match self.save_ctxt.get_path_res(id) {
905 Res::Local(hir_id) => {
906 let id = self.tcx.hir().hir_to_node_id(hir_id);
910 .node_type_opt(hir_id)
911 .map(|t| t.to_string())
912 .unwrap_or_default();
914 // Rust uses the id of the pattern for var lookups, so we'll use it too.
915 if !self.span.filter_generated(ident.span) {
916 let qualname = format!("{}${}", ident.to_string(), id);
917 let id = id_from_node_id(id, &self.save_ctxt);
918 let span = self.span_from_span(ident.span);
920 self.dumper.dump_def(
921 &Access { public: false, reachable: false },
923 kind: DefKind::Local,
926 name: ident.to_string(),
939 Res::Def(HirDefKind::Ctor(..), _)
940 | Res::Def(HirDefKind::Const, _)
941 | Res::Def(HirDefKind::AssocConst, _)
942 | Res::Def(HirDefKind::Struct, _)
943 | Res::Def(HirDefKind::Variant, _)
944 | Res::Def(HirDefKind::TyAlias, _)
945 | Res::Def(HirDefKind::AssocTy, _)
946 | Res::SelfTy(..) => {
947 self.dump_path_ref(id, &ast::Path::from_ident(ident));
950 error!("unexpected definition kind when processing collected idents: {:?}", def)
955 for (id, ref path) in collector.collected_paths {
956 self.process_path(id, path);
960 /// Extracts macro use and definition information from the AST node defined
961 /// by the given NodeId, using the expansion information from the node's
964 /// If the span is not macro-generated, do nothing, else use callee and
965 /// callsite spans to record macro definition and use data, using the
966 /// mac_uses and mac_defs sets to prevent multiples.
967 fn process_macro_use(&mut self, _span: Span) {
968 // FIXME if we're not dumping the defs (see below), there is no point
969 // dumping refs either.
970 // let source_span = span.source_callsite();
971 // if !self.macro_calls.insert(source_span) {
975 // let data = match self.save_ctxt.get_macro_use_data(span) {
977 // Some(data) => data,
980 // self.dumper.macro_use(data);
982 // FIXME write the macro def
983 // let mut hasher = DefaultHasher::new();
984 // data.callee_span.hash(&mut hasher);
985 // let hash = hasher.finish();
986 // let qualname = format!("{}::{}", data.name, hash);
987 // Don't write macro definition for imported macros
988 // if !self.mac_defs.contains(&data.callee_span)
989 // && !data.imported {
990 // self.mac_defs.insert(data.callee_span);
991 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
992 // self.dumper.macro_data(MacroData {
994 // name: data.name.clone(),
995 // qualname: qualname.clone(),
996 // // FIXME where do macro docs come from?
997 // docs: String::new(),
998 // }.lower(self.tcx));
1003 fn process_trait_item(&mut self, trait_item: &'l ast::AssocItem, trait_id: DefId) {
1004 self.process_macro_use(trait_item.span);
1005 let vis_span = trait_item.span.shrink_to_lo();
1006 match trait_item.kind {
1007 ast::AssocItemKind::Const(ref ty, ref expr) => {
1008 self.process_assoc_const(
1012 expr.as_ref().map(|e| &**e),
1014 respan(vis_span, ast::VisibilityKind::Public),
1018 ast::AssocItemKind::Fn(ref sig, ref body) => {
1019 self.process_method(
1021 body.as_ref().map(|x| &**x),
1024 &trait_item.generics,
1025 respan(vis_span, ast::VisibilityKind::Public),
1029 ast::AssocItemKind::TyAlias(ref bounds, ref default_ty) => {
1030 // FIXME do something with _bounds (for type refs)
1031 let name = trait_item.ident.name.to_string();
1032 let qualname = format!(
1034 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(trait_item.id))
1037 if !self.span.filter_generated(trait_item.ident.span) {
1038 let span = self.span_from_span(trait_item.ident.span);
1039 let id = id_from_node_id(trait_item.id, &self.save_ctxt);
1041 self.dumper.dump_def(
1042 &Access { public: true, reachable: true },
1044 kind: DefKind::Type,
1049 value: self.span.snippet(trait_item.span),
1050 parent: Some(id_from_def_id(trait_id)),
1053 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1054 sig: sig::assoc_type_signature(
1058 default_ty.as_ref().map(|ty| &**ty),
1061 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1066 if let &Some(ref default_ty) = default_ty {
1067 self.visit_ty(default_ty)
1070 ast::AssocItemKind::Macro(_) => {}
1074 fn process_impl_item(&mut self, impl_item: &'l ast::AssocItem, impl_id: DefId) {
1075 self.process_macro_use(impl_item.span);
1076 match impl_item.kind {
1077 ast::AssocItemKind::Const(ref ty, ref expr) => {
1078 self.process_assoc_const(
1084 impl_item.vis.clone(),
1088 ast::AssocItemKind::Fn(ref sig, ref body) => {
1089 self.process_method(
1094 &impl_item.generics,
1095 impl_item.vis.clone(),
1099 ast::AssocItemKind::TyAlias(_, None) => {}
1100 ast::AssocItemKind::TyAlias(_, Some(ref ty)) => {
1101 // FIXME: uses of the assoc type should ideally point to this
1102 // 'def' and the name here should be a ref to the def in the
1106 ast::AssocItemKind::Macro(_) => {}
1110 /// Dumps imports in a use tree recursively.
1112 /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1113 /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1114 /// ID and path. `root_item` is the topmost use tree in the hierarchy.
1116 /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1117 /// each child use tree is dumped recursively.
1118 fn process_use_tree(
1120 use_tree: &'l ast::UseTree,
1122 root_item: &'l ast::Item,
1125 let path = &use_tree.prefix;
1127 // The access is calculated using the current tree ID, but with the root tree's visibility
1128 // (since nested trees don't have their own visibility).
1129 let hir_id = self.tcx.hir().node_to_hir_id(id);
1130 let access = access_from!(self.save_ctxt, root_item, hir_id);
1132 // The parent `DefId` of a given use tree is always the enclosing item.
1137 .opt_local_def_id_from_node_id(id)
1138 .and_then(|id| self.save_ctxt.tcx.parent(id))
1139 .map(id_from_def_id);
1141 match use_tree.kind {
1142 ast::UseTreeKind::Simple(alias, ..) => {
1143 let ident = use_tree.ident();
1144 let path = ast::Path {
1145 segments: prefix.segments.iter().chain(path.segments.iter()).cloned().collect(),
1149 let sub_span = path.segments.last().unwrap().ident.span;
1150 if !self.span.filter_generated(sub_span) {
1151 let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id));
1152 let alias_span = alias.map(|i| self.span_from_span(i.span));
1153 let span = self.span_from_span(sub_span);
1157 kind: ImportKind::Use,
1161 name: ident.to_string(),
1162 value: String::new(),
1166 self.write_sub_paths_truncated(&path);
1169 ast::UseTreeKind::Glob => {
1170 let path = ast::Path {
1171 segments: prefix.segments.iter().chain(path.segments.iter()).cloned().collect(),
1175 // Make a comma-separated list of names of imported modules.
1176 let def_id = self.tcx.hir().local_def_id_from_node_id(id);
1177 let names = self.tcx.names_imported_by_glob_use(def_id);
1178 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1180 // Otherwise it's a span with wrong macro expansion info, which
1181 // we don't want to track anyway, since it's probably macro-internal `use`
1182 if let Some(sub_span) =
1183 self.span.sub_span_of_token(use_tree.span, token::BinOp(token::Star))
1185 if !self.span.filter_generated(use_tree.span) {
1186 let span = self.span_from_span(sub_span);
1191 kind: ImportKind::GlobUse,
1195 name: "*".to_owned(),
1196 value: names.join(", "),
1200 self.write_sub_paths(&path);
1204 ast::UseTreeKind::Nested(ref nested_items) => {
1205 let prefix = ast::Path {
1206 segments: prefix.segments.iter().chain(path.segments.iter()).cloned().collect(),
1209 for &(ref tree, id) in nested_items {
1210 self.process_use_tree(tree, id, root_item, &prefix);
1216 fn process_bounds(&mut self, bounds: &'l ast::GenericBounds) {
1217 for bound in bounds {
1218 if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1219 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1225 impl<'l, 'tcx> Visitor<'l> for DumpVisitor<'l, 'tcx> {
1226 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1227 // Since we handle explicit modules ourselves in visit_item, this should
1228 // only get called for the root module of a crate.
1229 assert_eq!(id, ast::CRATE_NODE_ID);
1232 format!("::{}", self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
1234 let cm = self.tcx.sess.source_map();
1235 let filename = cm.span_to_filename(span);
1236 let data_id = id_from_node_id(id, &self.save_ctxt);
1237 let children = m.items.iter().map(|i| id_from_node_id(i.id, &self.save_ctxt)).collect();
1238 let span = self.span_from_span(span);
1240 self.dumper.dump_def(
1241 &Access { public: true, reachable: true },
1245 name: String::new(),
1248 value: filename.to_string(),
1252 docs: self.save_ctxt.docs_for_attrs(attrs),
1254 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1257 visit::walk_mod(self, m);
1260 fn visit_item(&mut self, item: &'l ast::Item) {
1261 use syntax::ast::ItemKind::*;
1262 self.process_macro_use(item.span);
1264 Use(ref use_tree) => {
1265 let prefix = ast::Path { segments: vec![], span: DUMMY_SP };
1266 self.process_use_tree(use_tree, item.id, item, &prefix);
1269 let name_span = item.ident.span;
1270 if !self.span.filter_generated(name_span) {
1271 let span = self.span_from_span(name_span);
1276 .opt_local_def_id_from_node_id(item.id)
1277 .and_then(|id| self.save_ctxt.tcx.parent(id))
1278 .map(id_from_def_id);
1280 &Access { public: false, reachable: false },
1282 kind: ImportKind::ExternCrate,
1286 name: item.ident.to_string(),
1287 value: String::new(),
1293 Fn(ref sig, ref ty_params, ref body) => {
1294 self.process_fn(item, &sig.decl, &sig.header, ty_params, body.as_deref())
1296 Static(ref typ, _, ref expr) => self.process_static_or_const_item(item, typ, expr),
1297 Const(ref typ, ref expr) => self.process_static_or_const_item(item, &typ, &expr),
1298 Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1299 self.process_struct(item, def, ty_params)
1301 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1302 Impl { ref generics, ref of_trait, ref self_ty, ref items, .. } => {
1303 self.process_impl(item, generics, of_trait, &self_ty, items)
1305 Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1306 self.process_trait(item, generics, trait_refs, methods)
1309 self.process_mod(item);
1310 visit::walk_mod(self, m);
1312 TyAlias(ref ty, ref ty_params) => {
1313 let qualname = format!(
1315 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id))
1317 let value = ty_to_string(&ty);
1318 if !self.span.filter_generated(item.ident.span) {
1319 let span = self.span_from_span(item.ident.span);
1320 let id = id_from_node_id(item.id, &self.save_ctxt);
1321 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1323 self.dumper.dump_def(
1324 &access_from!(self.save_ctxt, item, hir_id),
1326 kind: DefKind::Type,
1329 name: item.ident.to_string(),
1330 qualname: qualname.clone(),
1335 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1336 sig: sig::item_signature(item, &self.save_ctxt),
1337 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1343 self.process_generic_params(ty_params, &qualname, item.id);
1346 _ => visit::walk_item(self, item),
1350 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1351 for param in &generics.params {
1353 ast::GenericParamKind::Lifetime { .. } => {}
1354 ast::GenericParamKind::Type { ref default, .. } => {
1355 self.process_bounds(¶m.bounds);
1356 if let Some(ref ty) = default {
1360 ast::GenericParamKind::Const { ref ty } => {
1361 self.process_bounds(¶m.bounds);
1366 for pred in &generics.where_clause.predicates {
1367 if let ast::WherePredicate::BoundPredicate(ref wbp) = *pred {
1368 self.process_bounds(&wbp.bounds);
1369 self.visit_ty(&wbp.bounded_ty);
1374 fn visit_ty(&mut self, t: &'l ast::Ty) {
1375 self.process_macro_use(t.span);
1377 ast::TyKind::Path(_, ref path) => {
1378 if generated_code(t.span) {
1382 if let Some(id) = self.lookup_def_id(t.id) {
1383 let sub_span = path.segments.last().unwrap().ident.span;
1384 let span = self.span_from_span(sub_span);
1385 self.dumper.dump_ref(Ref {
1386 kind: RefKind::Type,
1388 ref_id: id_from_def_id(id),
1392 self.write_sub_paths_truncated(path);
1393 visit::walk_path(self, path);
1395 ast::TyKind::Array(ref element, ref length) => {
1396 self.visit_ty(element);
1397 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1399 ast::TyKind::ImplTrait(id, ref bounds) => {
1400 // FIXME: As of writing, the opaque type lowering introduces
1401 // another DefPath scope/segment (used to declare the resulting
1402 // opaque type item).
1403 // However, the synthetic scope does *not* have associated
1404 // typeck tables, which means we can't nest it and we fire an
1405 // assertion when resolving the qualified type paths in trait
1407 // This will panic if called on return type `impl Trait`, which
1408 // we guard against in `process_fn`.
1409 self.nest_tables(id, |v| v.process_bounds(bounds));
1411 _ => visit::walk_ty(self, t),
1415 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1416 debug!("visit_expr {:?}", ex.kind);
1417 self.process_macro_use(ex.span);
1419 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1420 let expr_hir_id = self.save_ctxt.tcx.hir().node_to_hir_id(ex.id);
1421 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(expr_hir_id);
1422 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1423 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1425 visit::walk_expr(self, ex);
1429 let node_id = self.save_ctxt.tcx.hir().hir_to_node_id(hir_expr.hir_id);
1430 let res = self.save_ctxt.get_path_res(node_id);
1431 self.process_struct_lit(ex, path, fields, adt.variant_of_res(res), base)
1433 ast::ExprKind::MethodCall(ref seg, ref args) => self.process_method_call(ex, seg, args),
1434 ast::ExprKind::Field(ref sub_ex, _) => {
1435 self.visit_expr(&sub_ex);
1437 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1438 down_cast_data!(field_data, RefData, ex.span);
1439 if !generated_code(ex.span) {
1440 self.dumper.dump_ref(field_data);
1444 ast::ExprKind::Closure(_, _, _, ref decl, ref body, _fn_decl_span) => {
1445 let id = format!("${}", ex.id);
1447 // walk arg and return types
1448 for arg in &decl.inputs {
1449 self.visit_ty(&arg.ty);
1452 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1453 self.visit_ty(&ret_ty);
1457 self.nest_tables(ex.id, |v| {
1458 v.process_formals(&decl.inputs, &id);
1462 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1463 self.process_var_decl(pattern);
1464 debug!("for loop, walk sub-expr: {:?}", subexpression.kind);
1465 self.visit_expr(subexpression);
1466 visit::walk_block(self, block);
1468 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1469 self.process_var_decl(pat);
1470 self.visit_expr(scrutinee);
1472 ast::ExprKind::Repeat(ref element, ref count) => {
1473 self.visit_expr(element);
1474 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1476 // In particular, we take this branch for call and path expressions,
1477 // where we'll index the idents involved just by continuing to walk.
1478 _ => visit::walk_expr(self, ex),
1482 fn visit_pat(&mut self, p: &'l ast::Pat) {
1483 self.process_macro_use(p.span);
1484 self.process_pat(p);
1487 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1488 self.process_var_decl(&arm.pat);
1489 if let Some(expr) = &arm.guard {
1490 self.visit_expr(expr);
1492 self.visit_expr(&arm.body);
1495 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1496 self.process_path(id, p);
1499 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1500 self.process_macro_use(s.span);
1501 visit::walk_stmt(self, s)
1504 fn visit_local(&mut self, l: &'l ast::Local) {
1505 self.process_macro_use(l.span);
1506 self.process_var_decl(&l.pat);
1508 // Just walk the initialiser and type (don't want to walk the pattern again).
1509 walk_list!(self, visit_ty, &l.ty);
1510 walk_list!(self, visit_expr, &l.init);
1513 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1514 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1515 let access = access_from!(self.save_ctxt, item, hir_id);
1518 ast::ForeignItemKind::Fn(ref sig, ref generics, _) => {
1519 let decl = &sig.decl;
1520 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1521 down_cast_data!(fn_data, DefData, item.span);
1523 self.process_generic_params(generics, &fn_data.qualname, item.id);
1524 self.dumper.dump_def(&access, fn_data);
1527 for arg in &decl.inputs {
1528 self.visit_ty(&arg.ty);
1531 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1532 self.visit_ty(&ret_ty);
1535 ast::ForeignItemKind::Static(ref ty, _) => {
1536 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1537 down_cast_data!(var_data, DefData, item.span);
1538 self.dumper.dump_def(&access, var_data);
1543 ast::ForeignItemKind::Ty => {
1544 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1545 down_cast_data!(var_data, DefData, item.span);
1546 self.dumper.dump_def(&access, var_data);
1549 ast::ForeignItemKind::Macro(..) => {}