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/")]
18 #![cfg_attr(not(stage0), deny(warnings))]
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 analysis: &'l ty::CrateAnalysis<'tcx>,
88 span_utils: SpanUtils<'tcx>,
91 macro_rules! option_try(
92 ($e:expr) => (match $e { Some(e) => e, None => return None })
95 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
96 pub fn new(tcx: TyCtxt<'l, 'tcx, 'tcx>,
97 analysis: &'l ty::CrateAnalysis<'tcx>)
98 -> SaveContext<'l, 'tcx> {
99 let span_utils = SpanUtils::new(&tcx.sess);
100 SaveContext::from_span_utils(tcx, analysis, span_utils)
103 pub fn from_span_utils(tcx: TyCtxt<'l, 'tcx, 'tcx>,
104 analysis: &'l ty::CrateAnalysis<'tcx>,
105 span_utils: SpanUtils<'tcx>)
106 -> SaveContext<'l, 'tcx> {
110 span_utils: span_utils,
114 // List external crates used by the current crate.
115 pub fn get_external_crates(&self) -> Vec<CrateData> {
116 let mut result = Vec::new();
118 for n in self.tcx.sess.cstore.crates() {
119 let span = match self.tcx.sess.cstore.extern_crate(n) {
120 Some(ref c) => c.span,
122 debug!("Skipping crate {}, no data", n);
126 result.push(CrateData {
127 name: self.tcx.sess.cstore.crate_name(n).to_string(),
136 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
138 ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
139 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
140 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
141 filter!(self.span_utils, sub_span, item.span, None);
144 Some(Data::FunctionData(FunctionData {
146 name: item.ident.to_string(),
149 span: sub_span.unwrap(),
150 scope: self.enclosing_scope(item.id),
151 value: make_signature(decl, generics),
152 visibility: From::from(&item.vis),
154 docs: docs_for_attrs(&item.attrs),
155 sig: self.sig_base(item),
158 ast::ItemKind::Static(ref typ, mt, ref expr) => {
159 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
161 // If the variable is immutable, save the initialising expression.
162 let (value, keyword) = match mt {
163 ast::Mutability::Mutable => (String::from("<mutable>"), keywords::Mut),
164 ast::Mutability::Immutable => {
165 (self.span_utils.snippet(expr.span), keywords::Static)
169 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
170 filter!(self.span_utils, sub_span, item.span, None);
171 Some(Data::VariableData(VariableData {
173 kind: VariableKind::Static,
174 name: item.ident.to_string(),
176 span: sub_span.unwrap(),
177 scope: self.enclosing_scope(item.id),
180 type_value: ty_to_string(&typ),
181 visibility: From::from(&item.vis),
182 docs: docs_for_attrs(&item.attrs),
183 sig: Some(self.sig_base(item)),
186 ast::ItemKind::Const(ref typ, ref expr) => {
187 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
188 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
189 filter!(self.span_utils, sub_span, item.span, None);
190 Some(Data::VariableData(VariableData {
192 kind: VariableKind::Const,
193 name: item.ident.to_string(),
195 span: sub_span.unwrap(),
196 scope: self.enclosing_scope(item.id),
198 value: self.span_utils.snippet(expr.span),
199 type_value: ty_to_string(&typ),
200 visibility: From::from(&item.vis),
201 docs: docs_for_attrs(&item.attrs),
202 sig: Some(self.sig_base(item)),
205 ast::ItemKind::Mod(ref m) => {
206 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
208 let cm = self.tcx.sess.codemap();
209 let filename = cm.span_to_filename(m.inner);
211 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
212 filter!(self.span_utils, sub_span, item.span, None);
214 Some(Data::ModData(ModData {
216 name: item.ident.to_string(),
218 span: sub_span.unwrap(),
219 scope: self.enclosing_scope(item.id),
221 items: m.items.iter().map(|i| i.id).collect(),
222 visibility: From::from(&item.vis),
223 docs: docs_for_attrs(&item.attrs),
224 sig: self.sig_base(item),
227 ast::ItemKind::Enum(ref def, _) => {
228 let name = item.ident.to_string();
229 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
230 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
231 filter!(self.span_utils, sub_span, item.span, None);
232 let variants_str = def.variants.iter()
233 .map(|v| v.node.name.to_string())
236 let val = format!("{}::{{{}}}", name, variants_str);
237 Some(Data::EnumData(EnumData {
241 span: sub_span.unwrap(),
243 scope: self.enclosing_scope(item.id),
244 variants: def.variants.iter().map(|v| v.node.data.id()).collect(),
245 visibility: From::from(&item.vis),
246 docs: docs_for_attrs(&item.attrs),
247 sig: self.sig_base(item),
250 ast::ItemKind::Impl(.., ref trait_ref, ref typ, _) => {
251 let mut type_data = None;
254 let parent = self.enclosing_scope(item.id);
257 // Common case impl for a struct or something basic.
258 ast::TyKind::Path(None, ref path) => {
259 filter!(self.span_utils, None, path.span, None);
260 sub_span = self.span_utils.sub_span_for_type_name(path.span);
261 type_data = self.lookup_ref_id(typ.id).map(|id| {
263 span: sub_span.unwrap(),
266 qualname: String::new() // FIXME: generate the real qualname
271 // Less useful case, impl for a compound type.
273 sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
277 let trait_data = trait_ref.as_ref()
278 .and_then(|tr| self.get_trait_ref_data(tr, parent));
280 filter!(self.span_utils, sub_span, typ.span, None);
281 Some(Data::ImplData(ImplData2 {
283 span: sub_span.unwrap(),
285 trait_ref: trait_data,
296 pub fn get_field_data(&self,
297 field: &ast::StructField,
299 -> Option<VariableData> {
300 if let Some(ident) = field.ident {
301 let name = ident.to_string();
302 let qualname = format!("::{}::{}", self.tcx.node_path_str(scope), ident);
303 let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
304 filter!(self.span_utils, sub_span, field.span, None);
305 let def_id = self.tcx.map.local_def_id(field.id);
306 let typ = self.tcx.item_type(def_id).to_string();
308 let span = field.span;
309 let text = self.span_utils.snippet(field.span);
310 let ident_start = text.find(&name).unwrap();
311 let ident_end = ident_start + name.len();
312 let sig = Signature {
315 ident_start: ident_start,
316 ident_end: ident_end,
322 kind: VariableKind::Field,
325 span: sub_span.unwrap(),
327 parent: Some(make_def_id(scope, &self.tcx.map)),
328 value: "".to_owned(),
330 visibility: From::from(&field.vis),
331 docs: docs_for_attrs(&field.attrs),
339 // FIXME would be nice to take a MethodItem here, but the ast provides both
340 // trait and impl flavours, so the caller must do the disassembly.
341 pub fn get_method_data(&self, id: ast::NodeId,
342 name: ast::Name, span: Span) -> Option<FunctionData> {
343 // The qualname for a method is the trait name or name of the struct in an impl in
344 // which the method is declared in, followed by the method's name.
345 let (qualname, parent_scope, decl_id, vis, docs) =
346 match self.tcx.impl_of_method(self.tcx.map.local_def_id(id)) {
347 Some(impl_id) => match self.tcx.map.get_if_local(impl_id) {
348 Some(Node::NodeItem(item)) => {
350 hir::ItemImpl(.., ref ty, _) => {
351 let mut result = String::from("<");
352 result.push_str(&rustc::hir::print::ty_to_string(&ty));
354 let trait_id = self.tcx.trait_id_of_impl(impl_id);
355 let mut decl_id = None;
356 if let Some(def_id) = trait_id {
357 result.push_str(" as ");
358 result.push_str(&self.tcx.item_path_str(def_id));
359 self.tcx.associated_items(def_id)
360 .find(|item| item.name == name)
361 .map(|item| decl_id = Some(item.def_id));
363 result.push_str(">");
365 (result, trait_id, decl_id,
366 From::from(&item.vis),
367 docs_for_attrs(&item.attrs))
371 "Container {:?} for method {} not an impl?",
379 "Container {:?} for method {} is not a node item {:?}",
385 None => match self.tcx.trait_of_item(self.tcx.map.local_def_id(id)) {
387 match self.tcx.map.get_if_local(def_id) {
388 Some(Node::NodeItem(item)) => {
389 (format!("::{}", self.tcx.item_path_str(def_id)),
391 From::from(&item.vis),
392 docs_for_attrs(&item.attrs))
396 "Could not find container {:?} for \
397 method {}, got {:?}",
405 span_bug!(span, "Could not find container for method {}", id);
410 let qualname = format!("{}::{}", qualname, name);
412 let sub_span = self.span_utils.sub_span_after_keyword(span, keywords::Fn);
413 filter!(self.span_utils, sub_span, span, None);
415 let name = name.to_string();
416 let text = self.span_utils.signature_string_for_span(span);
417 println!("text: `{}`, name: `{}`", text, name);
418 let ident_start = text.find(&name).unwrap();
419 let ident_end = ident_start + name.len();
420 let sig = Signature {
423 ident_start: ident_start,
424 ident_end: ident_end,
433 declaration: decl_id,
434 span: sub_span.unwrap(),
435 scope: self.enclosing_scope(id),
436 // FIXME you get better data here by using the visitor.
437 value: String::new(),
439 parent: parent_scope,
445 pub fn get_trait_ref_data(&self,
446 trait_ref: &ast::TraitRef,
448 -> Option<TypeRefData> {
449 self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
450 let span = trait_ref.path.span;
451 let sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
452 filter!(self.span_utils, sub_span, span, None);
454 span: sub_span.unwrap(),
456 ref_id: Some(def_id),
457 qualname: String::new() // FIXME: generate the real qualname
462 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
463 let hir_node = self.tcx.map.expect_expr(expr.id);
464 let ty = self.tcx.tables().expr_ty_adjusted_opt(&hir_node);
465 if ty.is_none() || ty.unwrap().sty == ty::TyError {
469 ast::ExprKind::Field(ref sub_ex, ident) => {
470 let hir_node = match self.tcx.map.find(sub_ex.id) {
471 Some(Node::NodeExpr(expr)) => expr,
473 debug!("Missing or weird node for sub-expression {} in {:?}",
478 match self.tcx.tables().expr_ty_adjusted(&hir_node).sty {
479 ty::TyAdt(def, _) if !def.is_enum() => {
480 let f = def.struct_variant().field_named(ident.node.name);
481 let sub_span = self.span_utils.span_for_last_ident(expr.span);
482 filter!(self.span_utils, sub_span, expr.span, None);
483 return Some(Data::VariableRefData(VariableRefData {
484 name: ident.node.to_string(),
485 span: sub_span.unwrap(),
486 scope: self.enclosing_scope(expr.id),
491 debug!("Expected struct or union type, found {:?}", ty);
496 ast::ExprKind::Struct(ref path, ..) => {
497 match self.tcx.tables().expr_ty_adjusted(&hir_node).sty {
498 ty::TyAdt(def, _) if !def.is_enum() => {
499 let sub_span = self.span_utils.span_for_last_ident(path.span);
500 filter!(self.span_utils, sub_span, path.span, None);
501 Some(Data::TypeRefData(TypeRefData {
502 span: sub_span.unwrap(),
503 scope: self.enclosing_scope(expr.id),
504 ref_id: Some(def.did),
505 qualname: String::new() // FIXME: generate the real qualname
509 // FIXME ty could legitimately be an enum, but then we will fail
510 // later if we try to look up the fields.
511 debug!("expected struct or union, found {:?}", ty);
516 ast::ExprKind::MethodCall(..) => {
517 let method_call = ty::MethodCall::expr(expr.id);
518 let method_id = self.tcx.tables().method_map[&method_call].def_id;
519 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
520 ty::ImplContainer(_) => (Some(method_id), None),
521 ty::TraitContainer(_) => (None, Some(method_id)),
523 let sub_span = self.span_utils.sub_span_for_meth_name(expr.span);
524 filter!(self.span_utils, sub_span, expr.span, None);
525 let parent = self.enclosing_scope(expr.id);
526 Some(Data::MethodCallData(MethodCallData {
527 span: sub_span.unwrap(),
533 ast::ExprKind::Path(_, ref path) => {
534 self.get_path_data(expr.id, path)
543 pub fn get_path_def(&self, id: NodeId) -> Def {
544 match self.tcx.map.get(id) {
545 Node::NodeTraitRef(tr) => tr.path.def,
547 Node::NodeItem(&hir::Item { node: hir::ItemUse(ref path, _), .. }) |
548 Node::NodeVisibility(&hir::Visibility::Restricted { ref path, .. }) => path.def,
550 Node::NodeExpr(&hir::Expr { node: hir::ExprPath(ref qpath), .. }) |
551 Node::NodeExpr(&hir::Expr { node: hir::ExprStruct(ref qpath, ..), .. }) |
552 Node::NodePat(&hir::Pat { node: hir::PatKind::Path(ref qpath), .. }) |
553 Node::NodePat(&hir::Pat { node: hir::PatKind::Struct(ref qpath, ..), .. }) |
554 Node::NodePat(&hir::Pat { node: hir::PatKind::TupleStruct(ref qpath, ..), .. }) => {
555 self.tcx.tables().qpath_def(qpath, id)
558 Node::NodeLocal(&hir::Pat { node: hir::PatKind::Binding(_, def_id, ..), .. }) => {
562 Node::NodeTy(&hir::Ty { node: hir::TyPath(ref qpath), .. }) => {
564 hir::QPath::Resolved(_, ref path) => path.def,
565 hir::QPath::TypeRelative(..) => {
566 if let Some(ty) = self.analysis.hir_ty_to_ty.get(&id) {
567 if let ty::TyProjection(proj) = ty.sty {
568 for item in self.tcx.associated_items(proj.trait_ref.def_id) {
569 if item.kind == ty::AssociatedKind::Type {
570 if item.name == proj.item_name {
571 return Def::AssociatedTy(item.def_id);
586 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Data> {
587 let def = self.get_path_def(id);
588 let sub_span = self.span_utils.span_for_last_ident(path.span);
589 filter!(self.span_utils, sub_span, path.span, None);
595 Def::AssociatedConst(..) |
596 Def::StructCtor(..) |
597 Def::VariantCtor(..) => {
598 Some(Data::VariableRefData(VariableRefData {
599 name: self.span_utils.snippet(sub_span.unwrap()),
600 span: sub_span.unwrap(),
601 scope: self.enclosing_scope(id),
602 ref_id: def.def_id(),
605 Def::Struct(def_id) |
606 Def::Variant(def_id, ..) |
609 Def::TyAlias(def_id) |
610 Def::AssociatedTy(def_id) |
612 Def::TyParam(def_id) => {
613 Some(Data::TypeRefData(TypeRefData {
614 span: sub_span.unwrap(),
615 ref_id: Some(def_id),
616 scope: self.enclosing_scope(id),
617 qualname: String::new() // FIXME: generate the real qualname
620 Def::Method(decl_id) => {
621 let sub_span = self.span_utils.sub_span_for_meth_name(path.span);
622 filter!(self.span_utils, sub_span, path.span, None);
623 let def_id = if decl_id.is_local() {
624 let ti = self.tcx.associated_item(decl_id);
625 self.tcx.associated_items(ti.container.id())
626 .find(|item| item.name == ti.name && item.defaultness.has_value())
627 .map(|item| item.def_id)
631 Some(Data::MethodCallData(MethodCallData {
632 span: sub_span.unwrap(),
633 scope: self.enclosing_scope(id),
635 decl_id: Some(decl_id),
639 Some(Data::FunctionCallData(FunctionCallData {
641 span: sub_span.unwrap(),
642 scope: self.enclosing_scope(id),
645 Def::Mod(def_id) => {
646 Some(Data::ModRefData(ModRefData {
647 ref_id: Some(def_id),
648 span: sub_span.unwrap(),
649 scope: self.enclosing_scope(id),
650 qualname: String::new() // FIXME: generate the real qualname
661 pub fn get_field_ref_data(&self,
662 field_ref: &ast::Field,
663 variant: &ty::VariantDef,
665 -> Option<VariableRefData> {
666 let f = variant.field_named(field_ref.ident.node.name);
667 // We don't really need a sub-span here, but no harm done
668 let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
669 filter!(self.span_utils, sub_span, field_ref.ident.span, None);
670 Some(VariableRefData {
671 name: field_ref.ident.node.to_string(),
672 span: sub_span.unwrap(),
678 /// Attempt to return MacroUseData for any AST node.
680 /// For a given piece of AST defined by the supplied Span and NodeId,
681 /// returns None if the node is not macro-generated or the span is malformed,
682 /// else uses the expansion callsite and callee to return some MacroUseData.
683 pub fn get_macro_use_data(&self, span: Span, id: NodeId) -> Option<MacroUseData> {
684 if !generated_code(span) {
687 // Note we take care to use the source callsite/callee, to handle
688 // nested expansions and ensure we only generate data for source-visible
690 let callsite = self.tcx.sess.codemap().source_callsite(span);
691 let callee = self.tcx.sess.codemap().source_callee(span);
692 let callee = option_try!(callee);
693 let callee_span = option_try!(callee.span);
695 // Ignore attribute macros, their spans are usually mangled
696 if let MacroAttribute(_) = callee.format {
700 // If the callee is an imported macro from an external crate, need to get
701 // the source span and name from the session, as their spans are localized
702 // when read in, and no longer correspond to the source.
703 if let Some(mac) = self.tcx.sess.imported_macro_spans.borrow().get(&callee_span) {
704 let &(ref mac_name, mac_span) = mac;
705 return Some(MacroUseData {
707 name: mac_name.clone(),
708 callee_span: mac_span,
709 scope: self.enclosing_scope(id),
711 qualname: String::new()// FIXME: generate the real qualname
717 name: callee.name().to_string(),
718 callee_span: callee_span,
719 scope: self.enclosing_scope(id),
721 qualname: String::new() // FIXME: generate the real qualname
725 pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
730 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
731 match self.get_path_def(ref_id) {
732 Def::PrimTy(_) | Def::SelfTy(..) | Def::Err => None,
733 def => Some(def.def_id()),
737 fn sig_base(&self, item: &ast::Item) -> Signature {
738 let text = self.span_utils.signature_string_for_span(item.span);
739 let name = item.ident.to_string();
740 let ident_start = text.find(&name).expect("Name not in signature?");
741 let ident_end = ident_start + name.len();
743 span: mk_sp(item.span.lo, item.span.lo + BytePos(text.len() as u32)),
745 ident_start: ident_start,
746 ident_end: ident_end,
753 pub fn enclosing_scope(&self, id: NodeId) -> NodeId {
754 self.tcx.map.get_enclosing_scope(id).unwrap_or(CRATE_NODE_ID)
758 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
759 let mut sig = "fn ".to_owned();
760 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
762 sig.push_str(&generics.lifetimes.iter()
763 .map(|l| l.lifetime.name.to_string())
766 if !generics.lifetimes.is_empty() {
769 sig.push_str(&generics.ty_params.iter()
770 .map(|l| l.ident.to_string())
776 sig.push_str(&decl.inputs.iter().map(arg_to_string).collect::<Vec<_>>().join(", "));
779 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
780 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
786 // An AST visitor for collecting paths from patterns.
787 struct PathCollector {
788 // The Row field identifies the kind of pattern.
789 collected_paths: Vec<(NodeId, ast::Path, ast::Mutability, recorder::Row)>,
793 fn new() -> PathCollector {
794 PathCollector { collected_paths: vec![] }
798 impl<'a> Visitor<'a> for PathCollector {
799 fn visit_pat(&mut self, p: &ast::Pat) {
801 PatKind::Struct(ref path, ..) => {
802 self.collected_paths.push((p.id, path.clone(),
803 ast::Mutability::Mutable, recorder::TypeRef));
805 PatKind::TupleStruct(ref path, ..) |
806 PatKind::Path(_, ref path) => {
807 self.collected_paths.push((p.id, path.clone(),
808 ast::Mutability::Mutable, recorder::VarRef));
810 PatKind::Ident(bm, ref path1, _) => {
811 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
815 let immut = match bm {
816 // Even if the ref is mut, you can't change the ref, only
817 // the data pointed at, so showing the initialising expression
818 // is still worthwhile.
819 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
820 ast::BindingMode::ByValue(mt) => mt,
822 // collect path for either visit_local or visit_arm
823 let path = ast::Path::from_ident(path1.span, path1.node);
824 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
828 visit::walk_pat(self, p);
832 fn docs_for_attrs(attrs: &[Attribute]) -> String {
833 let doc = Symbol::intern("doc");
834 let mut result = String::new();
837 if attr.name() == doc {
838 if let Some(val) = attr.value_str() {
839 if attr.is_sugared_doc {
840 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
842 result.push_str(&val.as_str());
852 #[derive(Clone, Copy, Debug, RustcEncodable)]
860 fn extension(&self) -> &'static str {
862 Format::Csv => ".csv",
863 Format::Json | Format::JsonApi => ".json",
868 pub fn process_crate<'l, 'tcx>(tcx: TyCtxt<'l, 'tcx, 'tcx>,
870 analysis: &'l ty::CrateAnalysis<'tcx>,
874 let _ignore = tcx.dep_graph.in_ignore();
876 assert!(analysis.glob_map.is_some());
878 info!("Dumping crate {}", cratename);
880 // find a path to dump our data to
881 let mut root_path = match env::var_os("RUST_SAVE_ANALYSIS_FOLDER") {
882 Some(val) => PathBuf::from(val),
884 Some(val) => val.join("save-analysis"),
885 None => PathBuf::from("save-analysis-temp"),
889 if let Err(e) = rustc::util::fs::create_dir_racy(&root_path) {
890 tcx.sess.err(&format!("Could not create directory {}: {}",
896 let disp = root_path.display();
897 info!("Writing output to {}", disp);
900 // Create output file.
901 let executable = tcx.sess.crate_types.borrow().iter().any(|ct| *ct == CrateTypeExecutable);
902 let mut out_name = if executable {
907 out_name.push_str(&cratename);
908 out_name.push_str(&tcx.sess.opts.cg.extra_filename);
909 out_name.push_str(format.extension());
910 root_path.push(&out_name);
911 let mut output_file = File::create(&root_path).unwrap_or_else(|e| {
912 let disp = root_path.display();
913 tcx.sess.fatal(&format!("Could not open {}: {}", disp, e));
916 let output = &mut output_file;
918 let save_ctxt = SaveContext::new(tcx, analysis);
921 ($new_dumper: expr) => {{
922 let mut dumper = $new_dumper;
923 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
925 visitor.dump_crate_info(cratename, krate);
926 visit::walk_crate(&mut visitor, krate);
931 Format::Csv => dump!(CsvDumper::new(output)),
932 Format::Json => dump!(JsonDumper::new(output)),
933 Format::JsonApi => dump!(JsonApiDumper::new(output)),
937 // Utility functions for the module.
939 // Helper function to escape quotes in a string
940 fn escape(s: String) -> String {
941 s.replace("\"", "\"\"")
944 // Helper function to determine if a span came from a
945 // macro expansion or syntax extension.
946 pub fn generated_code(span: Span) -> bool {
947 span.expn_id != NO_EXPANSION || span == DUMMY_SP