1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Write the output of rustc's analysis to an implementor of Dump.
13 //! Dumping the analysis is implemented by walking the AST and getting a bunch of
14 //! info out from all over the place. We use Def IDs to identify objects. The
15 //! tricky part is getting syntactic (span, source text) and semantic (reference
16 //! Def IDs) information for parts of expressions which the compiler has discarded.
17 //! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
18 //! path and a reference to `baz`, but we want spans and references for all three
21 //! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
22 //! from spans (e.g., the span for `bar` from the above example path).
23 //! DumpVisitor walks the AST and processes it, and JsonDumper is used for
24 //! recording the output.
26 use rustc::hir::def::Def as HirDef;
27 use rustc::hir::def_id::DefId;
28 use rustc::session::config::Input;
29 use rustc::ty::{self, TyCtxt};
30 use rustc_data_structures::fx::FxHashSet;
35 use syntax::ast::{self, Attribute, NodeId, PatKind, CRATE_NODE_ID};
36 use syntax::parse::token;
37 use syntax::visit::{self, Visitor};
38 use syntax::print::pprust::{
40 generic_params_to_string,
44 use syntax::source_map::{Spanned, DUMMY_SP, respan};
47 use {escape, generated_code, lower_attributes, PathCollector, SaveContext};
48 use json_dumper::{Access, DumpOutput, JsonDumper};
49 use span_utils::SpanUtils;
52 use rls_data::{CompilationOptions, CratePreludeData, Def, DefKind, GlobalCrateId, Import,
53 ImportKind, Ref, RefKind, Relation, RelationKind, SpanData};
55 macro_rules! down_cast_data {
56 ($id:ident, $kind:ident, $sp:expr) => {
57 let $id = if let super::Data::$kind(data) = $id {
60 span_bug!($sp, "unexpected data kind: {:?}", $id);
65 macro_rules! access_from {
66 ($save_ctxt:expr, $vis:expr, $id:expr) => {
68 public: $vis.node.is_pub(),
69 reachable: $save_ctxt.analysis.access_levels.is_reachable($id),
73 ($save_ctxt:expr, $item:expr) => {
75 public: $item.vis.node.is_pub(),
76 reachable: $save_ctxt.analysis.access_levels.is_reachable($item.id),
81 pub struct DumpVisitor<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> {
82 save_ctxt: SaveContext<'l, 'tcx>,
83 tcx: TyCtxt<'l, 'tcx, 'tcx>,
84 dumper: &'ll mut JsonDumper<O>,
90 // Set of macro definition (callee) spans, and the set
91 // of macro use (callsite) spans. We store these to ensure
92 // we only write one macro def per unique macro definition, and
93 // one macro use per unique callsite span.
94 // mac_defs: FxHashSet<Span>,
95 // macro_calls: FxHashSet<Span>,
98 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> {
100 save_ctxt: SaveContext<'l, 'tcx>,
101 dumper: &'ll mut JsonDumper<O>,
102 ) -> DumpVisitor<'l, 'tcx, 'll, O> {
103 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
109 cur_scope: CRATE_NODE_ID,
110 // mac_defs: FxHashSet::default(),
111 // macro_calls: FxHashSet::default(),
115 fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
117 F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
119 let parent_scope = self.cur_scope;
120 self.cur_scope = scope_id;
122 self.cur_scope = parent_scope;
125 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
127 F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
129 let item_def_id = self.tcx.hir.local_def_id(item_id);
130 if self.tcx.has_typeck_tables(item_def_id) {
131 let tables = self.tcx.typeck_tables_of(item_def_id);
132 let old_tables = self.save_ctxt.tables;
133 self.save_ctxt.tables = tables;
135 self.save_ctxt.tables = old_tables;
141 fn span_from_span(&self, span: Span) -> SpanData {
142 self.save_ctxt.span_from_span(span)
145 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
146 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
147 let crate_root = source_file.map(|source_file| {
148 let source_file = Path::new(source_file);
149 match source_file.file_name() {
150 Some(_) => source_file.parent().unwrap().display(),
151 None => source_file.display(),
155 let data = CratePreludeData {
156 crate_id: GlobalCrateId {
158 disambiguator: self.tcx
160 .local_crate_disambiguator()
164 crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
165 external_crates: self.save_ctxt.get_external_crates(),
166 span: self.span_from_span(krate.span),
169 self.dumper.crate_prelude(data);
172 pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
173 // Apply possible `remap-path-prefix` remapping to the input source file
174 // (and don't include remapping args anymore)
175 let (program, arguments) = {
176 let remap_arg_indices = {
177 let mut indices = FxHashSet::default();
178 // Args are guaranteed to be valid UTF-8 (checked early)
179 for (i, e) in env::args().enumerate() {
180 if e.starts_with("--remap-path-prefix=") {
182 } else if e == "--remap-path-prefix" {
184 indices.insert(i + 1);
190 let mut args = env::args()
192 .filter(|(i, _)| !remap_arg_indices.contains(i))
195 Input::File(ref path) if path == Path::new(&arg) => {
196 let mapped = &self.tcx.sess.local_crate_source_file;
207 (args.next().unwrap(), args.collect())
210 let data = CompilationOptions {
211 directory: self.tcx.sess.working_dir.0.clone(),
214 output: self.save_ctxt.compilation_output(crate_name),
217 self.dumper.compilation_opts(data);
220 fn write_sub_paths(&mut self, path: &ast::Path) {
221 for seg in &path.segments {
222 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
223 self.dumper.dump_ref(data);
228 // As write_sub_paths, but does not process the last ident in the path (assuming it
229 // will be processed elsewhere). See note on write_sub_paths about global.
230 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
231 for seg in &path.segments[..path.segments.len() - 1] {
232 if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
233 self.dumper.dump_ref(data);
238 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
239 match self.save_ctxt.get_path_def(ref_id) {
240 HirDef::PrimTy(..) | HirDef::SelfTy(..) | HirDef::Err => None,
241 def => Some(def.def_id()),
245 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
247 self.visit_pat(&arg.pat);
248 let mut collector = PathCollector::new();
249 collector.visit_pat(&arg.pat);
251 for (id, ident, ..) in collector.collected_idents {
252 let hir_id = self.tcx.hir.node_to_hir_id(id);
253 let typ = match self.save_ctxt.tables.node_id_to_type_opt(hir_id) {
254 Some(s) => s.to_string(),
257 if !self.span.filter_generated(ident.span) {
258 let id = ::id_from_node_id(id, &self.save_ctxt);
259 let span = self.span_from_span(ident.span);
261 self.dumper.dump_def(
267 kind: DefKind::Local,
270 name: ident.to_string(),
271 qualname: format!("{}::{}", qualname, ident.to_string()),
288 sig: &'l ast::MethodSig,
289 body: Option<&'l ast::Block>,
292 generics: &'l ast::Generics,
293 vis: ast::Visibility,
296 debug!("process_method: {}:{}", id, ident);
298 if let Some(mut method_data) = self.save_ctxt.get_method_data(id, ident, span) {
299 let sig_str = ::make_signature(&sig.decl, &generics);
303 |v| v.process_formals(&sig.decl.inputs, &method_data.qualname),
307 self.process_generic_params(&generics, &method_data.qualname, id);
309 method_data.value = sig_str;
310 method_data.sig = sig::method_signature(id, ident, generics, sig, &self.save_ctxt);
311 self.dumper.dump_def(&access_from!(self.save_ctxt, vis, id), method_data);
314 // walk arg and return types
315 for arg in &sig.decl.inputs {
316 self.visit_ty(&arg.ty);
319 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
320 self.visit_ty(ret_ty);
324 if let Some(body) = body {
325 self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
329 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
330 let field_data = self.save_ctxt.get_field_data(field, parent_id);
331 if let Some(field_data) = field_data {
332 self.dumper.dump_def(&access_from!(self.save_ctxt, field), field_data);
336 // Dump generic params bindings, then visit_generics
337 fn process_generic_params(
339 generics: &'l ast::Generics,
343 for param in &generics.params {
345 ast::GenericParamKind::Lifetime { .. } => {}
346 ast::GenericParamKind::Type { .. } => {
347 let param_ss = param.ident.span;
348 let name = escape(self.span.snippet(param_ss));
349 // Append $id to name to make sure each one is unique.
350 let qualname = format!("{}::{}${}", prefix, name, id);
351 if !self.span.filter_generated(param_ss) {
352 let id = ::id_from_node_id(param.id, &self.save_ctxt);
353 let span = self.span_from_span(param_ss);
355 self.dumper.dump_def(
366 value: String::new(),
379 self.visit_generics(generics);
385 decl: &'l ast::FnDecl,
386 ty_params: &'l ast::Generics,
387 body: &'l ast::Block,
389 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
390 down_cast_data!(fn_data, DefData, item.span);
393 |v| v.process_formals(&decl.inputs, &fn_data.qualname),
395 self.process_generic_params(ty_params, &fn_data.qualname, item.id);
396 self.dumper.dump_def(&access_from!(self.save_ctxt, item), fn_data);
399 for arg in &decl.inputs {
400 self.visit_ty(&arg.ty);
403 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
404 self.visit_ty(&ret_ty);
407 self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
410 fn process_static_or_const_item(
416 self.nest_tables(item.id, |v| {
417 if let Some(var_data) = v.save_ctxt.get_item_data(item) {
418 down_cast_data!(var_data, DefData, item.span);
419 v.dumper.dump_def(&access_from!(v.save_ctxt, item), var_data);
426 fn process_assoc_const(
431 expr: Option<&'l ast::Expr>,
433 vis: ast::Visibility,
434 attrs: &'l [Attribute],
436 let qualname = format!("::{}", self.tcx.node_path_str(id));
438 if !self.span.filter_generated(ident.span) {
439 let sig = sig::assoc_const_signature(id, ident.name, typ, expr, &self.save_ctxt);
440 let span = self.span_from_span(ident.span);
442 self.dumper.dump_def(
443 &access_from!(self.save_ctxt, vis, id),
445 kind: DefKind::Const,
446 id: ::id_from_node_id(id, &self.save_ctxt),
448 name: ident.name.to_string(),
450 value: ty_to_string(&typ),
451 parent: Some(::id_from_def_id(parent_id)),
454 docs: self.save_ctxt.docs_for_attrs(attrs),
456 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
461 // walk type and init value
463 if let Some(expr) = expr {
464 self.visit_expr(expr);
468 // FIXME tuple structs should generate tuple-specific data.
472 def: &'l ast::VariantData,
473 ty_params: &'l ast::Generics,
475 debug!("process_struct {:?} {:?}", item, item.span);
476 let name = item.ident.to_string();
477 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
479 let kind = match item.node {
480 ast::ItemKind::Struct(_, _) => DefKind::Struct,
481 ast::ItemKind::Union(_, _) => DefKind::Union,
485 let (value, fields) = match item.node {
486 ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, _), _) |
487 ast::ItemKind::Union(ast::VariantData::Struct(ref fields, _), _) => {
488 let include_priv_fields = !self.save_ctxt.config.pub_only;
489 let fields_str = fields
492 .filter_map(|(i, f)| {
493 if include_priv_fields || f.vis.node.is_pub() {
495 .map(|i| i.to_string())
496 .or_else(|| Some(i.to_string()))
503 let value = format!("{} {{ {} }}", name, fields_str);
508 .map(|f| ::id_from_node_id(f.id, &self.save_ctxt))
512 _ => (String::new(), vec![]),
515 if !self.span.filter_generated(item.ident.span) {
516 let span = self.span_from_span(item.ident.span);
517 self.dumper.dump_def(
518 &access_from!(self.save_ctxt, item),
521 id: ::id_from_node_id(item.id, &self.save_ctxt),
524 qualname: qualname.clone(),
529 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
530 sig: sig::item_signature(item, &self.save_ctxt),
531 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
536 for field in def.fields() {
537 self.process_struct_field_def(field, item.id);
538 self.visit_ty(&field.ty);
541 self.process_generic_params(ty_params, &qualname, item.id);
547 enum_definition: &'l ast::EnumDef,
548 ty_params: &'l ast::Generics,
550 let enum_data = self.save_ctxt.get_item_data(item);
551 let enum_data = match enum_data {
555 down_cast_data!(enum_data, DefData, item.span);
557 let access = access_from!(self.save_ctxt, item);
559 for variant in &enum_definition.variants {
560 let name = variant.node.ident.name.to_string();
561 let qualname = format!("{}::{}", enum_data.qualname, name);
562 let name_span = variant.node.ident.span;
564 match variant.node.data {
565 ast::VariantData::Struct(ref fields, _) => {
566 let fields_str = fields
570 f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
574 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
575 if !self.span.filter_generated(name_span) {
576 let span = self.span_from_span(name_span);
577 let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
578 let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
580 self.dumper.dump_def(
583 kind: DefKind::StructVariant,
592 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
593 sig: sig::variant_signature(variant, &self.save_ctxt),
594 attributes: lower_attributes(
595 variant.node.attrs.clone(),
603 let mut value = format!("{}::{}", enum_data.name, name);
604 if let &ast::VariantData::Tuple(ref fields, _) = v {
606 value.push_str(&fields
608 .map(|f| ty_to_string(&f.ty))
613 if !self.span.filter_generated(name_span) {
614 let span = self.span_from_span(name_span);
615 let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
616 let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
618 self.dumper.dump_def(
621 kind: DefKind::TupleVariant,
630 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
631 sig: sig::variant_signature(variant, &self.save_ctxt),
632 attributes: lower_attributes(
633 variant.node.attrs.clone(),
643 for field in variant.node.data.fields() {
644 self.process_struct_field_def(field, variant.node.data.id());
645 self.visit_ty(&field.ty);
648 self.process_generic_params(ty_params, &enum_data.qualname, item.id);
649 self.dumper.dump_def(&access, enum_data);
655 type_parameters: &'l ast::Generics,
656 trait_ref: &'l Option<ast::TraitRef>,
658 impl_items: &'l [ast::ImplItem],
660 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
661 if let super::Data::RelationData(rel, imp) = impl_data {
662 self.dumper.dump_relation(rel);
663 self.dumper.dump_impl(imp);
665 span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
669 if let &Some(ref trait_ref) = trait_ref {
670 self.process_path(trait_ref.ref_id, &trait_ref.path);
672 self.process_generic_params(type_parameters, "", item.id);
673 for impl_item in impl_items {
674 let map = &self.tcx.hir;
675 self.process_impl_item(impl_item, map.local_def_id(item.id));
682 generics: &'l ast::Generics,
683 trait_refs: &'l ast::GenericBounds,
684 methods: &'l [ast::TraitItem],
686 let name = item.ident.to_string();
687 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
688 let mut val = name.clone();
689 if !generics.params.is_empty() {
690 val.push_str(&generic_params_to_string(&generics.params));
692 if !trait_refs.is_empty() {
694 val.push_str(&bounds_to_string(trait_refs));
696 if !self.span.filter_generated(item.ident.span) {
697 let id = ::id_from_node_id(item.id, &self.save_ctxt);
698 let span = self.span_from_span(item.ident.span);
699 let children = methods
701 .map(|i| ::id_from_node_id(i.id, &self.save_ctxt))
703 self.dumper.dump_def(
704 &access_from!(self.save_ctxt, item),
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(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 self.dumper.dump_def(&access_from!(self.save_ctxt, item), mod_data);
766 fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
767 let path_data = self.save_ctxt.get_path_data(id, path);
768 if let Some(path_data) = path_data {
769 self.dumper.dump_ref(path_data);
773 fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
774 if self.span.filter_generated(path.span) {
777 self.dump_path_ref(id, path);
780 for seg in &path.segments {
781 if let Some(ref generic_args) = seg.args {
782 match **generic_args {
783 ast::GenericArgs::AngleBracketed(ref data) => {
784 for arg in &data.args {
786 ast::GenericArg::Type(ty) => self.visit_ty(ty),
791 ast::GenericArgs::Parenthesized(ref data) => {
792 for t in &data.inputs {
795 if let Some(ref t) = 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_id_to_type_opt(hir_id) {
869 Some(ty) => ty.ty_adt_def().unwrap(),
871 visit::walk_pat(self, p);
875 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
877 for &Spanned { node: ref 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_multi(&mut self, pats: &'l [P<ast::Pat>]) {
896 let mut collector = PathCollector::new();
897 for pattern in pats {
898 // collect paths from the arm's patterns
899 collector.visit_pat(&pattern);
900 self.visit_pat(&pattern);
903 // process collected paths
904 for (id, ident, immut) in collector.collected_idents {
905 match self.save_ctxt.get_path_def(id) {
906 HirDef::Local(id) => {
907 let mut value = if immut == ast::Mutability::Immutable {
908 self.span.snippet(ident.span)
910 "<mutable>".to_owned()
912 let hir_id = self.tcx.hir.node_to_hir_id(id);
913 let typ = self.save_ctxt
915 .node_id_to_type_opt(hir_id)
916 .map(|t| t.to_string())
917 .unwrap_or_default();
918 value.push_str(": ");
919 value.push_str(&typ);
921 if !self.span.filter_generated(ident.span) {
922 let qualname = format!("{}${}", ident.to_string(), id);
923 let id = ::id_from_node_id(id, &self.save_ctxt);
924 let span = self.span_from_span(ident.span);
926 self.dumper.dump_def(
932 kind: DefKind::Local,
935 name: ident.to_string(),
948 HirDef::StructCtor(..) |
949 HirDef::VariantCtor(..) |
951 HirDef::AssociatedConst(..) |
953 HirDef::Variant(..) |
954 HirDef::TyAlias(..) |
955 HirDef::AssociatedTy(..) |
956 HirDef::SelfTy(..) => {
957 self.dump_path_ref(id, &ast::Path::from_ident(ident));
960 "unexpected definition kind when processing collected idents: {:?}",
966 for (id, ref path) in collector.collected_paths {
967 self.process_path(id, path);
971 fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
972 // The local could declare multiple new vars, we must walk the
973 // pattern and collect them all.
974 let mut collector = PathCollector::new();
975 collector.visit_pat(&p);
978 for (id, ident, immut) in collector.collected_idents {
979 let mut value = match immut {
980 ast::Mutability::Immutable => value.to_string(),
983 let hir_id = self.tcx.hir.node_to_hir_id(id);
984 let typ = match self.save_ctxt.tables.node_id_to_type_opt(hir_id) {
986 let typ = typ.to_string();
987 if !value.is_empty() {
988 value.push_str(": ");
990 value.push_str(&typ);
993 None => String::new(),
996 // Rust uses the id of the pattern for var lookups, so we'll use it too.
997 if !self.span.filter_generated(ident.span) {
998 let qualname = format!("{}${}", ident.to_string(), id);
999 let id = ::id_from_node_id(id, &self.save_ctxt);
1000 let span = self.span_from_span(ident.span);
1002 self.dumper.dump_def(
1008 kind: DefKind::Local,
1011 name: ident.to_string(),
1017 docs: String::new(),
1026 /// Extract macro use and definition information from the AST node defined
1027 /// by the given NodeId, using the expansion information from the node's
1030 /// If the span is not macro-generated, do nothing, else use callee and
1031 /// callsite spans to record macro definition and use data, using the
1032 /// mac_uses and mac_defs sets to prevent multiples.
1033 fn process_macro_use(&mut self, _span: Span) {
1034 // FIXME if we're not dumping the defs (see below), there is no point
1035 // dumping refs either.
1036 // let source_span = span.source_callsite();
1037 // if !self.macro_calls.insert(source_span) {
1041 // let data = match self.save_ctxt.get_macro_use_data(span) {
1043 // Some(data) => data,
1046 // self.dumper.macro_use(data);
1048 // FIXME write the macro def
1049 // let mut hasher = DefaultHasher::new();
1050 // data.callee_span.hash(&mut hasher);
1051 // let hash = hasher.finish();
1052 // let qualname = format!("{}::{}", data.name, hash);
1053 // Don't write macro definition for imported macros
1054 // if !self.mac_defs.contains(&data.callee_span)
1055 // && !data.imported {
1056 // self.mac_defs.insert(data.callee_span);
1057 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1058 // self.dumper.macro_data(MacroData {
1060 // name: data.name.clone(),
1061 // qualname: qualname.clone(),
1062 // // FIXME where do macro docs come from?
1063 // docs: String::new(),
1064 // }.lower(self.tcx));
1069 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1070 self.process_macro_use(trait_item.span);
1071 let vis_span = trait_item.span.shrink_to_lo();
1072 match trait_item.node {
1073 ast::TraitItemKind::Const(ref ty, ref expr) => {
1074 self.process_assoc_const(
1078 expr.as_ref().map(|e| &**e),
1080 respan(vis_span, ast::VisibilityKind::Public),
1084 ast::TraitItemKind::Method(ref sig, ref body) => {
1085 self.process_method(
1087 body.as_ref().map(|x| &**x),
1090 &trait_item.generics,
1091 respan(vis_span, ast::VisibilityKind::Public),
1095 ast::TraitItemKind::Type(ref bounds, ref default_ty) => {
1096 // FIXME do something with _bounds (for type refs)
1097 let name = trait_item.ident.name.to_string();
1098 let qualname = format!("::{}", self.tcx.node_path_str(trait_item.id));
1100 if !self.span.filter_generated(trait_item.ident.span) {
1101 let span = self.span_from_span(trait_item.ident.span);
1102 let id = ::id_from_node_id(trait_item.id, &self.save_ctxt);
1104 self.dumper.dump_def(
1110 kind: DefKind::Type,
1115 value: self.span.snippet(trait_item.span),
1116 parent: Some(::id_from_def_id(trait_id)),
1119 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1120 sig: sig::assoc_type_signature(
1124 default_ty.as_ref().map(|ty| &**ty),
1127 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1132 if let &Some(ref default_ty) = default_ty {
1133 self.visit_ty(default_ty)
1136 ast::TraitItemKind::Macro(_) => {}
1140 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1141 self.process_macro_use(impl_item.span);
1142 match impl_item.node {
1143 ast::ImplItemKind::Const(ref ty, ref expr) => {
1144 self.process_assoc_const(
1150 impl_item.vis.clone(),
1154 ast::ImplItemKind::Method(ref sig, ref body) => {
1155 self.process_method(
1160 &impl_item.generics,
1161 impl_item.vis.clone(),
1165 ast::ImplItemKind::Type(ref ty) => {
1166 // FIXME uses of the assoc type should ideally point to this
1167 // 'def' and the name here should be a ref to the def in the
1171 ast::ImplItemKind::Existential(ref bounds) => {
1172 // FIXME uses of the assoc type should ideally point to this
1173 // 'def' and the name here should be a ref to the def in the
1175 for bound in bounds.iter() {
1176 if let ast::GenericBound::Trait(trait_ref, _) = bound {
1177 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1181 ast::ImplItemKind::Macro(_) => {}
1185 /// Dumps imports in a use tree recursively.
1187 /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1188 /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1189 /// id and path. `root_item` is the topmost use tree in the hierarchy.
1191 /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1192 /// each child use tree is dumped recursively.
1193 fn process_use_tree(&mut self,
1194 use_tree: &'l ast::UseTree,
1196 root_item: &'l ast::Item,
1197 prefix: &ast::Path) {
1198 let path = &use_tree.prefix;
1200 // The access is calculated using the current tree ID, but with the root tree's visibility
1201 // (since nested trees don't have their own visibility).
1202 let access = access_from!(self.save_ctxt, root_item.vis, id);
1204 // The parent def id of a given use tree is always the enclosing item.
1205 let parent = self.save_ctxt.tcx.hir.opt_local_def_id(id)
1206 .and_then(|id| self.save_ctxt.tcx.parent_def_id(id))
1207 .map(::id_from_def_id);
1209 match use_tree.kind {
1210 ast::UseTreeKind::Simple(alias, ..) => {
1211 let ident = use_tree.ident();
1212 let path = ast::Path {
1213 segments: prefix.segments
1215 .chain(path.segments.iter())
1221 let sub_span = path.segments.last().unwrap().ident.span;
1222 if !self.span.filter_generated(sub_span) {
1223 let ref_id = self.lookup_def_id(id).map(|id| ::id_from_def_id(id));
1224 let alias_span = alias.map(|i| self.span_from_span(i.span));
1225 let span = self.span_from_span(sub_span);
1226 self.dumper.import(&access, Import {
1227 kind: ImportKind::Use,
1231 name: ident.to_string(),
1232 value: String::new(),
1235 self.write_sub_paths_truncated(&path);
1238 ast::UseTreeKind::Glob => {
1239 let path = ast::Path {
1240 segments: prefix.segments
1242 .chain(path.segments.iter())
1248 // Make a comma-separated list of names of imported modules.
1249 let glob_map = &self.save_ctxt.analysis.glob_map;
1250 let glob_map = glob_map.as_ref().unwrap();
1251 let names = if glob_map.contains_key(&id) {
1252 glob_map.get(&id).unwrap().iter().map(|n| n.to_string()).collect()
1258 self.span.sub_span_of_token(use_tree.span, token::BinOp(token::Star));
1259 if !self.span.filter_generated(use_tree.span) {
1261 self.span_from_span(sub_span.expect("No span found for use glob"));
1262 self.dumper.import(&access, Import {
1263 kind: ImportKind::GlobUse,
1267 name: "*".to_owned(),
1268 value: names.join(", "),
1271 self.write_sub_paths(&path);
1274 ast::UseTreeKind::Nested(ref nested_items) => {
1275 let prefix = ast::Path {
1276 segments: prefix.segments
1278 .chain(path.segments.iter())
1283 for &(ref tree, id) in nested_items {
1284 self.process_use_tree(tree, id, root_item, &prefix);
1290 fn process_bounds(&mut self, bounds: &'l ast::GenericBounds) {
1291 for bound in bounds {
1292 if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1293 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1299 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, O> {
1300 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1301 // Since we handle explicit modules ourselves in visit_item, this should
1302 // only get called for the root module of a crate.
1303 assert_eq!(id, ast::CRATE_NODE_ID);
1305 let qualname = format!("::{}", self.tcx.node_path_str(id));
1307 let cm = self.tcx.sess.source_map();
1308 let filename = cm.span_to_filename(span);
1309 let data_id = ::id_from_node_id(id, &self.save_ctxt);
1310 let children = m.items
1312 .map(|i| ::id_from_node_id(i.id, &self.save_ctxt))
1314 let span = self.span_from_span(span);
1316 self.dumper.dump_def(
1324 name: String::new(),
1327 value: filename.to_string(),
1331 docs: self.save_ctxt.docs_for_attrs(attrs),
1333 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1336 self.nest_scope(id, |v| visit::walk_mod(v, m));
1339 fn visit_item(&mut self, item: &'l ast::Item) {
1340 use syntax::ast::ItemKind::*;
1341 self.process_macro_use(item.span);
1343 Use(ref use_tree) => {
1344 let prefix = ast::Path {
1348 self.process_use_tree(use_tree, item.id, item, &prefix);
1351 let name_span = item.ident.span;
1352 if !self.span.filter_generated(name_span) {
1353 let span = self.span_from_span(name_span);
1354 let parent = self.save_ctxt.tcx.hir.opt_local_def_id(item.id)
1355 .and_then(|id| self.save_ctxt.tcx.parent_def_id(id))
1356 .map(::id_from_def_id);
1363 kind: ImportKind::ExternCrate,
1367 name: item.ident.to_string(),
1368 value: String::new(),
1374 Fn(ref decl, .., ref ty_params, ref body) => {
1375 self.process_fn(item, &decl, ty_params, &body)
1377 Static(ref typ, _, ref expr) => self.process_static_or_const_item(item, typ, expr),
1378 Const(ref typ, ref expr) => self.process_static_or_const_item(item, &typ, &expr),
1379 Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1380 self.process_struct(item, def, ty_params)
1382 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1383 Impl(.., ref ty_params, ref trait_ref, ref typ, ref impl_items) => {
1384 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1386 Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1387 self.process_trait(item, generics, trait_refs, methods)
1390 self.process_mod(item);
1391 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1393 Ty(ref ty, ref ty_params) => {
1394 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1395 let value = ty_to_string(&ty);
1396 if !self.span.filter_generated(item.ident.span) {
1397 let span = self.span_from_span(item.ident.span);
1398 let id = ::id_from_node_id(item.id, &self.save_ctxt);
1400 self.dumper.dump_def(
1401 &access_from!(self.save_ctxt, item),
1403 kind: DefKind::Type,
1406 name: item.ident.to_string(),
1407 qualname: qualname.clone(),
1412 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1413 sig: sig::item_signature(item, &self.save_ctxt),
1414 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1420 self.process_generic_params(ty_params, &qualname, item.id);
1422 Existential(ref _bounds, ref ty_params) => {
1423 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1424 // FIXME do something with _bounds
1425 let value = String::new();
1426 if !self.span.filter_generated(item.ident.span) {
1427 let span = self.span_from_span(item.ident.span);
1428 let id = ::id_from_node_id(item.id, &self.save_ctxt);
1430 self.dumper.dump_def(
1431 &access_from!(self.save_ctxt, item),
1433 kind: DefKind::Type,
1436 name: item.ident.to_string(),
1437 qualname: qualname.clone(),
1442 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1443 sig: sig::item_signature(item, &self.save_ctxt),
1444 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1449 self.process_generic_params(ty_params, &qualname, item.id);
1452 _ => visit::walk_item(self, item),
1456 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1457 for param in &generics.params {
1458 if let ast::GenericParamKind::Type { ref default, .. } = param.kind {
1459 self.process_bounds(¶m.bounds);
1460 if let Some(ref ty) = default {
1465 for pred in &generics.where_clause.predicates {
1466 if let ast::WherePredicate::BoundPredicate(ref wbp) = *pred {
1467 self.process_bounds(&wbp.bounds);
1468 self.visit_ty(&wbp.bounded_ty);
1473 fn visit_ty(&mut self, t: &'l ast::Ty) {
1474 self.process_macro_use(t.span);
1476 ast::TyKind::Path(_, ref path) => {
1477 if generated_code(t.span) {
1481 if let Some(id) = self.lookup_def_id(t.id) {
1482 let sub_span = path.segments.last().unwrap().ident.span;
1483 let span = self.span_from_span(sub_span);
1484 self.dumper.dump_ref(Ref {
1485 kind: RefKind::Type,
1487 ref_id: ::id_from_def_id(id),
1491 self.write_sub_paths_truncated(path);
1492 visit::walk_path(self, path);
1494 ast::TyKind::Array(ref element, ref length) => {
1495 self.visit_ty(element);
1496 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1498 _ => visit::walk_ty(self, t),
1502 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1503 debug!("visit_expr {:?}", ex.node);
1504 self.process_macro_use(ex.span);
1506 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1507 let hir_expr = self.save_ctxt.tcx.hir.expect_expr(ex.id);
1508 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1509 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1511 visit::walk_expr(self, ex);
1515 let def = self.save_ctxt.get_path_def(hir_expr.id);
1516 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1518 ast::ExprKind::MethodCall(ref seg, ref args) => self.process_method_call(ex, seg, args),
1519 ast::ExprKind::Field(ref sub_ex, _) => {
1520 self.visit_expr(&sub_ex);
1522 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1523 down_cast_data!(field_data, RefData, ex.span);
1524 if !generated_code(ex.span) {
1525 self.dumper.dump_ref(field_data);
1529 ast::ExprKind::Closure(_, _, _, ref decl, ref body, _fn_decl_span) => {
1530 let id = format!("${}", ex.id);
1532 // walk arg and return types
1533 for arg in &decl.inputs {
1534 self.visit_ty(&arg.ty);
1537 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1538 self.visit_ty(&ret_ty);
1542 self.nest_tables(ex.id, |v| {
1543 v.process_formals(&decl.inputs, &id);
1544 v.nest_scope(ex.id, |v| v.visit_expr(body))
1547 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1548 let value = self.span.snippet(subexpression.span);
1549 self.process_var_decl(pattern, value);
1550 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1551 self.visit_expr(subexpression);
1552 visit::walk_block(self, block);
1554 ast::ExprKind::WhileLet(ref pats, ref subexpression, ref block, _) => {
1555 self.process_var_decl_multi(pats);
1556 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1557 self.visit_expr(subexpression);
1558 visit::walk_block(self, block);
1560 ast::ExprKind::IfLet(ref pats, ref subexpression, ref block, ref opt_else) => {
1561 self.process_var_decl_multi(pats);
1562 self.visit_expr(subexpression);
1563 visit::walk_block(self, block);
1564 opt_else.as_ref().map(|el| self.visit_expr(el));
1566 ast::ExprKind::Repeat(ref element, ref count) => {
1567 self.visit_expr(element);
1568 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1570 // In particular, we take this branch for call and path expressions,
1571 // where we'll index the idents involved just by continuing to walk.
1572 _ => visit::walk_expr(self, ex),
1576 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1577 // These shouldn't exist in the AST at this point, log a span bug.
1580 "macro invocation should have been expanded out of AST"
1584 fn visit_pat(&mut self, p: &'l ast::Pat) {
1585 self.process_macro_use(p.span);
1586 self.process_pat(p);
1589 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1590 self.process_var_decl_multi(&arm.pats);
1592 Some(ast::Guard::If(ref expr)) => self.visit_expr(expr),
1595 self.visit_expr(&arm.body);
1598 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1599 self.process_path(id, p);
1602 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1603 self.process_macro_use(s.span);
1604 visit::walk_stmt(self, s)
1607 fn visit_local(&mut self, l: &'l ast::Local) {
1608 self.process_macro_use(l.span);
1611 .map(|i| self.span.snippet(i.span))
1612 .unwrap_or_default();
1613 self.process_var_decl(&l.pat, value);
1615 // Just walk the initialiser and type (don't want to walk the pattern again).
1616 walk_list!(self, visit_ty, &l.ty);
1617 walk_list!(self, visit_expr, &l.init);
1620 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1621 let access = access_from!(self.save_ctxt, item);
1624 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1625 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1626 down_cast_data!(fn_data, DefData, item.span);
1628 self.process_generic_params(generics, &fn_data.qualname, item.id);
1629 self.dumper.dump_def(&access, fn_data);
1632 for arg in &decl.inputs {
1633 self.visit_ty(&arg.ty);
1636 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1637 self.visit_ty(&ret_ty);
1640 ast::ForeignItemKind::Static(ref ty, _) => {
1641 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1642 down_cast_data!(var_data, DefData, item.span);
1643 self.dumper.dump_def(&access, var_data);
1648 ast::ForeignItemKind::Ty => {
1649 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1650 down_cast_data!(var_data, DefData, item.span);
1651 self.dumper.dump_def(&access, var_data);
1654 ast::ForeignItemKind::Macro(..) => {}