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.
17 use rustc_ast::walk_list;
18 use rustc_data_structures::fx::FxHashSet;
20 use rustc_hir::def::{DefKind as HirDefKind, Res};
21 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
22 use rustc_hir::intravisit::{self, Visitor};
23 use rustc_hir_pretty::{bounds_to_string, fn_to_string, generic_params_to_string, ty_to_string};
24 use rustc_middle::hir::nested_filter;
25 use rustc_middle::span_bug;
26 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
27 use rustc_session::config::Input;
28 use rustc_span::symbol::Ident;
34 use crate::dumper::{Access, Dumper};
36 use crate::span_utils::SpanUtils;
38 escape, generated_code, id_from_def_id, id_from_hir_id, lower_attributes, PathCollector,
43 CompilationOptions, CratePreludeData, Def, DefKind, GlobalCrateId, Import, ImportKind, Ref,
44 RefKind, Relation, RelationKind, SpanData,
47 #[rustfmt::skip] // https://github.com/rust-lang/rustfmt/issues/5213
48 macro_rules! down_cast_data {
49 ($id:ident, $kind:ident, $sp:expr) => {
50 let super::Data::$kind($id) = $id else {
51 span_bug!($sp, "unexpected data kind: {:?}", $id);
56 macro_rules! access_from {
57 ($save_ctxt:expr, $id:expr) => {
59 public: $save_ctxt.tcx.visibility($id).is_public(),
60 reachable: $save_ctxt.effective_visibilities.is_reachable($id),
65 pub struct DumpVisitor<'tcx> {
66 pub save_ctxt: SaveContext<'tcx>,
70 span: SpanUtils<'tcx>,
71 // Set of macro definition (callee) spans, and the set
72 // of macro use (callsite) spans. We store these to ensure
73 // we only write one macro def per unique macro definition, and
74 // one macro use per unique callsite span.
75 // mac_defs: FxHashSet<Span>,
76 // macro_calls: FxHashSet<Span>,
79 impl<'tcx> DumpVisitor<'tcx> {
80 pub fn new(save_ctxt: SaveContext<'tcx>) -> DumpVisitor<'tcx> {
81 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
82 let dumper = Dumper::new(save_ctxt.config.clone());
83 DumpVisitor { tcx: save_ctxt.tcx, save_ctxt, dumper, span: span_utils }
86 pub fn analysis(&self) -> &rls_data::Analysis {
87 self.dumper.analysis()
90 fn nest_typeck_results<F>(&mut self, item_def_id: LocalDefId, f: F)
94 let typeck_results = if self.tcx.has_typeck_results(item_def_id) {
95 Some(self.tcx.typeck(item_def_id))
100 let old_maybe_typeck_results = self.save_ctxt.maybe_typeck_results;
101 self.save_ctxt.maybe_typeck_results = typeck_results;
103 self.save_ctxt.maybe_typeck_results = old_maybe_typeck_results;
106 fn span_from_span(&self, span: Span) -> SpanData {
107 self.save_ctxt.span_from_span(span)
110 fn lookup_def_id(&self, ref_id: hir::HirId) -> Option<DefId> {
111 self.save_ctxt.lookup_def_id(ref_id)
114 pub fn dump_crate_info(&mut self, name: Symbol) {
115 let crate_root = self.tcx.sess.local_crate_source_file().map(|source_file| {
116 match source_file.file_name() {
117 Some(_) => source_file.parent().unwrap().display(),
118 None => source_file.display(),
123 let data = CratePreludeData {
124 crate_id: GlobalCrateId {
125 name: name.to_string(),
126 disambiguator: (self.tcx.sess.local_stable_crate_id().to_u64(), 0),
128 crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
129 external_crates: self.save_ctxt.get_external_crates(),
130 span: self.span_from_span(self.tcx.def_span(CRATE_DEF_ID)),
133 self.dumper.crate_prelude(data);
136 pub fn dump_compilation_options(&mut self, input: &Input, crate_name: Symbol) {
137 // Apply possible `remap-path-prefix` remapping to the input source file
138 // (and don't include remapping args anymore)
139 let (program, arguments) = {
140 let remap_arg_indices = {
141 let mut indices = FxHashSet::default();
142 // Args are guaranteed to be valid UTF-8 (checked early)
143 for (i, e) in env::args().enumerate() {
144 if e.starts_with("--remap-path-prefix=") {
146 } else if e == "--remap-path-prefix" {
148 indices.insert(i + 1);
154 let mut args = env::args()
156 .filter(|(i, _)| !remap_arg_indices.contains(i))
157 .map(|(_, arg)| match input {
158 Input::File(ref path) if path == Path::new(&arg) => self
161 .local_crate_source_file()
169 (args.next().unwrap(), args.collect())
172 let data = CompilationOptions {
173 directory: self.tcx.sess.opts.working_dir.remapped_path_if_available().into(),
176 output: self.save_ctxt.compilation_output(crate_name),
179 self.dumper.compilation_opts(data);
182 fn write_segments(&mut self, segments: impl IntoIterator<Item = &'tcx hir::PathSegment<'tcx>>) {
183 for seg in segments {
184 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
185 self.dumper.dump_ref(data);
190 fn write_sub_paths<R>(&mut self, path: &'tcx hir::Path<'tcx, R>) {
191 self.write_segments(path.segments)
194 // As write_sub_paths, but does not process the last ident in the path (assuming it
195 // will be processed elsewhere). See note on write_sub_paths about global.
196 fn write_sub_paths_truncated<R>(&mut self, path: &'tcx hir::Path<'tcx, R>) {
197 if let [segments @ .., _] = path.segments {
198 self.write_segments(segments)
202 fn process_formals(&mut self, formals: &'tcx [hir::Param<'tcx>], qualname: &str) {
204 self.visit_pat(&arg.pat);
205 let mut collector = PathCollector::new(self.tcx);
206 collector.visit_pat(&arg.pat);
208 for (hir_id, ident, ..) in collector.collected_idents {
209 let typ = match self.save_ctxt.typeck_results().node_type_opt(hir_id) {
210 Some(s) => s.to_string(),
213 if !self.span.filter_generated(ident.span) {
214 let id = id_from_hir_id(hir_id);
215 let span = self.span_from_span(ident.span);
217 self.dumper.dump_def(
218 &Access { public: false, reachable: false },
220 kind: DefKind::Local,
223 name: ident.to_string(),
224 qualname: format!("{}::{}", qualname, ident),
241 sig: &'tcx hir::FnSig<'tcx>,
242 body: Option<hir::BodyId>,
243 owner_id: hir::OwnerId,
245 generics: &'tcx hir::Generics<'tcx>,
248 debug!("process_method: {:?}:{}", owner_id, ident);
250 let map = self.tcx.hir();
251 let hir_id: hir::HirId = owner_id.into();
252 self.nest_typeck_results(owner_id.def_id, |v| {
253 if let Some(mut method_data) = v.save_ctxt.get_method_data(owner_id, ident, span) {
254 if let Some(body) = body {
255 v.process_formals(map.body(body).params, &method_data.qualname);
257 v.process_generic_params(&generics, &method_data.qualname, hir_id);
260 fn_to_string(sig.decl, sig.header, Some(ident.name), generics, &[], None);
262 sig::method_signature(owner_id, ident, generics, sig, &v.save_ctxt);
264 v.dumper.dump_def(&access_from!(v.save_ctxt, owner_id.def_id), method_data);
267 // walk arg and return types
268 for arg in sig.decl.inputs {
272 if let hir::FnRetTy::Return(ref ret_ty) = sig.decl.output {
277 if let Some(body) = body {
278 v.visit_expr(&map.body(body).value);
283 fn process_struct_field_def(
285 field: &'tcx hir::FieldDef<'tcx>,
286 parent_id: LocalDefId,
288 let field_data = self.save_ctxt.get_field_data(field, parent_id);
289 if let Some(field_data) = field_data {
290 self.dumper.dump_def(&access_from!(self.save_ctxt, field.def_id), field_data);
294 // Dump generic params bindings, then visit_generics
295 fn process_generic_params(
297 generics: &'tcx hir::Generics<'tcx>,
301 for param in generics.params {
303 hir::GenericParamKind::Lifetime { .. } => {}
304 hir::GenericParamKind::Type { .. } => {
305 let param_ss = param.name.ident().span;
306 let name = escape(self.span.snippet(param_ss));
307 // Append $id to name to make sure each one is unique.
308 let qualname = format!("{}::{}${}", prefix, name, id);
309 if !self.span.filter_generated(param_ss) {
310 let id = id_from_def_id(param.def_id.to_def_id());
311 let span = self.span_from_span(param_ss);
313 self.dumper.dump_def(
314 &Access { public: false, reachable: false },
321 value: String::new(),
332 hir::GenericParamKind::Const { .. } => {}
336 self.visit_generics(generics)
341 item: &'tcx hir::Item<'tcx>,
342 decl: &'tcx hir::FnDecl<'tcx>,
343 _header: &'tcx hir::FnHeader,
344 ty_params: &'tcx hir::Generics<'tcx>,
347 let map = self.tcx.hir();
348 self.nest_typeck_results(item.owner_id.def_id, |v| {
349 let body = map.body(body);
350 if let Some(fn_data) = v.save_ctxt.get_item_data(item) {
351 down_cast_data!(fn_data, DefData, item.span);
352 v.process_formals(body.params, &fn_data.qualname);
353 v.process_generic_params(ty_params, &fn_data.qualname, item.hir_id());
355 v.dumper.dump_def(&access_from!(v.save_ctxt, item.owner_id.def_id), fn_data);
358 for arg in decl.inputs {
362 if let hir::FnRetTy::Return(ref ret_ty) = decl.output {
366 v.visit_expr(&body.value);
370 fn process_static_or_const_item(
372 item: &'tcx hir::Item<'tcx>,
373 typ: &'tcx hir::Ty<'tcx>,
374 expr: &'tcx hir::Expr<'tcx>,
376 self.nest_typeck_results(item.owner_id.def_id, |v| {
377 if let Some(var_data) = v.save_ctxt.get_item_data(item) {
378 down_cast_data!(var_data, DefData, item.span);
379 v.dumper.dump_def(&access_from!(v.save_ctxt, item.owner_id.def_id), var_data);
386 fn process_assoc_const(
388 owner_id: hir::OwnerId,
390 typ: &'tcx hir::Ty<'tcx>,
391 expr: Option<&'tcx hir::Expr<'tcx>>,
393 attrs: &'tcx [ast::Attribute],
395 let qualname = format!("::{}", self.tcx.def_path_str(owner_id.to_def_id()));
397 if !self.span.filter_generated(ident.span) {
398 let sig = sig::assoc_const_signature(owner_id, ident.name, typ, expr, &self.save_ctxt);
399 let span = self.span_from_span(ident.span);
401 self.dumper.dump_def(
402 &access_from!(self.save_ctxt, owner_id.def_id),
404 kind: DefKind::Const,
405 id: id_from_def_id(owner_id.to_def_id()),
407 name: ident.name.to_string(),
409 value: ty_to_string(&typ),
410 parent: Some(id_from_def_id(parent_id)),
413 docs: self.save_ctxt.docs_for_attrs(attrs),
415 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
420 // walk type and init value
421 self.nest_typeck_results(owner_id.def_id, |v| {
423 if let Some(expr) = expr {
429 // FIXME tuple structs should generate tuple-specific data.
432 item: &'tcx hir::Item<'tcx>,
433 def: &'tcx hir::VariantData<'tcx>,
434 ty_params: &'tcx hir::Generics<'tcx>,
436 debug!("process_struct {:?} {:?}", item, item.span);
437 let name = item.ident.to_string();
438 let qualname = format!("::{}", self.tcx.def_path_str(item.owner_id.to_def_id()));
440 let kind = match item.kind {
441 hir::ItemKind::Struct(_, _) => DefKind::Struct,
442 hir::ItemKind::Union(_, _) => DefKind::Union,
446 let (value, fields) = match item.kind {
447 hir::ItemKind::Struct(hir::VariantData::Struct(ref fields, ..), ..)
448 | hir::ItemKind::Union(hir::VariantData::Struct(ref fields, ..), ..) => {
449 let include_priv_fields = !self.save_ctxt.config.pub_only;
450 let fields_str = fields
453 if include_priv_fields {
454 return Some(f.ident.to_string());
456 if self.save_ctxt.tcx.visibility(f.def_id).is_public() {
457 Some(f.ident.to_string())
464 let value = format!("{} {{ {} }}", name, fields_str);
465 (value, fields.iter().map(|f| id_from_def_id(f.def_id.to_def_id())).collect())
467 _ => (String::new(), vec![]),
470 if !self.span.filter_generated(item.ident.span) {
471 let span = self.span_from_span(item.ident.span);
472 let attrs = self.tcx.hir().attrs(item.hir_id());
473 self.dumper.dump_def(
474 &access_from!(self.save_ctxt, item.owner_id.def_id),
477 id: id_from_def_id(item.owner_id.to_def_id()),
480 qualname: qualname.clone(),
485 docs: self.save_ctxt.docs_for_attrs(attrs),
486 sig: sig::item_signature(item, &self.save_ctxt),
487 attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),
492 self.nest_typeck_results(item.owner_id.def_id, |v| {
493 for field in def.fields() {
494 v.process_struct_field_def(field, item.owner_id.def_id);
495 v.visit_ty(&field.ty);
498 v.process_generic_params(ty_params, &qualname, item.hir_id());
504 item: &'tcx hir::Item<'tcx>,
505 enum_definition: &'tcx hir::EnumDef<'tcx>,
506 ty_params: &'tcx hir::Generics<'tcx>,
508 let enum_data = self.save_ctxt.get_item_data(item);
509 let Some(enum_data) = enum_data else {
512 down_cast_data!(enum_data, DefData, item.span);
514 let access = access_from!(self.save_ctxt, item.owner_id.def_id);
516 for variant in enum_definition.variants {
517 let name = variant.ident.name.to_string();
518 let qualname = format!("{}::{}", enum_data.qualname, name);
519 let name_span = variant.ident.span;
522 hir::VariantData::Struct(ref fields, ..) => {
524 fields.iter().map(|f| f.ident.to_string()).collect::<Vec<_>>().join(", ");
525 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
526 if !self.span.filter_generated(name_span) {
527 let span = self.span_from_span(name_span);
528 let id = id_from_def_id(variant.def_id.to_def_id());
529 let parent = Some(id_from_def_id(item.owner_id.to_def_id()));
530 let attrs = self.tcx.hir().attrs(variant.hir_id);
532 self.dumper.dump_def(
535 kind: DefKind::StructVariant,
544 docs: self.save_ctxt.docs_for_attrs(attrs),
545 sig: sig::variant_signature(variant, &self.save_ctxt),
546 attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),
552 let mut value = format!("{}::{}", enum_data.name, name);
553 if let hir::VariantData::Tuple(fields, _, _) = v {
558 .map(|f| ty_to_string(&f.ty))
564 if !self.span.filter_generated(name_span) {
565 let span = self.span_from_span(name_span);
566 let id = id_from_def_id(variant.def_id.to_def_id());
567 let parent = Some(id_from_def_id(item.owner_id.to_def_id()));
568 let attrs = self.tcx.hir().attrs(variant.hir_id);
570 self.dumper.dump_def(
573 kind: DefKind::TupleVariant,
582 docs: self.save_ctxt.docs_for_attrs(attrs),
583 sig: sig::variant_signature(variant, &self.save_ctxt),
584 attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),
591 for field in variant.data.fields() {
592 self.process_struct_field_def(field, variant.def_id);
593 self.visit_ty(field.ty);
596 self.process_generic_params(ty_params, &enum_data.qualname, item.hir_id());
597 self.dumper.dump_def(&access, enum_data);
600 fn process_impl(&mut self, item: &'tcx hir::Item<'tcx>, impl_: &'tcx hir::Impl<'tcx>) {
601 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
602 if !self.span.filter_generated(item.span) {
603 if let super::Data::RelationData(rel, imp) = impl_data {
604 self.dumper.dump_relation(rel);
605 self.dumper.dump_impl(imp);
607 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
612 let map = self.tcx.hir();
613 self.nest_typeck_results(item.owner_id.def_id, |v| {
614 v.visit_ty(&impl_.self_ty);
615 if let Some(trait_ref) = &impl_.of_trait {
616 v.process_path(trait_ref.hir_ref_id, &hir::QPath::Resolved(None, &trait_ref.path));
618 v.process_generic_params(&impl_.generics, "", item.hir_id());
619 for impl_item in impl_.items {
620 v.process_impl_item(map.impl_item(impl_item.id), item.owner_id.to_def_id());
627 item: &'tcx hir::Item<'tcx>,
628 generics: &'tcx hir::Generics<'tcx>,
629 trait_refs: hir::GenericBounds<'tcx>,
630 methods: &'tcx [hir::TraitItemRef],
632 let name = item.ident.to_string();
633 let qualname = format!("::{}", self.tcx.def_path_str(item.owner_id.to_def_id()));
634 let mut val = name.clone();
635 if !generics.params.is_empty() {
636 val.push_str(&generic_params_to_string(generics.params));
638 if !trait_refs.is_empty() {
640 val.push_str(&bounds_to_string(trait_refs));
642 if !self.span.filter_generated(item.ident.span) {
643 let id = id_from_def_id(item.owner_id.to_def_id());
644 let span = self.span_from_span(item.ident.span);
646 methods.iter().map(|i| id_from_def_id(i.id.owner_id.to_def_id())).collect();
647 let attrs = self.tcx.hir().attrs(item.hir_id());
648 self.dumper.dump_def(
649 &access_from!(self.save_ctxt, item.owner_id.def_id),
651 kind: DefKind::Trait,
655 qualname: qualname.clone(),
660 docs: self.save_ctxt.docs_for_attrs(attrs),
661 sig: sig::item_signature(item, &self.save_ctxt),
662 attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),
668 for super_bound in trait_refs.iter() {
669 let (def_id, sub_span) = match *super_bound {
670 hir::GenericBound::Trait(ref trait_ref, _) => (
671 self.lookup_def_id(trait_ref.trait_ref.hir_ref_id),
672 trait_ref.trait_ref.path.segments.last().unwrap().ident.span,
674 hir::GenericBound::LangItemTrait(lang_item, span, _, _) => {
675 (Some(self.tcx.require_lang_item(lang_item, Some(span))), span)
677 hir::GenericBound::Outlives(..) => continue,
680 if let Some(id) = def_id {
681 if !self.span.filter_generated(sub_span) {
682 let span = self.span_from_span(sub_span);
683 self.dumper.dump_ref(Ref {
686 ref_id: id_from_def_id(id),
689 self.dumper.dump_relation(Relation {
690 kind: RelationKind::SuperTrait,
692 from: id_from_def_id(id),
693 to: id_from_def_id(item.owner_id.to_def_id()),
699 // walk generics and methods
700 self.process_generic_params(generics, &qualname, item.hir_id());
701 for method in methods {
702 let map = self.tcx.hir();
703 self.process_trait_item(map.trait_item(method.id), item.owner_id.to_def_id())
707 // `item` is the module in question, represented as an( item.
708 fn process_mod(&mut self, item: &'tcx hir::Item<'tcx>) {
709 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
710 down_cast_data!(mod_data, DefData, item.span);
711 self.dumper.dump_def(&access_from!(self.save_ctxt, item.owner_id.def_id), mod_data);
715 fn dump_path_ref(&mut self, id: hir::HirId, path: &hir::QPath<'tcx>) {
716 let path_data = self.save_ctxt.get_path_data(id, path);
717 if let Some(path_data) = path_data {
718 self.dumper.dump_ref(path_data);
722 fn dump_path_segment_ref(&mut self, id: hir::HirId, segment: &hir::PathSegment<'tcx>) {
723 let segment_data = self.save_ctxt.get_path_segment_data_with_id(segment, id);
724 if let Some(segment_data) = segment_data {
725 self.dumper.dump_ref(segment_data);
729 fn process_path(&mut self, id: hir::HirId, path: &hir::QPath<'tcx>) {
730 if self.span.filter_generated(path.span()) {
733 self.dump_path_ref(id, path);
736 let segments = match path {
737 hir::QPath::Resolved(ty, path) => {
738 if let Some(ty) = ty {
743 hir::QPath::TypeRelative(ty, segment) => {
745 std::slice::from_ref(*segment)
747 hir::QPath::LangItem(..) => return,
749 for seg in segments {
750 if let Some(ref generic_args) = seg.args {
751 for arg in generic_args.args {
752 if let hir::GenericArg::Type(ref ty) = arg {
759 if let hir::QPath::Resolved(_, path) = path {
760 self.write_sub_paths_truncated(path);
764 fn process_struct_lit(
766 ex: &'tcx hir::Expr<'tcx>,
767 path: &'tcx hir::QPath<'tcx>,
768 fields: &'tcx [hir::ExprField<'tcx>],
769 variant: &'tcx ty::VariantDef,
770 rest: Option<&'tcx hir::Expr<'tcx>>,
772 if let Some(_ex_res_data) = self.save_ctxt.get_expr_data(ex) {
773 if let hir::QPath::Resolved(_, path) = path {
774 self.write_sub_paths_truncated(path);
776 // For MyEnum::MyVariant, get_expr_data gives us MyEnum, not MyVariant.
777 // For recording the span's ref id, we want MyVariant.
778 if !generated_code(ex.span) {
779 let sub_span = path.last_segment_span();
780 let span = self.save_ctxt.span_from_span(sub_span);
782 Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(variant.def_id) };
783 self.dumper.dump_ref(reff);
786 for field in fields {
787 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
788 self.dumper.dump_ref(field_data);
791 self.visit_expr(&field.expr)
795 if let Some(base) = rest {
796 self.visit_expr(&base);
800 fn process_method_call(
802 ex: &'tcx hir::Expr<'tcx>,
803 seg: &'tcx hir::PathSegment<'tcx>,
804 receiver: &'tcx hir::Expr<'tcx>,
805 args: &'tcx [hir::Expr<'tcx>],
807 debug!("process_method_call {:?} {:?}", ex, ex.span);
808 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
809 down_cast_data!(mcd, RefData, ex.span);
810 if !generated_code(ex.span) {
811 self.dumper.dump_ref(mcd);
815 // Explicit types in the turbo-fish.
816 if let Some(generic_args) = seg.args {
817 for arg in generic_args.args {
818 if let hir::GenericArg::Type(ty) = arg {
824 // walk receiver and args
825 self.visit_expr(receiver);
826 walk_list!(self, visit_expr, args);
829 fn process_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
831 hir::PatKind::Struct(ref _path, fields, _) => {
832 // FIXME do something with _path?
833 let adt = match self.save_ctxt.typeck_results().node_type_opt(p.hir_id) {
834 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
836 intravisit::walk_pat(self, p);
840 let variant = adt.variant_of_res(self.save_ctxt.get_path_res(p.hir_id));
842 for field in fields {
843 if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
844 if !self.span.filter_generated(field.ident.span) {
845 let span = self.span_from_span(field.ident.span);
846 self.dumper.dump_ref(Ref {
847 kind: RefKind::Variable,
849 ref_id: id_from_def_id(variant.fields[index].did),
853 self.visit_pat(&field.pat);
856 _ => intravisit::walk_pat(self, p),
860 fn process_var_decl(&mut self, pat: &'tcx hir::Pat<'tcx>) {
861 // The pattern could declare multiple new vars,
862 // we must walk the pattern and collect them all.
863 let mut collector = PathCollector::new(self.tcx);
864 collector.visit_pat(&pat);
865 self.visit_pat(&pat);
867 // Process collected paths.
868 for (id, ident, _) in collector.collected_idents {
869 let res = self.save_ctxt.get_path_res(id);
871 Res::Local(hir_id) => {
875 .node_type_opt(hir_id)
876 .map(|t| t.to_string())
877 .unwrap_or_default();
879 // Rust uses the id of the pattern for var lookups, so we'll use it too.
880 if !self.span.filter_generated(ident.span) {
881 let qualname = format!("{}${}", ident, hir_id);
882 let id = id_from_hir_id(hir_id);
883 let span = self.span_from_span(ident.span);
885 self.dumper.dump_def(
886 &Access { public: false, reachable: false },
888 kind: DefKind::Local,
891 name: ident.to_string(),
907 | HirDefKind::AssocConst
909 | HirDefKind::Variant
910 | HirDefKind::TyAlias
911 | HirDefKind::AssocTy,
914 | Res::SelfTyParam { .. }
915 | Res::SelfTyAlias { .. } => {
916 self.dump_path_segment_ref(
918 &hir::PathSegment::new(ident, hir::HirId::INVALID, Res::Err),
922 error!("unexpected definition kind when processing collected idents: {:?}", def)
927 for (id, ref path) in collector.collected_paths {
928 self.process_path(id, path);
932 /// Extracts macro use and definition information from the AST node defined
933 /// by the given NodeId, using the expansion information from the node's
936 /// If the span is not macro-generated, do nothing, else use callee and
937 /// callsite spans to record macro definition and use data, using the
938 /// mac_uses and mac_defs sets to prevent multiples.
939 fn process_macro_use(&mut self, _span: Span) {
940 // FIXME if we're not dumping the defs (see below), there is no point
941 // dumping refs either.
942 // let source_span = span.source_callsite();
943 // if !self.macro_calls.insert(source_span) {
947 // let data = match self.save_ctxt.get_macro_use_data(span) {
949 // Some(data) => data,
952 // self.dumper.macro_use(data);
954 // FIXME write the macro def
955 // let mut hasher = DefaultHasher::new();
956 // data.callee_span.hash(&mut hasher);
957 // let hash = hasher.finish();
958 // let qualname = format!("{}::{}", data.name, hash);
959 // Don't write macro definition for imported macros
960 // if !self.mac_defs.contains(&data.callee_span)
961 // && !data.imported {
962 // self.mac_defs.insert(data.callee_span);
963 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
964 // self.dumper.macro_data(MacroData {
966 // name: data.name.clone(),
967 // qualname: qualname.clone(),
968 // // FIXME where do macro docs come from?
969 // docs: String::new(),
970 // }.lower(self.tcx));
975 fn process_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>, trait_id: DefId) {
976 self.process_macro_use(trait_item.span);
977 match trait_item.kind {
978 hir::TraitItemKind::Const(ref ty, body) => {
979 let body = body.map(|b| self.tcx.hir().body(b).value);
980 let attrs = self.tcx.hir().attrs(trait_item.hir_id());
981 self.process_assoc_const(
990 hir::TraitItemKind::Fn(ref sig, ref trait_fn) => {
992 if let hir::TraitFn::Provided(body) = trait_fn { Some(*body) } else { None };
998 &trait_item.generics,
1002 hir::TraitItemKind::Type(ref bounds, ref default_ty) => {
1003 // FIXME do something with _bounds (for type refs)
1004 let name = trait_item.ident.name.to_string();
1006 format!("::{}", self.tcx.def_path_str(trait_item.owner_id.to_def_id()));
1008 if !self.span.filter_generated(trait_item.ident.span) {
1009 let span = self.span_from_span(trait_item.ident.span);
1010 let id = id_from_def_id(trait_item.owner_id.to_def_id());
1011 let attrs = self.tcx.hir().attrs(trait_item.hir_id());
1013 self.dumper.dump_def(
1014 &Access { public: true, reachable: true },
1016 kind: DefKind::Type,
1021 value: self.span.snippet(trait_item.span),
1022 parent: Some(id_from_def_id(trait_id)),
1025 docs: self.save_ctxt.docs_for_attrs(attrs),
1026 sig: sig::assoc_type_signature(
1027 trait_item.owner_id,
1030 default_ty.as_deref(),
1033 attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),
1038 if let Some(default_ty) = default_ty {
1039 self.visit_ty(default_ty)
1045 fn process_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>, impl_id: DefId) {
1046 self.process_macro_use(impl_item.span);
1047 match impl_item.kind {
1048 hir::ImplItemKind::Const(ref ty, body) => {
1049 let body = self.tcx.hir().body(body);
1050 let attrs = self.tcx.hir().attrs(impl_item.hir_id());
1051 self.process_assoc_const(
1060 hir::ImplItemKind::Fn(ref sig, body) => {
1061 self.process_method(
1066 &impl_item.generics,
1070 hir::ImplItemKind::Type(ref ty) => {
1071 // FIXME: uses of the assoc type should ideally point to this
1072 // 'def' and the name here should be a ref to the def in the
1079 pub(crate) fn process_crate(&mut self) {
1080 let qualname = format!("::{}", self.tcx.def_path_str(CRATE_DEF_ID.to_def_id()));
1082 let sm = self.tcx.sess.source_map();
1083 let krate_mod = self.tcx.hir().root_module();
1084 let filename = sm.span_to_filename(krate_mod.spans.inner_span);
1085 let data_id = id_from_def_id(CRATE_DEF_ID.to_def_id());
1087 krate_mod.item_ids.iter().map(|i| id_from_def_id(i.owner_id.to_def_id())).collect();
1088 let span = self.span_from_span(krate_mod.spans.inner_span);
1089 let attrs = self.tcx.hir().attrs(hir::CRATE_HIR_ID);
1091 self.dumper.dump_def(
1092 &Access { public: true, reachable: true },
1096 name: String::new(),
1099 value: filename.prefer_remapped().to_string(),
1103 docs: self.save_ctxt.docs_for_attrs(attrs),
1105 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1108 self.tcx.hir().walk_toplevel_module(self);
1111 fn process_bounds(&mut self, bounds: hir::GenericBounds<'tcx>) {
1112 for bound in bounds {
1113 if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1115 trait_ref.trait_ref.hir_ref_id,
1116 &hir::QPath::Resolved(None, &trait_ref.trait_ref.path),
1123 impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> {
1124 type NestedFilter = nested_filter::All;
1126 fn nested_visit_map(&mut self) -> Self::Map {
1130 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1131 self.process_macro_use(item.span);
1133 hir::ItemKind::Use(path, hir::UseKind::Single) => {
1134 let sub_span = path.segments.last().unwrap().ident.span;
1135 if !self.span.filter_generated(sub_span) {
1136 let access = access_from!(self.save_ctxt, item.owner_id.def_id);
1137 let ref_id = self.lookup_def_id(item.hir_id()).map(id_from_def_id);
1138 let span = self.span_from_span(sub_span);
1139 let parent = self.save_ctxt.tcx.local_parent(item.owner_id.def_id);
1143 kind: ImportKind::Use,
1147 name: item.ident.to_string(),
1148 value: String::new(),
1149 parent: Some(id_from_def_id(parent.to_def_id())),
1152 self.write_sub_paths_truncated(&path);
1155 hir::ItemKind::Use(path, hir::UseKind::Glob) => {
1156 // Make a comma-separated list of names of imported modules.
1157 let names = self.tcx.names_imported_by_glob_use(item.owner_id.def_id);
1158 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1160 // Otherwise it's a span with wrong macro expansion info, which
1161 // we don't want to track anyway, since it's probably macro-internal `use`
1162 if let Some(sub_span) = self.span.sub_span_of_star(item.span) {
1163 if !self.span.filter_generated(item.span) {
1164 let access = access_from!(self.save_ctxt, item.owner_id.def_id);
1165 let span = self.span_from_span(sub_span);
1166 let parent = self.save_ctxt.tcx.local_parent(item.owner_id.def_id);
1170 kind: ImportKind::GlobUse,
1174 name: "*".to_owned(),
1175 value: names.join(", "),
1176 parent: Some(id_from_def_id(parent.to_def_id())),
1179 self.write_sub_paths(&path);
1183 hir::ItemKind::ExternCrate(_) => {
1184 let name_span = item.ident.span;
1185 if !self.span.filter_generated(name_span) {
1186 let span = self.span_from_span(name_span);
1187 let parent = self.save_ctxt.tcx.local_parent(item.owner_id.def_id);
1189 &Access { public: false, reachable: false },
1191 kind: ImportKind::ExternCrate,
1195 name: item.ident.to_string(),
1196 value: String::new(),
1197 parent: Some(id_from_def_id(parent.to_def_id())),
1202 hir::ItemKind::Fn(ref sig, ref ty_params, body) => {
1203 self.process_fn(item, sig.decl, &sig.header, ty_params, body)
1205 hir::ItemKind::Static(ref typ, _, body) => {
1206 let body = self.tcx.hir().body(body);
1207 self.process_static_or_const_item(item, typ, &body.value)
1209 hir::ItemKind::Const(ref typ, body) => {
1210 let body = self.tcx.hir().body(body);
1211 self.process_static_or_const_item(item, typ, &body.value)
1213 hir::ItemKind::Struct(ref def, ref ty_params)
1214 | hir::ItemKind::Union(ref def, ref ty_params) => {
1215 self.process_struct(item, def, ty_params)
1217 hir::ItemKind::Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1218 hir::ItemKind::Impl(ref impl_) => self.process_impl(item, impl_),
1219 hir::ItemKind::Trait(_, _, ref generics, ref trait_refs, methods) => {
1220 self.process_trait(item, generics, trait_refs, methods)
1222 hir::ItemKind::Mod(ref m) => {
1223 self.process_mod(item);
1224 intravisit::walk_mod(self, m, item.hir_id());
1226 hir::ItemKind::TyAlias(ty, ref generics) => {
1227 let qualname = format!("::{}", self.tcx.def_path_str(item.owner_id.to_def_id()));
1228 let value = ty_to_string(&ty);
1229 if !self.span.filter_generated(item.ident.span) {
1230 let span = self.span_from_span(item.ident.span);
1231 let id = id_from_def_id(item.owner_id.to_def_id());
1232 let attrs = self.tcx.hir().attrs(item.hir_id());
1234 self.dumper.dump_def(
1235 &access_from!(self.save_ctxt, item.owner_id.def_id),
1237 kind: DefKind::Type,
1240 name: item.ident.to_string(),
1241 qualname: qualname.clone(),
1246 docs: self.save_ctxt.docs_for_attrs(attrs),
1247 sig: sig::item_signature(item, &self.save_ctxt),
1248 attributes: lower_attributes(attrs.to_vec(), &self.save_ctxt),
1254 self.process_generic_params(generics, &qualname, item.hir_id());
1256 _ => intravisit::walk_item(self, item),
1260 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1261 for param in generics.params {
1263 hir::GenericParamKind::Lifetime { .. } => {}
1264 hir::GenericParamKind::Type { ref default, .. } => {
1265 if let Some(ref ty) = default {
1269 hir::GenericParamKind::Const { ref ty, ref default } => {
1271 if let Some(default) = default {
1272 self.visit_anon_const(default);
1277 for pred in generics.predicates {
1278 if let hir::WherePredicate::BoundPredicate(ref wbp) = *pred {
1279 self.process_bounds(wbp.bounds);
1280 self.visit_ty(wbp.bounded_ty);
1285 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
1286 self.process_macro_use(t.span);
1288 hir::TyKind::Path(ref path) => {
1289 if generated_code(t.span) {
1293 if let Some(id) = self.lookup_def_id(t.hir_id) {
1294 let sub_span = path.last_segment_span();
1295 let span = self.span_from_span(sub_span);
1296 self.dumper.dump_ref(Ref {
1297 kind: RefKind::Type,
1299 ref_id: id_from_def_id(id),
1303 if let hir::QPath::Resolved(_, path) = path {
1304 self.write_sub_paths_truncated(path);
1306 intravisit::walk_qpath(self, path, t.hir_id);
1308 hir::TyKind::Array(ref ty, ref length) => {
1310 let map = self.tcx.hir();
1312 // FIXME(generic_arg_infer): We probably want to
1313 // output the inferred type here? :shrug:
1314 hir::ArrayLen::Infer(..) => {}
1315 hir::ArrayLen::Body(anon_const) => self
1316 .nest_typeck_results(anon_const.def_id, |v| {
1317 v.visit_expr(&map.body(anon_const.body).value)
1321 hir::TyKind::OpaqueDef(item_id, _, _) => {
1322 let item = self.tcx.hir().item(item_id);
1323 self.nest_typeck_results(item_id.owner_id.def_id, |v| v.visit_item(item));
1325 _ => intravisit::walk_ty(self, t),
1329 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1330 debug!("visit_expr {:?}", ex.kind);
1331 self.process_macro_use(ex.span);
1333 hir::ExprKind::Struct(ref path, ref fields, ref rest) => {
1334 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(ex.hir_id);
1335 let adt = match self.save_ctxt.typeck_results().expr_ty_opt(&hir_expr) {
1336 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1338 intravisit::walk_expr(self, ex);
1342 let res = self.save_ctxt.get_path_res(hir_expr.hir_id);
1343 self.process_struct_lit(ex, path, fields, adt.variant_of_res(res), *rest)
1345 hir::ExprKind::MethodCall(ref seg, receiver, args, _) => {
1346 self.process_method_call(ex, seg, receiver, args)
1348 hir::ExprKind::Field(ref sub_ex, _) => {
1349 self.visit_expr(&sub_ex);
1351 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1352 down_cast_data!(field_data, RefData, ex.span);
1353 if !generated_code(ex.span) {
1354 self.dumper.dump_ref(field_data);
1358 hir::ExprKind::Closure(&hir::Closure { ref fn_decl, body, def_id, .. }) => {
1359 let id = format!("${}", ex.hir_id);
1361 // walk arg and return types
1362 for ty in fn_decl.inputs {
1366 if let hir::FnRetTy::Return(ref ret_ty) = fn_decl.output {
1367 self.visit_ty(ret_ty);
1371 let map = self.tcx.hir();
1372 self.nest_typeck_results(def_id, |v| {
1373 let body = map.body(body);
1374 v.process_formals(body.params, &id);
1375 v.visit_expr(&body.value)
1378 hir::ExprKind::Repeat(ref expr, ref length) => {
1379 self.visit_expr(expr);
1380 let map = self.tcx.hir();
1382 // FIXME(generic_arg_infer): We probably want to
1383 // output the inferred type here? :shrug:
1384 hir::ArrayLen::Infer(..) => {}
1385 hir::ArrayLen::Body(anon_const) => self
1386 .nest_typeck_results(anon_const.def_id, |v| {
1387 v.visit_expr(&map.body(anon_const.body).value)
1391 // In particular, we take this branch for call and path expressions,
1392 // where we'll index the idents involved just by continuing to walk.
1393 _ => intravisit::walk_expr(self, ex),
1397 fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
1398 self.process_macro_use(p.span);
1399 self.process_pat(p);
1402 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1403 self.process_var_decl(&arm.pat);
1404 if let Some(hir::Guard::If(expr)) = &arm.guard {
1405 self.visit_expr(expr);
1407 self.visit_expr(&arm.body);
1410 fn visit_qpath(&mut self, path: &'tcx hir::QPath<'tcx>, id: hir::HirId, _: Span) {
1411 self.process_path(id, path);
1414 fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) {
1415 self.process_macro_use(s.span);
1416 intravisit::walk_stmt(self, s)
1419 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
1420 self.process_macro_use(l.span);
1421 self.process_var_decl(&l.pat);
1423 // Just walk the initializer, the else branch and type (don't want to walk the pattern again).
1424 walk_list!(self, visit_ty, &l.ty);
1425 walk_list!(self, visit_expr, &l.init);
1426 walk_list!(self, visit_block, l.els);
1429 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
1430 let access = access_from!(self.save_ctxt, item.owner_id.def_id);
1433 hir::ForeignItemKind::Fn(decl, _, ref generics) => {
1434 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1435 down_cast_data!(fn_data, DefData, item.span);
1437 self.process_generic_params(generics, &fn_data.qualname, item.hir_id());
1438 self.dumper.dump_def(&access, fn_data);
1441 for ty in decl.inputs {
1445 if let hir::FnRetTy::Return(ref ret_ty) = decl.output {
1446 self.visit_ty(ret_ty);
1449 hir::ForeignItemKind::Static(ref ty, _) => {
1450 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1451 down_cast_data!(var_data, DefData, item.span);
1452 self.dumper.dump_def(&access, var_data);
1457 hir::ForeignItemKind::Type => {
1458 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1459 down_cast_data!(var_data, DefData, item.span);
1460 self.dumper.dump_def(&access, var_data);