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 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13 html_root_url = "https://doc.rust-lang.org/nightly/")]
14 #![feature(custom_attribute)]
15 #![feature(macro_lifetime_matcher)]
16 #![allow(unused_attributes)]
23 extern crate rustc_data_structures;
24 extern crate rustc_serialize;
25 extern crate rustc_target;
26 extern crate rustc_typeck;
29 extern crate syntax_pos;
31 extern crate rls_data;
32 extern crate rls_span;
42 use rustc::hir::def::Def as HirDef;
43 use rustc::hir::map::{Node, NodeTraitItem, NodeImplItem};
44 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
45 use rustc::middle::cstore::ExternCrate;
46 use rustc::session::config::CrateType::CrateTypeExecutable;
47 use rustc::ty::{self, TyCtxt};
48 use rustc_typeck::hir_ty_to_ty;
51 use std::default::Default;
54 use std::path::{Path, PathBuf};
56 use syntax::ast::{self, Attribute, NodeId, PatKind};
57 use syntax::parse::lexer::comments::strip_doc_comment_decoration;
58 use syntax::parse::token;
59 use syntax::print::pprust;
60 use syntax::symbol::keywords;
61 use syntax::visit::{self, Visitor};
62 use syntax::print::pprust::{arg_to_string, ty_to_string};
63 use syntax::codemap::MacroAttribute;
66 use json_dumper::JsonDumper;
67 use dump_visitor::DumpVisitor;
68 use span_utils::SpanUtils;
70 use rls_data::{Def, DefKind, ExternalCrateData, GlobalCrateId, MacroRef, Ref, RefKind, Relation,
71 RelationKind, SpanData, Impl, ImplKind};
72 use rls_data::config::Config;
75 pub struct SaveContext<'l, 'tcx: 'l> {
76 tcx: TyCtxt<'l, 'tcx, 'tcx>,
77 tables: &'l ty::TypeckTables<'tcx>,
78 analysis: &'l ty::CrateAnalysis,
79 span_utils: SpanUtils<'tcx>,
81 impl_counter: Cell<u32>,
88 RelationData(Relation, Impl),
91 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
92 fn span_from_span(&self, span: Span) -> SpanData {
93 use rls_span::{Column, Row};
95 let cm = self.tcx.sess.codemap();
96 let start = cm.lookup_char_pos(span.lo());
97 let end = cm.lookup_char_pos(span.hi());
100 file_name: start.file.name.clone().to_string().into(),
101 byte_start: span.lo().0,
102 byte_end: span.hi().0,
103 line_start: Row::new_one_indexed(start.line as u32),
104 line_end: Row::new_one_indexed(end.line as u32),
105 column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
106 column_end: Column::new_one_indexed(end.col.0 as u32 + 1),
110 // List external crates used by the current crate.
111 pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
112 let mut result = Vec::new();
114 for &n in self.tcx.crates().iter() {
115 let span = match *self.tcx.extern_crate(n.as_def_id()) {
116 Some(ExternCrate { span, .. }) => span,
118 debug!("Skipping crate {}, no data", n);
122 let lo_loc = self.span_utils.sess.codemap().lookup_char_pos(span.lo());
123 result.push(ExternalCrateData {
124 // FIXME: change file_name field to PathBuf in rls-data
125 // https://github.com/nrc/rls-data/issues/7
126 file_name: SpanUtils::make_path_string(&lo_loc.file.name),
129 name: self.tcx.crate_name(n).to_string(),
130 disambiguator: self.tcx.crate_disambiguator(n).to_fingerprint().as_value(),
138 pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
139 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
141 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
142 let sub_span = self.span_utils
143 .sub_span_after_keyword(item.span, keywords::Fn);
144 filter!(self.span_utils, sub_span, item.span, None);
146 Some(Data::DefData(Def {
147 kind: DefKind::Function,
148 id: id_from_node_id(item.id, self),
149 span: self.span_from_span(sub_span.unwrap()),
150 name: item.ident.to_string(),
152 value: make_signature(decl, generics),
156 docs: self.docs_for_attrs(&item.attrs),
157 sig: sig::foreign_item_signature(item, self),
158 attributes: lower_attributes(item.attrs.clone(), self),
161 ast::ForeignItemKind::Static(ref ty, m) => {
162 let keyword = if m { keywords::Mut } else { keywords::Static };
163 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
164 filter!(self.span_utils, sub_span, item.span, None);
166 let id = ::id_from_node_id(item.id, self);
167 let span = self.span_from_span(sub_span.unwrap());
169 Some(Data::DefData(Def {
170 kind: DefKind::Static,
173 name: item.ident.to_string(),
175 value: ty_to_string(ty),
179 docs: self.docs_for_attrs(&item.attrs),
180 sig: sig::foreign_item_signature(item, self),
181 attributes: lower_attributes(item.attrs.clone(), self),
184 // FIXME(plietar): needs a new DefKind in rls-data
185 ast::ForeignItemKind::Ty => None,
186 ast::ForeignItemKind::Macro(..) => None,
190 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
192 ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
193 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
194 let sub_span = self.span_utils
195 .sub_span_after_keyword(item.span, keywords::Fn);
196 filter!(self.span_utils, sub_span, item.span, None);
197 Some(Data::DefData(Def {
198 kind: DefKind::Function,
199 id: id_from_node_id(item.id, self),
200 span: self.span_from_span(sub_span.unwrap()),
201 name: item.ident.to_string(),
203 value: make_signature(decl, generics),
207 docs: self.docs_for_attrs(&item.attrs),
208 sig: sig::item_signature(item, self),
209 attributes: lower_attributes(item.attrs.clone(), self),
212 ast::ItemKind::Static(ref typ, mt, _) => {
213 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
215 let keyword = match mt {
216 ast::Mutability::Mutable => keywords::Mut,
217 ast::Mutability::Immutable => keywords::Static,
220 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
221 filter!(self.span_utils, sub_span, item.span, None);
223 let id = id_from_node_id(item.id, self);
224 let span = self.span_from_span(sub_span.unwrap());
226 Some(Data::DefData(Def {
227 kind: DefKind::Static,
230 name: item.ident.to_string(),
232 value: ty_to_string(&typ),
236 docs: self.docs_for_attrs(&item.attrs),
237 sig: sig::item_signature(item, self),
238 attributes: lower_attributes(item.attrs.clone(), self),
241 ast::ItemKind::Const(ref typ, _) => {
242 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
243 let sub_span = self.span_utils
244 .sub_span_after_keyword(item.span, keywords::Const);
245 filter!(self.span_utils, sub_span, item.span, None);
247 let id = id_from_node_id(item.id, self);
248 let span = self.span_from_span(sub_span.unwrap());
250 Some(Data::DefData(Def {
251 kind: DefKind::Const,
254 name: item.ident.to_string(),
256 value: ty_to_string(typ),
260 docs: self.docs_for_attrs(&item.attrs),
261 sig: sig::item_signature(item, self),
262 attributes: lower_attributes(item.attrs.clone(), self),
265 ast::ItemKind::Mod(ref m) => {
266 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
268 let cm = self.tcx.sess.codemap();
269 let filename = cm.span_to_filename(m.inner);
271 let sub_span = self.span_utils
272 .sub_span_after_keyword(item.span, keywords::Mod);
273 filter!(self.span_utils, sub_span, item.span, None);
275 Some(Data::DefData(Def {
277 id: id_from_node_id(item.id, self),
278 name: item.ident.to_string(),
280 span: self.span_from_span(sub_span.unwrap()),
281 value: filename.to_string(),
285 .map(|i| id_from_node_id(i.id, self))
288 docs: self.docs_for_attrs(&item.attrs),
289 sig: sig::item_signature(item, self),
290 attributes: lower_attributes(item.attrs.clone(), self),
293 ast::ItemKind::Enum(ref def, _) => {
294 let name = item.ident.to_string();
295 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
296 let sub_span = self.span_utils
297 .sub_span_after_keyword(item.span, keywords::Enum);
298 filter!(self.span_utils, sub_span, item.span, None);
299 let variants_str = def.variants
301 .map(|v| v.node.ident.to_string())
304 let value = format!("{}::{{{}}}", name, variants_str);
305 Some(Data::DefData(Def {
307 id: id_from_node_id(item.id, self),
308 span: self.span_from_span(sub_span.unwrap()),
313 children: def.variants
315 .map(|v| id_from_node_id(v.node.data.id(), self))
318 docs: self.docs_for_attrs(&item.attrs),
319 sig: sig::item_signature(item, self),
320 attributes: lower_attributes(item.attrs.to_owned(), self),
323 ast::ItemKind::Impl(.., ref trait_ref, ref typ, ref impls) => {
324 if let ast::TyKind::Path(None, ref path) = typ.node {
325 // Common case impl for a struct or something basic.
326 if generated_code(path.span) {
329 let sub_span = self.span_utils.sub_span_for_type_name(path.span);
330 filter!(self.span_utils, sub_span, typ.span, None);
332 let impl_id = self.next_impl_id();
333 let span = self.span_from_span(sub_span.unwrap());
335 let type_data = self.lookup_ref_id(typ.id);
336 type_data.map(|type_data| {
337 Data::RelationData(Relation {
338 kind: RelationKind::Impl {
342 from: id_from_def_id(type_data),
345 .and_then(|t| self.lookup_ref_id(t.ref_id))
347 .unwrap_or(null_id()),
351 kind: match *trait_ref {
352 Some(_) => ImplKind::Direct,
353 None => ImplKind::Inherent,
356 value: String::new(),
360 .map(|i| id_from_node_id(i.id, self))
378 pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<Def> {
379 if let Some(ident) = field.ident {
380 let name = ident.to_string();
381 let qualname = format!("::{}::{}", self.tcx.node_path_str(scope), ident);
382 let sub_span = self.span_utils
383 .sub_span_before_token(field.span, token::Colon);
384 filter!(self.span_utils, sub_span, field.span, None);
385 let def_id = self.tcx.hir.local_def_id(field.id);
386 let typ = self.tcx.type_of(def_id).to_string();
389 let id = id_from_node_id(field.id, self);
390 let span = self.span_from_span(sub_span.unwrap());
393 kind: DefKind::Field,
399 parent: Some(id_from_node_id(scope, self)),
402 docs: self.docs_for_attrs(&field.attrs),
403 sig: sig::field_signature(field, self),
404 attributes: lower_attributes(field.attrs.clone(), self),
411 // FIXME would be nice to take a MethodItem here, but the ast provides both
412 // trait and impl flavours, so the caller must do the disassembly.
413 pub fn get_method_data(&self, id: ast::NodeId, name: ast::Name, span: Span) -> Option<Def> {
414 // The qualname for a method is the trait name or name of the struct in an impl in
415 // which the method is declared in, followed by the method's name.
416 let (qualname, parent_scope, decl_id, docs, attributes) =
417 match self.tcx.impl_of_method(self.tcx.hir.local_def_id(id)) {
418 Some(impl_id) => match self.tcx.hir.get_if_local(impl_id) {
419 Some(Node::NodeItem(item)) => match item.node {
420 hir::ItemImpl(.., ref ty, _) => {
421 let mut qualname = String::from("<");
422 qualname.push_str(&self.tcx.hir.node_to_pretty_string(ty.id));
424 let mut trait_id = self.tcx.trait_id_of_impl(impl_id);
425 let mut decl_id = None;
426 let mut docs = String::new();
427 let mut attrs = vec![];
428 if let Some(NodeImplItem(item)) = self.tcx.hir.find(id) {
429 docs = self.docs_for_attrs(&item.attrs);
430 attrs = item.attrs.to_vec();
433 if let Some(def_id) = trait_id {
434 // A method in a trait impl.
435 qualname.push_str(" as ");
436 qualname.push_str(&self.tcx.item_path_str(def_id));
438 .associated_items(def_id)
439 .find(|item| item.name == name)
440 .map(|item| decl_id = Some(item.def_id));
442 qualname.push_str(">");
444 (qualname, trait_id, decl_id, docs, attrs)
449 "Container {:?} for method {} not an impl?",
458 "Container {:?} for method {} is not a node item {:?}",
465 None => match self.tcx.trait_of_item(self.tcx.hir.local_def_id(id)) {
467 let mut docs = String::new();
468 let mut attrs = vec![];
470 if let Some(NodeTraitItem(item)) = self.tcx.hir.find(id) {
471 docs = self.docs_for_attrs(&item.attrs);
472 attrs = item.attrs.to_vec();
476 format!("::{}", self.tcx.item_path_str(def_id)),
484 debug!("Could not find container for method {} at {:?}", id, span);
485 // This is not necessarily a bug, if there was a compilation error,
486 // the tables we need might not exist.
492 let qualname = format!("{}::{}", qualname, name);
494 let sub_span = self.span_utils.sub_span_after_keyword(span, keywords::Fn);
495 filter!(self.span_utils, sub_span, span, None);
498 kind: DefKind::Method,
499 id: id_from_node_id(id, self),
500 span: self.span_from_span(sub_span.unwrap()),
501 name: name.to_string(),
503 // FIXME you get better data here by using the visitor.
504 value: String::new(),
505 parent: parent_scope.map(|id| id_from_def_id(id)),
507 decl_id: decl_id.map(|id| id_from_def_id(id)),
510 attributes: lower_attributes(attributes, self),
514 pub fn get_trait_ref_data(&self, trait_ref: &ast::TraitRef) -> Option<Ref> {
515 self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
516 let span = trait_ref.path.span;
517 if generated_code(span) {
520 let sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
521 filter!(self.span_utils, sub_span, span, None);
522 let span = self.span_from_span(sub_span.unwrap());
526 ref_id: id_from_def_id(def_id),
531 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
532 let hir_node = self.tcx.hir.expect_expr(expr.id);
533 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
534 if ty.is_none() || ty.unwrap().sty == ty::TyError {
538 ast::ExprKind::Field(ref sub_ex, ident) => {
539 let hir_node = match self.tcx.hir.find(sub_ex.id) {
540 Some(Node::NodeExpr(expr)) => expr,
543 "Missing or weird node for sub-expression {} in {:?}",
550 match self.tables.expr_ty_adjusted(&hir_node).sty {
551 ty::TyAdt(def, _) if !def.is_enum() => {
552 let variant = &def.non_enum_variant();
553 let index = self.tcx.find_field_index(ident, variant).unwrap();
554 let sub_span = self.span_utils.span_for_last_ident(expr.span);
555 filter!(self.span_utils, sub_span, expr.span, None);
556 let span = self.span_from_span(sub_span.unwrap());
557 return Some(Data::RefData(Ref {
558 kind: RefKind::Variable,
560 ref_id: id_from_def_id(variant.fields[index].did),
563 ty::TyTuple(..) => None,
565 debug!("Expected struct or union type, found {:?}", ty);
570 ast::ExprKind::Struct(ref path, ..) => {
571 match self.tables.expr_ty_adjusted(&hir_node).sty {
572 ty::TyAdt(def, _) if !def.is_enum() => {
573 let sub_span = self.span_utils.span_for_last_ident(path.span);
574 filter!(self.span_utils, sub_span, path.span, None);
575 let span = self.span_from_span(sub_span.unwrap());
576 Some(Data::RefData(Ref {
579 ref_id: id_from_def_id(def.did),
583 // FIXME ty could legitimately be an enum, but then we will fail
584 // later if we try to look up the fields.
585 debug!("expected struct or union, found {:?}", ty);
590 ast::ExprKind::MethodCall(ref seg, ..) => {
591 let expr_hir_id = self.tcx.hir.definitions().node_to_hir_id(expr.id);
592 let method_id = match self.tables.type_dependent_defs().get(expr_hir_id) {
593 Some(id) => id.def_id(),
595 debug!("Could not resolve method id for {:?}", expr);
599 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
600 ty::ImplContainer(_) => (Some(method_id), None),
601 ty::TraitContainer(_) => (None, Some(method_id)),
603 let sub_span = seg.ident.span;
604 filter!(self.span_utils, Some(sub_span), expr.span, None);
605 let span = self.span_from_span(sub_span);
606 Some(Data::RefData(Ref {
607 kind: RefKind::Function,
611 .map(|id| id_from_def_id(id))
612 .unwrap_or(null_id()),
615 ast::ExprKind::Path(_, ref path) => {
616 self.get_path_data(expr.id, path).map(|d| Data::RefData(d))
625 pub fn get_path_def(&self, id: NodeId) -> HirDef {
626 match self.tcx.hir.get(id) {
627 Node::NodeTraitRef(tr) => tr.path.def,
629 Node::NodeItem(&hir::Item {
630 node: hir::ItemUse(ref path, _),
633 Node::NodeVisibility(&hir::Visibility::Restricted { ref path, .. }) => path.def,
635 Node::NodeExpr(&hir::Expr {
636 node: hir::ExprStruct(ref qpath, ..),
639 Node::NodeExpr(&hir::Expr {
640 node: hir::ExprPath(ref qpath),
643 Node::NodePat(&hir::Pat {
644 node: hir::PatKind::Path(ref qpath),
647 Node::NodePat(&hir::Pat {
648 node: hir::PatKind::Struct(ref qpath, ..),
651 Node::NodePat(&hir::Pat {
652 node: hir::PatKind::TupleStruct(ref qpath, ..),
655 let hir_id = self.tcx.hir.node_to_hir_id(id);
656 self.tables.qpath_def(qpath, hir_id)
659 Node::NodeBinding(&hir::Pat {
660 node: hir::PatKind::Binding(_, canonical_id, ..),
662 }) => HirDef::Local(canonical_id),
664 Node::NodeTy(ty) => if let hir::Ty {
665 node: hir::TyPath(ref qpath),
670 hir::QPath::Resolved(_, ref path) => path.def,
671 hir::QPath::TypeRelative(..) => {
672 let ty = hir_ty_to_ty(self.tcx, ty);
673 if let ty::TyProjection(proj) = ty.sty {
674 return HirDef::AssociatedTy(proj.item_def_id);
687 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Ref> {
688 // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
689 fn fn_type(path: &ast::Path) -> bool {
690 if path.segments.len() != 1 {
693 if let Some(ref params) = path.segments[0].parameters {
694 if let ast::PathParameters::Parenthesized(_) = **params {
701 if path.segments.is_empty() {
705 let def = self.get_path_def(id);
706 let last_seg = &path.segments[path.segments.len() - 1];
707 let sub_span = last_seg.ident.span;
708 filter!(self.span_utils, Some(sub_span), path.span, None);
710 HirDef::Upvar(id, ..) | HirDef::Local(id) => {
711 let span = self.span_from_span(sub_span);
713 kind: RefKind::Variable,
715 ref_id: id_from_node_id(id, self),
720 HirDef::AssociatedConst(..) |
721 HirDef::VariantCtor(..) => {
722 let span = self.span_from_span(sub_span);
724 kind: RefKind::Variable,
726 ref_id: id_from_def_id(def.def_id()),
729 HirDef::Trait(def_id) if fn_type(path) => {
730 // Function type bounds are desugared in the parser, so we have to
731 // special case them here.
732 let fn_span = self.span_utils.span_for_first_ident(path.span);
736 span: self.span_from_span(span),
737 ref_id: id_from_def_id(def_id),
741 HirDef::Struct(def_id) |
742 HirDef::Variant(def_id, ..) |
743 HirDef::Union(def_id) |
744 HirDef::Enum(def_id) |
745 HirDef::TyAlias(def_id) |
746 HirDef::TyForeign(def_id) |
747 HirDef::TraitAlias(def_id) |
748 HirDef::AssociatedTy(def_id) |
749 HirDef::Trait(def_id) |
750 HirDef::TyParam(def_id) => {
751 let span = self.span_from_span(sub_span);
755 ref_id: id_from_def_id(def_id),
758 HirDef::StructCtor(def_id, _) => {
759 // This is a reference to a tuple struct where the def_id points
760 // to an invisible constructor function. That is not a very useful
761 // def, so adjust to point to the tuple struct itself.
762 let span = self.span_from_span(sub_span);
763 let parent_def_id = self.tcx.parent_def_id(def_id).unwrap();
767 ref_id: id_from_def_id(parent_def_id),
770 HirDef::Method(decl_id) => {
771 let def_id = if decl_id.is_local() {
772 let ti = self.tcx.associated_item(decl_id);
774 .associated_items(ti.container.id())
775 .find(|item| item.name == ti.name && item.defaultness.has_value())
776 .map(|item| item.def_id)
780 let span = self.span_from_span(sub_span);
782 kind: RefKind::Function,
784 ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
787 HirDef::Fn(def_id) => {
788 let span = self.span_from_span(sub_span);
790 kind: RefKind::Function,
792 ref_id: id_from_def_id(def_id),
795 HirDef::Mod(def_id) => {
796 let span = self.span_from_span(sub_span);
800 ref_id: id_from_def_id(def_id),
807 HirDef::GlobalAsm(..) |
812 pub fn get_field_ref_data(
814 field_ref: &ast::Field,
815 variant: &ty::VariantDef,
817 let index = self.tcx.find_field_index(field_ref.ident, variant).unwrap();
818 // We don't really need a sub-span here, but no harm done
819 let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
820 filter!(self.span_utils, sub_span, field_ref.ident.span, None);
821 let span = self.span_from_span(sub_span.unwrap());
823 kind: RefKind::Variable,
825 ref_id: id_from_def_id(variant.fields[index].did),
829 /// Attempt to return MacroRef for any AST node.
831 /// For a given piece of AST defined by the supplied Span and NodeId,
832 /// returns None if the node is not macro-generated or the span is malformed,
833 /// else uses the expansion callsite and callee to return some MacroRef.
834 pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
835 if !generated_code(span) {
838 // Note we take care to use the source callsite/callee, to handle
839 // nested expansions and ensure we only generate data for source-visible
841 let callsite = span.source_callsite();
842 let callsite_span = self.span_from_span(callsite);
843 let callee = span.source_callee()?;
844 let callee_span = callee.span?;
846 // Ignore attribute macros, their spans are usually mangled
847 if let MacroAttribute(_) = callee.format {
851 // If the callee is an imported macro from an external crate, need to get
852 // the source span and name from the session, as their spans are localized
853 // when read in, and no longer correspond to the source.
854 if let Some(mac) = self.tcx
856 .imported_macro_spans
860 let &(ref mac_name, mac_span) = mac;
861 let mac_span = self.span_from_span(mac_span);
862 return Some(MacroRef {
864 qualname: mac_name.clone(), // FIXME: generate the real qualname
865 callee_span: mac_span,
869 let callee_span = self.span_from_span(callee_span);
872 qualname: callee.name().to_string(), // FIXME: generate the real qualname
877 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
878 match self.get_path_def(ref_id) {
879 HirDef::PrimTy(_) | HirDef::SelfTy(..) | HirDef::Err => None,
880 def => Some(def.def_id()),
884 fn docs_for_attrs(&self, attrs: &[Attribute]) -> String {
885 let mut result = String::new();
888 if attr.check_name("doc") {
889 if let Some(val) = attr.value_str() {
890 if attr.is_sugared_doc {
891 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
893 result.push_str(&val.as_str());
896 } else if let Some(meta_list) = attr.meta_item_list() {
897 meta_list.into_iter()
898 .filter(|it| it.check_name("include"))
899 .filter_map(|it| it.meta_item_list().map(|l| l.to_owned()))
901 .filter(|meta| meta.check_name("contents"))
902 .filter_map(|meta| meta.value_str())
904 result.push_str(&val.as_str());
911 if !self.config.full_docs {
912 if let Some(index) = result.find("\n\n") {
913 result.truncate(index);
920 fn next_impl_id(&self) -> u32 {
921 let next = self.impl_counter.get();
922 self.impl_counter.set(next + 1);
927 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
928 let mut sig = "fn ".to_owned();
929 if !generics.params.is_empty() {
931 sig.push_str(&generics
934 .map(|param| match *param {
935 ast::GenericParam::Lifetime(ref l) => l.lifetime.ident.name.to_string(),
936 ast::GenericParam::Type(ref t) => t.ident.to_string(),
943 sig.push_str(&decl.inputs
950 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
951 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
957 // An AST visitor for collecting paths (e.g., the names of structs) and formal
958 // variables (idents) from patterns.
959 struct PathCollector<'l> {
960 collected_paths: Vec<(NodeId, &'l ast::Path)>,
961 collected_idents: Vec<(NodeId, ast::Ident, ast::Mutability)>,
964 impl<'l> PathCollector<'l> {
965 fn new() -> PathCollector<'l> {
967 collected_paths: vec![],
968 collected_idents: vec![],
973 impl<'l, 'a: 'l> Visitor<'a> for PathCollector<'l> {
974 fn visit_pat(&mut self, p: &'a ast::Pat) {
976 PatKind::Struct(ref path, ..) => {
977 self.collected_paths.push((p.id, path));
979 PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => {
980 self.collected_paths.push((p.id, path));
982 PatKind::Ident(bm, ident, _) => {
984 "PathCollector, visit ident in pat {}: {:?} {:?}",
989 let immut = match bm {
990 // Even if the ref is mut, you can't change the ref, only
991 // the data pointed at, so showing the initialising expression
992 // is still worthwhile.
993 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
994 ast::BindingMode::ByValue(mt) => mt,
996 self.collected_idents
997 .push((p.id, ident, immut));
1001 visit::walk_pat(self, p);
1005 /// Defines what to do with the results of saving the analysis.
1006 pub trait SaveHandler {
1009 save_ctxt: SaveContext<'l, 'tcx>,
1015 /// Dump the save-analysis results to a file.
1016 pub struct DumpHandler<'a> {
1017 odir: Option<&'a Path>,
1021 impl<'a> DumpHandler<'a> {
1022 pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
1025 cratename: cratename.to_owned(),
1029 fn output_file(&self, ctx: &SaveContext) -> File {
1030 let sess = &ctx.tcx.sess;
1031 let file_name = match ctx.config.output_file {
1032 Some(ref s) => PathBuf::from(s),
1034 let mut root_path = match self.odir {
1035 Some(val) => val.join("save-analysis"),
1036 None => PathBuf::from("save-analysis-temp"),
1039 if let Err(e) = std::fs::create_dir_all(&root_path) {
1040 error!("Could not create directory {}: {}", root_path.display(), e);
1043 let executable = sess.crate_types
1046 .any(|ct| *ct == CrateTypeExecutable);
1047 let mut out_name = if executable {
1052 out_name.push_str(&self.cratename);
1053 out_name.push_str(&sess.opts.cg.extra_filename);
1054 out_name.push_str(".json");
1055 root_path.push(&out_name);
1061 info!("Writing output to {}", file_name.display());
1063 let output_file = File::create(&file_name).unwrap_or_else(
1064 |e| sess.fatal(&format!("Could not open {}: {}", file_name.display(), e)),
1071 impl<'a> SaveHandler for DumpHandler<'a> {
1074 save_ctxt: SaveContext<'l, 'tcx>,
1078 let output = &mut self.output_file(&save_ctxt);
1079 let mut dumper = JsonDumper::new(output, save_ctxt.config.clone());
1080 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1082 visitor.dump_crate_info(cratename, krate);
1083 visit::walk_crate(&mut visitor, krate);
1087 /// Call a callback with the results of save-analysis.
1088 pub struct CallbackHandler<'b> {
1089 pub callback: &'b mut FnMut(&rls_data::Analysis),
1092 impl<'b> SaveHandler for CallbackHandler<'b> {
1095 save_ctxt: SaveContext<'l, 'tcx>,
1099 // We're using the JsonDumper here because it has the format of the
1100 // save-analysis results that we will pass to the callback. IOW, we are
1101 // using the JsonDumper to collect the save-analysis results, but not
1102 // actually to dump them to a file. This is all a bit convoluted and
1103 // there is certainly a simpler design here trying to get out (FIXME).
1104 let mut dumper = JsonDumper::with_callback(self.callback, save_ctxt.config.clone());
1105 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1107 visitor.dump_crate_info(cratename, krate);
1108 visit::walk_crate(&mut visitor, krate);
1112 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
1113 tcx: TyCtxt<'l, 'tcx, 'tcx>,
1115 analysis: &'l ty::CrateAnalysis,
1117 config: Option<Config>,
1120 tcx.dep_graph.with_ignore(|| {
1121 assert!(analysis.glob_map.is_some());
1123 info!("Dumping crate {}", cratename);
1125 let save_ctxt = SaveContext {
1127 tables: &ty::TypeckTables::empty(None),
1129 span_utils: SpanUtils::new(&tcx.sess),
1130 config: find_config(config),
1131 impl_counter: Cell::new(0),
1134 handler.save(save_ctxt, krate, cratename)
1138 fn find_config(supplied: Option<Config>) -> Config {
1139 if let Some(config) = supplied {
1142 match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
1143 Some(config_string) => rustc_serialize::json::decode(config_string.to_str().unwrap())
1144 .expect("Could not deserialize save-analysis config"),
1145 None => Config::default(),
1149 // Utility functions for the module.
1151 // Helper function to escape quotes in a string
1152 fn escape(s: String) -> String {
1153 s.replace("\"", "\"\"")
1156 // Helper function to determine if a span came from a
1157 // macro expansion or syntax extension.
1158 fn generated_code(span: Span) -> bool {
1159 span.ctxt() != NO_EXPANSION || span == DUMMY_SP
1162 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
1163 // we use our own Id which is the same, but without the newtype.
1164 fn id_from_def_id(id: DefId) -> rls_data::Id {
1166 krate: id.krate.as_u32(),
1167 index: id.index.as_raw_u32(),
1171 fn id_from_node_id(id: NodeId, scx: &SaveContext) -> rls_data::Id {
1172 let def_id = scx.tcx.hir.opt_local_def_id(id);
1173 def_id.map(|id| id_from_def_id(id)).unwrap_or_else(|| {
1174 // Create a *fake* `DefId` out of a `NodeId` by subtracting the `NodeId`
1175 // out of the maximum u32 value. This will work unless you have *billions*
1176 // of definitions in a single crate (very unlikely to actually happen).
1178 krate: LOCAL_CRATE.as_u32(),
1179 index: !id.as_u32(),
1184 fn null_id() -> rls_data::Id {
1186 krate: u32::max_value(),
1187 index: u32::max_value(),
1191 fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext) -> Vec<rls_data::Attribute> {
1193 // Only retain real attributes. Doc comments are lowered separately.
1194 .filter(|attr| attr.path != "doc")
1196 // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
1197 // attribute. First normalize all inner attribute (#![..]) to outer
1198 // ones (#[..]), then remove the two leading and the one trailing character.
1199 attr.style = ast::AttrStyle::Outer;
1200 let value = pprust::attribute_to_string(&attr);
1201 // This str slicing works correctly, because the leading and trailing characters
1202 // are in the ASCII range and thus exactly one byte each.
1203 let value = value[2..value.len()-1].to_string();
1205 rls_data::Attribute {
1207 span: scx.span_from_span(attr.span),