1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
4 #![recursion_limit="256"]
13 use rustc::hir::def::{CtorOf, Res, DefKind as HirDefKind};
15 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
16 use rustc::middle::privacy::AccessLevels;
17 use rustc::middle::cstore::ExternCrate;
18 use rustc::session::config::{CrateType, Input, OutputType};
19 use rustc::ty::{self, DefIdTree, TyCtxt};
20 use rustc::{bug, span_bug};
21 use rustc_codegen_utils::link::{filename_for_metadata, out_filename};
24 use std::default::Default;
27 use std::io::BufWriter;
28 use std::path::{Path, PathBuf};
30 use syntax::ast::{self, Attribute, DUMMY_NODE_ID, NodeId, PatKind};
31 use syntax::source_map::Spanned;
32 use syntax::parse::lexer::comments::strip_doc_comment_decoration;
33 use syntax::print::pprust;
34 use syntax::visit::{self, Visitor};
35 use syntax::print::pprust::{arg_to_string, ty_to_string};
38 use dump_visitor::DumpVisitor;
39 use span_utils::SpanUtils;
41 use rls_data::{Def, DefKind, ExternalCrateData, GlobalCrateId, MacroRef, Ref, RefKind, Relation,
42 RelationKind, SpanData, Impl, ImplKind, Analysis};
43 use rls_data::config::Config;
45 use log::{debug, error, info};
48 pub struct SaveContext<'l, 'tcx> {
50 tables: &'l ty::TypeckTables<'tcx>,
51 access_levels: &'l AccessLevels,
52 span_utils: SpanUtils<'tcx>,
54 impl_counter: Cell<u32>,
61 RelationData(Relation, Impl),
64 impl<'l, 'tcx> SaveContext<'l, 'tcx> {
65 fn span_from_span(&self, span: Span) -> SpanData {
66 use rls_span::{Column, Row};
68 let cm = self.tcx.sess.source_map();
69 let start = cm.lookup_char_pos(span.lo());
70 let end = cm.lookup_char_pos(span.hi());
73 file_name: start.file.name.to_string().into(),
74 byte_start: span.lo().0,
75 byte_end: span.hi().0,
76 line_start: Row::new_one_indexed(start.line as u32),
77 line_end: Row::new_one_indexed(end.line as u32),
78 column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
79 column_end: Column::new_one_indexed(end.col.0 as u32 + 1),
83 // Returns path to the compilation output (e.g., libfoo-12345678.rmeta)
84 pub fn compilation_output(&self, crate_name: &str) -> PathBuf {
85 let sess = &self.tcx.sess;
86 // Save-analysis is emitted per whole session, not per each crate type
87 let crate_type = sess.crate_types.borrow()[0];
88 let outputs = &*self.tcx.output_filenames(LOCAL_CRATE);
90 if outputs.outputs.contains_key(&OutputType::Metadata) {
91 filename_for_metadata(sess, crate_name, outputs)
92 } else if outputs.outputs.should_codegen() {
93 out_filename(sess, crate_type, outputs, crate_name)
95 // Otherwise it's only a DepInfo, in which case we return early and
96 // not even reach the analysis stage.
101 // List external crates used by the current crate.
102 pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
103 let mut result = Vec::with_capacity(self.tcx.crates().len());
105 for &n in self.tcx.crates().iter() {
106 let span = match self.tcx.extern_crate(n.as_def_id()) {
107 Some(&ExternCrate { span, .. }) => span,
109 debug!("skipping crate {}, no data", n);
113 let lo_loc = self.span_utils.sess.source_map().lookup_char_pos(span.lo());
114 result.push(ExternalCrateData {
115 // FIXME: change file_name field to PathBuf in rls-data
116 // https://github.com/nrc/rls-data/issues/7
117 file_name: self.span_utils.make_filename_string(&lo_loc.file),
120 name: self.tcx.crate_name(n).to_string(),
121 disambiguator: self.tcx.crate_disambiguator(n).to_fingerprint().as_value(),
129 pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
130 let qualname = format!("::{}",
131 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
133 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
134 filter!(self.span_utils, item.ident.span);
136 Some(Data::DefData(Def {
137 kind: DefKind::ForeignFunction,
138 id: id_from_node_id(item.id, self),
139 span: self.span_from_span(item.ident.span),
140 name: item.ident.to_string(),
142 value: make_signature(decl, generics),
146 docs: self.docs_for_attrs(&item.attrs),
147 sig: sig::foreign_item_signature(item, self),
148 attributes: lower_attributes(item.attrs.clone(), self),
151 ast::ForeignItemKind::Static(ref ty, _) => {
152 filter!(self.span_utils, item.ident.span);
154 let id = id_from_node_id(item.id, self);
155 let span = self.span_from_span(item.ident.span);
157 Some(Data::DefData(Def {
158 kind: DefKind::ForeignStatic,
161 name: item.ident.to_string(),
163 value: ty_to_string(ty),
167 docs: self.docs_for_attrs(&item.attrs),
168 sig: sig::foreign_item_signature(item, self),
169 attributes: lower_attributes(item.attrs.clone(), self),
172 // FIXME(plietar): needs a new DefKind in rls-data
173 ast::ForeignItemKind::Ty => None,
174 ast::ForeignItemKind::Macro(..) => None,
178 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
180 ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
181 let qualname = format!("::{}",
182 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
183 filter!(self.span_utils, item.ident.span);
184 Some(Data::DefData(Def {
185 kind: DefKind::Function,
186 id: id_from_node_id(item.id, self),
187 span: self.span_from_span(item.ident.span),
188 name: item.ident.to_string(),
190 value: make_signature(decl, generics),
194 docs: self.docs_for_attrs(&item.attrs),
195 sig: sig::item_signature(item, self),
196 attributes: lower_attributes(item.attrs.clone(), self),
199 ast::ItemKind::Static(ref typ, ..) => {
200 let qualname = format!("::{}",
201 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
203 filter!(self.span_utils, item.ident.span);
205 let id = id_from_node_id(item.id, self);
206 let span = self.span_from_span(item.ident.span);
208 Some(Data::DefData(Def {
209 kind: DefKind::Static,
212 name: item.ident.to_string(),
214 value: ty_to_string(&typ),
218 docs: self.docs_for_attrs(&item.attrs),
219 sig: sig::item_signature(item, self),
220 attributes: lower_attributes(item.attrs.clone(), self),
223 ast::ItemKind::Const(ref typ, _) => {
224 let qualname = format!("::{}",
225 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
226 filter!(self.span_utils, item.ident.span);
228 let id = id_from_node_id(item.id, self);
229 let span = self.span_from_span(item.ident.span);
231 Some(Data::DefData(Def {
232 kind: DefKind::Const,
235 name: item.ident.to_string(),
237 value: ty_to_string(typ),
241 docs: self.docs_for_attrs(&item.attrs),
242 sig: sig::item_signature(item, self),
243 attributes: lower_attributes(item.attrs.clone(), self),
246 ast::ItemKind::Mod(ref m) => {
247 let qualname = format!("::{}",
248 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
250 let cm = self.tcx.sess.source_map();
251 let filename = cm.span_to_filename(m.inner);
253 filter!(self.span_utils, item.ident.span);
255 Some(Data::DefData(Def {
257 id: id_from_node_id(item.id, self),
258 name: item.ident.to_string(),
260 span: self.span_from_span(item.ident.span),
261 value: filename.to_string(),
265 .map(|i| id_from_node_id(i.id, self))
268 docs: self.docs_for_attrs(&item.attrs),
269 sig: sig::item_signature(item, self),
270 attributes: lower_attributes(item.attrs.clone(), self),
273 ast::ItemKind::Enum(ref def, _) => {
274 let name = item.ident.to_string();
275 let qualname = format!("::{}",
276 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
277 filter!(self.span_utils, item.ident.span);
278 let variants_str = def.variants
280 .map(|v| v.node.ident.to_string())
283 let value = format!("{}::{{{}}}", name, variants_str);
284 Some(Data::DefData(Def {
286 id: id_from_node_id(item.id, self),
287 span: self.span_from_span(item.ident.span),
292 children: def.variants
294 .map(|v| id_from_node_id(v.node.id, self))
297 docs: self.docs_for_attrs(&item.attrs),
298 sig: sig::item_signature(item, self),
299 attributes: lower_attributes(item.attrs.clone(), self),
302 ast::ItemKind::Impl(.., ref trait_ref, ref typ, ref impls) => {
303 if let ast::TyKind::Path(None, ref path) = typ.node {
304 // Common case impl for a struct or something basic.
305 if generated_code(path.span) {
308 let sub_span = path.segments.last().unwrap().ident.span;
309 filter!(self.span_utils, sub_span);
311 let impl_id = self.next_impl_id();
312 let span = self.span_from_span(sub_span);
314 let type_data = self.lookup_ref_id(typ.id);
315 type_data.map(|type_data| {
316 Data::RelationData(Relation {
317 kind: RelationKind::Impl {
321 from: id_from_def_id(type_data),
324 .and_then(|t| self.lookup_ref_id(t.ref_id))
326 .unwrap_or_else(|| null_id()),
330 kind: match *trait_ref {
331 Some(_) => ImplKind::Direct,
332 None => ImplKind::Inherent,
335 value: String::new(),
339 .map(|i| id_from_node_id(i.id, self))
357 pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<Def> {
358 if let Some(ident) = field.ident {
359 let name = ident.to_string();
360 let qualname = format!("::{}::{}",
361 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(scope)),
363 filter!(self.span_utils, ident.span);
364 let def_id = self.tcx.hir().local_def_id_from_node_id(field.id);
365 let typ = self.tcx.type_of(def_id).to_string();
368 let id = id_from_node_id(field.id, self);
369 let span = self.span_from_span(ident.span);
372 kind: DefKind::Field,
378 parent: Some(id_from_node_id(scope, self)),
381 docs: self.docs_for_attrs(&field.attrs),
382 sig: sig::field_signature(field, self),
383 attributes: lower_attributes(field.attrs.clone(), self),
390 // FIXME would be nice to take a MethodItem here, but the ast provides both
391 // trait and impl flavours, so the caller must do the disassembly.
392 pub fn get_method_data(&self, id: ast::NodeId, ident: ast::Ident, span: Span) -> Option<Def> {
393 // The qualname for a method is the trait name or name of the struct in an impl in
394 // which the method is declared in, followed by the method's name.
395 let (qualname, parent_scope, decl_id, docs, attributes) =
396 match self.tcx.impl_of_method(self.tcx.hir().local_def_id_from_node_id(id)) {
397 Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) {
398 Some(Node::Item(item)) => match item.node {
399 hir::ItemKind::Impl(.., ref ty, _) => {
400 let mut qualname = String::from("<");
401 qualname.push_str(&self.tcx.hir().hir_to_pretty_string(ty.hir_id));
403 let trait_id = self.tcx.trait_id_of_impl(impl_id);
404 let mut decl_id = None;
405 let mut docs = String::new();
406 let mut attrs = vec![];
407 let hir_id = self.tcx.hir().node_to_hir_id(id);
408 if let Some(Node::ImplItem(item)) =
409 self.tcx.hir().find(hir_id)
411 docs = self.docs_for_attrs(&item.attrs);
412 attrs = item.attrs.to_vec();
415 if let Some(def_id) = trait_id {
416 // A method in a trait impl.
417 qualname.push_str(" as ");
418 qualname.push_str(&self.tcx.def_path_str(def_id));
420 .associated_items(def_id)
421 .find(|item| item.ident.name == ident.name)
422 .map(|item| decl_id = Some(item.def_id));
424 qualname.push_str(">");
426 (qualname, trait_id, decl_id, docs, attrs)
431 "Container {:?} for method {} not an impl?",
440 "Container {:?} for method {} is not a node item {:?}",
447 None => match self.tcx.trait_of_item(self.tcx.hir().local_def_id_from_node_id(id)) {
449 let mut docs = String::new();
450 let mut attrs = vec![];
451 let hir_id = self.tcx.hir().node_to_hir_id(id);
453 if let Some(Node::TraitItem(item)) = self.tcx.hir().find(hir_id) {
454 docs = self.docs_for_attrs(&item.attrs);
455 attrs = item.attrs.to_vec();
459 format!("::{}", self.tcx.def_path_str(def_id)),
467 debug!("could not find container for method {} at {:?}", id, span);
468 // This is not necessarily a bug, if there was a compilation error,
469 // the tables we need might not exist.
475 let qualname = format!("{}::{}", qualname, ident.name);
477 filter!(self.span_utils, ident.span);
480 kind: DefKind::Method,
481 id: id_from_node_id(id, self),
482 span: self.span_from_span(ident.span),
483 name: ident.name.to_string(),
485 // FIXME you get better data here by using the visitor.
486 value: String::new(),
487 parent: parent_scope.map(|id| id_from_def_id(id)),
489 decl_id: decl_id.map(|id| id_from_def_id(id)),
492 attributes: lower_attributes(attributes, self),
496 pub fn get_trait_ref_data(&self, trait_ref: &ast::TraitRef) -> Option<Ref> {
497 self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
498 let span = trait_ref.path.span;
499 if generated_code(span) {
502 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
503 filter!(self.span_utils, sub_span);
504 let span = self.span_from_span(sub_span);
508 ref_id: id_from_def_id(def_id),
513 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
514 let expr_hir_id = self.tcx.hir().node_to_hir_id(expr.id);
515 let hir_node = self.tcx.hir().expect_expr(expr_hir_id);
516 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
517 if ty.is_none() || ty.unwrap().sty == ty::Error {
521 ast::ExprKind::Field(ref sub_ex, ident) => {
522 let sub_ex_hir_id = self.tcx.hir().node_to_hir_id(sub_ex.id);
523 let hir_node = match self.tcx.hir().find(sub_ex_hir_id) {
524 Some(Node::Expr(expr)) => expr,
527 "Missing or weird node for sub-expression {} in {:?}",
534 match self.tables.expr_ty_adjusted(&hir_node).sty {
535 ty::Adt(def, _) if !def.is_enum() => {
536 let variant = &def.non_enum_variant();
537 let index = self.tcx.find_field_index(ident, variant).unwrap();
538 filter!(self.span_utils, ident.span);
539 let span = self.span_from_span(ident.span);
540 return Some(Data::RefData(Ref {
541 kind: RefKind::Variable,
543 ref_id: id_from_def_id(variant.fields[index].did),
546 ty::Tuple(..) => None,
548 debug!("expected struct or union type, found {:?}", ty);
553 ast::ExprKind::Struct(ref path, ..) => {
554 match self.tables.expr_ty_adjusted(&hir_node).sty {
555 ty::Adt(def, _) if !def.is_enum() => {
556 let sub_span = path.segments.last().unwrap().ident.span;
557 filter!(self.span_utils, sub_span);
558 let span = self.span_from_span(sub_span);
559 Some(Data::RefData(Ref {
562 ref_id: id_from_def_id(def.did),
566 // FIXME ty could legitimately be an enum, but then we will fail
567 // later if we try to look up the fields.
568 debug!("expected struct or union, found {:?}", ty);
573 ast::ExprKind::MethodCall(ref seg, ..) => {
574 let expr_hir_id = self.tcx.hir().definitions().node_to_hir_id(expr.id);
575 let method_id = match self.tables.type_dependent_def_id(expr_hir_id) {
578 debug!("could not resolve method id for {:?}", expr);
582 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
583 ty::ImplContainer(_) => (Some(method_id), None),
584 ty::TraitContainer(_) => (None, Some(method_id)),
586 let sub_span = seg.ident.span;
587 filter!(self.span_utils, sub_span);
588 let span = self.span_from_span(sub_span);
589 Some(Data::RefData(Ref {
590 kind: RefKind::Function,
594 .map(|id| id_from_def_id(id))
595 .unwrap_or_else(|| null_id()),
598 ast::ExprKind::Path(_, ref path) => {
599 self.get_path_data(expr.id, path).map(|d| Data::RefData(d))
608 pub fn get_path_res(&self, id: NodeId) -> Res {
609 let hir_id = self.tcx.hir().node_to_hir_id(id);
610 match self.tcx.hir().get(hir_id) {
611 Node::TraitRef(tr) => tr.path.res,
613 Node::Item(&hir::Item {
614 node: hir::ItemKind::Use(ref path, _),
617 Node::Visibility(&Spanned {
618 node: hir::VisibilityKind::Restricted { ref path, .. }, .. }) => path.res,
620 Node::PathSegment(seg) => {
622 Some(res) if res != Res::Err => res,
624 let parent_node = self.tcx.hir().get_parent_node(hir_id);
625 self.get_path_res(self.tcx.hir().hir_to_node_id(parent_node))
630 Node::Expr(&hir::Expr {
631 node: hir::ExprKind::Struct(ref qpath, ..),
634 self.tables.qpath_res(qpath, hir_id)
637 Node::Expr(&hir::Expr {
638 node: hir::ExprKind::Path(ref qpath),
641 Node::Pat(&hir::Pat {
642 node: hir::PatKind::Path(ref qpath),
645 Node::Pat(&hir::Pat {
646 node: hir::PatKind::Struct(ref qpath, ..),
649 Node::Pat(&hir::Pat {
650 node: hir::PatKind::TupleStruct(ref qpath, ..),
654 node: hir::TyKind::Path(ref qpath),
657 self.tables.qpath_res(qpath, hir_id)
660 Node::Binding(&hir::Pat {
661 node: hir::PatKind::Binding(_, canonical_id, ..),
663 }) => Res::Local(canonical_id),
669 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Ref> {
673 self.get_path_segment_data(seg)
674 .or_else(|| self.get_path_segment_data_with_id(seg, id))
678 pub fn get_path_segment_data(&self, path_seg: &ast::PathSegment) -> Option<Ref> {
679 self.get_path_segment_data_with_id(path_seg, path_seg.id)
682 fn get_path_segment_data_with_id(
684 path_seg: &ast::PathSegment,
687 // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
688 fn fn_type(seg: &ast::PathSegment) -> bool {
689 if let Some(ref generic_args) = seg.args {
690 if let ast::GenericArgs::Parenthesized(_) = **generic_args {
697 if id == DUMMY_NODE_ID {
701 let res = self.get_path_res(id);
702 let span = path_seg.ident.span;
703 filter!(self.span_utils, span);
704 let span = self.span_from_span(span);
709 kind: RefKind::Variable,
711 ref_id: id_from_node_id(self.tcx.hir().hir_to_node_id(id), self),
714 Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
718 ref_id: id_from_def_id(def_id),
721 Res::Def(HirDefKind::Struct, def_id) |
722 Res::Def(HirDefKind::Variant, def_id) |
723 Res::Def(HirDefKind::Union, def_id) |
724 Res::Def(HirDefKind::Enum, def_id) |
725 Res::Def(HirDefKind::TyAlias, def_id) |
726 Res::Def(HirDefKind::ForeignTy, def_id) |
727 Res::Def(HirDefKind::TraitAlias, def_id) |
728 Res::Def(HirDefKind::AssocExistential, def_id) |
729 Res::Def(HirDefKind::AssocTy, def_id) |
730 Res::Def(HirDefKind::Trait, def_id) |
731 Res::Def(HirDefKind::Existential, def_id) |
732 Res::Def(HirDefKind::TyParam, def_id) => {
736 ref_id: id_from_def_id(def_id),
739 Res::Def(HirDefKind::ConstParam, def_id) => {
741 kind: RefKind::Variable,
743 ref_id: id_from_def_id(def_id),
746 Res::Def(HirDefKind::Ctor(CtorOf::Struct, ..), def_id) => {
747 // This is a reference to a tuple struct where the def_id points
748 // to an invisible constructor function. That is not a very useful
749 // def, so adjust to point to the tuple struct itself.
750 let parent_def_id = self.tcx.parent(def_id).unwrap();
754 ref_id: id_from_def_id(parent_def_id),
757 Res::Def(HirDefKind::Static, _) |
758 Res::Def(HirDefKind::Const, _) |
759 Res::Def(HirDefKind::AssocConst, _) |
760 Res::Def(HirDefKind::Ctor(..), _) => {
762 kind: RefKind::Variable,
764 ref_id: id_from_def_id(res.def_id()),
767 Res::Def(HirDefKind::Method, decl_id) => {
768 let def_id = if decl_id.is_local() {
769 let ti = self.tcx.associated_item(decl_id);
771 .associated_items(ti.container.id())
772 .find(|item| item.ident.name == ti.ident.name &&
773 item.defaultness.has_value())
774 .map(|item| item.def_id)
779 kind: RefKind::Function,
781 ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
784 Res::Def(HirDefKind::Fn, def_id) => {
786 kind: RefKind::Function,
788 ref_id: id_from_def_id(def_id),
791 Res::Def(HirDefKind::Mod, def_id) => {
795 ref_id: id_from_def_id(def_id),
800 Res::Def(HirDefKind::Macro(..), _) |
802 Res::NonMacroAttr(..) |
808 pub fn get_field_ref_data(
810 field_ref: &ast::Field,
811 variant: &ty::VariantDef,
813 filter!(self.span_utils, field_ref.ident.span);
814 self.tcx.find_field_index(field_ref.ident, variant).map(|index| {
815 let span = self.span_from_span(field_ref.ident.span);
817 kind: RefKind::Variable,
819 ref_id: id_from_def_id(variant.fields[index].did),
824 /// Attempt to return MacroRef for any AST node.
826 /// For a given piece of AST defined by the supplied Span and NodeId,
827 /// returns `None` if the node is not macro-generated or the span is malformed,
828 /// else uses the expansion callsite and callee to return some MacroRef.
829 pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
830 if !generated_code(span) {
833 // Note we take care to use the source callsite/callee, to handle
834 // nested expansions and ensure we only generate data for source-visible
836 let callsite = span.source_callsite();
837 let callsite_span = self.span_from_span(callsite);
838 let callee = span.source_callee()?;
840 // Ignore attribute macros, their spans are usually mangled
841 if let ExpnKind::Macro(MacroKind::Attr, _) |
842 ExpnKind::Macro(MacroKind::Derive, _) = callee.kind {
846 // If the callee is an imported macro from an external crate, need to get
847 // the source span and name from the session, as their spans are localized
848 // when read in, and no longer correspond to the source.
849 if let Some(mac) = self.tcx
851 .imported_macro_spans
853 .get(&callee.def_site)
855 let &(ref mac_name, mac_span) = mac;
856 let mac_span = self.span_from_span(mac_span);
857 return Some(MacroRef {
859 qualname: mac_name.clone(), // FIXME: generate the real qualname
860 callee_span: mac_span,
864 let callee_span = self.span_from_span(callee.def_site);
867 qualname: callee.kind.descr().to_string(), // FIXME: generate the real qualname
872 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
873 match self.get_path_res(ref_id) {
874 Res::PrimTy(_) | Res::SelfTy(..) | Res::Err => None,
875 def => Some(def.def_id()),
879 fn docs_for_attrs(&self, attrs: &[Attribute]) -> String {
880 let mut result = String::new();
883 if attr.check_name(sym::doc) {
884 if let Some(val) = attr.value_str() {
885 if attr.is_sugared_doc {
886 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
888 result.push_str(&val.as_str());
891 } else if let Some(meta_list) = attr.meta_item_list() {
892 meta_list.into_iter()
893 .filter(|it| it.check_name(sym::include))
894 .filter_map(|it| it.meta_item_list().map(|l| l.to_owned()))
896 .filter(|meta| meta.check_name(sym::contents))
897 .filter_map(|meta| meta.value_str())
899 result.push_str(&val.as_str());
906 if !self.config.full_docs {
907 if let Some(index) = result.find("\n\n") {
908 result.truncate(index);
915 fn next_impl_id(&self) -> u32 {
916 let next = self.impl_counter.get();
917 self.impl_counter.set(next + 1);
922 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
923 let mut sig = "fn ".to_owned();
924 if !generics.params.is_empty() {
926 sig.push_str(&generics
929 .map(|param| param.ident.to_string())
935 sig.push_str(&decl.inputs
942 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
943 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
949 // An AST visitor for collecting paths (e.g., the names of structs) and formal
950 // variables (idents) from patterns.
951 struct PathCollector<'l> {
952 collected_paths: Vec<(NodeId, &'l ast::Path)>,
953 collected_idents: Vec<(NodeId, ast::Ident, ast::Mutability)>,
956 impl<'l> PathCollector<'l> {
957 fn new() -> PathCollector<'l> {
959 collected_paths: vec![],
960 collected_idents: vec![],
965 impl<'l> Visitor<'l> for PathCollector<'l> {
966 fn visit_pat(&mut self, p: &'l ast::Pat) {
968 PatKind::Struct(ref path, ..) => {
969 self.collected_paths.push((p.id, path));
971 PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => {
972 self.collected_paths.push((p.id, path));
974 PatKind::Ident(bm, ident, _) => {
976 "PathCollector, visit ident in pat {}: {:?} {:?}",
981 let immut = match bm {
982 // Even if the ref is mut, you can't change the ref, only
983 // the data pointed at, so showing the initialising expression
984 // is still worthwhile.
985 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
986 ast::BindingMode::ByValue(mt) => mt,
988 self.collected_idents
989 .push((p.id, ident, immut));
993 visit::walk_pat(self, p);
997 /// Defines what to do with the results of saving the analysis.
998 pub trait SaveHandler {
1001 save_ctxt: &SaveContext<'_, '_>,
1002 analysis: &Analysis,
1006 /// Dump the save-analysis results to a file.
1007 pub struct DumpHandler<'a> {
1008 odir: Option<&'a Path>,
1012 impl<'a> DumpHandler<'a> {
1013 pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
1016 cratename: cratename.to_owned(),
1020 fn output_file(&self, ctx: &SaveContext<'_, '_>) -> (BufWriter<File>, PathBuf) {
1021 let sess = &ctx.tcx.sess;
1022 let file_name = match ctx.config.output_file {
1023 Some(ref s) => PathBuf::from(s),
1025 let mut root_path = match self.odir {
1026 Some(val) => val.join("save-analysis"),
1027 None => PathBuf::from("save-analysis-temp"),
1030 if let Err(e) = std::fs::create_dir_all(&root_path) {
1031 error!("Could not create directory {}: {}", root_path.display(), e);
1034 let executable = sess.crate_types
1037 .any(|ct| *ct == CrateType::Executable);
1038 let mut out_name = if executable {
1043 out_name.push_str(&self.cratename);
1044 out_name.push_str(&sess.opts.cg.extra_filename);
1045 out_name.push_str(".json");
1046 root_path.push(&out_name);
1052 info!("Writing output to {}", file_name.display());
1054 let output_file = BufWriter::new(File::create(&file_name).unwrap_or_else(
1055 |e| sess.fatal(&format!("Could not open {}: {}", file_name.display(), e)),
1058 (output_file, file_name)
1062 impl SaveHandler for DumpHandler<'_> {
1065 save_ctxt: &SaveContext<'_, '_>,
1066 analysis: &Analysis,
1068 let sess = &save_ctxt.tcx.sess;
1069 let (output, file_name) = self.output_file(&save_ctxt);
1070 if let Err(e) = serde_json::to_writer(output, &analysis) {
1071 error!("Can't serialize save-analysis: {:?}", e);
1074 if sess.opts.json_artifact_notifications {
1075 sess.parse_sess.span_diagnostic
1076 .emit_artifact_notification(&file_name, "save-analysis");
1081 /// Call a callback with the results of save-analysis.
1082 pub struct CallbackHandler<'b> {
1083 pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
1086 impl SaveHandler for CallbackHandler<'_> {
1089 _: &SaveContext<'_, '_>,
1090 analysis: &Analysis,
1092 (self.callback)(analysis)
1096 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
1101 config: Option<Config>,
1104 tcx.dep_graph.with_ignore(|| {
1105 info!("Dumping crate {}", cratename);
1107 // Privacy checking requires and is done after type checking; use a
1108 // fallback in case the access levels couldn't have been correctly computed.
1109 let access_levels = match tcx.sess.compile_status() {
1110 Ok(..) => tcx.privacy_access_levels(LOCAL_CRATE),
1111 Err(..) => tcx.arena.alloc(AccessLevels::default()),
1114 let save_ctxt = SaveContext {
1116 tables: &ty::TypeckTables::empty(None),
1117 access_levels: &access_levels,
1118 span_utils: SpanUtils::new(&tcx.sess),
1119 config: find_config(config),
1120 impl_counter: Cell::new(0),
1123 let mut visitor = DumpVisitor::new(save_ctxt);
1125 visitor.dump_crate_info(cratename, krate);
1126 visitor.dump_compilation_options(input, cratename);
1127 visit::walk_crate(&mut visitor, krate);
1129 handler.save(&visitor.save_ctxt, &visitor.analysis())
1133 fn find_config(supplied: Option<Config>) -> Config {
1134 if let Some(config) = supplied {
1138 match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
1139 None => Config::default(),
1140 Some(config) => config.to_str()
1142 .map_err(|_| error!("`RUST_SAVE_ANALYSIS_CONFIG` isn't UTF-8"))
1143 .and_then(|cfg| serde_json::from_str(cfg)
1144 .map_err(|_| error!("Could not deserialize save-analysis config"))
1145 ).unwrap_or_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.is_dummy()
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_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_from_node_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 != sym::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),