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 #![cfg_attr(not(stage0), feature(nll))]
16 #![allow(unused_attributes)]
18 #![recursion_limit="256"]
25 extern crate rustc_data_structures;
26 extern crate rustc_serialize;
27 extern crate rustc_target;
28 extern crate rustc_typeck;
31 extern crate syntax_pos;
33 extern crate rls_data;
34 extern crate rls_span;
44 use rustc::hir::def::Def as HirDef;
45 use rustc::hir::map::{Node, NodeTraitItem, NodeImplItem};
46 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
47 use rustc::middle::cstore::ExternCrate;
48 use rustc::session::config::CrateType;
49 use rustc::ty::{self, TyCtxt};
50 use rustc_typeck::hir_ty_to_ty;
53 use std::default::Default;
56 use std::path::{Path, PathBuf};
58 use syntax::ast::{self, Attribute, NodeId, PatKind};
59 use syntax::codemap::Spanned;
60 use syntax::parse::lexer::comments::strip_doc_comment_decoration;
61 use syntax::parse::token;
62 use syntax::print::pprust;
63 use syntax::symbol::keywords;
64 use syntax::visit::{self, Visitor};
65 use syntax::print::pprust::{arg_to_string, ty_to_string};
66 use syntax::codemap::MacroAttribute;
69 use json_dumper::JsonDumper;
70 use dump_visitor::DumpVisitor;
71 use span_utils::SpanUtils;
73 use rls_data::{Def, DefKind, ExternalCrateData, GlobalCrateId, MacroRef, Ref, RefKind, Relation,
74 RelationKind, SpanData, Impl, ImplKind};
75 use rls_data::config::Config;
78 pub struct SaveContext<'l, 'tcx: 'l> {
79 tcx: TyCtxt<'l, 'tcx, 'tcx>,
80 tables: &'l ty::TypeckTables<'tcx>,
81 analysis: &'l ty::CrateAnalysis,
82 span_utils: SpanUtils<'tcx>,
84 impl_counter: Cell<u32>,
91 RelationData(Relation, Impl),
94 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
95 fn span_from_span(&self, span: Span) -> SpanData {
96 use rls_span::{Column, Row};
98 let cm = self.tcx.sess.codemap();
99 let start = cm.lookup_char_pos(span.lo());
100 let end = cm.lookup_char_pos(span.hi());
103 file_name: start.file.name.clone().to_string().into(),
104 byte_start: span.lo().0,
105 byte_end: span.hi().0,
106 line_start: Row::new_one_indexed(start.line as u32),
107 line_end: Row::new_one_indexed(end.line as u32),
108 column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
109 column_end: Column::new_one_indexed(end.col.0 as u32 + 1),
113 // List external crates used by the current crate.
114 pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
115 let mut result = Vec::new();
117 for &n in self.tcx.crates().iter() {
118 let span = match *self.tcx.extern_crate(n.as_def_id()) {
119 Some(ExternCrate { span, .. }) => span,
121 debug!("Skipping crate {}, no data", n);
125 let lo_loc = self.span_utils.sess.codemap().lookup_char_pos(span.lo());
126 result.push(ExternalCrateData {
127 // FIXME: change file_name field to PathBuf in rls-data
128 // https://github.com/nrc/rls-data/issues/7
129 file_name: self.span_utils.make_path_string(&lo_loc.file.name),
132 name: self.tcx.crate_name(n).to_string(),
133 disambiguator: self.tcx.crate_disambiguator(n).to_fingerprint().as_value(),
141 pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
142 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
144 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
145 let sub_span = self.span_utils
146 .sub_span_after_keyword(item.span, keywords::Fn);
147 filter!(self.span_utils, sub_span, item.span, None);
149 Some(Data::DefData(Def {
150 kind: DefKind::Function,
151 id: id_from_node_id(item.id, self),
152 span: self.span_from_span(sub_span.unwrap()),
153 name: item.ident.to_string(),
155 value: make_signature(decl, generics),
159 docs: self.docs_for_attrs(&item.attrs),
160 sig: sig::foreign_item_signature(item, self),
161 attributes: lower_attributes(item.attrs.clone(), self),
164 ast::ForeignItemKind::Static(ref ty, m) => {
165 let keyword = if m { keywords::Mut } else { keywords::Static };
166 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
167 filter!(self.span_utils, sub_span, item.span, None);
169 let id = ::id_from_node_id(item.id, self);
170 let span = self.span_from_span(sub_span.unwrap());
172 Some(Data::DefData(Def {
173 kind: DefKind::Static,
176 name: item.ident.to_string(),
178 value: ty_to_string(ty),
182 docs: self.docs_for_attrs(&item.attrs),
183 sig: sig::foreign_item_signature(item, self),
184 attributes: lower_attributes(item.attrs.clone(), self),
187 // FIXME(plietar): needs a new DefKind in rls-data
188 ast::ForeignItemKind::Ty => None,
189 ast::ForeignItemKind::Macro(..) => None,
193 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
195 ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
196 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
197 let sub_span = self.span_utils
198 .sub_span_after_keyword(item.span, keywords::Fn);
199 filter!(self.span_utils, sub_span, item.span, None);
200 Some(Data::DefData(Def {
201 kind: DefKind::Function,
202 id: id_from_node_id(item.id, self),
203 span: self.span_from_span(sub_span.unwrap()),
204 name: item.ident.to_string(),
206 value: make_signature(decl, generics),
210 docs: self.docs_for_attrs(&item.attrs),
211 sig: sig::item_signature(item, self),
212 attributes: lower_attributes(item.attrs.clone(), self),
215 ast::ItemKind::Static(ref typ, mt, _) => {
216 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
218 let keyword = match mt {
219 ast::Mutability::Mutable => keywords::Mut,
220 ast::Mutability::Immutable => keywords::Static,
223 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
224 filter!(self.span_utils, sub_span, item.span, None);
226 let id = id_from_node_id(item.id, self);
227 let span = self.span_from_span(sub_span.unwrap());
229 Some(Data::DefData(Def {
230 kind: DefKind::Static,
233 name: item.ident.to_string(),
235 value: ty_to_string(&typ),
239 docs: self.docs_for_attrs(&item.attrs),
240 sig: sig::item_signature(item, self),
241 attributes: lower_attributes(item.attrs.clone(), self),
244 ast::ItemKind::Const(ref typ, _) => {
245 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
246 let sub_span = self.span_utils
247 .sub_span_after_keyword(item.span, keywords::Const);
248 filter!(self.span_utils, sub_span, item.span, None);
250 let id = id_from_node_id(item.id, self);
251 let span = self.span_from_span(sub_span.unwrap());
253 Some(Data::DefData(Def {
254 kind: DefKind::Const,
257 name: item.ident.to_string(),
259 value: ty_to_string(typ),
263 docs: self.docs_for_attrs(&item.attrs),
264 sig: sig::item_signature(item, self),
265 attributes: lower_attributes(item.attrs.clone(), self),
268 ast::ItemKind::Mod(ref m) => {
269 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
271 let cm = self.tcx.sess.codemap();
272 let filename = cm.span_to_filename(m.inner);
274 let sub_span = self.span_utils
275 .sub_span_after_keyword(item.span, keywords::Mod);
276 filter!(self.span_utils, sub_span, item.span, None);
278 Some(Data::DefData(Def {
280 id: id_from_node_id(item.id, self),
281 name: item.ident.to_string(),
283 span: self.span_from_span(sub_span.unwrap()),
284 value: filename.to_string(),
288 .map(|i| id_from_node_id(i.id, self))
291 docs: self.docs_for_attrs(&item.attrs),
292 sig: sig::item_signature(item, self),
293 attributes: lower_attributes(item.attrs.clone(), self),
296 ast::ItemKind::Enum(ref def, _) => {
297 let name = item.ident.to_string();
298 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
299 let sub_span = self.span_utils
300 .sub_span_after_keyword(item.span, keywords::Enum);
301 filter!(self.span_utils, sub_span, item.span, None);
302 let variants_str = def.variants
304 .map(|v| v.node.ident.to_string())
307 let value = format!("{}::{{{}}}", name, variants_str);
308 Some(Data::DefData(Def {
310 id: id_from_node_id(item.id, self),
311 span: self.span_from_span(sub_span.unwrap()),
316 children: def.variants
318 .map(|v| id_from_node_id(v.node.data.id(), self))
321 docs: self.docs_for_attrs(&item.attrs),
322 sig: sig::item_signature(item, self),
323 attributes: lower_attributes(item.attrs.to_owned(), self),
326 ast::ItemKind::Impl(.., ref trait_ref, ref typ, ref impls) => {
327 if let ast::TyKind::Path(None, ref path) = typ.node {
328 // Common case impl for a struct or something basic.
329 if generated_code(path.span) {
332 let sub_span = self.span_utils.sub_span_for_type_name(path.span);
333 filter!(self.span_utils, sub_span, typ.span, None);
335 let impl_id = self.next_impl_id();
336 let span = self.span_from_span(sub_span.unwrap());
338 let type_data = self.lookup_ref_id(typ.id);
339 type_data.map(|type_data| {
340 Data::RelationData(Relation {
341 kind: RelationKind::Impl {
345 from: id_from_def_id(type_data),
348 .and_then(|t| self.lookup_ref_id(t.ref_id))
350 .unwrap_or(null_id()),
354 kind: match *trait_ref {
355 Some(_) => ImplKind::Direct,
356 None => ImplKind::Inherent,
359 value: String::new(),
363 .map(|i| id_from_node_id(i.id, self))
381 pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<Def> {
382 if let Some(ident) = field.ident {
383 let name = ident.to_string();
384 let qualname = format!("::{}::{}", self.tcx.node_path_str(scope), ident);
385 let sub_span = self.span_utils
386 .sub_span_before_token(field.span, token::Colon);
387 filter!(self.span_utils, sub_span, field.span, None);
388 let def_id = self.tcx.hir.local_def_id(field.id);
389 let typ = self.tcx.type_of(def_id).to_string();
392 let id = id_from_node_id(field.id, self);
393 let span = self.span_from_span(sub_span.unwrap());
396 kind: DefKind::Field,
402 parent: Some(id_from_node_id(scope, self)),
405 docs: self.docs_for_attrs(&field.attrs),
406 sig: sig::field_signature(field, self),
407 attributes: lower_attributes(field.attrs.clone(), self),
414 // FIXME would be nice to take a MethodItem here, but the ast provides both
415 // trait and impl flavours, so the caller must do the disassembly.
416 pub fn get_method_data(&self, id: ast::NodeId, name: ast::Name, span: Span) -> Option<Def> {
417 // The qualname for a method is the trait name or name of the struct in an impl in
418 // which the method is declared in, followed by the method's name.
419 let (qualname, parent_scope, decl_id, docs, attributes) =
420 match self.tcx.impl_of_method(self.tcx.hir.local_def_id(id)) {
421 Some(impl_id) => match self.tcx.hir.get_if_local(impl_id) {
422 Some(Node::NodeItem(item)) => match item.node {
423 hir::ItemKind::Impl(.., ref ty, _) => {
424 let mut qualname = String::from("<");
425 qualname.push_str(&self.tcx.hir.node_to_pretty_string(ty.id));
427 let trait_id = self.tcx.trait_id_of_impl(impl_id);
428 let mut decl_id = None;
429 let mut docs = String::new();
430 let mut attrs = vec![];
431 if let Some(NodeImplItem(item)) = self.tcx.hir.find(id) {
432 docs = self.docs_for_attrs(&item.attrs);
433 attrs = item.attrs.to_vec();
436 if let Some(def_id) = trait_id {
437 // A method in a trait impl.
438 qualname.push_str(" as ");
439 qualname.push_str(&self.tcx.item_path_str(def_id));
441 .associated_items(def_id)
442 .find(|item| item.ident.name == name)
443 .map(|item| decl_id = Some(item.def_id));
445 qualname.push_str(">");
447 (qualname, trait_id, decl_id, docs, attrs)
452 "Container {:?} for method {} not an impl?",
461 "Container {:?} for method {} is not a node item {:?}",
468 None => match self.tcx.trait_of_item(self.tcx.hir.local_def_id(id)) {
470 let mut docs = String::new();
471 let mut attrs = vec![];
473 if let Some(NodeTraitItem(item)) = self.tcx.hir.find(id) {
474 docs = self.docs_for_attrs(&item.attrs);
475 attrs = item.attrs.to_vec();
479 format!("::{}", self.tcx.item_path_str(def_id)),
487 debug!("Could not find container for method {} at {:?}", id, span);
488 // This is not necessarily a bug, if there was a compilation error,
489 // the tables we need might not exist.
495 let qualname = format!("{}::{}", qualname, name);
497 let sub_span = self.span_utils.sub_span_after_keyword(span, keywords::Fn);
498 filter!(self.span_utils, sub_span, span, None);
501 kind: DefKind::Method,
502 id: id_from_node_id(id, self),
503 span: self.span_from_span(sub_span.unwrap()),
504 name: name.to_string(),
506 // FIXME you get better data here by using the visitor.
507 value: String::new(),
508 parent: parent_scope.map(|id| id_from_def_id(id)),
510 decl_id: decl_id.map(|id| id_from_def_id(id)),
513 attributes: lower_attributes(attributes, self),
517 pub fn get_trait_ref_data(&self, trait_ref: &ast::TraitRef) -> Option<Ref> {
518 self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
519 let span = trait_ref.path.span;
520 if generated_code(span) {
523 let sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
524 filter!(self.span_utils, sub_span, span, None);
525 let span = self.span_from_span(sub_span.unwrap());
529 ref_id: id_from_def_id(def_id),
534 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
535 let hir_node = self.tcx.hir.expect_expr(expr.id);
536 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
537 if ty.is_none() || ty.unwrap().sty == ty::TyError {
541 ast::ExprKind::Field(ref sub_ex, ident) => {
542 let hir_node = match self.tcx.hir.find(sub_ex.id) {
543 Some(Node::NodeExpr(expr)) => expr,
546 "Missing or weird node for sub-expression {} in {:?}",
553 match self.tables.expr_ty_adjusted(&hir_node).sty {
554 ty::TyAdt(def, _) if !def.is_enum() => {
555 let variant = &def.non_enum_variant();
556 let index = self.tcx.find_field_index(ident, variant).unwrap();
557 let sub_span = self.span_utils.span_for_last_ident(expr.span);
558 filter!(self.span_utils, sub_span, expr.span, None);
559 let span = self.span_from_span(sub_span.unwrap());
560 return Some(Data::RefData(Ref {
561 kind: RefKind::Variable,
563 ref_id: id_from_def_id(variant.fields[index].did),
566 ty::TyTuple(..) => None,
568 debug!("Expected struct or union type, found {:?}", ty);
573 ast::ExprKind::Struct(ref path, ..) => {
574 match self.tables.expr_ty_adjusted(&hir_node).sty {
575 ty::TyAdt(def, _) if !def.is_enum() => {
576 let sub_span = self.span_utils.span_for_last_ident(path.span);
577 filter!(self.span_utils, sub_span, path.span, None);
578 let span = self.span_from_span(sub_span.unwrap());
579 Some(Data::RefData(Ref {
582 ref_id: id_from_def_id(def.did),
586 // FIXME ty could legitimately be an enum, but then we will fail
587 // later if we try to look up the fields.
588 debug!("expected struct or union, found {:?}", ty);
593 ast::ExprKind::MethodCall(ref seg, ..) => {
594 let expr_hir_id = self.tcx.hir.definitions().node_to_hir_id(expr.id);
595 let method_id = match self.tables.type_dependent_defs().get(expr_hir_id) {
596 Some(id) => id.def_id(),
598 debug!("Could not resolve method id for {:?}", expr);
602 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
603 ty::ImplContainer(_) => (Some(method_id), None),
604 ty::TraitContainer(_) => (None, Some(method_id)),
606 let sub_span = seg.ident.span;
607 filter!(self.span_utils, Some(sub_span), expr.span, None);
608 let span = self.span_from_span(sub_span);
609 Some(Data::RefData(Ref {
610 kind: RefKind::Function,
614 .map(|id| id_from_def_id(id))
615 .unwrap_or(null_id()),
618 ast::ExprKind::Path(_, ref path) => {
619 self.get_path_data(expr.id, path).map(|d| Data::RefData(d))
628 pub fn get_path_def(&self, id: NodeId) -> HirDef {
629 match self.tcx.hir.get(id) {
630 Node::NodeTraitRef(tr) => tr.path.def,
632 Node::NodeItem(&hir::Item {
633 node: hir::ItemKind::Use(ref path, _),
636 Node::NodeVisibility(&Spanned {
637 node: hir::VisibilityKind::Restricted { ref path, .. }, .. }) => path.def,
639 Node::NodeExpr(&hir::Expr {
640 node: hir::ExprKind::Struct(ref qpath, ..),
643 Node::NodeExpr(&hir::Expr {
644 node: hir::ExprKind::Path(ref qpath),
647 Node::NodePat(&hir::Pat {
648 node: hir::PatKind::Path(ref qpath),
651 Node::NodePat(&hir::Pat {
652 node: hir::PatKind::Struct(ref qpath, ..),
655 Node::NodePat(&hir::Pat {
656 node: hir::PatKind::TupleStruct(ref qpath, ..),
659 let hir_id = self.tcx.hir.node_to_hir_id(id);
660 self.tables.qpath_def(qpath, hir_id)
663 Node::NodeBinding(&hir::Pat {
664 node: hir::PatKind::Binding(_, canonical_id, ..),
666 }) => HirDef::Local(canonical_id),
668 Node::NodeTy(ty) => if let hir::Ty {
669 node: hir::TyKind::Path(ref qpath),
674 hir::QPath::Resolved(_, ref path) => path.def,
675 hir::QPath::TypeRelative(..) => {
676 let ty = hir_ty_to_ty(self.tcx, ty);
677 if let ty::TyProjection(proj) = ty.sty {
678 return HirDef::AssociatedTy(proj.item_def_id);
691 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Ref> {
692 // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
693 fn fn_type(path: &ast::Path) -> bool {
694 if path.segments.len() != 1 {
697 if let Some(ref generic_args) = path.segments[0].args {
698 if let ast::GenericArgs::Parenthesized(_) = **generic_args {
705 if path.segments.is_empty() {
709 let def = self.get_path_def(id);
710 let last_seg = &path.segments[path.segments.len() - 1];
711 let sub_span = last_seg.ident.span;
712 filter!(self.span_utils, Some(sub_span), path.span, None);
714 HirDef::Upvar(id, ..) | HirDef::Local(id) => {
715 let span = self.span_from_span(sub_span);
717 kind: RefKind::Variable,
719 ref_id: id_from_node_id(id, self),
724 HirDef::AssociatedConst(..) |
725 HirDef::VariantCtor(..) => {
726 let span = self.span_from_span(sub_span);
728 kind: RefKind::Variable,
730 ref_id: id_from_def_id(def.def_id()),
733 HirDef::Trait(def_id) if fn_type(path) => {
734 // Function type bounds are desugared in the parser, so we have to
735 // special case them here.
736 let fn_span = self.span_utils.span_for_first_ident(path.span);
740 span: self.span_from_span(span),
741 ref_id: id_from_def_id(def_id),
745 HirDef::Struct(def_id) |
746 HirDef::Variant(def_id, ..) |
747 HirDef::Union(def_id) |
748 HirDef::Enum(def_id) |
749 HirDef::TyAlias(def_id) |
750 HirDef::TyForeign(def_id) |
751 HirDef::TraitAlias(def_id) |
752 HirDef::AssociatedExistential(def_id) |
753 HirDef::AssociatedTy(def_id) |
754 HirDef::Trait(def_id) |
755 HirDef::Existential(def_id) |
756 HirDef::TyParam(def_id) => {
757 let span = self.span_from_span(sub_span);
761 ref_id: id_from_def_id(def_id),
764 HirDef::StructCtor(def_id, _) => {
765 // This is a reference to a tuple struct where the def_id points
766 // to an invisible constructor function. That is not a very useful
767 // def, so adjust to point to the tuple struct itself.
768 let span = self.span_from_span(sub_span);
769 let parent_def_id = self.tcx.parent_def_id(def_id).unwrap();
773 ref_id: id_from_def_id(parent_def_id),
776 HirDef::Method(decl_id) => {
777 let def_id = if decl_id.is_local() {
778 let ti = self.tcx.associated_item(decl_id);
780 .associated_items(ti.container.id())
781 .find(|item| item.ident.name == ti.ident.name &&
782 item.defaultness.has_value())
783 .map(|item| item.def_id)
787 let span = self.span_from_span(sub_span);
789 kind: RefKind::Function,
791 ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
794 HirDef::Fn(def_id) => {
795 let span = self.span_from_span(sub_span);
797 kind: RefKind::Function,
799 ref_id: id_from_def_id(def_id),
802 HirDef::Mod(def_id) => {
803 let span = self.span_from_span(sub_span);
807 ref_id: id_from_def_id(def_id),
815 HirDef::NonMacroAttr(..) |
820 pub fn get_field_ref_data(
822 field_ref: &ast::Field,
823 variant: &ty::VariantDef,
825 let index = self.tcx.find_field_index(field_ref.ident, variant).unwrap();
826 // We don't really need a sub-span here, but no harm done
827 let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
828 filter!(self.span_utils, sub_span, field_ref.ident.span, None);
829 let span = self.span_from_span(sub_span.unwrap());
831 kind: RefKind::Variable,
833 ref_id: id_from_def_id(variant.fields[index].did),
837 /// Attempt to return MacroRef for any AST node.
839 /// For a given piece of AST defined by the supplied Span and NodeId,
840 /// returns None if the node is not macro-generated or the span is malformed,
841 /// else uses the expansion callsite and callee to return some MacroRef.
842 pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
843 if !generated_code(span) {
846 // Note we take care to use the source callsite/callee, to handle
847 // nested expansions and ensure we only generate data for source-visible
849 let callsite = span.source_callsite();
850 let callsite_span = self.span_from_span(callsite);
851 let callee = span.source_callee()?;
852 let callee_span = callee.def_site?;
854 // Ignore attribute macros, their spans are usually mangled
855 if let MacroAttribute(_) = callee.format {
859 // If the callee is an imported macro from an external crate, need to get
860 // the source span and name from the session, as their spans are localized
861 // when read in, and no longer correspond to the source.
862 if let Some(mac) = self.tcx
864 .imported_macro_spans
868 let &(ref mac_name, mac_span) = mac;
869 let mac_span = self.span_from_span(mac_span);
870 return Some(MacroRef {
872 qualname: mac_name.clone(), // FIXME: generate the real qualname
873 callee_span: mac_span,
877 let callee_span = self.span_from_span(callee_span);
880 qualname: callee.format.name().to_string(), // FIXME: generate the real qualname
885 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
886 match self.get_path_def(ref_id) {
887 HirDef::PrimTy(_) | HirDef::SelfTy(..) | HirDef::Err => None,
888 def => Some(def.def_id()),
892 fn docs_for_attrs(&self, attrs: &[Attribute]) -> String {
893 let mut result = String::new();
896 if attr.check_name("doc") {
897 if let Some(val) = attr.value_str() {
898 if attr.is_sugared_doc {
899 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
901 result.push_str(&val.as_str());
904 } else if let Some(meta_list) = attr.meta_item_list() {
905 meta_list.into_iter()
906 .filter(|it| it.check_name("include"))
907 .filter_map(|it| it.meta_item_list().map(|l| l.to_owned()))
909 .filter(|meta| meta.check_name("contents"))
910 .filter_map(|meta| meta.value_str())
912 result.push_str(&val.as_str());
919 if !self.config.full_docs {
920 if let Some(index) = result.find("\n\n") {
921 result.truncate(index);
928 fn next_impl_id(&self) -> u32 {
929 let next = self.impl_counter.get();
930 self.impl_counter.set(next + 1);
935 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
936 let mut sig = "fn ".to_owned();
937 if !generics.params.is_empty() {
939 sig.push_str(&generics
942 .map(|param| param.ident.to_string())
948 sig.push_str(&decl.inputs
955 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
956 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
962 // An AST visitor for collecting paths (e.g., the names of structs) and formal
963 // variables (idents) from patterns.
964 struct PathCollector<'l> {
965 collected_paths: Vec<(NodeId, &'l ast::Path)>,
966 collected_idents: Vec<(NodeId, ast::Ident, ast::Mutability)>,
969 impl<'l> PathCollector<'l> {
970 fn new() -> PathCollector<'l> {
972 collected_paths: vec![],
973 collected_idents: vec![],
978 impl<'l, 'a: 'l> Visitor<'a> for PathCollector<'l> {
979 fn visit_pat(&mut self, p: &'a ast::Pat) {
981 PatKind::Struct(ref path, ..) => {
982 self.collected_paths.push((p.id, path));
984 PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => {
985 self.collected_paths.push((p.id, path));
987 PatKind::Ident(bm, ident, _) => {
989 "PathCollector, visit ident in pat {}: {:?} {:?}",
994 let immut = match bm {
995 // Even if the ref is mut, you can't change the ref, only
996 // the data pointed at, so showing the initialising expression
997 // is still worthwhile.
998 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
999 ast::BindingMode::ByValue(mt) => mt,
1001 self.collected_idents
1002 .push((p.id, ident, immut));
1006 visit::walk_pat(self, p);
1010 /// Defines what to do with the results of saving the analysis.
1011 pub trait SaveHandler {
1014 save_ctxt: SaveContext<'l, 'tcx>,
1020 /// Dump the save-analysis results to a file.
1021 pub struct DumpHandler<'a> {
1022 odir: Option<&'a Path>,
1026 impl<'a> DumpHandler<'a> {
1027 pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
1030 cratename: cratename.to_owned(),
1034 fn output_file(&self, ctx: &SaveContext) -> File {
1035 let sess = &ctx.tcx.sess;
1036 let file_name = match ctx.config.output_file {
1037 Some(ref s) => PathBuf::from(s),
1039 let mut root_path = match self.odir {
1040 Some(val) => val.join("save-analysis"),
1041 None => PathBuf::from("save-analysis-temp"),
1044 if let Err(e) = std::fs::create_dir_all(&root_path) {
1045 error!("Could not create directory {}: {}", root_path.display(), e);
1048 let executable = sess.crate_types
1051 .any(|ct| *ct == CrateType::Executable);
1052 let mut out_name = if executable {
1057 out_name.push_str(&self.cratename);
1058 out_name.push_str(&sess.opts.cg.extra_filename);
1059 out_name.push_str(".json");
1060 root_path.push(&out_name);
1066 info!("Writing output to {}", file_name.display());
1068 let output_file = File::create(&file_name).unwrap_or_else(
1069 |e| sess.fatal(&format!("Could not open {}: {}", file_name.display(), e)),
1076 impl<'a> SaveHandler for DumpHandler<'a> {
1079 save_ctxt: SaveContext<'l, 'tcx>,
1083 let output = &mut self.output_file(&save_ctxt);
1084 let mut dumper = JsonDumper::new(output, save_ctxt.config.clone());
1085 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1087 visitor.dump_crate_info(cratename, krate);
1088 visit::walk_crate(&mut visitor, krate);
1092 /// Call a callback with the results of save-analysis.
1093 pub struct CallbackHandler<'b> {
1094 pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
1097 impl<'b> SaveHandler for CallbackHandler<'b> {
1100 save_ctxt: SaveContext<'l, 'tcx>,
1104 // We're using the JsonDumper here because it has the format of the
1105 // save-analysis results that we will pass to the callback. IOW, we are
1106 // using the JsonDumper to collect the save-analysis results, but not
1107 // actually to dump them to a file. This is all a bit convoluted and
1108 // there is certainly a simpler design here trying to get out (FIXME).
1109 let mut dumper = JsonDumper::with_callback(self.callback, save_ctxt.config.clone());
1110 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1112 visitor.dump_crate_info(cratename, krate);
1113 visit::walk_crate(&mut visitor, krate);
1117 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
1118 tcx: TyCtxt<'l, 'tcx, 'tcx>,
1120 analysis: &'l ty::CrateAnalysis,
1122 config: Option<Config>,
1125 tcx.dep_graph.with_ignore(|| {
1126 assert!(analysis.glob_map.is_some());
1128 info!("Dumping crate {}", cratename);
1130 let save_ctxt = SaveContext {
1132 tables: &ty::TypeckTables::empty(None),
1134 span_utils: SpanUtils::new(&tcx.sess),
1135 config: find_config(config),
1136 impl_counter: Cell::new(0),
1139 handler.save(save_ctxt, krate, cratename)
1143 fn find_config(supplied: Option<Config>) -> Config {
1144 if let Some(config) = supplied {
1147 match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
1148 Some(config_string) => rustc_serialize::json::decode(config_string.to_str().unwrap())
1149 .expect("Could not deserialize save-analysis config"),
1150 None => Config::default(),
1154 // Utility functions for the module.
1156 // Helper function to escape quotes in a string
1157 fn escape(s: String) -> String {
1158 s.replace("\"", "\"\"")
1161 // Helper function to determine if a span came from a
1162 // macro expansion or syntax extension.
1163 fn generated_code(span: Span) -> bool {
1164 span.ctxt() != NO_EXPANSION || span.is_dummy()
1167 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
1168 // we use our own Id which is the same, but without the newtype.
1169 fn id_from_def_id(id: DefId) -> rls_data::Id {
1171 krate: id.krate.as_u32(),
1172 index: id.index.as_raw_u32(),
1176 fn id_from_node_id(id: NodeId, scx: &SaveContext) -> rls_data::Id {
1177 let def_id = scx.tcx.hir.opt_local_def_id(id);
1178 def_id.map(|id| id_from_def_id(id)).unwrap_or_else(|| {
1179 // Create a *fake* `DefId` out of a `NodeId` by subtracting the `NodeId`
1180 // out of the maximum u32 value. This will work unless you have *billions*
1181 // of definitions in a single crate (very unlikely to actually happen).
1183 krate: LOCAL_CRATE.as_u32(),
1184 index: !id.as_u32(),
1189 fn null_id() -> rls_data::Id {
1191 krate: u32::max_value(),
1192 index: u32::max_value(),
1196 fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext) -> Vec<rls_data::Attribute> {
1198 // Only retain real attributes. Doc comments are lowered separately.
1199 .filter(|attr| attr.path != "doc")
1201 // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
1202 // attribute. First normalize all inner attribute (#![..]) to outer
1203 // ones (#[..]), then remove the two leading and the one trailing character.
1204 attr.style = ast::AttrStyle::Outer;
1205 let value = pprust::attribute_to_string(&attr);
1206 // This str slicing works correctly, because the leading and trailing characters
1207 // are in the ASCII range and thus exactly one byte each.
1208 let value = value[2..value.len()-1].to_string();
1210 rls_data::Attribute {
1212 span: scx.span_from_span(attr.span),