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::{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<'tcx>,
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),
141 ast::ItemKind::Static(ref typ, mt, ref expr) => {
142 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
144 // If the variable is immutable, save the initialising expression.
145 let (value, keyword) = match mt {
146 ast::Mutability::Mutable => (String::from("<mutable>"), keywords::Mut),
147 ast::Mutability::Immutable => {
148 (self.span_utils.snippet(expr.span), keywords::Static)
152 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
153 filter!(self.span_utils, sub_span, item.span, None);
154 Some(Data::VariableData(VariableData {
156 kind: VariableKind::Static,
157 name: item.ident.to_string(),
159 span: sub_span.unwrap(),
160 scope: self.enclosing_scope(item.id),
163 type_value: ty_to_string(&typ),
164 visibility: From::from(&item.vis),
165 docs: docs_for_attrs(&item.attrs),
166 sig: Some(self.sig_base(item)),
169 ast::ItemKind::Const(ref typ, ref expr) => {
170 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
171 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
172 filter!(self.span_utils, sub_span, item.span, None);
173 Some(Data::VariableData(VariableData {
175 kind: VariableKind::Const,
176 name: item.ident.to_string(),
178 span: sub_span.unwrap(),
179 scope: self.enclosing_scope(item.id),
181 value: self.span_utils.snippet(expr.span),
182 type_value: ty_to_string(&typ),
183 visibility: From::from(&item.vis),
184 docs: docs_for_attrs(&item.attrs),
185 sig: Some(self.sig_base(item)),
188 ast::ItemKind::Mod(ref m) => {
189 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
191 let cm = self.tcx.sess.codemap();
192 let filename = cm.span_to_filename(m.inner);
194 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
195 filter!(self.span_utils, sub_span, item.span, None);
197 Some(Data::ModData(ModData {
199 name: item.ident.to_string(),
201 span: sub_span.unwrap(),
202 scope: self.enclosing_scope(item.id),
204 items: m.items.iter().map(|i| i.id).collect(),
205 visibility: From::from(&item.vis),
206 docs: docs_for_attrs(&item.attrs),
207 sig: self.sig_base(item),
210 ast::ItemKind::Enum(ref def, _) => {
211 let name = item.ident.to_string();
212 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
213 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
214 filter!(self.span_utils, sub_span, item.span, None);
215 let variants_str = def.variants.iter()
216 .map(|v| v.node.name.to_string())
219 let val = format!("{}::{{{}}}", name, variants_str);
220 Some(Data::EnumData(EnumData {
224 span: sub_span.unwrap(),
226 scope: self.enclosing_scope(item.id),
227 variants: def.variants.iter().map(|v| v.node.data.id()).collect(),
228 visibility: From::from(&item.vis),
229 docs: docs_for_attrs(&item.attrs),
230 sig: self.sig_base(item),
233 ast::ItemKind::Impl(.., ref trait_ref, ref typ, _) => {
234 let mut type_data = None;
237 let parent = self.enclosing_scope(item.id);
240 // Common case impl for a struct or something basic.
241 ast::TyKind::Path(None, ref path) => {
242 if generated_code(path.span) {
245 sub_span = self.span_utils.sub_span_for_type_name(path.span);
246 type_data = self.lookup_ref_id(typ.id).map(|id| {
248 span: sub_span.unwrap(),
251 qualname: String::new() // FIXME: generate the real qualname
256 // Less useful case, impl for a compound type.
258 sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
262 let trait_data = trait_ref.as_ref()
263 .and_then(|tr| self.get_trait_ref_data(tr, parent));
265 filter!(self.span_utils, sub_span, typ.span, None);
266 Some(Data::ImplData(ImplData2 {
268 span: sub_span.unwrap(),
270 trait_ref: trait_data,
281 pub fn get_field_data(&self,
282 field: &ast::StructField,
284 -> Option<VariableData> {
285 if let Some(ident) = field.ident {
286 let name = ident.to_string();
287 let qualname = format!("::{}::{}", self.tcx.node_path_str(scope), ident);
288 let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
289 filter!(self.span_utils, sub_span, field.span, None);
290 let def_id = self.tcx.hir.local_def_id(field.id);
291 let typ = self.tcx.item_type(def_id).to_string();
293 let span = field.span;
294 let text = self.span_utils.snippet(field.span);
295 let ident_start = text.find(&name).unwrap();
296 let ident_end = ident_start + name.len();
297 let sig = Signature {
300 ident_start: ident_start,
301 ident_end: ident_end,
307 kind: VariableKind::Field,
310 span: sub_span.unwrap(),
312 parent: Some(make_def_id(scope, &self.tcx.hir)),
313 value: "".to_owned(),
315 visibility: From::from(&field.vis),
316 docs: docs_for_attrs(&field.attrs),
324 // FIXME would be nice to take a MethodItem here, but the ast provides both
325 // trait and impl flavours, so the caller must do the disassembly.
326 pub fn get_method_data(&self, id: ast::NodeId,
327 name: ast::Name, span: Span) -> Option<FunctionData> {
328 // The qualname for a method is the trait name or name of the struct in an impl in
329 // which the method is declared in, followed by the method's name.
330 let (qualname, parent_scope, decl_id, vis, docs) =
331 match self.tcx.impl_of_method(self.tcx.hir.local_def_id(id)) {
332 Some(impl_id) => match self.tcx.hir.get_if_local(impl_id) {
333 Some(Node::NodeItem(item)) => {
335 hir::ItemImpl(.., ref ty, _) => {
336 let mut result = String::from("<");
337 result.push_str(&self.tcx.hir.node_to_pretty_string(ty.id));
339 let trait_id = self.tcx.trait_id_of_impl(impl_id);
340 let mut decl_id = None;
341 if let Some(def_id) = trait_id {
342 result.push_str(" as ");
343 result.push_str(&self.tcx.item_path_str(def_id));
344 self.tcx.associated_items(def_id)
345 .find(|item| item.name == name)
346 .map(|item| decl_id = Some(item.def_id));
348 result.push_str(">");
350 (result, trait_id, decl_id,
351 From::from(&item.vis),
352 docs_for_attrs(&item.attrs))
356 "Container {:?} for method {} not an impl?",
364 "Container {:?} for method {} is not a node item {:?}",
370 None => match self.tcx.trait_of_item(self.tcx.hir.local_def_id(id)) {
372 match self.tcx.hir.get_if_local(def_id) {
373 Some(Node::NodeItem(item)) => {
374 (format!("::{}", self.tcx.item_path_str(def_id)),
376 From::from(&item.vis),
377 docs_for_attrs(&item.attrs))
381 "Could not find container {:?} for \
382 method {}, got {:?}",
390 span_bug!(span, "Could not find container for method {}", id);
395 let qualname = format!("{}::{}", qualname, name);
397 let sub_span = self.span_utils.sub_span_after_keyword(span, keywords::Fn);
398 filter!(self.span_utils, sub_span, span, None);
400 let name = name.to_string();
401 let text = self.span_utils.signature_string_for_span(span);
402 let ident_start = text.find(&name).unwrap();
403 let ident_end = ident_start + name.len();
404 let sig = Signature {
407 ident_start: ident_start,
408 ident_end: ident_end,
417 declaration: decl_id,
418 span: sub_span.unwrap(),
419 scope: self.enclosing_scope(id),
420 // FIXME you get better data here by using the visitor.
421 value: String::new(),
423 parent: parent_scope,
429 pub fn get_trait_ref_data(&self,
430 trait_ref: &ast::TraitRef,
432 -> Option<TypeRefData> {
433 self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
434 let span = trait_ref.path.span;
435 if generated_code(span) {
438 let sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
439 filter!(self.span_utils, sub_span, span, None);
441 span: sub_span.unwrap(),
443 ref_id: Some(def_id),
444 qualname: String::new() // FIXME: generate the real qualname
449 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
450 let hir_node = self.tcx.hir.expect_expr(expr.id);
451 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
452 if ty.is_none() || ty.unwrap().sty == ty::TyError {
456 ast::ExprKind::Field(ref sub_ex, ident) => {
457 let hir_node = match self.tcx.hir.find(sub_ex.id) {
458 Some(Node::NodeExpr(expr)) => expr,
460 debug!("Missing or weird node for sub-expression {} in {:?}",
465 match self.tables.expr_ty_adjusted(&hir_node).sty {
466 ty::TyAdt(def, _) if !def.is_enum() => {
467 let f = def.struct_variant().field_named(ident.node.name);
468 let sub_span = self.span_utils.span_for_last_ident(expr.span);
469 filter!(self.span_utils, sub_span, expr.span, None);
470 return Some(Data::VariableRefData(VariableRefData {
471 name: ident.node.to_string(),
472 span: sub_span.unwrap(),
473 scope: self.enclosing_scope(expr.id),
478 debug!("Expected struct or union type, found {:?}", ty);
483 ast::ExprKind::Struct(ref path, ..) => {
484 match self.tables.expr_ty_adjusted(&hir_node).sty {
485 ty::TyAdt(def, _) if !def.is_enum() => {
486 let sub_span = self.span_utils.span_for_last_ident(path.span);
487 filter!(self.span_utils, sub_span, path.span, None);
488 Some(Data::TypeRefData(TypeRefData {
489 span: sub_span.unwrap(),
490 scope: self.enclosing_scope(expr.id),
491 ref_id: Some(def.did),
492 qualname: String::new() // FIXME: generate the real qualname
496 // FIXME ty could legitimately be an enum, but then we will fail
497 // later if we try to look up the fields.
498 debug!("expected struct or union, found {:?}", ty);
503 ast::ExprKind::MethodCall(..) => {
504 let method_call = ty::MethodCall::expr(expr.id);
505 let method_id = self.tables.method_map[&method_call].def_id;
506 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
507 ty::ImplContainer(_) => (Some(method_id), None),
508 ty::TraitContainer(_) => (None, Some(method_id)),
510 let sub_span = self.span_utils.sub_span_for_meth_name(expr.span);
511 filter!(self.span_utils, sub_span, expr.span, None);
512 let parent = self.enclosing_scope(expr.id);
513 Some(Data::MethodCallData(MethodCallData {
514 span: sub_span.unwrap(),
520 ast::ExprKind::Path(_, ref path) => {
521 self.get_path_data(expr.id, path)
530 pub fn get_path_def(&self, id: NodeId) -> Def {
531 match self.tcx.hir.get(id) {
532 Node::NodeTraitRef(tr) => tr.path.def,
534 Node::NodeItem(&hir::Item { node: hir::ItemUse(ref path, _), .. }) |
535 Node::NodeVisibility(&hir::Visibility::Restricted { ref path, .. }) => path.def,
537 Node::NodeExpr(&hir::Expr { node: hir::ExprPath(ref qpath), .. }) |
538 Node::NodeExpr(&hir::Expr { node: hir::ExprStruct(ref qpath, ..), .. }) |
539 Node::NodePat(&hir::Pat { node: hir::PatKind::Path(ref qpath), .. }) |
540 Node::NodePat(&hir::Pat { node: hir::PatKind::Struct(ref qpath, ..), .. }) |
541 Node::NodePat(&hir::Pat { node: hir::PatKind::TupleStruct(ref qpath, ..), .. }) => {
542 self.tables.qpath_def(qpath, id)
545 Node::NodeLocal(&hir::Pat { node: hir::PatKind::Binding(_, def_id, ..), .. }) => {
549 Node::NodeTy(&hir::Ty { node: hir::TyPath(ref qpath), .. }) => {
551 hir::QPath::Resolved(_, ref path) => path.def,
552 hir::QPath::TypeRelative(..) => {
553 if let Some(ty) = self.analysis.hir_ty_to_ty.get(&id) {
554 if let ty::TyProjection(proj) = ty.sty {
555 for item in self.tcx.associated_items(proj.trait_ref.def_id) {
556 if item.kind == ty::AssociatedKind::Type {
557 if item.name == proj.item_name {
558 return Def::AssociatedTy(item.def_id);
573 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Data> {
574 let def = self.get_path_def(id);
575 let sub_span = self.span_utils.span_for_last_ident(path.span);
576 filter!(self.span_utils, sub_span, path.span, None);
582 Def::AssociatedConst(..) |
583 Def::StructCtor(..) |
584 Def::VariantCtor(..) => {
585 Some(Data::VariableRefData(VariableRefData {
586 name: self.span_utils.snippet(sub_span.unwrap()),
587 span: sub_span.unwrap(),
588 scope: self.enclosing_scope(id),
589 ref_id: def.def_id(),
592 Def::Struct(def_id) |
593 Def::Variant(def_id, ..) |
596 Def::TyAlias(def_id) |
597 Def::AssociatedTy(def_id) |
599 Def::TyParam(def_id) => {
600 Some(Data::TypeRefData(TypeRefData {
601 span: sub_span.unwrap(),
602 ref_id: Some(def_id),
603 scope: self.enclosing_scope(id),
604 qualname: String::new() // FIXME: generate the real qualname
607 Def::Method(decl_id) => {
608 let sub_span = self.span_utils.sub_span_for_meth_name(path.span);
609 filter!(self.span_utils, sub_span, path.span, None);
610 let def_id = if decl_id.is_local() {
611 let ti = self.tcx.associated_item(decl_id);
612 self.tcx.associated_items(ti.container.id())
613 .find(|item| item.name == ti.name && item.defaultness.has_value())
614 .map(|item| item.def_id)
618 Some(Data::MethodCallData(MethodCallData {
619 span: sub_span.unwrap(),
620 scope: self.enclosing_scope(id),
622 decl_id: Some(decl_id),
626 Some(Data::FunctionCallData(FunctionCallData {
628 span: sub_span.unwrap(),
629 scope: self.enclosing_scope(id),
632 Def::Mod(def_id) => {
633 Some(Data::ModRefData(ModRefData {
634 ref_id: Some(def_id),
635 span: sub_span.unwrap(),
636 scope: self.enclosing_scope(id),
637 qualname: String::new() // FIXME: generate the real qualname
648 pub fn get_field_ref_data(&self,
649 field_ref: &ast::Field,
650 variant: &ty::VariantDef,
652 -> Option<VariableRefData> {
653 let f = variant.field_named(field_ref.ident.node.name);
654 // We don't really need a sub-span here, but no harm done
655 let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
656 filter!(self.span_utils, sub_span, field_ref.ident.span, None);
657 Some(VariableRefData {
658 name: field_ref.ident.node.to_string(),
659 span: sub_span.unwrap(),
665 /// Attempt to return MacroUseData for any AST node.
667 /// For a given piece of AST defined by the supplied Span and NodeId,
668 /// returns None if the node is not macro-generated or the span is malformed,
669 /// else uses the expansion callsite and callee to return some MacroUseData.
670 pub fn get_macro_use_data(&self, span: Span, id: NodeId) -> Option<MacroUseData> {
671 if !generated_code(span) {
674 // Note we take care to use the source callsite/callee, to handle
675 // nested expansions and ensure we only generate data for source-visible
677 let callsite = self.tcx.sess.codemap().source_callsite(span);
678 let callee = self.tcx.sess.codemap().source_callee(span);
679 let callee = option_try!(callee);
680 let callee_span = option_try!(callee.span);
682 // Ignore attribute macros, their spans are usually mangled
683 if let MacroAttribute(_) = callee.format {
687 // If the callee is an imported macro from an external crate, need to get
688 // the source span and name from the session, as their spans are localized
689 // when read in, and no longer correspond to the source.
690 if let Some(mac) = self.tcx.sess.imported_macro_spans.borrow().get(&callee_span) {
691 let &(ref mac_name, mac_span) = mac;
692 return Some(MacroUseData {
694 name: mac_name.clone(),
695 callee_span: mac_span,
696 scope: self.enclosing_scope(id),
698 qualname: String::new()// FIXME: generate the real qualname
704 name: callee.name().to_string(),
705 callee_span: callee_span,
706 scope: self.enclosing_scope(id),
708 qualname: String::new() // FIXME: generate the real qualname
712 pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
717 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
718 match self.get_path_def(ref_id) {
719 Def::PrimTy(_) | Def::SelfTy(..) | Def::Err => None,
720 def => Some(def.def_id()),
724 fn sig_base(&self, item: &ast::Item) -> Signature {
725 let text = self.span_utils.signature_string_for_span(item.span);
726 let name = item.ident.to_string();
727 let ident_start = text.find(&name).expect("Name not in signature?");
728 let ident_end = ident_start + name.len();
730 span: mk_sp(item.span.lo, item.span.lo + BytePos(text.len() as u32)),
732 ident_start: ident_start,
733 ident_end: ident_end,
740 pub fn enclosing_scope(&self, id: NodeId) -> NodeId {
741 self.tcx.hir.get_enclosing_scope(id).unwrap_or(CRATE_NODE_ID)
745 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
746 let mut sig = "fn ".to_owned();
747 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
749 sig.push_str(&generics.lifetimes.iter()
750 .map(|l| l.lifetime.name.to_string())
753 if !generics.lifetimes.is_empty() {
756 sig.push_str(&generics.ty_params.iter()
757 .map(|l| l.ident.to_string())
763 sig.push_str(&decl.inputs.iter().map(arg_to_string).collect::<Vec<_>>().join(", "));
766 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
767 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
773 // An AST visitor for collecting paths from patterns.
774 struct PathCollector {
775 // The Row field identifies the kind of pattern.
776 collected_paths: Vec<(NodeId, ast::Path, ast::Mutability, recorder::Row)>,
780 fn new() -> PathCollector {
781 PathCollector { collected_paths: vec![] }
785 impl<'a> Visitor<'a> for PathCollector {
786 fn visit_pat(&mut self, p: &ast::Pat) {
788 PatKind::Struct(ref path, ..) => {
789 self.collected_paths.push((p.id, path.clone(),
790 ast::Mutability::Mutable, recorder::TypeRef));
792 PatKind::TupleStruct(ref path, ..) |
793 PatKind::Path(_, ref path) => {
794 self.collected_paths.push((p.id, path.clone(),
795 ast::Mutability::Mutable, recorder::VarRef));
797 PatKind::Ident(bm, ref path1, _) => {
798 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
802 let immut = match bm {
803 // Even if the ref is mut, you can't change the ref, only
804 // the data pointed at, so showing the initialising expression
805 // is still worthwhile.
806 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
807 ast::BindingMode::ByValue(mt) => mt,
809 // collect path for either visit_local or visit_arm
810 let path = ast::Path::from_ident(path1.span, path1.node);
811 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
815 visit::walk_pat(self, p);
819 fn docs_for_attrs(attrs: &[Attribute]) -> String {
820 let doc = Symbol::intern("doc");
821 let mut result = String::new();
824 if attr.name() == doc {
825 if let Some(val) = attr.value_str() {
826 if attr.is_sugared_doc {
827 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
829 result.push_str(&val.as_str());
839 #[derive(Clone, Copy, Debug, RustcEncodable)]
847 fn extension(&self) -> &'static str {
849 Format::Csv => ".csv",
850 Format::Json | Format::JsonApi => ".json",
855 pub fn process_crate<'l, 'tcx>(tcx: TyCtxt<'l, 'tcx, 'tcx>,
857 analysis: &'l ty::CrateAnalysis<'tcx>,
861 let _ignore = tcx.dep_graph.in_ignore();
863 assert!(analysis.glob_map.is_some());
865 info!("Dumping crate {}", cratename);
867 // find a path to dump our data to
868 let mut root_path = match env::var_os("RUST_SAVE_ANALYSIS_FOLDER") {
869 Some(val) => PathBuf::from(val),
871 Some(val) => val.join("save-analysis"),
872 None => PathBuf::from("save-analysis-temp"),
876 if let Err(e) = rustc::util::fs::create_dir_racy(&root_path) {
877 tcx.sess.err(&format!("Could not create directory {}: {}",
883 let disp = root_path.display();
884 info!("Writing output to {}", disp);
887 // Create output file.
888 let executable = tcx.sess.crate_types.borrow().iter().any(|ct| *ct == CrateTypeExecutable);
889 let mut out_name = if executable {
894 out_name.push_str(&cratename);
895 out_name.push_str(&tcx.sess.opts.cg.extra_filename);
896 out_name.push_str(format.extension());
897 root_path.push(&out_name);
898 let mut output_file = File::create(&root_path).unwrap_or_else(|e| {
899 let disp = root_path.display();
900 tcx.sess.fatal(&format!("Could not open {}: {}", disp, e));
903 let output = &mut output_file;
905 let save_ctxt = SaveContext {
907 tables: &ty::TypeckTables::empty(),
909 span_utils: SpanUtils::new(&tcx.sess),
913 ($new_dumper: expr) => {{
914 let mut dumper = $new_dumper;
915 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
917 visitor.dump_crate_info(cratename, krate);
918 visit::walk_crate(&mut visitor, krate);
923 Format::Csv => dump!(CsvDumper::new(output)),
924 Format::Json => dump!(JsonDumper::new(output)),
925 Format::JsonApi => dump!(JsonApiDumper::new(output)),
929 // Utility functions for the module.
931 // Helper function to escape quotes in a string
932 fn escape(s: String) -> String {
933 s.replace("\"", "\"\"")
936 // Helper function to determine if a span came from a
937 // macro expansion or syntax extension.
938 pub fn generated_code(span: Span) -> bool {
939 span.expn_id != NO_EXPANSION || span == DUMMY_SP