1 // Copyright 2012-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 #![crate_name = "rustc_save_analysis"]
12 #![crate_type = "dylib"]
13 #![crate_type = "rlib"]
14 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
15 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
16 html_root_url = "https://doc.rust-lang.org/nightly/")]
19 #![feature(custom_attribute)]
20 #![allow(unused_attributes)]
22 #![cfg_attr(stage0, unstable(feature = "rustc_private", issue = "27812"))]
23 #![cfg_attr(stage0, feature(rustc_private))]
24 #![cfg_attr(stage0, feature(staged_api))]
26 #[macro_use] extern crate rustc;
28 #[macro_use] extern crate log;
29 #[macro_use] extern crate syntax;
30 extern crate rustc_serialize;
31 extern crate rustc_typeck;
32 extern crate syntax_pos;
34 extern crate rls_data;
35 extern crate rls_span;
44 pub mod external_data;
49 use rustc::hir::def::Def;
50 use rustc::hir::map::Node;
51 use rustc::hir::def_id::DefId;
52 use rustc::session::config::CrateType::CrateTypeExecutable;
53 use rustc::session::Session;
54 use rustc::ty::{self, TyCtxt};
55 use rustc_typeck::hir_ty_to_ty;
59 use std::path::{Path, PathBuf};
61 use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID};
62 use syntax::parse::lexer::comments::strip_doc_comment_decoration;
63 use syntax::parse::token;
64 use syntax::symbol::keywords;
65 use syntax::visit::{self, Visitor};
66 use syntax::print::pprust::{ty_to_string, arg_to_string};
67 use syntax::codemap::MacroAttribute;
70 pub use self::csv_dumper::CsvDumper;
71 pub use self::json_api_dumper::JsonApiDumper;
72 pub use self::json_dumper::JsonDumper;
73 pub use self::data::*;
74 pub use self::external_data::make_def_id;
75 pub use self::dump::Dump;
76 pub use self::dump_visitor::DumpVisitor;
77 use self::span_utils::SpanUtils;
79 // FIXME this is legacy code and should be removed
83 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
92 pub struct SaveContext<'l, 'tcx: 'l> {
93 tcx: TyCtxt<'l, 'tcx, 'tcx>,
94 tables: &'l ty::TypeckTables<'tcx>,
95 analysis: &'l ty::CrateAnalysis,
96 span_utils: SpanUtils<'tcx>,
99 macro_rules! option_try(
100 ($e:expr) => (match $e { Some(e) => e, None => return None })
103 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
104 // List external crates used by the current crate.
105 pub fn get_external_crates(&self) -> Vec<CrateData> {
106 let mut result = Vec::new();
108 for n in self.tcx.sess.cstore.crates() {
109 let span = match self.tcx.sess.cstore.extern_crate(n) {
110 Some(ref c) => c.span,
112 debug!("Skipping crate {}, no data", n);
116 result.push(CrateData {
117 name: self.tcx.sess.cstore.crate_name(n).to_string(),
126 pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
127 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
129 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
130 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
131 filter!(self.span_utils, sub_span, item.span, None);
132 Some(Data::FunctionData(FunctionData {
134 name: item.ident.to_string(),
137 span: sub_span.unwrap(),
138 scope: self.enclosing_scope(item.id),
139 value: make_signature(decl, generics),
140 visibility: From::from(&item.vis),
142 docs: docs_for_attrs(&item.attrs),
143 sig: self.sig_base_extern(item),
144 attributes: item.attrs.clone(),
147 ast::ForeignItemKind::Static(ref ty, m) => {
148 let keyword = if m { keywords::Mut } else { keywords::Static };
149 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
150 filter!(self.span_utils, sub_span, item.span, None);
151 Some(Data::VariableData(VariableData {
153 kind: VariableKind::Static,
154 name: item.ident.to_string(),
156 span: sub_span.unwrap(),
157 scope: self.enclosing_scope(item.id),
159 value: String::new(),
160 type_value: ty_to_string(ty),
161 visibility: From::from(&item.vis),
162 docs: docs_for_attrs(&item.attrs),
163 sig: Some(self.sig_base_extern(item)),
164 attributes: item.attrs.clone(),
170 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
172 ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
173 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
174 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
175 filter!(self.span_utils, sub_span, item.span, None);
178 Some(Data::FunctionData(FunctionData {
180 name: item.ident.to_string(),
183 span: sub_span.unwrap(),
184 scope: self.enclosing_scope(item.id),
185 value: make_signature(decl, generics),
186 visibility: From::from(&item.vis),
188 docs: docs_for_attrs(&item.attrs),
189 sig: self.sig_base(item),
190 attributes: item.attrs.clone(),
193 ast::ItemKind::Static(ref typ, mt, ref expr) => {
194 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
196 // If the variable is immutable, save the initialising expression.
197 let (value, keyword) = match mt {
198 ast::Mutability::Mutable => (String::from("<mutable>"), keywords::Mut),
199 ast::Mutability::Immutable => {
200 (self.span_utils.snippet(expr.span), keywords::Static)
204 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
205 filter!(self.span_utils, sub_span, item.span, None);
206 Some(Data::VariableData(VariableData {
208 kind: VariableKind::Static,
209 name: item.ident.to_string(),
211 span: sub_span.unwrap(),
212 scope: self.enclosing_scope(item.id),
215 type_value: ty_to_string(&typ),
216 visibility: From::from(&item.vis),
217 docs: docs_for_attrs(&item.attrs),
218 sig: Some(self.sig_base(item)),
219 attributes: item.attrs.clone(),
222 ast::ItemKind::Const(ref typ, ref expr) => {
223 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
224 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
225 filter!(self.span_utils, sub_span, item.span, None);
226 Some(Data::VariableData(VariableData {
228 kind: VariableKind::Const,
229 name: item.ident.to_string(),
231 span: sub_span.unwrap(),
232 scope: self.enclosing_scope(item.id),
234 value: self.span_utils.snippet(expr.span),
235 type_value: ty_to_string(&typ),
236 visibility: From::from(&item.vis),
237 docs: docs_for_attrs(&item.attrs),
238 sig: Some(self.sig_base(item)),
239 attributes: item.attrs.clone(),
242 ast::ItemKind::Mod(ref m) => {
243 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
245 let cm = self.tcx.sess.codemap();
246 let filename = cm.span_to_filename(m.inner);
248 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
249 filter!(self.span_utils, sub_span, item.span, None);
251 Some(Data::ModData(ModData {
253 name: item.ident.to_string(),
255 span: sub_span.unwrap(),
256 scope: self.enclosing_scope(item.id),
258 items: m.items.iter().map(|i| i.id).collect(),
259 visibility: From::from(&item.vis),
260 docs: docs_for_attrs(&item.attrs),
261 sig: Some(self.sig_base(item)),
262 attributes: item.attrs.clone(),
265 ast::ItemKind::Enum(ref def, _) => {
266 let name = item.ident.to_string();
267 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
268 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
269 filter!(self.span_utils, sub_span, item.span, None);
270 let variants_str = def.variants.iter()
271 .map(|v| v.node.name.to_string())
274 let val = format!("{}::{{{}}}", name, variants_str);
275 Some(Data::EnumData(EnumData {
279 span: sub_span.unwrap(),
281 scope: self.enclosing_scope(item.id),
282 variants: def.variants.iter().map(|v| v.node.data.id()).collect(),
283 visibility: From::from(&item.vis),
284 docs: docs_for_attrs(&item.attrs),
285 sig: self.sig_base(item),
286 attributes: item.attrs.clone(),
289 ast::ItemKind::Impl(.., ref trait_ref, ref typ, _) => {
290 let mut type_data = None;
293 let parent = self.enclosing_scope(item.id);
296 // Common case impl for a struct or something basic.
297 ast::TyKind::Path(None, ref path) => {
298 if generated_code(path.span) {
301 sub_span = self.span_utils.sub_span_for_type_name(path.span);
302 type_data = self.lookup_ref_id(typ.id).map(|id| {
304 span: sub_span.unwrap(),
307 qualname: String::new() // FIXME: generate the real qualname
312 // Less useful case, impl for a compound type.
314 sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
318 let trait_data = trait_ref.as_ref()
319 .and_then(|tr| self.get_trait_ref_data(tr, parent));
321 filter!(self.span_utils, sub_span, typ.span, None);
322 Some(Data::ImplData(ImplData2 {
324 span: sub_span.unwrap(),
326 trait_ref: trait_data,
337 pub fn get_field_data(&self,
338 field: &ast::StructField,
340 -> Option<VariableData> {
341 if let Some(ident) = field.ident {
342 let name = ident.to_string();
343 let qualname = format!("::{}::{}", self.tcx.node_path_str(scope), ident);
344 let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
345 filter!(self.span_utils, sub_span, field.span, None);
346 let def_id = self.tcx.hir.local_def_id(field.id);
347 let typ = self.tcx.type_of(def_id).to_string();
349 let span = field.span;
350 let text = self.span_utils.snippet(field.span);
351 let ident_start = text.find(&name).unwrap();
352 let ident_end = ident_start + name.len();
353 let sig = Signature {
356 ident_start: ident_start,
357 ident_end: ident_end,
363 kind: VariableKind::Field,
366 span: sub_span.unwrap(),
368 parent: Some(make_def_id(scope, &self.tcx.hir)),
369 value: "".to_owned(),
371 visibility: From::from(&field.vis),
372 docs: docs_for_attrs(&field.attrs),
374 attributes: field.attrs.clone(),
381 // FIXME would be nice to take a MethodItem here, but the ast provides both
382 // trait and impl flavours, so the caller must do the disassembly.
383 pub fn get_method_data(&self, id: ast::NodeId,
384 name: ast::Name, span: Span) -> Option<FunctionData> {
385 // The qualname for a method is the trait name or name of the struct in an impl in
386 // which the method is declared in, followed by the method's name.
387 let (qualname, parent_scope, decl_id, vis, docs, attributes) =
388 match self.tcx.impl_of_method(self.tcx.hir.local_def_id(id)) {
389 Some(impl_id) => match self.tcx.hir.get_if_local(impl_id) {
390 Some(Node::NodeItem(item)) => {
392 hir::ItemImpl(.., ref ty, _) => {
393 let mut result = String::from("<");
394 result.push_str(&self.tcx.hir.node_to_pretty_string(ty.id));
396 let trait_id = self.tcx.trait_id_of_impl(impl_id);
397 let mut decl_id = None;
398 if let Some(def_id) = trait_id {
399 result.push_str(" as ");
400 result.push_str(&self.tcx.item_path_str(def_id));
401 self.tcx.associated_items(def_id)
402 .find(|item| item.name == name)
403 .map(|item| decl_id = Some(item.def_id));
405 result.push_str(">");
407 (result, trait_id, decl_id,
408 From::from(&item.vis),
409 docs_for_attrs(&item.attrs),
414 "Container {:?} for method {} not an impl?",
422 "Container {:?} for method {} is not a node item {:?}",
428 None => match self.tcx.trait_of_item(self.tcx.hir.local_def_id(id)) {
430 match self.tcx.hir.get_if_local(def_id) {
431 Some(Node::NodeItem(item)) => {
432 (format!("::{}", self.tcx.item_path_str(def_id)),
434 From::from(&item.vis),
435 docs_for_attrs(&item.attrs),
440 "Could not find container {:?} for \
441 method {}, got {:?}",
449 debug!("Could not find container for method {} at {:?}", id, span);
450 // This is not necessarily a bug, if there was a compilation error, the tables
451 // we need might not exist.
457 let qualname = format!("{}::{}", qualname, name);
459 let sub_span = self.span_utils.sub_span_after_keyword(span, keywords::Fn);
460 filter!(self.span_utils, sub_span, span, None);
462 let name = name.to_string();
463 let text = self.span_utils.signature_string_for_span(span);
464 let ident_start = text.find(&name).unwrap();
465 let ident_end = ident_start + name.len();
466 let sig = Signature {
469 ident_start: ident_start,
470 ident_end: ident_end,
479 declaration: decl_id,
480 span: sub_span.unwrap(),
481 scope: self.enclosing_scope(id),
482 // FIXME you get better data here by using the visitor.
483 value: String::new(),
485 parent: parent_scope,
488 attributes: attributes,
492 pub fn get_trait_ref_data(&self,
493 trait_ref: &ast::TraitRef,
495 -> Option<TypeRefData> {
496 self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
497 let span = trait_ref.path.span;
498 if generated_code(span) {
501 let sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
502 filter!(self.span_utils, sub_span, span, None);
504 span: sub_span.unwrap(),
506 ref_id: Some(def_id),
507 qualname: String::new() // FIXME: generate the real qualname
512 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
513 let hir_node = self.tcx.hir.expect_expr(expr.id);
514 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
515 if ty.is_none() || ty.unwrap().sty == ty::TyError {
519 ast::ExprKind::Field(ref sub_ex, ident) => {
520 let hir_node = match self.tcx.hir.find(sub_ex.id) {
521 Some(Node::NodeExpr(expr)) => expr,
523 debug!("Missing or weird node for sub-expression {} in {:?}",
528 match self.tables.expr_ty_adjusted(&hir_node).sty {
529 ty::TyAdt(def, _) if !def.is_enum() => {
530 let f = def.struct_variant().field_named(ident.node.name);
531 let sub_span = self.span_utils.span_for_last_ident(expr.span);
532 filter!(self.span_utils, sub_span, expr.span, None);
533 return Some(Data::VariableRefData(VariableRefData {
534 name: ident.node.to_string(),
535 span: sub_span.unwrap(),
536 scope: self.enclosing_scope(expr.id),
541 debug!("Expected struct or union type, found {:?}", ty);
546 ast::ExprKind::Struct(ref path, ..) => {
547 match self.tables.expr_ty_adjusted(&hir_node).sty {
548 ty::TyAdt(def, _) if !def.is_enum() => {
549 let sub_span = self.span_utils.span_for_last_ident(path.span);
550 filter!(self.span_utils, sub_span, path.span, None);
551 Some(Data::TypeRefData(TypeRefData {
552 span: sub_span.unwrap(),
553 scope: self.enclosing_scope(expr.id),
554 ref_id: Some(def.did),
555 qualname: String::new() // FIXME: generate the real qualname
559 // FIXME ty could legitimately be an enum, but then we will fail
560 // later if we try to look up the fields.
561 debug!("expected struct or union, found {:?}", ty);
566 ast::ExprKind::MethodCall(..) => {
567 let method_id = self.tables.type_dependent_defs[&expr.id].def_id();
568 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
569 ty::ImplContainer(_) => (Some(method_id), None),
570 ty::TraitContainer(_) => (None, Some(method_id)),
572 let sub_span = self.span_utils.sub_span_for_meth_name(expr.span);
573 filter!(self.span_utils, sub_span, expr.span, None);
574 let parent = self.enclosing_scope(expr.id);
575 Some(Data::MethodCallData(MethodCallData {
576 span: sub_span.unwrap(),
582 ast::ExprKind::Path(_, ref path) => {
583 self.get_path_data(expr.id, path)
592 pub fn get_path_def(&self, id: NodeId) -> Def {
593 match self.tcx.hir.get(id) {
594 Node::NodeTraitRef(tr) => tr.path.def,
596 Node::NodeItem(&hir::Item { node: hir::ItemUse(ref path, _), .. }) |
597 Node::NodeVisibility(&hir::Visibility::Restricted { ref path, .. }) => path.def,
599 Node::NodeExpr(&hir::Expr { node: hir::ExprPath(ref qpath), .. }) |
600 Node::NodeExpr(&hir::Expr { node: hir::ExprStruct(ref qpath, ..), .. }) |
601 Node::NodePat(&hir::Pat { node: hir::PatKind::Path(ref qpath), .. }) |
602 Node::NodePat(&hir::Pat { node: hir::PatKind::Struct(ref qpath, ..), .. }) |
603 Node::NodePat(&hir::Pat { node: hir::PatKind::TupleStruct(ref qpath, ..), .. }) => {
604 self.tables.qpath_def(qpath, id)
607 Node::NodeLocal(&hir::Pat { node: hir::PatKind::Binding(_, def_id, ..), .. }) => {
611 Node::NodeTy(ty) => {
612 if let hir::Ty { node: hir::TyPath(ref qpath), .. } = *ty {
614 hir::QPath::Resolved(_, ref path) => path.def,
615 hir::QPath::TypeRelative(..) => {
616 let ty = hir_ty_to_ty(self.tcx, ty);
617 if let ty::TyProjection(proj) = ty.sty {
618 for item in self.tcx.associated_items(proj.trait_ref.def_id) {
619 if item.kind == ty::AssociatedKind::Type {
620 if item.name == proj.item_name {
621 return Def::AssociatedTy(item.def_id);
638 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Data> {
639 let def = self.get_path_def(id);
640 let sub_span = self.span_utils.span_for_last_ident(path.span);
641 filter!(self.span_utils, sub_span, path.span, None);
647 Def::AssociatedConst(..) |
648 Def::StructCtor(..) |
649 Def::VariantCtor(..) => {
650 Some(Data::VariableRefData(VariableRefData {
651 name: self.span_utils.snippet(sub_span.unwrap()),
652 span: sub_span.unwrap(),
653 scope: self.enclosing_scope(id),
654 ref_id: def.def_id(),
657 Def::Struct(def_id) |
658 Def::Variant(def_id, ..) |
661 Def::TyAlias(def_id) |
662 Def::AssociatedTy(def_id) |
664 Def::TyParam(def_id) => {
665 Some(Data::TypeRefData(TypeRefData {
666 span: sub_span.unwrap(),
667 ref_id: Some(def_id),
668 scope: self.enclosing_scope(id),
669 qualname: String::new() // FIXME: generate the real qualname
672 Def::Method(decl_id) => {
673 let sub_span = self.span_utils.sub_span_for_meth_name(path.span);
674 filter!(self.span_utils, sub_span, path.span, None);
675 let def_id = if decl_id.is_local() {
676 let ti = self.tcx.associated_item(decl_id);
677 self.tcx.associated_items(ti.container.id())
678 .find(|item| item.name == ti.name && item.defaultness.has_value())
679 .map(|item| item.def_id)
683 Some(Data::MethodCallData(MethodCallData {
684 span: sub_span.unwrap(),
685 scope: self.enclosing_scope(id),
687 decl_id: Some(decl_id),
691 Some(Data::FunctionCallData(FunctionCallData {
693 span: sub_span.unwrap(),
694 scope: self.enclosing_scope(id),
697 Def::Mod(def_id) => {
698 Some(Data::ModRefData(ModRefData {
699 ref_id: Some(def_id),
700 span: sub_span.unwrap(),
701 scope: self.enclosing_scope(id),
702 qualname: String::new() // FIXME: generate the real qualname
714 pub fn get_field_ref_data(&self,
715 field_ref: &ast::Field,
716 variant: &ty::VariantDef,
718 -> Option<VariableRefData> {
719 let f = variant.field_named(field_ref.ident.node.name);
720 // We don't really need a sub-span here, but no harm done
721 let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
722 filter!(self.span_utils, sub_span, field_ref.ident.span, None);
723 Some(VariableRefData {
724 name: field_ref.ident.node.to_string(),
725 span: sub_span.unwrap(),
731 /// Attempt to return MacroUseData for any AST node.
733 /// For a given piece of AST defined by the supplied Span and NodeId,
734 /// returns None if the node is not macro-generated or the span is malformed,
735 /// else uses the expansion callsite and callee to return some MacroUseData.
736 pub fn get_macro_use_data(&self, span: Span, id: NodeId) -> Option<MacroUseData> {
737 if !generated_code(span) {
740 // Note we take care to use the source callsite/callee, to handle
741 // nested expansions and ensure we only generate data for source-visible
743 let callsite = span.source_callsite();
744 let callee = option_try!(span.source_callee());
745 let callee_span = option_try!(callee.span);
747 // Ignore attribute macros, their spans are usually mangled
748 if let MacroAttribute(_) = callee.format {
752 // If the callee is an imported macro from an external crate, need to get
753 // the source span and name from the session, as their spans are localized
754 // when read in, and no longer correspond to the source.
755 if let Some(mac) = self.tcx.sess.imported_macro_spans.borrow().get(&callee_span) {
756 let &(ref mac_name, mac_span) = mac;
757 return Some(MacroUseData {
759 name: mac_name.clone(),
760 callee_span: mac_span,
761 scope: self.enclosing_scope(id),
763 qualname: String::new()// FIXME: generate the real qualname
769 name: callee.name().to_string(),
770 callee_span: callee_span,
771 scope: self.enclosing_scope(id),
773 qualname: String::new() // FIXME: generate the real qualname
777 pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
782 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
783 match self.get_path_def(ref_id) {
784 Def::PrimTy(_) | Def::SelfTy(..) | Def::Err => None,
785 def => Some(def.def_id()),
789 fn sig_base(&self, item: &ast::Item) -> Signature {
790 let text = self.span_utils.signature_string_for_span(item.span);
791 let name = item.ident.to_string();
792 let ident_start = text.find(&name).expect("Name not in signature?");
793 let ident_end = ident_start + name.len();
795 span: Span { hi: item.span.lo + BytePos(text.len() as u32), ..item.span },
797 ident_start: ident_start,
798 ident_end: ident_end,
804 fn sig_base_extern(&self, item: &ast::ForeignItem) -> Signature {
805 let text = self.span_utils.signature_string_for_span(item.span);
806 let name = item.ident.to_string();
807 let ident_start = text.find(&name).expect("Name not in signature?");
808 let ident_end = ident_start + name.len();
810 span: Span { hi: item.span.lo + BytePos(text.len() as u32), ..item.span },
812 ident_start: ident_start,
813 ident_end: ident_end,
820 pub fn enclosing_scope(&self, id: NodeId) -> NodeId {
821 self.tcx.hir.get_enclosing_scope(id).unwrap_or(CRATE_NODE_ID)
825 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
826 let mut sig = "fn ".to_owned();
827 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
829 sig.push_str(&generics.lifetimes.iter()
830 .map(|l| l.lifetime.ident.name.to_string())
833 if !generics.lifetimes.is_empty() {
836 sig.push_str(&generics.ty_params.iter()
837 .map(|l| l.ident.to_string())
843 sig.push_str(&decl.inputs.iter().map(arg_to_string).collect::<Vec<_>>().join(", "));
846 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
847 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
853 // An AST visitor for collecting paths from patterns.
854 struct PathCollector {
855 // The Row field identifies the kind of pattern.
856 collected_paths: Vec<(NodeId, ast::Path, ast::Mutability, recorder::Row)>,
860 fn new() -> PathCollector {
861 PathCollector { collected_paths: vec![] }
865 impl<'a> Visitor<'a> for PathCollector {
866 fn visit_pat(&mut self, p: &ast::Pat) {
868 PatKind::Struct(ref path, ..) => {
869 self.collected_paths.push((p.id, path.clone(),
870 ast::Mutability::Mutable, recorder::TypeRef));
872 PatKind::TupleStruct(ref path, ..) |
873 PatKind::Path(_, ref path) => {
874 self.collected_paths.push((p.id, path.clone(),
875 ast::Mutability::Mutable, recorder::VarRef));
877 PatKind::Ident(bm, ref path1, _) => {
878 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
882 let immut = match bm {
883 // Even if the ref is mut, you can't change the ref, only
884 // the data pointed at, so showing the initialising expression
885 // is still worthwhile.
886 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
887 ast::BindingMode::ByValue(mt) => mt,
889 // collect path for either visit_local or visit_arm
890 let path = ast::Path::from_ident(path1.span, path1.node);
891 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
895 visit::walk_pat(self, p);
899 fn docs_for_attrs(attrs: &[Attribute]) -> String {
900 let mut result = String::new();
903 if attr.check_name("doc") {
904 if let Some(val) = attr.value_str() {
905 if attr.is_sugared_doc {
906 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
908 result.push_str(&val.as_str());
918 #[derive(Clone, Copy, Debug, RustcEncodable)]
926 fn extension(&self) -> &'static str {
928 Format::Csv => ".csv",
929 Format::Json | Format::JsonApi => ".json",
934 /// Defines what to do with the results of saving the analysis.
935 pub trait SaveHandler {
936 fn save<'l, 'tcx>(&mut self,
937 save_ctxt: SaveContext<'l, 'tcx>,
942 /// Dump the save-analysis results to a file.
943 pub struct DumpHandler<'a> {
945 odir: Option<&'a Path>,
949 impl<'a> DumpHandler<'a> {
950 pub fn new(format: Format, odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
954 cratename: cratename.to_owned()
958 fn output_file(&self, sess: &Session) -> File {
959 let mut root_path = match env::var_os("RUST_SAVE_ANALYSIS_FOLDER") {
960 Some(val) => PathBuf::from(val),
961 None => match self.odir {
962 Some(val) => val.join("save-analysis"),
963 None => PathBuf::from("save-analysis-temp"),
967 if let Err(e) = std::fs::create_dir_all(&root_path) {
968 error!("Could not create directory {}: {}", root_path.display(), e);
972 let disp = root_path.display();
973 info!("Writing output to {}", disp);
976 let executable = sess.crate_types.borrow().iter().any(|ct| *ct == CrateTypeExecutable);
977 let mut out_name = if executable {
982 out_name.push_str(&self.cratename);
983 out_name.push_str(&sess.opts.cg.extra_filename);
984 out_name.push_str(self.format.extension());
985 root_path.push(&out_name);
986 let output_file = File::create(&root_path).unwrap_or_else(|e| {
987 let disp = root_path.display();
988 sess.fatal(&format!("Could not open {}: {}", disp, e));
995 impl<'a> SaveHandler for DumpHandler<'a> {
996 fn save<'l, 'tcx>(&mut self,
997 save_ctxt: SaveContext<'l, 'tcx>,
1001 ($new_dumper: expr) => {{
1002 let mut dumper = $new_dumper;
1003 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1005 visitor.dump_crate_info(cratename, krate);
1006 visit::walk_crate(&mut visitor, krate);
1010 let output = &mut self.output_file(&save_ctxt.tcx.sess);
1013 Format::Csv => dump!(CsvDumper::new(output)),
1014 Format::Json => dump!(JsonDumper::new(output)),
1015 Format::JsonApi => dump!(JsonApiDumper::new(output)),
1020 /// Call a callback with the results of save-analysis.
1021 pub struct CallbackHandler<'b> {
1022 pub callback: &'b mut FnMut(&rls_data::Analysis),
1025 impl<'b> SaveHandler for CallbackHandler<'b> {
1026 fn save<'l, 'tcx>(&mut self,
1027 save_ctxt: SaveContext<'l, 'tcx>,
1031 ($new_dumper: expr) => {{
1032 let mut dumper = $new_dumper;
1033 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1035 visitor.dump_crate_info(cratename, krate);
1036 visit::walk_crate(&mut visitor, krate);
1040 // We're using the JsonDumper here because it has the format of the
1041 // save-analysis results that we will pass to the callback. IOW, we are
1042 // using the JsonDumper to collect the save-analysis results, but not
1043 // actually to dump them to a file. This is all a bit convoluted and
1044 // there is certainly a simpler design here trying to get out (FIXME).
1045 dump!(JsonDumper::with_callback(self.callback))
1049 pub fn process_crate<'l, 'tcx, H: SaveHandler>(tcx: TyCtxt<'l, 'tcx, 'tcx>,
1051 analysis: &'l ty::CrateAnalysis,
1054 let _ignore = tcx.dep_graph.in_ignore();
1056 assert!(analysis.glob_map.is_some());
1058 info!("Dumping crate {}", cratename);
1060 let save_ctxt = SaveContext {
1062 tables: &ty::TypeckTables::empty(),
1064 span_utils: SpanUtils::new(&tcx.sess),
1067 handler.save(save_ctxt, krate, cratename)
1070 // Utility functions for the module.
1072 // Helper function to escape quotes in a string
1073 fn escape(s: String) -> String {
1074 s.replace("\"", "\"\"")
1077 // Helper function to determine if a span came from a
1078 // macro expansion or syntax extension.
1079 pub fn generated_code(span: Span) -> bool {
1080 span.ctxt != NO_EXPANSION || span == DUMMY_SP