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;
43 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::json_api_dumper::JsonApiDumper;
71 pub use self::json_dumper::JsonDumper;
72 pub use self::data::*;
73 pub use self::external_data::make_def_id;
74 pub use self::dump::Dump;
75 pub use self::dump_visitor::DumpVisitor;
76 use self::span_utils::SpanUtils;
78 // FIXME this is legacy code and should be removed
82 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
91 pub struct SaveContext<'l, 'tcx: 'l> {
92 tcx: TyCtxt<'l, 'tcx, 'tcx>,
93 tables: &'l ty::TypeckTables<'tcx>,
94 analysis: &'l ty::CrateAnalysis,
95 span_utils: SpanUtils<'tcx>,
98 macro_rules! option_try(
99 ($e:expr) => (match $e { Some(e) => e, None => return None })
102 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
103 // List external crates used by the current crate.
104 pub fn get_external_crates(&self) -> Vec<CrateData> {
105 let mut result = Vec::new();
107 for n in self.tcx.sess.cstore.crates() {
108 let span = match self.tcx.sess.cstore.extern_crate(n) {
109 Some(ref c) => c.span,
111 debug!("Skipping crate {}, no data", n);
115 result.push(CrateData {
116 name: self.tcx.sess.cstore.crate_name(n).to_string(),
125 pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
126 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
128 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
129 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
130 filter!(self.span_utils, sub_span, item.span, None);
131 Some(Data::FunctionData(FunctionData {
133 name: item.ident.to_string(),
136 span: sub_span.unwrap(),
137 scope: self.enclosing_scope(item.id),
138 value: make_signature(decl, generics),
139 visibility: From::from(&item.vis),
141 docs: docs_for_attrs(&item.attrs),
142 sig: sig::foreign_item_signature(item, self),
143 attributes: item.attrs.clone(),
146 ast::ForeignItemKind::Static(ref ty, m) => {
147 let keyword = if m { keywords::Mut } else { keywords::Static };
148 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
149 filter!(self.span_utils, sub_span, item.span, None);
150 Some(Data::VariableData(VariableData {
152 kind: VariableKind::Static,
153 name: item.ident.to_string(),
155 span: sub_span.unwrap(),
156 scope: self.enclosing_scope(item.id),
158 value: String::new(),
159 type_value: ty_to_string(ty),
160 visibility: From::from(&item.vis),
161 docs: docs_for_attrs(&item.attrs),
162 sig: sig::foreign_item_signature(item, self),
163 attributes: item.attrs.clone(),
169 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
171 ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
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::Fn);
174 filter!(self.span_utils, sub_span, item.span, None);
177 Some(Data::FunctionData(FunctionData {
179 name: item.ident.to_string(),
182 span: sub_span.unwrap(),
183 scope: self.enclosing_scope(item.id),
184 value: make_signature(decl, generics),
185 visibility: From::from(&item.vis),
187 docs: docs_for_attrs(&item.attrs),
188 sig: sig::item_signature(item, self),
189 attributes: item.attrs.clone(),
192 ast::ItemKind::Static(ref typ, mt, ref expr) => {
193 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
195 // If the variable is immutable, save the initialising expression.
196 let (value, keyword) = match mt {
197 ast::Mutability::Mutable => (String::from("<mutable>"), keywords::Mut),
198 ast::Mutability::Immutable => {
199 (self.span_utils.snippet(expr.span), keywords::Static)
203 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
204 filter!(self.span_utils, sub_span, item.span, None);
205 Some(Data::VariableData(VariableData {
207 kind: VariableKind::Static,
208 name: item.ident.to_string(),
210 span: sub_span.unwrap(),
211 scope: self.enclosing_scope(item.id),
214 type_value: ty_to_string(&typ),
215 visibility: From::from(&item.vis),
216 docs: docs_for_attrs(&item.attrs),
217 sig: sig::item_signature(item, self),
218 attributes: item.attrs.clone(),
221 ast::ItemKind::Const(ref typ, ref expr) => {
222 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
223 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
224 filter!(self.span_utils, sub_span, item.span, None);
225 Some(Data::VariableData(VariableData {
227 kind: VariableKind::Const,
228 name: item.ident.to_string(),
230 span: sub_span.unwrap(),
231 scope: self.enclosing_scope(item.id),
233 value: self.span_utils.snippet(expr.span),
234 type_value: ty_to_string(&typ),
235 visibility: From::from(&item.vis),
236 docs: docs_for_attrs(&item.attrs),
237 sig: sig::item_signature(item, self),
238 attributes: item.attrs.clone(),
241 ast::ItemKind::Mod(ref m) => {
242 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
244 let cm = self.tcx.sess.codemap();
245 let filename = cm.span_to_filename(m.inner);
247 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
248 filter!(self.span_utils, sub_span, item.span, None);
250 Some(Data::ModData(ModData {
252 name: item.ident.to_string(),
254 span: sub_span.unwrap(),
255 scope: self.enclosing_scope(item.id),
257 items: m.items.iter().map(|i| i.id).collect(),
258 visibility: From::from(&item.vis),
259 docs: docs_for_attrs(&item.attrs),
260 sig: sig::item_signature(item, self),
261 attributes: item.attrs.clone(),
264 ast::ItemKind::Enum(ref def, _) => {
265 let name = item.ident.to_string();
266 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
267 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
268 filter!(self.span_utils, sub_span, item.span, None);
269 let variants_str = def.variants.iter()
270 .map(|v| v.node.name.to_string())
273 let val = format!("{}::{{{}}}", name, variants_str);
274 Some(Data::EnumData(EnumData {
278 span: sub_span.unwrap(),
280 scope: self.enclosing_scope(item.id),
281 variants: def.variants.iter().map(|v| v.node.data.id()).collect(),
282 visibility: From::from(&item.vis),
283 docs: docs_for_attrs(&item.attrs),
284 sig: sig::item_signature(item, self),
285 attributes: item.attrs.clone(),
288 ast::ItemKind::Impl(.., ref trait_ref, ref typ, _) => {
289 let mut type_data = None;
292 let parent = self.enclosing_scope(item.id);
295 // Common case impl for a struct or something basic.
296 ast::TyKind::Path(None, ref path) => {
297 if generated_code(path.span) {
300 sub_span = self.span_utils.sub_span_for_type_name(path.span);
301 type_data = self.lookup_ref_id(typ.id).map(|id| {
303 span: sub_span.unwrap(),
306 qualname: String::new() // FIXME: generate the real qualname
311 // Less useful case, impl for a compound type.
313 sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
317 let trait_data = trait_ref.as_ref()
318 .and_then(|tr| self.get_trait_ref_data(tr, parent));
320 filter!(self.span_utils, sub_span, typ.span, None);
321 Some(Data::ImplData(ImplData2 {
323 span: sub_span.unwrap(),
325 trait_ref: trait_data,
336 pub fn get_field_data(&self,
337 field: &ast::StructField,
339 -> Option<VariableData> {
340 if let Some(ident) = field.ident {
341 let name = ident.to_string();
342 let qualname = format!("::{}::{}", self.tcx.node_path_str(scope), ident);
343 let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
344 filter!(self.span_utils, sub_span, field.span, None);
345 let def_id = self.tcx.hir.local_def_id(field.id);
346 let typ = self.tcx.type_of(def_id).to_string();
350 kind: VariableKind::Field,
353 span: sub_span.unwrap(),
355 parent: Some(make_def_id(scope, &self.tcx.hir)),
356 value: "".to_owned(),
358 visibility: From::from(&field.vis),
359 docs: docs_for_attrs(&field.attrs),
360 sig: sig::field_signature(field, self),
361 attributes: field.attrs.clone(),
368 // FIXME would be nice to take a MethodItem here, but the ast provides both
369 // trait and impl flavours, so the caller must do the disassembly.
370 pub fn get_method_data(&self,
374 -> Option<FunctionData> {
375 // The qualname for a method is the trait name or name of the struct in an impl in
376 // which the method is declared in, followed by the method's name.
377 let (qualname, parent_scope, decl_id, vis, docs, attributes) =
378 match self.tcx.impl_of_method(self.tcx.hir.local_def_id(id)) {
379 Some(impl_id) => match self.tcx.hir.get_if_local(impl_id) {
380 Some(Node::NodeItem(item)) => {
382 hir::ItemImpl(.., ref ty, _) => {
383 let mut result = String::from("<");
384 result.push_str(&self.tcx.hir.node_to_pretty_string(ty.id));
386 let trait_id = self.tcx.trait_id_of_impl(impl_id);
387 let mut decl_id = None;
388 if let Some(def_id) = trait_id {
389 result.push_str(" as ");
390 result.push_str(&self.tcx.item_path_str(def_id));
391 self.tcx.associated_items(def_id)
392 .find(|item| item.name == name)
393 .map(|item| decl_id = Some(item.def_id));
395 result.push_str(">");
397 (result, trait_id, decl_id,
398 From::from(&item.vis),
399 docs_for_attrs(&item.attrs),
404 "Container {:?} for method {} not an impl?",
412 "Container {:?} for method {} is not a node item {:?}",
418 None => match self.tcx.trait_of_item(self.tcx.hir.local_def_id(id)) {
420 match self.tcx.hir.get_if_local(def_id) {
421 Some(Node::NodeItem(item)) => {
422 (format!("::{}", self.tcx.item_path_str(def_id)),
424 From::from(&item.vis),
425 docs_for_attrs(&item.attrs),
430 "Could not find container {:?} for \
431 method {}, got {:?}",
439 debug!("Could not find container for method {} at {:?}", id, span);
440 // This is not necessarily a bug, if there was a compilation error, the tables
441 // we need might not exist.
447 let qualname = format!("{}::{}", qualname, name);
449 let sub_span = self.span_utils.sub_span_after_keyword(span, keywords::Fn);
450 filter!(self.span_utils, sub_span, span, None);
454 name: name.to_string(),
456 declaration: decl_id,
457 span: sub_span.unwrap(),
458 scope: self.enclosing_scope(id),
459 // FIXME you get better data here by using the visitor.
460 value: String::new(),
462 parent: parent_scope,
465 attributes: attributes,
469 pub fn get_trait_ref_data(&self,
470 trait_ref: &ast::TraitRef,
472 -> Option<TypeRefData> {
473 self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
474 let span = trait_ref.path.span;
475 if generated_code(span) {
478 let sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
479 filter!(self.span_utils, sub_span, span, None);
481 span: sub_span.unwrap(),
483 ref_id: Some(def_id),
484 qualname: String::new() // FIXME: generate the real qualname
489 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
490 let hir_node = self.tcx.hir.expect_expr(expr.id);
491 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
492 if ty.is_none() || ty.unwrap().sty == ty::TyError {
496 ast::ExprKind::Field(ref sub_ex, ident) => {
497 let hir_node = match self.tcx.hir.find(sub_ex.id) {
498 Some(Node::NodeExpr(expr)) => expr,
500 debug!("Missing or weird node for sub-expression {} in {:?}",
505 match self.tables.expr_ty_adjusted(&hir_node).sty {
506 ty::TyAdt(def, _) if !def.is_enum() => {
507 let f = def.struct_variant().field_named(ident.node.name);
508 let sub_span = self.span_utils.span_for_last_ident(expr.span);
509 filter!(self.span_utils, sub_span, expr.span, None);
510 return Some(Data::VariableRefData(VariableRefData {
511 name: ident.node.to_string(),
512 span: sub_span.unwrap(),
513 scope: self.enclosing_scope(expr.id),
518 debug!("Expected struct or union type, found {:?}", ty);
523 ast::ExprKind::Struct(ref path, ..) => {
524 match self.tables.expr_ty_adjusted(&hir_node).sty {
525 ty::TyAdt(def, _) if !def.is_enum() => {
526 let sub_span = self.span_utils.span_for_last_ident(path.span);
527 filter!(self.span_utils, sub_span, path.span, None);
528 Some(Data::TypeRefData(TypeRefData {
529 span: sub_span.unwrap(),
530 scope: self.enclosing_scope(expr.id),
531 ref_id: Some(def.did),
532 qualname: String::new() // FIXME: generate the real qualname
536 // FIXME ty could legitimately be an enum, but then we will fail
537 // later if we try to look up the fields.
538 debug!("expected struct or union, found {:?}", ty);
543 ast::ExprKind::MethodCall(..) => {
544 let method_id = self.tables.type_dependent_defs[&expr.id].def_id();
545 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
546 ty::ImplContainer(_) => (Some(method_id), None),
547 ty::TraitContainer(_) => (None, Some(method_id)),
549 let sub_span = self.span_utils.sub_span_for_meth_name(expr.span);
550 filter!(self.span_utils, sub_span, expr.span, None);
551 let parent = self.enclosing_scope(expr.id);
552 Some(Data::MethodCallData(MethodCallData {
553 span: sub_span.unwrap(),
559 ast::ExprKind::Path(_, ref path) => {
560 self.get_path_data(expr.id, path)
569 pub fn get_path_def(&self, id: NodeId) -> Def {
570 match self.tcx.hir.get(id) {
571 Node::NodeTraitRef(tr) => tr.path.def,
573 Node::NodeItem(&hir::Item { node: hir::ItemUse(ref path, _), .. }) |
574 Node::NodeVisibility(&hir::Visibility::Restricted { ref path, .. }) => path.def,
576 Node::NodeExpr(&hir::Expr { node: hir::ExprPath(ref qpath), .. }) |
577 Node::NodeExpr(&hir::Expr { node: hir::ExprStruct(ref qpath, ..), .. }) |
578 Node::NodePat(&hir::Pat { node: hir::PatKind::Path(ref qpath), .. }) |
579 Node::NodePat(&hir::Pat { node: hir::PatKind::Struct(ref qpath, ..), .. }) |
580 Node::NodePat(&hir::Pat { node: hir::PatKind::TupleStruct(ref qpath, ..), .. }) => {
581 self.tables.qpath_def(qpath, id)
584 Node::NodeLocal(&hir::Pat { node: hir::PatKind::Binding(_, def_id, ..), .. }) => {
588 Node::NodeTy(ty) => {
589 if let hir::Ty { node: hir::TyPath(ref qpath), .. } = *ty {
591 hir::QPath::Resolved(_, ref path) => path.def,
592 hir::QPath::TypeRelative(..) => {
593 let ty = hir_ty_to_ty(self.tcx, ty);
594 if let ty::TyProjection(proj) = ty.sty {
595 for item in self.tcx.associated_items(proj.trait_ref.def_id) {
596 if item.kind == ty::AssociatedKind::Type {
597 if item.name == proj.item_name(self.tcx) {
598 return Def::AssociatedTy(item.def_id);
615 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Data> {
616 let def = self.get_path_def(id);
617 let sub_span = self.span_utils.span_for_last_ident(path.span);
618 filter!(self.span_utils, sub_span, path.span, None);
624 Def::AssociatedConst(..) |
625 Def::StructCtor(..) |
626 Def::VariantCtor(..) => {
627 Some(Data::VariableRefData(VariableRefData {
628 name: self.span_utils.snippet(sub_span.unwrap()),
629 span: sub_span.unwrap(),
630 scope: self.enclosing_scope(id),
631 ref_id: def.def_id(),
634 Def::Struct(def_id) |
635 Def::Variant(def_id, ..) |
638 Def::TyAlias(def_id) |
639 Def::AssociatedTy(def_id) |
641 Def::TyParam(def_id) => {
642 Some(Data::TypeRefData(TypeRefData {
643 span: sub_span.unwrap(),
644 ref_id: Some(def_id),
645 scope: self.enclosing_scope(id),
646 qualname: String::new() // FIXME: generate the real qualname
649 Def::Method(decl_id) => {
650 let sub_span = self.span_utils.sub_span_for_meth_name(path.span);
651 filter!(self.span_utils, sub_span, path.span, None);
652 let def_id = if decl_id.is_local() {
653 let ti = self.tcx.associated_item(decl_id);
654 self.tcx.associated_items(ti.container.id())
655 .find(|item| item.name == ti.name && item.defaultness.has_value())
656 .map(|item| item.def_id)
660 Some(Data::MethodCallData(MethodCallData {
661 span: sub_span.unwrap(),
662 scope: self.enclosing_scope(id),
664 decl_id: Some(decl_id),
668 Some(Data::FunctionCallData(FunctionCallData {
670 span: sub_span.unwrap(),
671 scope: self.enclosing_scope(id),
674 Def::Mod(def_id) => {
675 Some(Data::ModRefData(ModRefData {
676 ref_id: Some(def_id),
677 span: sub_span.unwrap(),
678 scope: self.enclosing_scope(id),
679 qualname: String::new() // FIXME: generate the real qualname
691 pub fn get_field_ref_data(&self,
692 field_ref: &ast::Field,
693 variant: &ty::VariantDef,
695 -> Option<VariableRefData> {
696 let f = variant.field_named(field_ref.ident.node.name);
697 // We don't really need a sub-span here, but no harm done
698 let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
699 filter!(self.span_utils, sub_span, field_ref.ident.span, None);
700 Some(VariableRefData {
701 name: field_ref.ident.node.to_string(),
702 span: sub_span.unwrap(),
708 /// Attempt to return MacroUseData for any AST node.
710 /// For a given piece of AST defined by the supplied Span and NodeId,
711 /// returns None if the node is not macro-generated or the span is malformed,
712 /// else uses the expansion callsite and callee to return some MacroUseData.
713 pub fn get_macro_use_data(&self, span: Span, id: NodeId) -> Option<MacroUseData> {
714 if !generated_code(span) {
717 // Note we take care to use the source callsite/callee, to handle
718 // nested expansions and ensure we only generate data for source-visible
720 let callsite = span.source_callsite();
721 let callee = option_try!(span.source_callee());
722 let callee_span = option_try!(callee.span);
724 // Ignore attribute macros, their spans are usually mangled
725 if let MacroAttribute(_) = callee.format {
729 // If the callee is an imported macro from an external crate, need to get
730 // the source span and name from the session, as their spans are localized
731 // when read in, and no longer correspond to the source.
732 if let Some(mac) = self.tcx.sess.imported_macro_spans.borrow().get(&callee_span) {
733 let &(ref mac_name, mac_span) = mac;
734 return Some(MacroUseData {
736 name: mac_name.clone(),
737 callee_span: mac_span,
738 scope: self.enclosing_scope(id),
740 qualname: String::new()// FIXME: generate the real qualname
746 name: callee.name().to_string(),
747 callee_span: callee_span,
748 scope: self.enclosing_scope(id),
750 qualname: String::new() // FIXME: generate the real qualname
754 pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
759 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
760 match self.get_path_def(ref_id) {
761 Def::PrimTy(_) | Def::SelfTy(..) | Def::Err => None,
762 def => Some(def.def_id()),
767 pub fn enclosing_scope(&self, id: NodeId) -> NodeId {
768 self.tcx.hir.get_enclosing_scope(id).unwrap_or(CRATE_NODE_ID)
772 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
773 let mut sig = "fn ".to_owned();
774 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
776 sig.push_str(&generics.lifetimes.iter()
777 .map(|l| l.lifetime.ident.name.to_string())
780 if !generics.lifetimes.is_empty() {
783 sig.push_str(&generics.ty_params.iter()
784 .map(|l| l.ident.to_string())
790 sig.push_str(&decl.inputs.iter().map(arg_to_string).collect::<Vec<_>>().join(", "));
793 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
794 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
800 // An AST visitor for collecting paths from patterns.
801 struct PathCollector {
802 // The Row field identifies the kind of pattern.
803 collected_paths: Vec<(NodeId, ast::Path, ast::Mutability, recorder::Row)>,
807 fn new() -> PathCollector {
808 PathCollector { collected_paths: vec![] }
812 impl<'a> Visitor<'a> for PathCollector {
813 fn visit_pat(&mut self, p: &ast::Pat) {
815 PatKind::Struct(ref path, ..) => {
816 self.collected_paths.push((p.id, path.clone(),
817 ast::Mutability::Mutable, recorder::TypeRef));
819 PatKind::TupleStruct(ref path, ..) |
820 PatKind::Path(_, ref path) => {
821 self.collected_paths.push((p.id, path.clone(),
822 ast::Mutability::Mutable, recorder::VarRef));
824 PatKind::Ident(bm, ref path1, _) => {
825 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
829 let immut = match bm {
830 // Even if the ref is mut, you can't change the ref, only
831 // the data pointed at, so showing the initialising expression
832 // is still worthwhile.
833 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
834 ast::BindingMode::ByValue(mt) => mt,
836 // collect path for either visit_local or visit_arm
837 let path = ast::Path::from_ident(path1.span, path1.node);
838 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
842 visit::walk_pat(self, p);
846 fn docs_for_attrs(attrs: &[Attribute]) -> String {
847 let mut result = String::new();
850 if attr.check_name("doc") {
851 if let Some(val) = attr.value_str() {
852 if attr.is_sugared_doc {
853 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
855 result.push_str(&val.as_str());
865 #[derive(Clone, Copy, Debug, RustcEncodable)]
872 fn extension(&self) -> &'static str {
877 /// Defines what to do with the results of saving the analysis.
878 pub trait SaveHandler {
879 fn save<'l, 'tcx>(&mut self,
880 save_ctxt: SaveContext<'l, 'tcx>,
885 /// Dump the save-analysis results to a file.
886 pub struct DumpHandler<'a> {
888 odir: Option<&'a Path>,
892 impl<'a> DumpHandler<'a> {
893 pub fn new(format: Format, odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
897 cratename: cratename.to_owned()
901 fn output_file(&self, sess: &Session) -> File {
902 let mut root_path = match env::var_os("RUST_SAVE_ANALYSIS_FOLDER") {
903 Some(val) => PathBuf::from(val),
904 None => match self.odir {
905 Some(val) => val.join("save-analysis"),
906 None => PathBuf::from("save-analysis-temp"),
910 if let Err(e) = std::fs::create_dir_all(&root_path) {
911 error!("Could not create directory {}: {}", root_path.display(), e);
915 let disp = root_path.display();
916 info!("Writing output to {}", disp);
919 let executable = sess.crate_types.borrow().iter().any(|ct| *ct == CrateTypeExecutable);
920 let mut out_name = if executable {
925 out_name.push_str(&self.cratename);
926 out_name.push_str(&sess.opts.cg.extra_filename);
927 out_name.push_str(self.format.extension());
928 root_path.push(&out_name);
929 let output_file = File::create(&root_path).unwrap_or_else(|e| {
930 let disp = root_path.display();
931 sess.fatal(&format!("Could not open {}: {}", disp, e));
938 impl<'a> SaveHandler for DumpHandler<'a> {
939 fn save<'l, 'tcx>(&mut self,
940 save_ctxt: SaveContext<'l, 'tcx>,
944 ($new_dumper: expr) => {{
945 let mut dumper = $new_dumper;
946 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
948 visitor.dump_crate_info(cratename, krate);
949 visit::walk_crate(&mut visitor, krate);
953 let output = &mut self.output_file(&save_ctxt.tcx.sess);
956 Format::Json => dump!(JsonDumper::new(output)),
957 Format::JsonApi => dump!(JsonApiDumper::new(output)),
962 /// Call a callback with the results of save-analysis.
963 pub struct CallbackHandler<'b> {
964 pub callback: &'b mut FnMut(&rls_data::Analysis),
967 impl<'b> SaveHandler for CallbackHandler<'b> {
968 fn save<'l, 'tcx>(&mut self,
969 save_ctxt: SaveContext<'l, 'tcx>,
973 ($new_dumper: expr) => {{
974 let mut dumper = $new_dumper;
975 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
977 visitor.dump_crate_info(cratename, krate);
978 visit::walk_crate(&mut visitor, krate);
982 // We're using the JsonDumper here because it has the format of the
983 // save-analysis results that we will pass to the callback. IOW, we are
984 // using the JsonDumper to collect the save-analysis results, but not
985 // actually to dump them to a file. This is all a bit convoluted and
986 // there is certainly a simpler design here trying to get out (FIXME).
987 dump!(JsonDumper::with_callback(self.callback))
991 pub fn process_crate<'l, 'tcx, H: SaveHandler>(tcx: TyCtxt<'l, 'tcx, 'tcx>,
993 analysis: &'l ty::CrateAnalysis,
996 let _ignore = tcx.dep_graph.in_ignore();
998 assert!(analysis.glob_map.is_some());
1000 info!("Dumping crate {}", cratename);
1002 let save_ctxt = SaveContext {
1004 tables: &ty::TypeckTables::empty(),
1006 span_utils: SpanUtils::new(&tcx.sess),
1009 handler.save(save_ctxt, krate, cratename)
1012 // Utility functions for the module.
1014 // Helper function to escape quotes in a string
1015 fn escape(s: String) -> String {
1016 s.replace("\"", "\"\"")
1019 // Helper function to determine if a span came from a
1020 // macro expansion or syntax extension.
1021 fn generated_code(span: Span) -> bool {
1022 span.ctxt != NO_EXPANSION || span == DUMMY_SP
1025 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
1026 // we use our own Id which is the same, but without the newtype.
1027 fn id_from_def_id(id: DefId) -> rls_data::Id {
1029 krate: id.krate.as_u32(),
1030 index: id.index.as_u32(),
1034 fn id_from_node_id(id: NodeId, scx: &SaveContext) -> rls_data::Id {
1035 let def_id = scx.tcx.hir.local_def_id(id);
1036 id_from_def_id(def_id)