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 an implementor of Dump
24 //! is used for recording the output in a format-agnostic way (see CsvDumper
27 use rustc::hir::def::Def as HirDef;
28 use rustc::hir::def_id::DefId;
29 use rustc::hir::map::Node;
30 use rustc::session::Session;
31 use rustc::ty::{self, TyCtxt};
32 use rustc_data_structures::fx::FxHashSet;
36 use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID};
37 use syntax::parse::token;
38 use syntax::symbol::keywords;
39 use syntax::visit::{self, Visitor};
40 use syntax::print::pprust::{path_to_string, ty_to_string, bounds_to_string, generics_to_string};
42 use syntax::codemap::Spanned;
45 use {escape, generated_code, SaveContext, PathCollector, lower_attributes};
46 use json_dumper::{JsonDumper, DumpOutput};
47 use span_utils::SpanUtils;
50 use rls_data::{CratePreludeData, Import, ImportKind, SpanData, Ref, RefKind,
51 Def, DefKind, Relation, RelationKind};
53 macro_rules! down_cast_data {
54 ($id:ident, $kind:ident, $sp:expr) => {
55 let $id = if let super::Data::$kind(data) = $id {
58 span_bug!($sp, "unexpected data kind: {:?}", $id);
63 pub struct DumpVisitor<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> {
64 save_ctxt: SaveContext<'l, 'tcx>,
66 tcx: TyCtxt<'l, 'tcx, 'tcx>,
67 dumper: &'ll mut JsonDumper<O>,
73 // Set of macro definition (callee) spans, and the set
74 // of macro use (callsite) spans. We store these to ensure
75 // we only write one macro def per unique macro definition, and
76 // one macro use per unique callsite span.
77 // mac_defs: HashSet<Span>,
78 macro_calls: FxHashSet<Span>,
81 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> {
82 pub fn new(save_ctxt: SaveContext<'l, 'tcx>,
83 dumper: &'ll mut JsonDumper<O>)
84 -> DumpVisitor<'l, 'tcx, 'll, O> {
85 let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
87 sess: &save_ctxt.tcx.sess,
91 span: span_utils.clone(),
92 cur_scope: CRATE_NODE_ID,
93 // mac_defs: HashSet::new(),
94 macro_calls: FxHashSet(),
98 fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
99 where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>)
101 let parent_scope = self.cur_scope;
102 self.cur_scope = scope_id;
104 self.cur_scope = parent_scope;
107 fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
108 where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>)
110 let item_def_id = self.tcx.hir.local_def_id(item_id);
111 if self.tcx.has_typeck_tables(item_def_id) {
112 let tables = self.tcx.typeck_tables_of(item_def_id);
113 let old_tables = self.save_ctxt.tables;
114 self.save_ctxt.tables = tables;
116 self.save_ctxt.tables = old_tables;
122 fn span_from_span(&self, span: Span) -> SpanData {
123 self.save_ctxt.span_from_span(span)
126 pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
127 let source_file = self.tcx.sess.local_crate_source_file.as_ref();
128 let crate_root = source_file.map(|source_file| {
129 let source_file = Path::new(source_file);
130 match source_file.file_name() {
131 Some(_) => source_file.parent().unwrap().display().to_string(),
132 None => source_file.display().to_string(),
136 let data = CratePreludeData {
137 crate_name: name.into(),
138 crate_root: crate_root.unwrap_or("<no source>".to_owned()),
139 external_crates: self.save_ctxt.get_external_crates(),
140 span: self.span_from_span(krate.span),
143 self.dumper.crate_prelude(data);
146 // Return all non-empty prefixes of a path.
147 // For each prefix, we return the span for the last segment in the prefix and
148 // a str representation of the entire prefix.
149 fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
150 let spans = self.span.spans_for_path_segments(path);
151 let segments = &path.segments[if path.is_global() { 1 } else { 0 }..];
153 // Paths to enums seem to not match their spans - the span includes all the
154 // variants too. But they seem to always be at the end, so I hope we can cope with
155 // always using the first ones. So, only error out if we don't have enough spans.
156 // What could go wrong...?
157 if spans.len() < segments.len() {
158 if generated_code(path.span) {
161 error!("Mis-calculated spans for path '{}'. Found {} spans, expected {}. Found spans:",
162 path_to_string(path),
166 let loc = self.sess.codemap().lookup_char_pos(s.lo);
167 error!(" '{}' in {}, line {}",
168 self.span.snippet(*s),
172 error!(" master span: {:?}: `{}`", path.span, self.span.snippet(path.span));
176 let mut result: Vec<(Span, String)> = vec![];
178 let mut segs = vec![];
179 for (i, (seg, span)) in segments.iter().zip(&spans).enumerate() {
180 segs.push(seg.clone());
181 let sub_path = ast::Path {
182 span: *span, // span for the last segment
185 let qualname = if i == 0 && path.is_global() {
186 format!("::{}", path_to_string(&sub_path))
188 path_to_string(&sub_path)
190 result.push((*span, qualname));
191 segs = sub_path.segments;
197 fn write_sub_paths(&mut self, path: &ast::Path) {
198 let sub_paths = self.process_path_prefixes(path);
199 for (span, _) in sub_paths {
200 let span = self.span_from_span(span);
201 self.dumper.dump_ref(Ref {
209 // As write_sub_paths, but does not process the last ident in the path (assuming it
210 // will be processed elsewhere). See note on write_sub_paths about global.
211 fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
212 let sub_paths = self.process_path_prefixes(path);
213 let len = sub_paths.len();
218 for (span, _) in sub_paths.into_iter().take(len - 1) {
219 let span = self.span_from_span(span);
220 self.dumper.dump_ref(Ref {
228 // As write_sub_paths, but expects a path of the form module_path::trait::method
229 // Where trait could actually be a struct too.
230 fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
231 let sub_paths = self.process_path_prefixes(path);
232 let len = sub_paths.len();
236 let sub_paths = &sub_paths[.. (len-1)];
238 // write the trait part of the sub-path
239 let (ref span, _) = sub_paths[len-2];
240 let span = self.span_from_span(*span);
241 self.dumper.dump_ref(Ref {
247 // write the other sub-paths
251 let sub_paths = &sub_paths[..len-2];
252 for &(ref span, _) in sub_paths {
253 let span = self.span_from_span(*span);
254 self.dumper.dump_ref(Ref {
262 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
263 match self.save_ctxt.get_path_def(ref_id) {
264 HirDef::PrimTy(..) | HirDef::SelfTy(..) | HirDef::Err => None,
265 def => Some(def.def_id()),
269 fn process_def_kind(&mut self,
272 sub_span: Option<Span>,
274 if self.span.filter_generated(sub_span, span) {
278 let def = self.save_ctxt.get_path_def(ref_id);
281 let span = self.span_from_span(sub_span.expect("No span found for mod ref"));
282 self.dumper.dump_ref(Ref {
285 ref_id: ::id_from_def_id(def_id),
289 HirDef::Variant(..) |
292 HirDef::TyAlias(..) |
293 HirDef::Trait(_) => {
294 let span = self.span_from_span(sub_span.expect("No span found for type ref"));
295 self.dumper.dump_ref(Ref {
298 ref_id: ::id_from_def_id(def_id),
303 HirDef::StructCtor(..) |
304 HirDef::VariantCtor(..) => {
305 let span = self.span_from_span(sub_span.expect("No span found for var ref"));
306 self.dumper.dump_ref(Ref {
307 kind: RefKind::Variable,
309 ref_id: ::id_from_def_id(def_id),
313 let span = self.span_from_span(sub_span.expect("No span found for fn ref"));
314 self.dumper.dump_ref(Ref {
315 kind: RefKind::Function,
317 ref_id: ::id_from_def_id(def_id),
320 // With macros 2.0, we can legitimately get a ref to a macro, but
321 // we don't handle it properly for now (FIXME).
322 HirDef::Macro(..) => {}
327 HirDef::TyParam(..) |
329 HirDef::AssociatedTy(..) |
330 HirDef::AssociatedConst(..) |
332 HirDef::GlobalAsm(_) |
335 "process_def_kind for unexpected item: {:?}",
341 fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
343 self.visit_pat(&arg.pat);
344 let mut collector = PathCollector::new();
345 collector.visit_pat(&arg.pat);
346 let span_utils = self.span.clone();
347 for &(id, ref p, ..) in &collector.collected_paths {
348 let typ = match self.save_ctxt.tables.node_types.get(&id) {
349 Some(s) => s.to_string(),
352 // get the span only for the name of the variable (I hope the path is only ever a
353 // variable name, but who knows?)
354 let sub_span = span_utils.span_for_last_ident(p.span);
355 if !self.span.filter_generated(sub_span, p.span) {
356 let id = ::id_from_node_id(id, &self.save_ctxt);
357 let span = self.span_from_span(sub_span.expect("No span found for variable"));
359 self.dumper.dump_def(false, Def {
360 kind: DefKind::Local,
363 name: path_to_string(p),
364 qualname: format!("{}::{}", qualname, path_to_string(p)),
378 fn process_method(&mut self,
379 sig: &'l ast::MethodSig,
380 body: Option<&'l ast::Block>,
383 vis: ast::Visibility,
385 debug!("process_method: {}:{}", id, name);
387 if let Some(mut method_data) = self.save_ctxt.get_method_data(id, name.name, span) {
389 let sig_str = ::make_signature(&sig.decl, &sig.generics);
391 self.nest_tables(id, |v| {
392 v.process_formals(&sig.decl.inputs, &method_data.qualname)
396 self.process_generic_params(&sig.generics, span, &method_data.qualname, id);
398 method_data.value = sig_str;
399 method_data.sig = sig::method_signature(id, name, sig, &self.save_ctxt);
400 self.dumper.dump_def(vis == ast::Visibility::Public, method_data);
403 // walk arg and return types
404 for arg in &sig.decl.inputs {
405 self.visit_ty(&arg.ty);
408 if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
409 self.visit_ty(ret_ty);
413 if let Some(body) = body {
414 self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
418 fn process_trait_ref(&mut self, trait_ref: &'l ast::TraitRef) {
419 let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref);
420 if let Some(trait_ref_data) = trait_ref_data {
421 self.dumper.dump_ref(trait_ref_data);
423 self.process_path(trait_ref.ref_id, &trait_ref.path);
426 fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
427 let field_data = self.save_ctxt.get_field_data(field, parent_id);
428 if let Some(field_data) = field_data {
429 self.dumper.dump_def(field.vis == ast::Visibility::Public, field_data);
433 // Dump generic params bindings, then visit_generics
434 fn process_generic_params(&mut self,
435 generics: &'l ast::Generics,
439 // We can't only use visit_generics since we don't have spans for param
440 // bindings, so we reparse the full_span to get those sub spans.
441 // However full span is the entire enum/fn/struct block, so we only want
442 // the first few to match the number of generics we're looking for.
443 let param_sub_spans = self.span.spans_for_ty_params(full_span,
444 (generics.ty_params.len() as isize));
445 for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
446 let name = escape(self.span.snippet(param_ss));
447 // Append $id to name to make sure each one is unique
448 let qualname = format!("{}::{}${}",
452 if !self.span.filter_generated(Some(param_ss), full_span) {
453 let id = ::id_from_node_id(param.id, &self.save_ctxt);
454 let span = self.span_from_span(param_ss);
456 self.dumper.dump_def(false, Def {
462 value: String::new(),
472 self.visit_generics(generics);
475 fn process_fn(&mut self,
477 decl: &'l ast::FnDecl,
478 ty_params: &'l ast::Generics,
479 body: &'l ast::Block) {
480 if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
481 down_cast_data!(fn_data, DefData, item.span);
482 self.nest_tables(item.id, |v| v.process_formals(&decl.inputs, &fn_data.qualname));
483 self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
484 self.dumper.dump_def(item.vis == ast::Visibility::Public, fn_data);
487 for arg in &decl.inputs {
488 self.visit_ty(&arg.ty);
491 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
492 self.visit_ty(&ret_ty);
495 self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
498 fn process_static_or_const_item(&mut self,
501 expr: &'l ast::Expr) {
502 if let Some(var_data) = self.save_ctxt.get_item_data(item) {
503 down_cast_data!(var_data, DefData, item.span);
504 self.dumper.dump_def(item.vis == ast::Visibility::Public, var_data);
507 self.visit_expr(expr);
510 fn process_assoc_const(&mut self,
515 expr: Option<&'l ast::Expr>,
517 vis: ast::Visibility,
518 attrs: &'l [Attribute]) {
519 let qualname = format!("::{}", self.tcx.node_path_str(id));
521 let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
523 if !self.span.filter_generated(sub_span, span) {
524 let sig = sig::assoc_const_signature(id, name, typ, expr, &self.save_ctxt);
525 let id = ::id_from_node_id(id, &self.save_ctxt);
526 let span = self.span_from_span(sub_span.expect("No span found for variable"));
528 self.dumper.dump_def(vis == ast::Visibility::Public, Def {
529 kind: DefKind::Const,
532 name: name.to_string(),
534 value: ty_to_string(&typ),
535 parent: Some(::id_from_def_id(parent_id)),
538 docs: self.save_ctxt.docs_for_attrs(attrs),
540 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
544 // walk type and init value
546 if let Some(expr) = expr {
547 self.visit_expr(expr);
551 // FIXME tuple structs should generate tuple-specific data.
552 fn process_struct(&mut self,
554 def: &'l ast::VariantData,
555 ty_params: &'l ast::Generics) {
556 let name = item.ident.to_string();
557 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
559 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
560 let (value, fields) =
561 if let ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, _), _) = item.node
563 let fields_str = fields.iter()
565 .map(|(i, f)| f.ident.map(|i| i.to_string())
566 .unwrap_or(i.to_string()))
569 (format!("{} {{ {} }}", name, fields_str),
570 fields.iter().map(|f| ::id_from_node_id(f.id, &self.save_ctxt)).collect())
572 (String::new(), vec![])
575 if !self.span.filter_generated(sub_span, item.span) {
576 let span = self.span_from_span(sub_span.expect("No span found for struct"));
577 self.dumper.dump_def(item.vis == ast::Visibility::Public, Def {
578 kind: DefKind::Struct,
579 id: ::id_from_node_id(item.id, &self.save_ctxt),
582 qualname: qualname.clone(),
587 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
588 sig: sig::item_signature(item, &self.save_ctxt),
589 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
593 for field in def.fields() {
594 self.process_struct_field_def(field, item.id);
595 self.visit_ty(&field.ty);
598 self.process_generic_params(ty_params, item.span, &qualname, item.id);
601 fn process_enum(&mut self,
603 enum_definition: &'l ast::EnumDef,
604 ty_params: &'l ast::Generics) {
605 let enum_data = self.save_ctxt.get_item_data(item);
606 let enum_data = match enum_data {
610 down_cast_data!(enum_data, DefData, item.span);
612 for variant in &enum_definition.variants {
613 let name = variant.node.name.name.to_string();
614 let mut qualname = enum_data.qualname.clone();
615 qualname.push_str("::");
616 qualname.push_str(&name);
618 match variant.node.data {
619 ast::VariantData::Struct(ref fields, _) => {
620 let sub_span = self.span.span_for_first_ident(variant.span);
621 let fields_str = fields.iter()
623 .map(|(i, f)| f.ident.map(|i| i.to_string())
624 .unwrap_or(i.to_string()))
627 let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
628 if !self.span.filter_generated(sub_span, variant.span) {
629 let span = self.span_from_span(
630 sub_span.expect("No span found for struct variant"));
631 let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
632 let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
634 self.dumper.dump_def(item.vis == ast::Visibility::Public, Def {
635 kind: DefKind::Struct,
644 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
645 sig: sig::variant_signature(variant, &self.save_ctxt),
646 attributes: lower_attributes(variant.node.attrs.clone(),
652 let sub_span = self.span.span_for_first_ident(variant.span);
653 let mut value = format!("{}::{}", enum_data.name, name);
654 if let &ast::VariantData::Tuple(ref fields, _) = v {
656 value.push_str(&fields.iter()
657 .map(|f| ty_to_string(&f.ty))
662 if !self.span.filter_generated(sub_span, variant.span) {
664 self.span_from_span(sub_span.expect("No span found for tuple variant"));
665 let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
666 let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
668 self.dumper.dump_def(item.vis == ast::Visibility::Public, Def {
669 kind: DefKind::Tuple,
678 docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
679 sig: sig::variant_signature(variant, &self.save_ctxt),
680 attributes: lower_attributes(variant.node.attrs.clone(),
688 for field in variant.node.data.fields() {
689 self.process_struct_field_def(field, variant.node.data.id());
690 self.visit_ty(&field.ty);
693 self.process_generic_params(ty_params, item.span, &enum_data.qualname, item.id);
694 self.dumper.dump_def(item.vis == ast::Visibility::Public, enum_data);
697 fn process_impl(&mut self,
699 type_parameters: &'l ast::Generics,
700 trait_ref: &'l Option<ast::TraitRef>,
702 impl_items: &'l [ast::ImplItem]) {
703 if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
704 down_cast_data!(impl_data, RelationData, item.span);
705 self.dumper.dump_relation(impl_data);
708 if let &Some(ref trait_ref) = trait_ref {
709 self.process_path(trait_ref.ref_id, &trait_ref.path);
711 self.process_generic_params(type_parameters, item.span, "", item.id);
712 for impl_item in impl_items {
713 let map = &self.tcx.hir;
714 self.process_impl_item(impl_item, map.local_def_id(item.id));
718 fn process_trait(&mut self,
720 generics: &'l ast::Generics,
721 trait_refs: &'l ast::TyParamBounds,
722 methods: &'l [ast::TraitItem]) {
723 let name = item.ident.to_string();
724 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
725 let mut val = name.clone();
726 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
727 val.push_str(&generics_to_string(generics));
729 if !trait_refs.is_empty() {
731 val.push_str(&bounds_to_string(trait_refs));
733 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
734 if !self.span.filter_generated(sub_span, item.span) {
735 let id = ::id_from_node_id(item.id, &self.save_ctxt);
736 let span = self.span_from_span(sub_span.expect("No span found for trait"));
738 methods.iter().map(|i| ::id_from_node_id(i.id, &self.save_ctxt)).collect();
739 self.dumper.dump_def(item.vis == ast::Visibility::Public, Def {
740 kind: DefKind::Trait,
744 qualname: qualname.clone(),
749 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
750 sig: sig::item_signature(item, &self.save_ctxt),
751 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
756 for super_bound in trait_refs.iter() {
757 let trait_ref = match *super_bound {
758 ast::TraitTyParamBound(ref trait_ref, _) => {
761 ast::RegionTyParamBound(..) => {
766 let trait_ref = &trait_ref.trait_ref;
767 if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
768 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
769 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
770 let span = self.span_from_span(sub_span.expect("No span found for trait ref"));
771 self.dumper.dump_ref(Ref {
774 ref_id: ::id_from_def_id(id),
778 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
779 let sub_span = self.span_from_span(sub_span.expect("No span for inheritance"));
780 self.dumper.dump_relation(Relation {
781 kind: RelationKind::SuperTrait,
783 from: ::id_from_def_id(id),
784 to: ::id_from_node_id(item.id, &self.save_ctxt),
790 // walk generics and methods
791 self.process_generic_params(generics, item.span, &qualname, item.id);
792 for method in methods {
793 let map = &self.tcx.hir;
794 self.process_trait_item(method, map.local_def_id(item.id))
798 // `item` is the module in question, represented as an item.
799 fn process_mod(&mut self, item: &ast::Item) {
800 if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
801 down_cast_data!(mod_data, DefData, item.span);
802 self.dumper.dump_def(item.vis == ast::Visibility::Public, mod_data);
806 fn process_path(&mut self, id: NodeId, path: &ast::Path) {
807 let path_data = self.save_ctxt.get_path_data(id, path);
808 if generated_code(path.span) && path_data.is_none() {
812 let path_data = match path_data {
819 self.dumper.dump_ref(path_data);
821 // Modules or types in the path prefix.
822 match self.save_ctxt.get_path_def(id) {
823 HirDef::Method(did) => {
824 let ti = self.tcx.associated_item(did);
825 if ti.kind == ty::AssociatedKind::Method && ti.method_has_self_argument {
826 self.write_sub_path_trait_truncated(path);
832 HirDef::StructCtor(..) |
833 HirDef::VariantCtor(..) |
834 HirDef::AssociatedConst(..) |
839 HirDef::Variant(..) |
840 HirDef::TyAlias(..) |
841 HirDef::AssociatedTy(..) => self.write_sub_paths_truncated(path),
846 fn process_struct_lit(&mut self,
849 fields: &'l [ast::Field],
850 variant: &'l ty::VariantDef,
851 base: &'l Option<P<ast::Expr>>) {
852 self.write_sub_paths_truncated(path);
854 if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
855 down_cast_data!(struct_lit_data, RefData, ex.span);
856 if !generated_code(ex.span) {
857 self.dumper.dump_ref(struct_lit_data);
860 for field in fields {
861 if let Some(field_data) = self.save_ctxt
862 .get_field_ref_data(field, variant) {
863 self.dumper.dump_ref(field_data);
866 self.visit_expr(&field.expr)
870 walk_list!(self, visit_expr, base);
873 fn process_method_call(&mut self, ex: &'l ast::Expr, args: &'l [P<ast::Expr>]) {
874 if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
875 down_cast_data!(mcd, RefData, ex.span);
876 if !generated_code(ex.span) {
877 self.dumper.dump_ref(mcd);
881 // walk receiver and args
882 walk_list!(self, visit_expr, args);
885 fn process_pat(&mut self, p: &'l ast::Pat) {
887 PatKind::Struct(ref _path, ref fields, _) => {
888 // FIXME do something with _path?
889 let adt = match self.save_ctxt.tables.node_id_to_type_opt(p.id) {
890 Some(ty) => ty.ty_adt_def().unwrap(),
892 visit::walk_pat(self, p);
896 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
898 for &Spanned { node: ref field, span } in fields {
899 let sub_span = self.span.span_for_first_ident(span);
900 if let Some(f) = variant.find_field_named(field.ident.name) {
901 if !self.span.filter_generated(sub_span, span) {
903 self.span_from_span(sub_span.expect("No span fund for var ref"));
904 self.dumper.dump_ref(Ref {
905 kind: RefKind::Variable,
907 ref_id: ::id_from_def_id(f.did),
911 self.visit_pat(&field.pat);
914 _ => visit::walk_pat(self, p),
919 fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
920 // The local could declare multiple new vars, we must walk the
921 // pattern and collect them all.
922 let mut collector = PathCollector::new();
923 collector.visit_pat(&p);
926 for &(id, ref p, immut) in &collector.collected_paths {
927 let mut value = match immut {
928 ast::Mutability::Immutable => value.to_string(),
931 let typ = match self.save_ctxt.tables.node_types.get(&id) {
933 let typ = typ.to_string();
934 if !value.is_empty() {
935 value.push_str(": ");
937 value.push_str(&typ);
940 None => String::new(),
943 // Get the span only for the name of the variable (I hope the path
944 // is only ever a variable name, but who knows?).
945 let sub_span = self.span.span_for_last_ident(p.span);
946 // Rust uses the id of the pattern for var lookups, so we'll use it too.
947 if !self.span.filter_generated(sub_span, p.span) {
948 let qualname = format!("{}${}", path_to_string(p), id);
949 let id = ::id_from_node_id(id, &self.save_ctxt);
950 let span = self.span_from_span(sub_span.expect("No span found for variable"));
952 self.dumper.dump_def(false, Def {
953 kind: DefKind::Local,
956 name: path_to_string(p),
970 /// Extract macro use and definition information from the AST node defined
971 /// by the given NodeId, using the expansion information from the node's
974 /// If the span is not macro-generated, do nothing, else use callee and
975 /// callsite spans to record macro definition and use data, using the
976 /// mac_uses and mac_defs sets to prevent multiples.
977 fn process_macro_use(&mut self, span: Span) {
978 let source_span = span.source_callsite();
979 if self.macro_calls.contains(&source_span) {
982 self.macro_calls.insert(source_span);
984 let data = match self.save_ctxt.get_macro_use_data(span) {
989 self.dumper.macro_use(data);
991 // FIXME write the macro def
992 // let mut hasher = DefaultHasher::new();
993 // data.callee_span.hash(&mut hasher);
994 // let hash = hasher.finish();
995 // let qualname = format!("{}::{}", data.name, hash);
996 // Don't write macro definition for imported macros
997 // if !self.mac_defs.contains(&data.callee_span)
998 // && !data.imported {
999 // self.mac_defs.insert(data.callee_span);
1000 // if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1001 // self.dumper.macro_data(MacroData {
1003 // name: data.name.clone(),
1004 // qualname: qualname.clone(),
1005 // // FIXME where do macro docs come from?
1006 // docs: String::new(),
1007 // }.lower(self.tcx));
1012 fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1013 self.process_macro_use(trait_item.span);
1014 match trait_item.node {
1015 ast::TraitItemKind::Const(ref ty, ref expr) => {
1016 self.process_assoc_const(trait_item.id,
1017 trait_item.ident.name,
1020 expr.as_ref().map(|e| &**e),
1022 ast::Visibility::Public,
1025 ast::TraitItemKind::Method(ref sig, ref body) => {
1026 self.process_method(sig,
1027 body.as_ref().map(|x| &**x),
1030 ast::Visibility::Public,
1033 ast::TraitItemKind::Type(ref bounds, ref default_ty) => {
1034 // FIXME do something with _bounds (for type refs)
1035 let name = trait_item.ident.name.to_string();
1036 let qualname = format!("::{}", self.tcx.node_path_str(trait_item.id));
1037 let sub_span = self.span.sub_span_after_keyword(trait_item.span, keywords::Type);
1039 if !self.span.filter_generated(sub_span, trait_item.span) {
1040 let span = self.span_from_span(sub_span.expect("No span found for assoc type"));
1041 let id = ::id_from_node_id(trait_item.id, &self.save_ctxt);
1043 self.dumper.dump_def(true, Def {
1044 kind: DefKind::Type,
1049 value: self.span.snippet(trait_item.span),
1050 parent: Some(::id_from_def_id(trait_id)),
1053 docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1054 sig: sig::assoc_type_signature(trait_item.id,
1057 default_ty.as_ref().map(|ty| &**ty),
1059 attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1063 if let &Some(ref default_ty) = default_ty {
1064 self.visit_ty(default_ty)
1067 ast::TraitItemKind::Macro(_) => {}
1071 fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1072 self.process_macro_use(impl_item.span);
1073 match impl_item.node {
1074 ast::ImplItemKind::Const(ref ty, ref expr) => {
1075 self.process_assoc_const(impl_item.id,
1076 impl_item.ident.name,
1081 impl_item.vis.clone(),
1084 ast::ImplItemKind::Method(ref sig, ref body) => {
1085 self.process_method(sig,
1089 impl_item.vis.clone(),
1092 ast::ImplItemKind::Type(ref ty) => {
1093 // FIXME uses of the assoc type should ideally point to this
1094 // 'def' and the name here should be a ref to the def in the
1098 ast::ImplItemKind::Macro(_) => {}
1103 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, O> {
1104 fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1105 // Since we handle explicit modules ourselves in visit_item, this should
1106 // only get called for the root module of a crate.
1107 assert_eq!(id, ast::CRATE_NODE_ID);
1109 let qualname = format!("::{}", self.tcx.node_path_str(id));
1111 let cm = self.tcx.sess.codemap();
1112 let filename = cm.span_to_filename(span);
1113 let data_id = ::id_from_node_id(id, &self.save_ctxt);
1114 let children = m.items.iter().map(|i| ::id_from_node_id(i.id, &self.save_ctxt)).collect();
1115 let span = self.span_from_span(span);
1117 self.dumper.dump_def(true, Def {
1120 name: String::new(),
1127 docs: self.save_ctxt.docs_for_attrs(attrs),
1129 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1131 self.nest_scope(id, |v| visit::walk_mod(v, m));
1134 fn visit_item(&mut self, item: &'l ast::Item) {
1135 use syntax::ast::ItemKind::*;
1136 self.process_macro_use(item.span);
1138 Use(ref use_item) => {
1139 match use_item.node {
1140 ast::ViewPathSimple(ident, ref path) => {
1141 let sub_span = self.span.span_for_last_ident(path.span);
1142 let mod_id = match self.lookup_def_id(item.id) {
1144 self.process_def_kind(item.id, path.span, sub_span, def_id);
1150 // 'use' always introduces an alias, if there is not an explicit
1151 // one, there is an implicit one.
1152 let sub_span = match self.span.sub_span_after_keyword(use_item.span,
1154 Some(sub_span) => Some(sub_span),
1158 if !self.span.filter_generated(sub_span, path.span) {
1160 self.span_from_span(sub_span.expect("No span found for use"));
1161 self.dumper.import(item.vis == ast::Visibility::Public, Import {
1162 kind: ImportKind::Use,
1163 ref_id: mod_id.map(|id| ::id_from_def_id(id)),
1165 name: ident.to_string(),
1166 value: String::new(),
1169 self.write_sub_paths_truncated(path);
1171 ast::ViewPathGlob(ref path) => {
1172 // Make a comma-separated list of names of imported modules.
1173 let mut names = vec![];
1174 let glob_map = &self.save_ctxt.analysis.glob_map;
1175 let glob_map = glob_map.as_ref().unwrap();
1176 if glob_map.contains_key(&item.id) {
1177 for n in glob_map.get(&item.id).unwrap() {
1178 names.push(n.to_string());
1182 let sub_span = self.span
1183 .sub_span_of_token(item.span, token::BinOp(token::Star));
1184 if !self.span.filter_generated(sub_span, item.span) {
1186 self.span_from_span(sub_span.expect("No span found for use glob"));
1187 self.dumper.import(item.vis == ast::Visibility::Public, Import {
1188 kind: ImportKind::GlobUse,
1191 name: "*".to_owned(),
1192 value: names.join(", "),
1195 self.write_sub_paths(path);
1197 ast::ViewPathList(ref path, ref list) => {
1199 let id = plid.node.id;
1200 if let Some(def_id) = self.lookup_def_id(id) {
1201 let span = plid.span;
1202 self.process_def_kind(id, span, Some(span), def_id);
1206 self.write_sub_paths(path);
1211 let alias_span = self.span.span_for_last_ident(item.span);
1213 if !self.span.filter_generated(alias_span, item.span) {
1215 self.span_from_span(alias_span.expect("No span found for extern crate"));
1216 self.dumper.import(false, Import {
1217 kind: ImportKind::ExternCrate,
1220 name: item.ident.to_string(),
1221 value: String::new(),
1225 Fn(ref decl, .., ref ty_params, ref body) =>
1226 self.process_fn(item, &decl, ty_params, &body),
1227 Static(ref typ, _, ref expr) =>
1228 self.process_static_or_const_item(item, typ, expr),
1229 Const(ref typ, ref expr) =>
1230 self.process_static_or_const_item(item, &typ, &expr),
1231 Struct(ref def, ref ty_params) => self.process_struct(item, def, ty_params),
1232 Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1237 ref impl_items) => {
1238 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1240 Trait(_, ref generics, ref trait_refs, ref methods) =>
1241 self.process_trait(item, generics, trait_refs, methods),
1243 self.process_mod(item);
1244 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1246 Ty(ref ty, ref ty_params) => {
1247 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1248 let value = ty_to_string(&ty);
1249 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1250 if !self.span.filter_generated(sub_span, item.span) {
1251 let span = self.span_from_span(sub_span.expect("No span found for typedef"));
1252 let id = ::id_from_node_id(item.id, &self.save_ctxt);
1254 self.dumper.dump_def(item.vis == ast::Visibility::Public, Def {
1255 kind: DefKind::Type,
1258 name: item.ident.to_string(),
1259 qualname: qualname.clone(),
1264 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1265 sig: sig::item_signature(item, &self.save_ctxt),
1266 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1271 self.process_generic_params(ty_params, item.span, &qualname, item.id);
1274 _ => visit::walk_item(self, item),
1278 fn visit_generics(&mut self, generics: &'l ast::Generics) {
1279 for param in generics.ty_params.iter() {
1280 for bound in param.bounds.iter() {
1281 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
1282 self.process_trait_ref(&trait_ref.trait_ref);
1285 if let Some(ref ty) = param.default {
1291 fn visit_ty(&mut self, t: &'l ast::Ty) {
1292 self.process_macro_use(t.span);
1294 ast::TyKind::Path(_, ref path) => {
1295 if generated_code(t.span) {
1299 if let Some(id) = self.lookup_def_id(t.id) {
1300 if let Some(sub_span) = self.span.sub_span_for_type_name(t.span) {
1301 let span = self.span_from_span(sub_span);
1302 self.dumper.dump_ref(Ref {
1303 kind: RefKind::Type,
1305 ref_id: ::id_from_def_id(id),
1310 self.write_sub_paths_truncated(path);
1311 visit::walk_path(self, path);
1313 ast::TyKind::Array(ref element, ref length) => {
1314 self.visit_ty(element);
1315 self.nest_tables(length.id, |v| v.visit_expr(length));
1317 _ => visit::walk_ty(self, t),
1321 fn visit_expr(&mut self, ex: &'l ast::Expr) {
1322 debug!("visit_expr {:?}", ex.node);
1323 self.process_macro_use(ex.span);
1325 ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1326 let hir_expr = self.save_ctxt.tcx.hir.expect_expr(ex.id);
1327 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1328 Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1330 visit::walk_expr(self, ex);
1334 let def = self.save_ctxt.get_path_def(hir_expr.id);
1335 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1337 ast::ExprKind::MethodCall(.., ref args) => self.process_method_call(ex, args),
1338 ast::ExprKind::Field(ref sub_ex, _) => {
1339 self.visit_expr(&sub_ex);
1341 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1342 down_cast_data!(field_data, RefData, ex.span);
1343 if !generated_code(ex.span) {
1344 self.dumper.dump_ref(field_data);
1348 ast::ExprKind::TupField(ref sub_ex, idx) => {
1349 self.visit_expr(&sub_ex);
1351 let hir_node = match self.save_ctxt.tcx.hir.find(sub_ex.id) {
1352 Some(Node::NodeExpr(expr)) => expr,
1354 debug!("Missing or weird node for sub-expression {} in {:?}",
1359 let ty = match self.save_ctxt.tables.expr_ty_adjusted_opt(&hir_node) {
1360 Some(ty) => &ty.sty,
1362 visit::walk_expr(self, ex);
1367 ty::TyAdt(def, _) => {
1368 let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1369 if !self.span.filter_generated(sub_span, ex.span) {
1371 self.span_from_span(sub_span.expect("No span found for var ref"));
1372 self.dumper.dump_ref(Ref {
1373 kind: RefKind::Variable,
1375 ref_id: ::id_from_def_id(def.struct_variant().fields[idx.node].did),
1379 ty::TyTuple(..) => {}
1380 _ => span_bug!(ex.span,
1381 "Expected struct or tuple type, found {:?}",
1385 ast::ExprKind::Closure(_, ref decl, ref body, _fn_decl_span) => {
1386 let mut id = String::from("$");
1387 id.push_str(&ex.id.to_string());
1389 // walk arg and return types
1390 for arg in &decl.inputs {
1391 self.visit_ty(&arg.ty);
1394 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1395 self.visit_ty(&ret_ty);
1399 self.nest_tables(ex.id, |v| {
1400 v.process_formals(&decl.inputs, &id);
1401 v.nest_scope(ex.id, |v| v.visit_expr(body))
1404 ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) |
1405 ast::ExprKind::WhileLet(ref pattern, ref subexpression, ref block, _) => {
1406 let value = self.span.snippet(subexpression.span);
1407 self.process_var_decl(pattern, value);
1408 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1409 visit::walk_expr(self, subexpression);
1410 visit::walk_block(self, block);
1412 ast::ExprKind::IfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
1413 let value = self.span.snippet(subexpression.span);
1414 self.process_var_decl(pattern, value);
1415 visit::walk_expr(self, subexpression);
1416 visit::walk_block(self, block);
1417 opt_else.as_ref().map(|el| visit::walk_expr(self, el));
1419 ast::ExprKind::Repeat(ref element, ref count) => {
1420 self.visit_expr(element);
1421 self.nest_tables(count.id, |v| v.visit_expr(count));
1423 // In particular, we take this branch for call and path expressions,
1424 // where we'll index the idents involved just by continuing to walk.
1426 visit::walk_expr(self, ex)
1431 fn visit_mac(&mut self, mac: &'l ast::Mac) {
1432 // These shouldn't exist in the AST at this point, log a span bug.
1433 span_bug!(mac.span, "macro invocation should have been expanded out of AST");
1436 fn visit_pat(&mut self, p: &'l ast::Pat) {
1437 self.process_macro_use(p.span);
1438 self.process_pat(p);
1441 fn visit_arm(&mut self, arm: &'l ast::Arm) {
1442 let mut collector = PathCollector::new();
1443 for pattern in &arm.pats {
1444 // collect paths from the arm's patterns
1445 collector.visit_pat(&pattern);
1446 self.visit_pat(&pattern);
1449 // This is to get around borrow checking, because we need mut self to call process_path.
1450 let mut paths_to_process = vec![];
1452 // process collected paths
1453 for &(id, ref p, immut) in &collector.collected_paths {
1454 match self.save_ctxt.get_path_def(id) {
1455 HirDef::Local(def_id) => {
1456 let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1457 let mut value = if immut == ast::Mutability::Immutable {
1458 self.span.snippet(p.span).to_string()
1460 "<mutable>".to_string()
1462 let typ = self.save_ctxt.tables.node_types
1463 .get(&id).map(|t| t.to_string()).unwrap_or(String::new());
1464 value.push_str(": ");
1465 value.push_str(&typ);
1467 assert!(p.segments.len() == 1,
1468 "qualified path for local variable def in arm");
1469 if !self.span.filter_generated(Some(p.span), p.span) {
1470 let qualname = format!("{}${}", path_to_string(p), id);
1471 let id = ::id_from_node_id(id, &self.save_ctxt);
1472 let span = self.span_from_span(p.span);
1474 self.dumper.dump_def(false, Def {
1475 kind: DefKind::Local,
1478 name: path_to_string(p),
1484 docs: String::new(),
1490 HirDef::StructCtor(..) | HirDef::VariantCtor(..) |
1491 HirDef::Const(..) | HirDef::AssociatedConst(..) |
1492 HirDef::Struct(..) | HirDef::Variant(..) |
1493 HirDef::TyAlias(..) | HirDef::AssociatedTy(..) |
1494 HirDef::SelfTy(..) => {
1495 paths_to_process.push((id, p.clone()))
1497 def => error!("unexpected definition kind when processing collected paths: {:?}",
1502 for &(id, ref path) in &paths_to_process {
1503 self.process_path(id, path);
1505 walk_list!(self, visit_expr, &arm.guard);
1506 self.visit_expr(&arm.body);
1509 fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1510 self.process_path(id, p);
1513 fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1514 self.process_macro_use(s.span);
1515 visit::walk_stmt(self, s)
1518 fn visit_local(&mut self, l: &'l ast::Local) {
1519 self.process_macro_use(l.span);
1520 let value = l.init.as_ref().map(|i| self.span.snippet(i.span)).unwrap_or(String::new());
1521 self.process_var_decl(&l.pat, value);
1523 // Just walk the initialiser and type (don't want to walk the pattern again).
1524 walk_list!(self, visit_ty, &l.ty);
1525 walk_list!(self, visit_expr, &l.init);
1528 fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1530 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1531 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1532 down_cast_data!(fn_data, DefData, item.span);
1534 self.nest_tables(item.id, |v| v.process_formals(&decl.inputs,
1535 &fn_data.qualname));
1536 self.process_generic_params(generics, item.span, &fn_data.qualname, item.id);
1537 self.dumper.dump_def(item.vis == ast::Visibility::Public, fn_data);
1540 for arg in &decl.inputs {
1541 self.visit_ty(&arg.ty);
1544 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1545 self.visit_ty(&ret_ty);
1548 ast::ForeignItemKind::Static(ref ty, _) => {
1549 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1550 down_cast_data!(var_data, DefData, item.span);
1551 self.dumper.dump_def(item.vis == ast::Visibility::Public, var_data);