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_data_structures::fx::FxHashSet;
20 use rustc_hir::def::{DefKind as HirDefKind, Res};
21 use rustc_hir::def_id::DefId;
26 use rustc_span::source_map::{respan, DUMMY_SP};
28 use syntax::ast::{self, Attribute, NodeId, PatKind};
29 use syntax::print::pprust::{bounds_to_string, generic_params_to_string, ty_to_string};
32 use syntax::visit::{self, Visitor};
33 use syntax::walk_list;
35 use crate::dumper::{Access, Dumper};
37 use crate::span_utils::SpanUtils;
39 escape, generated_code, id_from_def_id, id_from_node_id, lower_attributes, PathCollector,
44 CompilationOptions, CratePreludeData, Def, DefKind, GlobalCrateId, Import, ImportKind, Ref,
45 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) => {
71 Access { public: $vis.node.is_pub(), reachable: $save_ctxt.access_levels.is_reachable($id) }
75 pub struct DumpVisitor<'l, 'tcx> {
76 pub save_ctxt: SaveContext<'l, 'tcx>,
81 // Set of macro definition (callee) spans, and the set
82 // of macro use (callsite) spans. We store these to ensure
83 // we only write one macro def per unique macro definition, and
84 // one macro use per unique callsite span.
85 // mac_defs: FxHashSet<Span>,
86 // macro_calls: FxHashSet<Span>,
89 impl<'l, 'tcx> DumpVisitor<'l, 'tcx> {
90 pub fn new(save_ctxt: SaveContext<'l, 'tcx>) -> DumpVisitor<'l, 'tcx> {
91 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
92 let dumper = Dumper::new(save_ctxt.config.clone());
98 // mac_defs: FxHashSet::default(),
99 // macro_calls: FxHashSet::default(),
103 pub fn analysis(&self) -> &rls_data::Analysis {
104 self.dumper.analysis()
107 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
109 F: FnOnce(&mut Self),
111 let item_def_id = self.tcx.hir().local_def_id_from_node_id(item_id);
113 let tables = if self.tcx.has_typeck_tables(item_def_id) {
114 self.tcx.typeck_tables_of(item_def_id)
116 self.save_ctxt.empty_tables
119 let old_tables = self.save_ctxt.tables;
120 self.save_ctxt.tables = tables;
122 self.save_ctxt.tables = old_tables;
125 fn span_from_span(&self, span: Span) -> SpanData {
126 self.save_ctxt.span_from_span(span)
129 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
130 self.save_ctxt.lookup_def_id(ref_id)
133 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
134 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
135 let crate_root = source_file.map(|source_file| {
136 let source_file = Path::new(source_file);
137 match source_file.file_name() {
138 Some(_) => source_file.parent().unwrap().display(),
139 None => source_file.display(),
144 let data = CratePreludeData {
145 crate_id: GlobalCrateId {
150 .local_crate_disambiguator()
154 crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
155 external_crates: self.save_ctxt.get_external_crates(),
156 span: self.span_from_span(krate.span),
159 self.dumper.crate_prelude(data);
162 pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
163 // Apply possible `remap-path-prefix` remapping to the input source file
164 // (and don't include remapping args anymore)
165 let (program, arguments) = {
166 let remap_arg_indices = {
167 let mut indices = FxHashSet::default();
168 // Args are guaranteed to be valid UTF-8 (checked early)
169 for (i, e) in env::args().enumerate() {
170 if e.starts_with("--remap-path-prefix=") {
172 } else if e == "--remap-path-prefix" {
174 indices.insert(i + 1);
180 let mut args = env::args()
182 .filter(|(i, _)| !remap_arg_indices.contains(i))
183 .map(|(_, arg)| match input {
184 Input::File(ref path) if path == Path::new(&arg) => {
185 let mapped = &self.tcx.sess.local_crate_source_file;
186 mapped.as_ref().unwrap().to_string_lossy().into()
191 (args.next().unwrap(), args.collect())
194 let data = CompilationOptions {
195 directory: self.tcx.sess.working_dir.0.clone(),
198 output: self.save_ctxt.compilation_output(crate_name),
201 self.dumper.compilation_opts(data);
204 fn write_sub_paths(&mut self, path: &ast::Path) {
205 for seg in &path.segments {
206 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
207 self.dumper.dump_ref(data);
212 // As write_sub_paths, but does not process the last ident in the path (assuming it
213 // will be processed elsewhere). See note on write_sub_paths about global.
214 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
215 for seg in &path.segments[..path.segments.len() - 1] {
216 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
217 self.dumper.dump_ref(data);
222 fn process_formals(&mut self, formals: &'l [ast::Param], qualname: &str) {
224 self.visit_pat(&arg.pat);
225 let mut collector = PathCollector::new();
226 collector.visit_pat(&arg.pat);
228 for (id, ident, ..) in collector.collected_idents {
229 let hir_id = self.tcx.hir().node_to_hir_id(id);
230 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
231 Some(s) => s.to_string(),
234 if !self.span.filter_generated(ident.span) {
235 let id = id_from_node_id(id, &self.save_ctxt);
236 let span = self.span_from_span(ident.span);
238 self.dumper.dump_def(
239 &Access { public: false, reachable: false },
241 kind: DefKind::Local,
244 name: ident.to_string(),
245 qualname: format!("{}::{}", qualname, ident.to_string()),
263 body: Option<&'l ast::Block>,
266 generics: &'l ast::Generics,
267 vis: ast::Visibility,
270 debug!("process_method: {}:{}", id, ident);
272 let hir_id = self.tcx.hir().node_to_hir_id(id);
273 self.nest_tables(id, |v| {
274 if let Some(mut method_data) = v.save_ctxt.get_method_data(id, ident, span) {
275 v.process_formals(&sig.decl.inputs, &method_data.qualname);
276 v.process_generic_params(&generics, &method_data.qualname, id);
278 method_data.value = crate::make_signature(&sig.decl, &generics);
279 method_data.sig = sig::method_signature(id, ident, generics, sig, &v.save_ctxt);
281 v.dumper.dump_def(&access_from_vis!(v.save_ctxt, vis, hir_id), method_data);
284 // walk arg and return types
285 for arg in &sig.decl.inputs {
289 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
290 // In async functions, return types are desugared and redefined
291 // as an `impl Trait` existential type. Because of this, to match
292 // the definition paths when resolving nested types we need to
293 // start walking from the newly-created definition.
294 match sig.header.asyncness.node {
295 ast::IsAsync::Async { return_impl_trait_id, .. } => {
296 v.nest_tables(return_impl_trait_id, |v| v.visit_ty(ret_ty))
298 _ => v.visit_ty(ret_ty),
303 if let Some(body) = body {
309 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
310 let field_data = self.save_ctxt.get_field_data(field, parent_id);
311 if let Some(field_data) = field_data {
312 let hir_id = self.tcx.hir().node_to_hir_id(field.id);
313 self.dumper.dump_def(&access_from!(self.save_ctxt, field, hir_id), field_data);
317 // Dump generic params bindings, then visit_generics
318 fn process_generic_params(&mut self, generics: &'l ast::Generics, prefix: &str, id: NodeId) {
319 for param in &generics.params {
321 ast::GenericParamKind::Lifetime { .. } => {}
322 ast::GenericParamKind::Type { .. } => {
323 let param_ss = param.ident.span;
324 let name = escape(self.span.snippet(param_ss));
325 // Append $id to name to make sure each one is unique.
326 let qualname = format!("{}::{}${}", prefix, name, id);
327 if !self.span.filter_generated(param_ss) {
328 let id = id_from_node_id(param.id, &self.save_ctxt);
329 let span = self.span_from_span(param_ss);
331 self.dumper.dump_def(
332 &Access { public: false, reachable: false },
339 value: String::new(),
350 ast::GenericParamKind::Const { .. } => {}
353 self.visit_generics(generics);
359 decl: &'l ast::FnDecl,
360 header: &'l ast::FnHeader,
361 ty_params: &'l ast::Generics,
362 body: &'l ast::Block,
364 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
365 self.nest_tables(item.id, |v| {
366 if let Some(fn_data) = v.save_ctxt.get_item_data(item) {
367 down_cast_data!(fn_data, DefData, item.span);
368 v.process_formals(&decl.inputs, &fn_data.qualname);
369 v.process_generic_params(ty_params, &fn_data.qualname, item.id);
371 v.dumper.dump_def(&access_from!(v.save_ctxt, item, hir_id), fn_data);
374 for arg in &decl.inputs {
378 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
379 if let ast::TyKind::ImplTrait(..) = ret_ty.kind {
380 // FIXME: Opaque type desugaring prevents us from easily
381 // processing trait bounds. See `visit_ty` for more details.
383 // In async functions, return types are desugared and redefined
384 // as an `impl Trait` existential type. Because of this, to match
385 // the definition paths when resolving nested types we need to
386 // start walking from the newly-created definition.
387 match header.asyncness.node {
388 ast::IsAsync::Async { return_impl_trait_id, .. } => {
389 v.nest_tables(return_impl_trait_id, |v| v.visit_ty(ret_ty))
391 _ => v.visit_ty(ret_ty),
396 v.visit_block(&body);
400 fn process_static_or_const_item(
406 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
407 self.nest_tables(item.id, |v| {
408 if let Some(var_data) = v.save_ctxt.get_item_data(item) {
409 down_cast_data!(var_data, DefData, item.span);
410 v.dumper.dump_def(&access_from!(v.save_ctxt, item, hir_id), var_data);
417 fn process_assoc_const(
422 expr: Option<&'l ast::Expr>,
424 vis: ast::Visibility,
425 attrs: &'l [Attribute],
428 format!("::{}", self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
430 if !self.span.filter_generated(ident.span) {
431 let sig = sig::assoc_const_signature(id, ident.name, typ, expr, &self.save_ctxt);
432 let span = self.span_from_span(ident.span);
433 let hir_id = self.tcx.hir().node_to_hir_id(id);
435 self.dumper.dump_def(
436 &access_from_vis!(self.save_ctxt, vis, hir_id),
438 kind: DefKind::Const,
439 id: id_from_node_id(id, &self.save_ctxt),
441 name: ident.name.to_string(),
443 value: ty_to_string(&typ),
444 parent: Some(id_from_def_id(parent_id)),
447 docs: self.save_ctxt.docs_for_attrs(attrs),
449 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
454 // walk type and init value
455 self.nest_tables(id, |v| {
457 if let Some(expr) = expr {
463 // FIXME tuple structs should generate tuple-specific data.
467 def: &'l ast::VariantData,
468 ty_params: &'l ast::Generics,
470 debug!("process_struct {:?} {:?}", item, item.span);
471 let name = item.ident.to_string();
472 let qualname = format!(
474 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() {
492 f.ident.map(|i| i.to_string()).or_else(|| Some(i.to_string()))
499 let value = format!("{} {{ {} }}", name, fields_str);
500 (value, fields.iter().map(|f| id_from_node_id(f.id, &self.save_ctxt)).collect())
502 _ => (String::new(), vec![]),
505 if !self.span.filter_generated(item.ident.span) {
506 let span = self.span_from_span(item.ident.span);
507 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
508 self.dumper.dump_def(
509 &access_from!(self.save_ctxt, item, hir_id),
512 id: id_from_node_id(item.id, &self.save_ctxt),
515 qualname: qualname.clone(),
520 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
521 sig: sig::item_signature(item, &self.save_ctxt),
522 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
527 self.nest_tables(item.id, |v| {
528 for field in def.fields() {
529 v.process_struct_field_def(field, item.id);
530 v.visit_ty(&field.ty);
533 v.process_generic_params(ty_params, &qualname, item.id);
540 enum_definition: &'l ast::EnumDef,
541 ty_params: &'l ast::Generics,
543 let enum_data = self.save_ctxt.get_item_data(item);
544 let enum_data = match enum_data {
548 down_cast_data!(enum_data, DefData, item.span);
550 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
551 let access = access_from!(self.save_ctxt, item, hir_id);
553 for variant in &enum_definition.variants {
554 let name = variant.ident.name.to_string();
555 let qualname = format!("{}::{}", enum_data.qualname, name);
556 let name_span = variant.ident.span;
559 ast::VariantData::Struct(ref fields, ..) => {
560 let fields_str = fields
564 f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
568 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
569 if !self.span.filter_generated(name_span) {
570 let span = self.span_from_span(name_span);
571 let id = id_from_node_id(variant.id, &self.save_ctxt);
572 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
574 self.dumper.dump_def(
577 kind: DefKind::StructVariant,
586 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
587 sig: sig::variant_signature(variant, &self.save_ctxt),
588 attributes: lower_attributes(
589 variant.attrs.clone(),
597 let mut value = format!("{}::{}", enum_data.name, name);
598 if let &ast::VariantData::Tuple(ref fields, _) = v {
603 .map(|f| ty_to_string(&f.ty))
609 if !self.span.filter_generated(name_span) {
610 let span = self.span_from_span(name_span);
611 let id = id_from_node_id(variant.id, &self.save_ctxt);
612 let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
614 self.dumper.dump_def(
617 kind: DefKind::TupleVariant,
626 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
627 sig: sig::variant_signature(variant, &self.save_ctxt),
628 attributes: lower_attributes(
629 variant.attrs.clone(),
638 for field in variant.data.fields() {
639 self.process_struct_field_def(field, variant.id);
640 self.visit_ty(&field.ty);
643 self.process_generic_params(ty_params, &enum_data.qualname, item.id);
644 self.dumper.dump_def(&access, enum_data);
650 generics: &'l ast::Generics,
651 trait_ref: &'l Option<ast::TraitRef>,
653 impl_items: &'l [ast::AssocItem],
655 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
656 if !self.span.filter_generated(item.span) {
657 if let super::Data::RelationData(rel, imp) = impl_data {
658 self.dumper.dump_relation(rel);
659 self.dumper.dump_impl(imp);
661 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
666 let map = &self.tcx.hir();
667 self.nest_tables(item.id, |v| {
669 if let &Some(ref trait_ref) = trait_ref {
670 v.process_path(trait_ref.ref_id, &trait_ref.path);
672 v.process_generic_params(generics, "", item.id);
673 for impl_item in impl_items {
674 v.process_impl_item(impl_item, map.local_def_id_from_node_id(item.id));
682 generics: &'l ast::Generics,
683 trait_refs: &'l ast::GenericBounds,
684 methods: &'l [ast::AssocItem],
686 let name = item.ident.to_string();
687 let qualname = format!(
689 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id))
691 let mut val = name.clone();
692 if !generics.params.is_empty() {
693 val.push_str(&generic_params_to_string(&generics.params));
695 if !trait_refs.is_empty() {
697 val.push_str(&bounds_to_string(trait_refs));
699 if !self.span.filter_generated(item.ident.span) {
700 let id = id_from_node_id(item.id, &self.save_ctxt);
701 let span = self.span_from_span(item.ident.span);
702 let children = methods.iter().map(|i| id_from_node_id(i.id, &self.save_ctxt)).collect();
703 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
704 self.dumper.dump_def(
705 &access_from!(self.save_ctxt, item, hir_id),
707 kind: DefKind::Trait,
711 qualname: qualname.clone(),
716 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
717 sig: sig::item_signature(item, &self.save_ctxt),
718 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
724 for super_bound in trait_refs.iter() {
725 let trait_ref = match *super_bound {
726 ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
727 ast::GenericBound::Outlives(..) => continue,
730 let trait_ref = &trait_ref.trait_ref;
731 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
732 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
733 if !self.span.filter_generated(sub_span) {
734 let span = self.span_from_span(sub_span);
735 self.dumper.dump_ref(Ref {
738 ref_id: id_from_def_id(id),
741 self.dumper.dump_relation(Relation {
742 kind: RelationKind::SuperTrait,
744 from: id_from_def_id(id),
745 to: id_from_node_id(item.id, &self.save_ctxt),
751 // walk generics and methods
752 self.process_generic_params(generics, &qualname, item.id);
753 for method in methods {
754 let map = &self.tcx.hir();
755 self.process_trait_item(method, map.local_def_id_from_node_id(item.id))
759 // `item` is the module in question, represented as an item.
760 fn process_mod(&mut self, item: &ast::Item) {
761 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
762 down_cast_data!(mod_data, DefData, item.span);
763 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
764 self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), mod_data);
768 fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
769 let path_data = self.save_ctxt.get_path_data(id, path);
770 if let Some(path_data) = path_data {
771 self.dumper.dump_ref(path_data);
775 fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
776 if self.span.filter_generated(path.span) {
779 self.dump_path_ref(id, path);
782 for seg in &path.segments {
783 if let Some(ref generic_args) = seg.args {
784 match **generic_args {
785 ast::GenericArgs::AngleBracketed(ref data) => {
786 for arg in &data.args {
787 if let ast::GenericArg::Type(ty) = arg {
792 ast::GenericArgs::Parenthesized(ref data) => {
793 for t in &data.inputs {
796 if let ast::FunctionRetTy::Ty(ty) = &data.output {
804 self.write_sub_paths_truncated(path);
807 fn process_struct_lit(
811 fields: &'l [ast::Field],
812 variant: &'l ty::VariantDef,
813 base: &'l Option<P<ast::Expr>>,
815 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
816 self.write_sub_paths_truncated(path);
817 down_cast_data!(struct_lit_data, RefData, ex.span);
818 if !generated_code(ex.span) {
819 self.dumper.dump_ref(struct_lit_data);
822 for field in fields {
823 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
824 self.dumper.dump_ref(field_data);
827 self.visit_expr(&field.expr)
831 walk_list!(self, visit_expr, base);
834 fn process_method_call(
837 seg: &'l ast::PathSegment,
838 args: &'l [P<ast::Expr>],
840 debug!("process_method_call {:?} {:?}", ex, ex.span);
841 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
842 down_cast_data!(mcd, RefData, ex.span);
843 if !generated_code(ex.span) {
844 self.dumper.dump_ref(mcd);
848 // Explicit types in the turbo-fish.
849 if let Some(ref generic_args) = seg.args {
850 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
851 for arg in &data.args {
853 ast::GenericArg::Type(ty) => self.visit_ty(ty),
860 // walk receiver and args
861 walk_list!(self, visit_expr, args);
864 fn process_pat(&mut self, p: &'l ast::Pat) {
866 PatKind::Struct(ref _path, ref fields, _) => {
867 // FIXME do something with _path?
868 let hir_id = self.tcx.hir().node_to_hir_id(p.id);
869 let adt = match self.save_ctxt.tables.node_type_opt(hir_id) {
870 Some(ty) => ty.ty_adt_def().unwrap(),
872 visit::walk_pat(self, p);
876 let variant = adt.variant_of_res(self.save_ctxt.get_path_res(p.id));
878 for field in fields {
879 if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
880 if !self.span.filter_generated(field.ident.span) {
881 let span = self.span_from_span(field.ident.span);
882 self.dumper.dump_ref(Ref {
883 kind: RefKind::Variable,
885 ref_id: id_from_def_id(variant.fields[index].did),
889 self.visit_pat(&field.pat);
892 _ => visit::walk_pat(self, p),
896 fn process_var_decl(&mut self, pat: &'l ast::Pat) {
897 // The pattern could declare multiple new vars,
898 // we must walk the pattern and collect them all.
899 let mut collector = PathCollector::new();
900 collector.visit_pat(&pat);
901 self.visit_pat(&pat);
903 // Process collected paths.
904 for (id, ident, _) in collector.collected_idents {
905 match self.save_ctxt.get_path_res(id) {
906 Res::Local(hir_id) => {
907 let id = self.tcx.hir().hir_to_node_id(hir_id);
911 .node_type_opt(hir_id)
912 .map(|t| t.to_string())
913 .unwrap_or_default();
915 // Rust uses the id of the pattern for var lookups, so we'll use it too.
916 if !self.span.filter_generated(ident.span) {
917 let qualname = format!("{}${}", ident.to_string(), id);
918 let id = id_from_node_id(id, &self.save_ctxt);
919 let span = self.span_from_span(ident.span);
921 self.dumper.dump_def(
922 &Access { public: false, reachable: false },
924 kind: DefKind::Local,
927 name: ident.to_string(),
940 Res::Def(HirDefKind::Ctor(..), _)
941 | Res::Def(HirDefKind::Const, _)
942 | Res::Def(HirDefKind::AssocConst, _)
943 | Res::Def(HirDefKind::Struct, _)
944 | Res::Def(HirDefKind::Variant, _)
945 | Res::Def(HirDefKind::TyAlias, _)
946 | Res::Def(HirDefKind::AssocTy, _)
947 | Res::SelfTy(..) => {
948 self.dump_path_ref(id, &ast::Path::from_ident(ident));
951 error!("unexpected definition kind when processing collected idents: {:?}", def)
956 for (id, ref path) in collector.collected_paths {
957 self.process_path(id, path);
961 /// Extracts macro use and definition information from the AST node defined
962 /// by the given NodeId, using the expansion information from the node's
965 /// If the span is not macro-generated, do nothing, else use callee and
966 /// callsite spans to record macro definition and use data, using the
967 /// mac_uses and mac_defs sets to prevent multiples.
968 fn process_macro_use(&mut self, _span: Span) {
969 // FIXME if we're not dumping the defs (see below), there is no point
970 // dumping refs either.
971 // let source_span = span.source_callsite();
972 // if !self.macro_calls.insert(source_span) {
976 // let data = match self.save_ctxt.get_macro_use_data(span) {
978 // Some(data) => data,
981 // self.dumper.macro_use(data);
983 // FIXME write the macro def
984 // let mut hasher = DefaultHasher::new();
985 // data.callee_span.hash(&mut hasher);
986 // let hash = hasher.finish();
987 // let qualname = format!("{}::{}", data.name, hash);
988 // Don't write macro definition for imported macros
989 // if !self.mac_defs.contains(&data.callee_span)
990 // && !data.imported {
991 // self.mac_defs.insert(data.callee_span);
992 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
993 // self.dumper.macro_data(MacroData {
995 // name: data.name.clone(),
996 // qualname: qualname.clone(),
997 // // FIXME where do macro docs come from?
998 // docs: String::new(),
999 // }.lower(self.tcx));
1004 fn process_trait_item(&mut self, trait_item: &'l ast::AssocItem, trait_id: DefId) {
1005 self.process_macro_use(trait_item.span);
1006 let vis_span = trait_item.span.shrink_to_lo();
1007 match trait_item.kind {
1008 ast::AssocItemKind::Const(ref ty, ref expr) => {
1009 self.process_assoc_const(
1013 expr.as_ref().map(|e| &**e),
1015 respan(vis_span, ast::VisibilityKind::Public),
1019 ast::AssocItemKind::Fn(ref sig, ref body) => {
1020 self.process_method(
1022 body.as_ref().map(|x| &**x),
1025 &trait_item.generics,
1026 respan(vis_span, ast::VisibilityKind::Public),
1030 ast::AssocItemKind::TyAlias(ref bounds, ref default_ty) => {
1031 // FIXME do something with _bounds (for type refs)
1032 let name = trait_item.ident.name.to_string();
1033 let qualname = format!(
1035 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(trait_item.id))
1038 if !self.span.filter_generated(trait_item.ident.span) {
1039 let span = self.span_from_span(trait_item.ident.span);
1040 let id = id_from_node_id(trait_item.id, &self.save_ctxt);
1042 self.dumper.dump_def(
1043 &Access { public: true, reachable: true },
1045 kind: DefKind::Type,
1050 value: self.span.snippet(trait_item.span),
1051 parent: Some(id_from_def_id(trait_id)),
1054 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1055 sig: sig::assoc_type_signature(
1059 default_ty.as_ref().map(|ty| &**ty),
1062 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1067 if let &Some(ref default_ty) = default_ty {
1068 self.visit_ty(default_ty)
1071 ast::AssocItemKind::Macro(_) => {}
1075 fn process_impl_item(&mut self, impl_item: &'l ast::AssocItem, impl_id: DefId) {
1076 self.process_macro_use(impl_item.span);
1077 match impl_item.kind {
1078 ast::AssocItemKind::Const(ref ty, ref expr) => {
1079 self.process_assoc_const(
1085 impl_item.vis.clone(),
1089 ast::AssocItemKind::Fn(ref sig, ref body) => {
1090 self.process_method(
1095 &impl_item.generics,
1096 impl_item.vis.clone(),
1100 ast::AssocItemKind::TyAlias(_, None) => {}
1101 ast::AssocItemKind::TyAlias(_, Some(ref ty)) => {
1102 // FIXME: uses of the assoc type should ideally point to this
1103 // 'def' and the name here should be a ref to the def in the
1107 ast::AssocItemKind::Macro(_) => {}
1111 /// Dumps imports in a use tree recursively.
1113 /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1114 /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1115 /// ID and path. `root_item` is the topmost use tree in the hierarchy.
1117 /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1118 /// each child use tree is dumped recursively.
1119 fn process_use_tree(
1121 use_tree: &'l ast::UseTree,
1123 root_item: &'l ast::Item,
1126 let path = &use_tree.prefix;
1128 // The access is calculated using the current tree ID, but with the root tree's visibility
1129 // (since nested trees don't have their own visibility).
1130 let hir_id = self.tcx.hir().node_to_hir_id(id);
1131 let access = access_from!(self.save_ctxt, root_item, hir_id);
1133 // The parent `DefId` of a given use tree is always the enclosing item.
1138 .opt_local_def_id_from_node_id(id)
1139 .and_then(|id| self.save_ctxt.tcx.parent(id))
1140 .map(id_from_def_id);
1142 match use_tree.kind {
1143 ast::UseTreeKind::Simple(alias, ..) => {
1144 let ident = use_tree.ident();
1145 let path = ast::Path {
1146 segments: prefix.segments.iter().chain(path.segments.iter()).cloned().collect(),
1150 let sub_span = path.segments.last().unwrap().ident.span;
1151 if !self.span.filter_generated(sub_span) {
1152 let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id));
1153 let alias_span = alias.map(|i| self.span_from_span(i.span));
1154 let span = self.span_from_span(sub_span);
1158 kind: ImportKind::Use,
1162 name: ident.to_string(),
1163 value: String::new(),
1167 self.write_sub_paths_truncated(&path);
1170 ast::UseTreeKind::Glob => {
1171 let path = ast::Path {
1172 segments: prefix.segments.iter().chain(path.segments.iter()).cloned().collect(),
1176 // Make a comma-separated list of names of imported modules.
1177 let def_id = self.tcx.hir().local_def_id_from_node_id(id);
1178 let names = self.tcx.names_imported_by_glob_use(def_id);
1179 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1181 // Otherwise it's a span with wrong macro expansion info, which
1182 // we don't want to track anyway, since it's probably macro-internal `use`
1183 if let Some(sub_span) =
1184 self.span.sub_span_of_token(use_tree.span, token::BinOp(token::Star))
1186 if !self.span.filter_generated(use_tree.span) {
1187 let span = self.span_from_span(sub_span);
1192 kind: ImportKind::GlobUse,
1196 name: "*".to_owned(),
1197 value: names.join(", "),
1201 self.write_sub_paths(&path);
1205 ast::UseTreeKind::Nested(ref nested_items) => {
1206 let prefix = ast::Path {
1207 segments: prefix.segments.iter().chain(path.segments.iter()).cloned().collect(),
1210 for &(ref tree, id) in nested_items {
1211 self.process_use_tree(tree, id, root_item, &prefix);
1217 fn process_bounds(&mut self, bounds: &'l ast::GenericBounds) {
1218 for bound in bounds {
1219 if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1220 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1226 impl<'l, 'tcx> Visitor<'l> for DumpVisitor<'l, 'tcx> {
1227 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1228 // Since we handle explicit modules ourselves in visit_item, this should
1229 // only get called for the root module of a crate.
1230 assert_eq!(id, ast::CRATE_NODE_ID);
1233 format!("::{}", self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
1235 let cm = self.tcx.sess.source_map();
1236 let filename = cm.span_to_filename(span);
1237 let data_id = id_from_node_id(id, &self.save_ctxt);
1238 let children = m.items.iter().map(|i| id_from_node_id(i.id, &self.save_ctxt)).collect();
1239 let span = self.span_from_span(span);
1241 self.dumper.dump_def(
1242 &Access { public: true, reachable: true },
1246 name: String::new(),
1249 value: filename.to_string(),
1253 docs: self.save_ctxt.docs_for_attrs(attrs),
1255 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1258 visit::walk_mod(self, m);
1261 fn visit_item(&mut self, item: &'l ast::Item) {
1262 use syntax::ast::ItemKind::*;
1263 self.process_macro_use(item.span);
1265 Use(ref use_tree) => {
1266 let prefix = ast::Path { segments: vec![], span: DUMMY_SP };
1267 self.process_use_tree(use_tree, item.id, item, &prefix);
1270 let name_span = item.ident.span;
1271 if !self.span.filter_generated(name_span) {
1272 let span = self.span_from_span(name_span);
1277 .opt_local_def_id_from_node_id(item.id)
1278 .and_then(|id| self.save_ctxt.tcx.parent(id))
1279 .map(id_from_def_id);
1281 &Access { public: false, reachable: false },
1283 kind: ImportKind::ExternCrate,
1287 name: item.ident.to_string(),
1288 value: String::new(),
1294 Fn(ref sig, ref ty_params, ref body) => {
1295 self.process_fn(item, &sig.decl, &sig.header, ty_params, &body)
1297 Static(ref typ, _, ref expr) => self.process_static_or_const_item(item, typ, expr),
1298 Const(ref typ, ref expr) => self.process_static_or_const_item(item, &typ, &expr),
1299 Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1300 self.process_struct(item, def, ty_params)
1302 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1303 Impl { ref generics, ref of_trait, ref self_ty, ref items, .. } => {
1304 self.process_impl(item, generics, of_trait, &self_ty, items)
1306 Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1307 self.process_trait(item, generics, trait_refs, methods)
1310 self.process_mod(item);
1311 visit::walk_mod(self, m);
1313 TyAlias(ref ty, ref ty_params) => {
1314 let qualname = format!(
1316 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id))
1318 let value = ty_to_string(&ty);
1319 if !self.span.filter_generated(item.ident.span) {
1320 let span = self.span_from_span(item.ident.span);
1321 let id = id_from_node_id(item.id, &self.save_ctxt);
1322 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1324 self.dumper.dump_def(
1325 &access_from!(self.save_ctxt, item, hir_id),
1327 kind: DefKind::Type,
1330 name: item.ident.to_string(),
1331 qualname: qualname.clone(),
1336 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1337 sig: sig::item_signature(item, &self.save_ctxt),
1338 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1344 self.process_generic_params(ty_params, &qualname, item.id);
1347 _ => visit::walk_item(self, item),
1351 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1352 for param in &generics.params {
1354 ast::GenericParamKind::Lifetime { .. } => {}
1355 ast::GenericParamKind::Type { ref default, .. } => {
1356 self.process_bounds(¶m.bounds);
1357 if let Some(ref ty) = default {
1361 ast::GenericParamKind::Const { ref ty } => {
1362 self.process_bounds(¶m.bounds);
1367 for pred in &generics.where_clause.predicates {
1368 if let ast::WherePredicate::BoundPredicate(ref wbp) = *pred {
1369 self.process_bounds(&wbp.bounds);
1370 self.visit_ty(&wbp.bounded_ty);
1375 fn visit_ty(&mut self, t: &'l ast::Ty) {
1376 self.process_macro_use(t.span);
1378 ast::TyKind::Path(_, ref path) => {
1379 if generated_code(t.span) {
1383 if let Some(id) = self.lookup_def_id(t.id) {
1384 let sub_span = path.segments.last().unwrap().ident.span;
1385 let span = self.span_from_span(sub_span);
1386 self.dumper.dump_ref(Ref {
1387 kind: RefKind::Type,
1389 ref_id: id_from_def_id(id),
1393 self.write_sub_paths_truncated(path);
1394 visit::walk_path(self, path);
1396 ast::TyKind::Array(ref element, ref length) => {
1397 self.visit_ty(element);
1398 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1400 ast::TyKind::ImplTrait(id, ref bounds) => {
1401 // FIXME: As of writing, the opaque type lowering introduces
1402 // another DefPath scope/segment (used to declare the resulting
1403 // opaque type item).
1404 // However, the synthetic scope does *not* have associated
1405 // typeck tables, which means we can't nest it and we fire an
1406 // assertion when resolving the qualified type paths in trait
1408 // This will panic if called on return type `impl Trait`, which
1409 // we guard against in `process_fn`.
1410 self.nest_tables(id, |v| v.process_bounds(bounds));
1412 _ => visit::walk_ty(self, t),
1416 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1417 debug!("visit_expr {:?}", ex.kind);
1418 self.process_macro_use(ex.span);
1420 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1421 let expr_hir_id = self.save_ctxt.tcx.hir().node_to_hir_id(ex.id);
1422 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(expr_hir_id);
1423 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1424 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1426 visit::walk_expr(self, ex);
1430 let node_id = self.save_ctxt.tcx.hir().hir_to_node_id(hir_expr.hir_id);
1431 let res = self.save_ctxt.get_path_res(node_id);
1432 self.process_struct_lit(ex, path, fields, adt.variant_of_res(res), base)
1434 ast::ExprKind::MethodCall(ref seg, ref args) => self.process_method_call(ex, seg, args),
1435 ast::ExprKind::Field(ref sub_ex, _) => {
1436 self.visit_expr(&sub_ex);
1438 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1439 down_cast_data!(field_data, RefData, ex.span);
1440 if !generated_code(ex.span) {
1441 self.dumper.dump_ref(field_data);
1445 ast::ExprKind::Closure(_, _, _, ref decl, ref body, _fn_decl_span) => {
1446 let id = format!("${}", ex.id);
1448 // walk arg and return types
1449 for arg in &decl.inputs {
1450 self.visit_ty(&arg.ty);
1453 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1454 self.visit_ty(&ret_ty);
1458 self.nest_tables(ex.id, |v| {
1459 v.process_formals(&decl.inputs, &id);
1463 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1464 self.process_var_decl(pattern);
1465 debug!("for loop, walk sub-expr: {:?}", subexpression.kind);
1466 self.visit_expr(subexpression);
1467 visit::walk_block(self, block);
1469 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1470 self.process_var_decl(pat);
1471 self.visit_expr(scrutinee);
1473 ast::ExprKind::Repeat(ref element, ref count) => {
1474 self.visit_expr(element);
1475 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1477 // In particular, we take this branch for call and path expressions,
1478 // where we'll index the idents involved just by continuing to walk.
1479 _ => visit::walk_expr(self, ex),
1483 fn visit_pat(&mut self, p: &'l ast::Pat) {
1484 self.process_macro_use(p.span);
1485 self.process_pat(p);
1488 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1489 self.process_var_decl(&arm.pat);
1490 if let Some(expr) = &arm.guard {
1491 self.visit_expr(expr);
1493 self.visit_expr(&arm.body);
1496 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1497 self.process_path(id, p);
1500 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1501 self.process_macro_use(s.span);
1502 visit::walk_stmt(self, s)
1505 fn visit_local(&mut self, l: &'l ast::Local) {
1506 self.process_macro_use(l.span);
1507 self.process_var_decl(&l.pat);
1509 // Just walk the initialiser and type (don't want to walk the pattern again).
1510 walk_list!(self, visit_ty, &l.ty);
1511 walk_list!(self, visit_expr, &l.init);
1514 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1515 let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1516 let access = access_from!(self.save_ctxt, item, hir_id);
1519 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
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(..) => {}