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 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17 html_root_url = "https://doc.rust-lang.org/nightly/")]
20 #![feature(custom_attribute)]
21 #![allow(unused_attributes)]
22 #![feature(rustc_private)]
23 #![feature(staged_api)]
25 #[macro_use] extern crate rustc;
27 #[macro_use] extern crate log;
28 #[macro_use] extern crate syntax;
29 extern crate serialize as rustc_serialize;
30 extern crate syntax_pos;
39 pub mod external_data;
44 use rustc::hir::def::Def;
45 use rustc::hir::map::Node;
46 use rustc::hir::def_id::DefId;
47 use rustc::session::config::CrateType::CrateTypeExecutable;
48 use rustc::ty::{self, TyCtxt};
52 use std::path::{Path, PathBuf};
54 use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID};
55 use syntax::parse::lexer::comments::strip_doc_comment_decoration;
56 use syntax::parse::token;
57 use syntax::symbol::keywords;
58 use syntax::visit::{self, Visitor};
59 use syntax::print::pprust::{ty_to_string, arg_to_string};
60 use syntax::codemap::MacroAttribute;
63 pub use self::csv_dumper::CsvDumper;
64 pub use self::json_api_dumper::JsonApiDumper;
65 pub use self::json_dumper::JsonDumper;
66 pub use self::data::*;
67 pub use self::external_data::make_def_id;
68 pub use self::dump::Dump;
69 pub use self::dump_visitor::DumpVisitor;
70 use self::span_utils::SpanUtils;
72 // FIXME this is legacy code and should be removed
76 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
85 pub struct SaveContext<'l, 'tcx: 'l> {
86 tcx: TyCtxt<'l, 'tcx, 'tcx>,
87 tables: &'l ty::TypeckTables<'tcx>,
88 analysis: &'l ty::CrateAnalysis,
89 span_utils: SpanUtils<'tcx>,
92 macro_rules! option_try(
93 ($e:expr) => (match $e { Some(e) => e, None => return None })
96 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
97 // List external crates used by the current crate.
98 pub fn get_external_crates(&self) -> Vec<CrateData> {
99 let mut result = Vec::new();
101 for n in self.tcx.sess.cstore.crates() {
102 let span = match self.tcx.sess.cstore.extern_crate(n) {
103 Some(ref c) => c.span,
105 debug!("Skipping crate {}, no data", n);
109 result.push(CrateData {
110 name: self.tcx.sess.cstore.crate_name(n).to_string(),
119 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
121 ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
122 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
123 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
124 filter!(self.span_utils, sub_span, item.span, None);
127 Some(Data::FunctionData(FunctionData {
129 name: item.ident.to_string(),
132 span: sub_span.unwrap(),
133 scope: self.enclosing_scope(item.id),
134 value: make_signature(decl, generics),
135 visibility: From::from(&item.vis),
137 docs: docs_for_attrs(&item.attrs),
138 sig: self.sig_base(item),
139 attributes: item.attrs.clone(),
142 ast::ItemKind::Static(ref typ, mt, ref expr) => {
143 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
145 // If the variable is immutable, save the initialising expression.
146 let (value, keyword) = match mt {
147 ast::Mutability::Mutable => (String::from("<mutable>"), keywords::Mut),
148 ast::Mutability::Immutable => {
149 (self.span_utils.snippet(expr.span), keywords::Static)
153 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
154 filter!(self.span_utils, sub_span, item.span, None);
155 Some(Data::VariableData(VariableData {
157 kind: VariableKind::Static,
158 name: item.ident.to_string(),
160 span: sub_span.unwrap(),
161 scope: self.enclosing_scope(item.id),
164 type_value: ty_to_string(&typ),
165 visibility: From::from(&item.vis),
166 docs: docs_for_attrs(&item.attrs),
167 sig: Some(self.sig_base(item)),
168 attributes: item.attrs.clone(),
171 ast::ItemKind::Const(ref typ, ref expr) => {
172 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
173 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
174 filter!(self.span_utils, sub_span, item.span, None);
175 Some(Data::VariableData(VariableData {
177 kind: VariableKind::Const,
178 name: item.ident.to_string(),
180 span: sub_span.unwrap(),
181 scope: self.enclosing_scope(item.id),
183 value: self.span_utils.snippet(expr.span),
184 type_value: ty_to_string(&typ),
185 visibility: From::from(&item.vis),
186 docs: docs_for_attrs(&item.attrs),
187 sig: Some(self.sig_base(item)),
188 attributes: item.attrs.clone(),
191 ast::ItemKind::Mod(ref m) => {
192 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
194 let cm = self.tcx.sess.codemap();
195 let filename = cm.span_to_filename(m.inner);
197 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
198 filter!(self.span_utils, sub_span, item.span, None);
200 Some(Data::ModData(ModData {
202 name: item.ident.to_string(),
204 span: sub_span.unwrap(),
205 scope: self.enclosing_scope(item.id),
207 items: m.items.iter().map(|i| i.id).collect(),
208 visibility: From::from(&item.vis),
209 docs: docs_for_attrs(&item.attrs),
210 sig: self.sig_base(item),
211 attributes: item.attrs.clone(),
214 ast::ItemKind::Enum(ref def, _) => {
215 let name = item.ident.to_string();
216 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
217 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
218 filter!(self.span_utils, sub_span, item.span, None);
219 let variants_str = def.variants.iter()
220 .map(|v| v.node.name.to_string())
223 let val = format!("{}::{{{}}}", name, variants_str);
224 Some(Data::EnumData(EnumData {
228 span: sub_span.unwrap(),
230 scope: self.enclosing_scope(item.id),
231 variants: def.variants.iter().map(|v| v.node.data.id()).collect(),
232 visibility: From::from(&item.vis),
233 docs: docs_for_attrs(&item.attrs),
234 sig: self.sig_base(item),
235 attributes: item.attrs.clone(),
238 ast::ItemKind::Impl(.., ref trait_ref, ref typ, _) => {
239 let mut type_data = None;
242 let parent = self.enclosing_scope(item.id);
245 // Common case impl for a struct or something basic.
246 ast::TyKind::Path(None, ref path) => {
247 if generated_code(path.span) {
250 sub_span = self.span_utils.sub_span_for_type_name(path.span);
251 type_data = self.lookup_ref_id(typ.id).map(|id| {
253 span: sub_span.unwrap(),
256 qualname: String::new() // FIXME: generate the real qualname
261 // Less useful case, impl for a compound type.
263 sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
267 let trait_data = trait_ref.as_ref()
268 .and_then(|tr| self.get_trait_ref_data(tr, parent));
270 filter!(self.span_utils, sub_span, typ.span, None);
271 Some(Data::ImplData(ImplData2 {
273 span: sub_span.unwrap(),
275 trait_ref: trait_data,
286 pub fn get_field_data(&self,
287 field: &ast::StructField,
289 -> Option<VariableData> {
290 if let Some(ident) = field.ident {
291 let name = ident.to_string();
292 let qualname = format!("::{}::{}", self.tcx.node_path_str(scope), ident);
293 let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
294 filter!(self.span_utils, sub_span, field.span, None);
295 let def_id = self.tcx.hir.local_def_id(field.id);
296 let typ = self.tcx.item_type(def_id).to_string();
298 let span = field.span;
299 let text = self.span_utils.snippet(field.span);
300 let ident_start = text.find(&name).unwrap();
301 let ident_end = ident_start + name.len();
302 let sig = Signature {
305 ident_start: ident_start,
306 ident_end: ident_end,
312 kind: VariableKind::Field,
315 span: sub_span.unwrap(),
317 parent: Some(make_def_id(scope, &self.tcx.hir)),
318 value: "".to_owned(),
320 visibility: From::from(&field.vis),
321 docs: docs_for_attrs(&field.attrs),
323 attributes: field.attrs.clone(),
330 // FIXME would be nice to take a MethodItem here, but the ast provides both
331 // trait and impl flavours, so the caller must do the disassembly.
332 pub fn get_method_data(&self, id: ast::NodeId,
333 name: ast::Name, span: Span) -> Option<FunctionData> {
334 // The qualname for a method is the trait name or name of the struct in an impl in
335 // which the method is declared in, followed by the method's name.
336 let (qualname, parent_scope, decl_id, vis, docs, attributes) =
337 match self.tcx.impl_of_method(self.tcx.hir.local_def_id(id)) {
338 Some(impl_id) => match self.tcx.hir.get_if_local(impl_id) {
339 Some(Node::NodeItem(item)) => {
341 hir::ItemImpl(.., ref ty, _) => {
342 let mut result = String::from("<");
343 result.push_str(&self.tcx.hir.node_to_pretty_string(ty.id));
345 let trait_id = self.tcx.trait_id_of_impl(impl_id);
346 let mut decl_id = None;
347 if let Some(def_id) = trait_id {
348 result.push_str(" as ");
349 result.push_str(&self.tcx.item_path_str(def_id));
350 self.tcx.associated_items(def_id)
351 .find(|item| item.name == name)
352 .map(|item| decl_id = Some(item.def_id));
354 result.push_str(">");
356 (result, trait_id, decl_id,
357 From::from(&item.vis),
358 docs_for_attrs(&item.attrs),
363 "Container {:?} for method {} not an impl?",
371 "Container {:?} for method {} is not a node item {:?}",
377 None => match self.tcx.trait_of_item(self.tcx.hir.local_def_id(id)) {
379 match self.tcx.hir.get_if_local(def_id) {
380 Some(Node::NodeItem(item)) => {
381 (format!("::{}", self.tcx.item_path_str(def_id)),
383 From::from(&item.vis),
384 docs_for_attrs(&item.attrs),
389 "Could not find container {:?} for \
390 method {}, got {:?}",
398 debug!("Could not find container for method {} at {:?}", id, span);
399 // This is not necessarily a bug, if there was a compilation error, the tables
400 // we need might not exist.
406 let qualname = format!("{}::{}", qualname, name);
408 let sub_span = self.span_utils.sub_span_after_keyword(span, keywords::Fn);
409 filter!(self.span_utils, sub_span, span, None);
411 let name = name.to_string();
412 let text = self.span_utils.signature_string_for_span(span);
413 let ident_start = text.find(&name).unwrap();
414 let ident_end = ident_start + name.len();
415 let sig = Signature {
418 ident_start: ident_start,
419 ident_end: ident_end,
428 declaration: decl_id,
429 span: sub_span.unwrap(),
430 scope: self.enclosing_scope(id),
431 // FIXME you get better data here by using the visitor.
432 value: String::new(),
434 parent: parent_scope,
437 attributes: attributes,
441 pub fn get_trait_ref_data(&self,
442 trait_ref: &ast::TraitRef,
444 -> Option<TypeRefData> {
445 self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
446 let span = trait_ref.path.span;
447 if generated_code(span) {
450 let sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
451 filter!(self.span_utils, sub_span, span, None);
453 span: sub_span.unwrap(),
455 ref_id: Some(def_id),
456 qualname: String::new() // FIXME: generate the real qualname
461 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
462 let hir_node = self.tcx.hir.expect_expr(expr.id);
463 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
464 if ty.is_none() || ty.unwrap().sty == ty::TyError {
468 ast::ExprKind::Field(ref sub_ex, ident) => {
469 let hir_node = match self.tcx.hir.find(sub_ex.id) {
470 Some(Node::NodeExpr(expr)) => expr,
472 debug!("Missing or weird node for sub-expression {} in {:?}",
477 match self.tables.expr_ty_adjusted(&hir_node).sty {
478 ty::TyAdt(def, _) if !def.is_enum() => {
479 let f = def.struct_variant().field_named(ident.node.name);
480 let sub_span = self.span_utils.span_for_last_ident(expr.span);
481 filter!(self.span_utils, sub_span, expr.span, None);
482 return Some(Data::VariableRefData(VariableRefData {
483 name: ident.node.to_string(),
484 span: sub_span.unwrap(),
485 scope: self.enclosing_scope(expr.id),
490 debug!("Expected struct or union type, found {:?}", ty);
495 ast::ExprKind::Struct(ref path, ..) => {
496 match self.tables.expr_ty_adjusted(&hir_node).sty {
497 ty::TyAdt(def, _) if !def.is_enum() => {
498 let sub_span = self.span_utils.span_for_last_ident(path.span);
499 filter!(self.span_utils, sub_span, path.span, None);
500 Some(Data::TypeRefData(TypeRefData {
501 span: sub_span.unwrap(),
502 scope: self.enclosing_scope(expr.id),
503 ref_id: Some(def.did),
504 qualname: String::new() // FIXME: generate the real qualname
508 // FIXME ty could legitimately be an enum, but then we will fail
509 // later if we try to look up the fields.
510 debug!("expected struct or union, found {:?}", ty);
515 ast::ExprKind::MethodCall(..) => {
516 let method_call = ty::MethodCall::expr(expr.id);
517 let method_id = self.tables.method_map[&method_call].def_id;
518 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
519 ty::ImplContainer(_) => (Some(method_id), None),
520 ty::TraitContainer(_) => (None, Some(method_id)),
522 let sub_span = self.span_utils.sub_span_for_meth_name(expr.span);
523 filter!(self.span_utils, sub_span, expr.span, None);
524 let parent = self.enclosing_scope(expr.id);
525 Some(Data::MethodCallData(MethodCallData {
526 span: sub_span.unwrap(),
532 ast::ExprKind::Path(_, ref path) => {
533 self.get_path_data(expr.id, path)
542 pub fn get_path_def(&self, id: NodeId) -> Def {
543 match self.tcx.hir.get(id) {
544 Node::NodeTraitRef(tr) => tr.path.def,
546 Node::NodeItem(&hir::Item { node: hir::ItemUse(ref path, _), .. }) |
547 Node::NodeVisibility(&hir::Visibility::Restricted { ref path, .. }) => path.def,
549 Node::NodeExpr(&hir::Expr { node: hir::ExprPath(ref qpath), .. }) |
550 Node::NodeExpr(&hir::Expr { node: hir::ExprStruct(ref qpath, ..), .. }) |
551 Node::NodePat(&hir::Pat { node: hir::PatKind::Path(ref qpath), .. }) |
552 Node::NodePat(&hir::Pat { node: hir::PatKind::Struct(ref qpath, ..), .. }) |
553 Node::NodePat(&hir::Pat { node: hir::PatKind::TupleStruct(ref qpath, ..), .. }) => {
554 self.tables.qpath_def(qpath, id)
557 Node::NodeLocal(&hir::Pat { node: hir::PatKind::Binding(_, def_id, ..), .. }) => {
561 Node::NodeTy(&hir::Ty { node: hir::TyPath(ref qpath), .. }) => {
563 hir::QPath::Resolved(_, ref path) => path.def,
564 hir::QPath::TypeRelative(..) => {
565 if let Some(ty) = self.tcx.ast_ty_to_ty_cache.borrow().get(&id) {
566 if let ty::TyProjection(proj) = ty.sty {
567 for item in self.tcx.associated_items(proj.trait_ref.def_id) {
568 if item.kind == ty::AssociatedKind::Type {
569 if item.name == proj.item_name {
570 return Def::AssociatedTy(item.def_id);
585 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Data> {
586 let def = self.get_path_def(id);
587 let sub_span = self.span_utils.span_for_last_ident(path.span);
588 filter!(self.span_utils, sub_span, path.span, None);
594 Def::AssociatedConst(..) |
595 Def::StructCtor(..) |
596 Def::VariantCtor(..) => {
597 Some(Data::VariableRefData(VariableRefData {
598 name: self.span_utils.snippet(sub_span.unwrap()),
599 span: sub_span.unwrap(),
600 scope: self.enclosing_scope(id),
601 ref_id: def.def_id(),
604 Def::Struct(def_id) |
605 Def::Variant(def_id, ..) |
608 Def::TyAlias(def_id) |
609 Def::AssociatedTy(def_id) |
611 Def::TyParam(def_id) => {
612 Some(Data::TypeRefData(TypeRefData {
613 span: sub_span.unwrap(),
614 ref_id: Some(def_id),
615 scope: self.enclosing_scope(id),
616 qualname: String::new() // FIXME: generate the real qualname
619 Def::Method(decl_id) => {
620 let sub_span = self.span_utils.sub_span_for_meth_name(path.span);
621 filter!(self.span_utils, sub_span, path.span, None);
622 let def_id = if decl_id.is_local() {
623 let ti = self.tcx.associated_item(decl_id);
624 self.tcx.associated_items(ti.container.id())
625 .find(|item| item.name == ti.name && item.defaultness.has_value())
626 .map(|item| item.def_id)
630 Some(Data::MethodCallData(MethodCallData {
631 span: sub_span.unwrap(),
632 scope: self.enclosing_scope(id),
634 decl_id: Some(decl_id),
638 Some(Data::FunctionCallData(FunctionCallData {
640 span: sub_span.unwrap(),
641 scope: self.enclosing_scope(id),
644 Def::Mod(def_id) => {
645 Some(Data::ModRefData(ModRefData {
646 ref_id: Some(def_id),
647 span: sub_span.unwrap(),
648 scope: self.enclosing_scope(id),
649 qualname: String::new() // FIXME: generate the real qualname
660 pub fn get_field_ref_data(&self,
661 field_ref: &ast::Field,
662 variant: &ty::VariantDef,
664 -> Option<VariableRefData> {
665 let f = variant.field_named(field_ref.ident.node.name);
666 // We don't really need a sub-span here, but no harm done
667 let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
668 filter!(self.span_utils, sub_span, field_ref.ident.span, None);
669 Some(VariableRefData {
670 name: field_ref.ident.node.to_string(),
671 span: sub_span.unwrap(),
677 /// Attempt to return MacroUseData for any AST node.
679 /// For a given piece of AST defined by the supplied Span and NodeId,
680 /// returns None if the node is not macro-generated or the span is malformed,
681 /// else uses the expansion callsite and callee to return some MacroUseData.
682 pub fn get_macro_use_data(&self, span: Span, id: NodeId) -> Option<MacroUseData> {
683 if !generated_code(span) {
686 // Note we take care to use the source callsite/callee, to handle
687 // nested expansions and ensure we only generate data for source-visible
689 let callsite = self.tcx.sess.codemap().source_callsite(span);
690 let callee = self.tcx.sess.codemap().source_callee(span);
691 let callee = option_try!(callee);
692 let callee_span = option_try!(callee.span);
694 // Ignore attribute macros, their spans are usually mangled
695 if let MacroAttribute(_) = callee.format {
699 // If the callee is an imported macro from an external crate, need to get
700 // the source span and name from the session, as their spans are localized
701 // when read in, and no longer correspond to the source.
702 if let Some(mac) = self.tcx.sess.imported_macro_spans.borrow().get(&callee_span) {
703 let &(ref mac_name, mac_span) = mac;
704 return Some(MacroUseData {
706 name: mac_name.clone(),
707 callee_span: mac_span,
708 scope: self.enclosing_scope(id),
710 qualname: String::new()// FIXME: generate the real qualname
716 name: callee.name().to_string(),
717 callee_span: callee_span,
718 scope: self.enclosing_scope(id),
720 qualname: String::new() // FIXME: generate the real qualname
724 pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
729 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
730 match self.get_path_def(ref_id) {
731 Def::PrimTy(_) | Def::SelfTy(..) | Def::Err => None,
732 def => Some(def.def_id()),
736 fn sig_base(&self, item: &ast::Item) -> Signature {
737 let text = self.span_utils.signature_string_for_span(item.span);
738 let name = item.ident.to_string();
739 let ident_start = text.find(&name).expect("Name not in signature?");
740 let ident_end = ident_start + name.len();
742 span: mk_sp(item.span.lo, item.span.lo + BytePos(text.len() as u32)),
744 ident_start: ident_start,
745 ident_end: ident_end,
752 pub fn enclosing_scope(&self, id: NodeId) -> NodeId {
753 self.tcx.hir.get_enclosing_scope(id).unwrap_or(CRATE_NODE_ID)
757 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
758 let mut sig = "fn ".to_owned();
759 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
761 sig.push_str(&generics.lifetimes.iter()
762 .map(|l| l.lifetime.name.to_string())
765 if !generics.lifetimes.is_empty() {
768 sig.push_str(&generics.ty_params.iter()
769 .map(|l| l.ident.to_string())
775 sig.push_str(&decl.inputs.iter().map(arg_to_string).collect::<Vec<_>>().join(", "));
778 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
779 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
785 // An AST visitor for collecting paths from patterns.
786 struct PathCollector {
787 // The Row field identifies the kind of pattern.
788 collected_paths: Vec<(NodeId, ast::Path, ast::Mutability, recorder::Row)>,
792 fn new() -> PathCollector {
793 PathCollector { collected_paths: vec![] }
797 impl<'a> Visitor<'a> for PathCollector {
798 fn visit_pat(&mut self, p: &ast::Pat) {
800 PatKind::Struct(ref path, ..) => {
801 self.collected_paths.push((p.id, path.clone(),
802 ast::Mutability::Mutable, recorder::TypeRef));
804 PatKind::TupleStruct(ref path, ..) |
805 PatKind::Path(_, ref path) => {
806 self.collected_paths.push((p.id, path.clone(),
807 ast::Mutability::Mutable, recorder::VarRef));
809 PatKind::Ident(bm, ref path1, _) => {
810 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
814 let immut = match bm {
815 // Even if the ref is mut, you can't change the ref, only
816 // the data pointed at, so showing the initialising expression
817 // is still worthwhile.
818 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
819 ast::BindingMode::ByValue(mt) => mt,
821 // collect path for either visit_local or visit_arm
822 let path = ast::Path::from_ident(path1.span, path1.node);
823 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
827 visit::walk_pat(self, p);
831 fn docs_for_attrs(attrs: &[Attribute]) -> String {
832 let mut result = String::new();
835 if attr.check_name("doc") {
836 if let Some(val) = attr.value_str() {
837 if attr.is_sugared_doc {
838 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
840 result.push_str(&val.as_str());
850 #[derive(Clone, Copy, Debug, RustcEncodable)]
858 fn extension(&self) -> &'static str {
860 Format::Csv => ".csv",
861 Format::Json | Format::JsonApi => ".json",
866 pub fn process_crate<'l, 'tcx>(tcx: TyCtxt<'l, 'tcx, 'tcx>,
868 analysis: &'l ty::CrateAnalysis,
872 let _ignore = tcx.dep_graph.in_ignore();
874 assert!(analysis.glob_map.is_some());
876 info!("Dumping crate {}", cratename);
878 // find a path to dump our data to
879 let mut root_path = match env::var_os("RUST_SAVE_ANALYSIS_FOLDER") {
880 Some(val) => PathBuf::from(val),
882 Some(val) => val.join("save-analysis"),
883 None => PathBuf::from("save-analysis-temp"),
887 if let Err(e) = std::fs::create_dir_all(&root_path) {
888 tcx.sess.err(&format!("Could not create directory {}: {}",
894 let disp = root_path.display();
895 info!("Writing output to {}", disp);
898 // Create output file.
899 let executable = tcx.sess.crate_types.borrow().iter().any(|ct| *ct == CrateTypeExecutable);
900 let mut out_name = if executable {
905 out_name.push_str(&cratename);
906 out_name.push_str(&tcx.sess.opts.cg.extra_filename);
907 out_name.push_str(format.extension());
908 root_path.push(&out_name);
909 let mut output_file = File::create(&root_path).unwrap_or_else(|e| {
910 let disp = root_path.display();
911 tcx.sess.fatal(&format!("Could not open {}: {}", disp, e));
914 let output = &mut output_file;
916 let save_ctxt = SaveContext {
918 tables: &ty::TypeckTables::empty(),
920 span_utils: SpanUtils::new(&tcx.sess),
924 ($new_dumper: expr) => {{
925 let mut dumper = $new_dumper;
926 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
928 visitor.dump_crate_info(cratename, krate);
929 visit::walk_crate(&mut visitor, krate);
934 Format::Csv => dump!(CsvDumper::new(output)),
935 Format::Json => dump!(JsonDumper::new(output)),
936 Format::JsonApi => dump!(JsonApiDumper::new(output)),
940 // Utility functions for the module.
942 // Helper function to escape quotes in a string
943 fn escape(s: String) -> String {
944 s.replace("\"", "\"\"")
947 // Helper function to determine if a span came from a
948 // macro expansion or syntax extension.
949 pub fn generated_code(span: Span) -> bool {
950 span.expn_id != NO_EXPANSION || span == DUMMY_SP