1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
3 #![feature(inner_deref)]
5 #![recursion_limit="256"]
14 use rustc::hir::def::{CtorOf, Res, DefKind as HirDefKind};
16 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
17 use rustc::middle::privacy::AccessLevels;
18 use rustc::middle::cstore::ExternCrate;
19 use rustc::session::config::{CrateType, Input, OutputType};
20 use rustc::ty::{self, DefIdTree, TyCtxt};
21 use rustc::{bug, span_bug};
22 use rustc_codegen_utils::link::{filename_for_metadata, out_filename};
25 use std::default::Default;
28 use std::io::BufWriter;
29 use std::path::{Path, PathBuf};
31 use syntax::ast::{self, Attribute, DUMMY_NODE_ID, NodeId, PatKind};
32 use syntax::source_map::Spanned;
33 use syntax::parse::lexer::comments::strip_doc_comment_decoration;
34 use syntax::print::pprust;
35 use syntax::visit::{self, Visitor};
36 use syntax::print::pprust::{param_to_string, ty_to_string};
39 use dump_visitor::DumpVisitor;
40 use span_utils::SpanUtils;
42 use rls_data::{Def, DefKind, ExternalCrateData, GlobalCrateId, MacroRef, Ref, RefKind, Relation,
43 RelationKind, SpanData, Impl, ImplKind, Analysis};
44 use rls_data::config::Config;
46 use log::{debug, error, info};
49 pub struct SaveContext<'l, 'tcx> {
51 tables: &'l ty::TypeckTables<'tcx>,
52 access_levels: &'l AccessLevels,
53 span_utils: SpanUtils<'tcx>,
55 impl_counter: Cell<u32>,
62 RelationData(Relation, Impl),
65 impl<'l, 'tcx> SaveContext<'l, 'tcx> {
66 fn span_from_span(&self, span: Span) -> SpanData {
67 use rls_span::{Column, Row};
69 let cm = self.tcx.sess.source_map();
70 let start = cm.lookup_char_pos(span.lo());
71 let end = cm.lookup_char_pos(span.hi());
74 file_name: start.file.name.to_string().into(),
75 byte_start: span.lo().0,
76 byte_end: span.hi().0,
77 line_start: Row::new_one_indexed(start.line as u32),
78 line_end: Row::new_one_indexed(end.line as u32),
79 column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
80 column_end: Column::new_one_indexed(end.col.0 as u32 + 1),
84 // Returns path to the compilation output (e.g., libfoo-12345678.rmeta)
85 pub fn compilation_output(&self, crate_name: &str) -> PathBuf {
86 let sess = &self.tcx.sess;
87 // Save-analysis is emitted per whole session, not per each crate type
88 let crate_type = sess.crate_types.borrow()[0];
89 let outputs = &*self.tcx.output_filenames(LOCAL_CRATE);
91 if outputs.outputs.contains_key(&OutputType::Metadata) {
92 filename_for_metadata(sess, crate_name, outputs)
93 } else if outputs.outputs.should_codegen() {
94 out_filename(sess, crate_type, outputs, crate_name)
96 // Otherwise it's only a DepInfo, in which case we return early and
97 // not even reach the analysis stage.
102 // List external crates used by the current crate.
103 pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
104 let mut result = Vec::with_capacity(self.tcx.crates().len());
106 for &n in self.tcx.crates().iter() {
107 let span = match self.tcx.extern_crate(n.as_def_id()) {
108 Some(&ExternCrate { span, .. }) => span,
110 debug!("skipping crate {}, no data", n);
114 let lo_loc = self.span_utils.sess.source_map().lookup_char_pos(span.lo());
115 result.push(ExternalCrateData {
116 // FIXME: change file_name field to PathBuf in rls-data
117 // https://github.com/nrc/rls-data/issues/7
118 file_name: self.span_utils.make_filename_string(&lo_loc.file),
121 name: self.tcx.crate_name(n).to_string(),
122 disambiguator: self.tcx.crate_disambiguator(n).to_fingerprint().as_value(),
130 pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
131 let qualname = format!("::{}",
132 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
134 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
135 filter!(self.span_utils, item.ident.span);
137 Some(Data::DefData(Def {
138 kind: DefKind::ForeignFunction,
139 id: id_from_node_id(item.id, self),
140 span: self.span_from_span(item.ident.span),
141 name: item.ident.to_string(),
143 value: make_signature(decl, generics),
147 docs: self.docs_for_attrs(&item.attrs),
148 sig: sig::foreign_item_signature(item, self),
149 attributes: lower_attributes(item.attrs.clone(), self),
152 ast::ForeignItemKind::Static(ref ty, _) => {
153 filter!(self.span_utils, item.ident.span);
155 let id = id_from_node_id(item.id, self);
156 let span = self.span_from_span(item.ident.span);
158 Some(Data::DefData(Def {
159 kind: DefKind::ForeignStatic,
162 name: item.ident.to_string(),
164 value: ty_to_string(ty),
168 docs: self.docs_for_attrs(&item.attrs),
169 sig: sig::foreign_item_signature(item, self),
170 attributes: lower_attributes(item.attrs.clone(), self),
173 // FIXME(plietar): needs a new DefKind in rls-data
174 ast::ForeignItemKind::Ty => None,
175 ast::ForeignItemKind::Macro(..) => None,
179 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
181 ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
182 let qualname = format!("::{}",
183 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
184 filter!(self.span_utils, item.ident.span);
185 Some(Data::DefData(Def {
186 kind: DefKind::Function,
187 id: id_from_node_id(item.id, self),
188 span: self.span_from_span(item.ident.span),
189 name: item.ident.to_string(),
191 value: make_signature(decl, generics),
195 docs: self.docs_for_attrs(&item.attrs),
196 sig: sig::item_signature(item, self),
197 attributes: lower_attributes(item.attrs.clone(), self),
200 ast::ItemKind::Static(ref typ, ..) => {
201 let qualname = format!("::{}",
202 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
204 filter!(self.span_utils, item.ident.span);
206 let id = id_from_node_id(item.id, self);
207 let span = self.span_from_span(item.ident.span);
209 Some(Data::DefData(Def {
210 kind: DefKind::Static,
213 name: item.ident.to_string(),
215 value: ty_to_string(&typ),
219 docs: self.docs_for_attrs(&item.attrs),
220 sig: sig::item_signature(item, self),
221 attributes: lower_attributes(item.attrs.clone(), self),
224 ast::ItemKind::Const(ref typ, _) => {
225 let qualname = format!("::{}",
226 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
227 filter!(self.span_utils, item.ident.span);
229 let id = id_from_node_id(item.id, self);
230 let span = self.span_from_span(item.ident.span);
232 Some(Data::DefData(Def {
233 kind: DefKind::Const,
236 name: item.ident.to_string(),
238 value: ty_to_string(typ),
242 docs: self.docs_for_attrs(&item.attrs),
243 sig: sig::item_signature(item, self),
244 attributes: lower_attributes(item.attrs.clone(), self),
247 ast::ItemKind::Mod(ref m) => {
248 let qualname = format!("::{}",
249 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
251 let cm = self.tcx.sess.source_map();
252 let filename = cm.span_to_filename(m.inner);
254 filter!(self.span_utils, item.ident.span);
256 Some(Data::DefData(Def {
258 id: id_from_node_id(item.id, self),
259 name: item.ident.to_string(),
261 span: self.span_from_span(item.ident.span),
262 value: filename.to_string(),
266 .map(|i| id_from_node_id(i.id, self))
269 docs: self.docs_for_attrs(&item.attrs),
270 sig: sig::item_signature(item, self),
271 attributes: lower_attributes(item.attrs.clone(), self),
274 ast::ItemKind::Enum(ref def, _) => {
275 let name = item.ident.to_string();
276 let qualname = format!("::{}",
277 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
278 filter!(self.span_utils, item.ident.span);
279 let variants_str = def.variants
281 .map(|v| v.ident.to_string())
284 let value = format!("{}::{{{}}}", name, variants_str);
285 Some(Data::DefData(Def {
287 id: id_from_node_id(item.id, self),
288 span: self.span_from_span(item.ident.span),
293 children: def.variants
295 .map(|v| id_from_node_id(v.id, self))
298 docs: self.docs_for_attrs(&item.attrs),
299 sig: sig::item_signature(item, self),
300 attributes: lower_attributes(item.attrs.clone(), self),
303 ast::ItemKind::Impl(.., ref trait_ref, ref typ, ref impls) => {
304 if let ast::TyKind::Path(None, ref path) = typ.kind {
305 // Common case impl for a struct or something basic.
306 if generated_code(path.span) {
309 let sub_span = path.segments.last().unwrap().ident.span;
310 filter!(self.span_utils, sub_span);
312 let impl_id = self.next_impl_id();
313 let span = self.span_from_span(sub_span);
315 let type_data = self.lookup_def_id(typ.id);
316 type_data.map(|type_data| {
317 Data::RelationData(Relation {
318 kind: RelationKind::Impl {
322 from: id_from_def_id(type_data),
325 .and_then(|t| self.lookup_def_id(t.ref_id))
327 .unwrap_or_else(|| null_id()),
331 kind: match *trait_ref {
332 Some(_) => ImplKind::Direct,
333 None => ImplKind::Inherent,
336 value: String::new(),
340 .map(|i| id_from_node_id(i.id, self))
358 pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<Def> {
359 if let Some(ident) = field.ident {
360 let name = ident.to_string();
361 let qualname = format!("::{}::{}",
362 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(scope)),
364 filter!(self.span_utils, ident.span);
365 let def_id = self.tcx.hir().local_def_id_from_node_id(field.id);
366 let typ = self.tcx.type_of(def_id).to_string();
369 let id = id_from_node_id(field.id, self);
370 let span = self.span_from_span(ident.span);
373 kind: DefKind::Field,
379 parent: Some(id_from_node_id(scope, self)),
382 docs: self.docs_for_attrs(&field.attrs),
383 sig: sig::field_signature(field, self),
384 attributes: lower_attributes(field.attrs.clone(), self),
391 // FIXME would be nice to take a MethodItem here, but the ast provides both
392 // trait and impl flavours, so the caller must do the disassembly.
393 pub fn get_method_data(&self, id: ast::NodeId, ident: ast::Ident, span: Span) -> Option<Def> {
394 // The qualname for a method is the trait name or name of the struct in an impl in
395 // which the method is declared in, followed by the method's name.
396 let (qualname, parent_scope, decl_id, docs, attributes) =
397 match self.tcx.impl_of_method(self.tcx.hir().local_def_id_from_node_id(id)) {
398 Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) {
399 Some(Node::Item(item)) => match item.kind {
400 hir::ItemKind::Impl(.., ref ty, _) => {
401 let mut qualname = String::from("<");
402 qualname.push_str(&self.tcx.hir().hir_to_pretty_string(ty.hir_id));
404 let trait_id = self.tcx.trait_id_of_impl(impl_id);
405 let mut decl_id = None;
406 let mut docs = String::new();
407 let mut attrs = vec![];
408 let hir_id = self.tcx.hir().node_to_hir_id(id);
409 if let Some(Node::ImplItem(item)) =
410 self.tcx.hir().find(hir_id)
412 docs = self.docs_for_attrs(&item.attrs);
413 attrs = item.attrs.to_vec();
416 if let Some(def_id) = trait_id {
417 // A method in a trait impl.
418 qualname.push_str(" as ");
419 qualname.push_str(&self.tcx.def_path_str(def_id));
421 .associated_items(def_id)
422 .find(|item| item.ident.name == ident.name)
423 .map(|item| decl_id = Some(item.def_id));
425 qualname.push_str(">");
427 (qualname, trait_id, decl_id, docs, attrs)
432 "Container {:?} for method {} not an impl?",
441 "Container {:?} for method {} is not a node item {:?}",
448 None => match self.tcx.trait_of_item(self.tcx.hir().local_def_id_from_node_id(id)) {
450 let mut docs = String::new();
451 let mut attrs = vec![];
452 let hir_id = self.tcx.hir().node_to_hir_id(id);
454 if let Some(Node::TraitItem(item)) = self.tcx.hir().find(hir_id) {
455 docs = self.docs_for_attrs(&item.attrs);
456 attrs = item.attrs.to_vec();
460 format!("::{}", self.tcx.def_path_str(def_id)),
468 debug!("could not find container for method {} at {:?}", id, span);
469 // This is not necessarily a bug, if there was a compilation error,
470 // the tables we need might not exist.
476 let qualname = format!("{}::{}", qualname, ident.name);
478 filter!(self.span_utils, ident.span);
481 kind: DefKind::Method,
482 id: id_from_node_id(id, self),
483 span: self.span_from_span(ident.span),
484 name: ident.name.to_string(),
486 // FIXME you get better data here by using the visitor.
487 value: String::new(),
488 parent: parent_scope.map(|id| id_from_def_id(id)),
490 decl_id: decl_id.map(|id| id_from_def_id(id)),
493 attributes: lower_attributes(attributes, self),
497 pub fn get_trait_ref_data(&self, trait_ref: &ast::TraitRef) -> Option<Ref> {
498 self.lookup_def_id(trait_ref.ref_id).and_then(|def_id| {
499 let span = trait_ref.path.span;
500 if generated_code(span) {
503 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
504 filter!(self.span_utils, sub_span);
505 let span = self.span_from_span(sub_span);
509 ref_id: id_from_def_id(def_id),
514 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
515 let expr_hir_id = self.tcx.hir().node_to_hir_id(expr.id);
516 let hir_node = self.tcx.hir().expect_expr(expr_hir_id);
517 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
518 if ty.is_none() || ty.unwrap().kind == ty::Error {
522 ast::ExprKind::Field(ref sub_ex, ident) => {
523 let sub_ex_hir_id = self.tcx.hir().node_to_hir_id(sub_ex.id);
524 let hir_node = match self.tcx.hir().find(sub_ex_hir_id) {
525 Some(Node::Expr(expr)) => expr,
528 "Missing or weird node for sub-expression {} in {:?}",
535 match self.tables.expr_ty_adjusted(&hir_node).kind {
536 ty::Adt(def, _) if !def.is_enum() => {
537 let variant = &def.non_enum_variant();
538 let index = self.tcx.find_field_index(ident, variant).unwrap();
539 filter!(self.span_utils, ident.span);
540 let span = self.span_from_span(ident.span);
541 return Some(Data::RefData(Ref {
542 kind: RefKind::Variable,
544 ref_id: id_from_def_id(variant.fields[index].did),
547 ty::Tuple(..) => None,
549 debug!("expected struct or union type, found {:?}", ty);
554 ast::ExprKind::Struct(ref path, ..) => {
555 match self.tables.expr_ty_adjusted(&hir_node).kind {
556 ty::Adt(def, _) if !def.is_enum() => {
557 let sub_span = path.segments.last().unwrap().ident.span;
558 filter!(self.span_utils, sub_span);
559 let span = self.span_from_span(sub_span);
560 Some(Data::RefData(Ref {
563 ref_id: id_from_def_id(def.did),
567 // FIXME ty could legitimately be an enum, but then we will fail
568 // later if we try to look up the fields.
569 debug!("expected struct or union, found {:?}", ty);
574 ast::ExprKind::MethodCall(ref seg, ..) => {
575 let expr_hir_id = self.tcx.hir().definitions().node_to_hir_id(expr.id);
576 let method_id = match self.tables.type_dependent_def_id(expr_hir_id) {
579 debug!("could not resolve method id for {:?}", expr);
583 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
584 ty::ImplContainer(_) => (Some(method_id), None),
585 ty::TraitContainer(_) => (None, Some(method_id)),
587 let sub_span = seg.ident.span;
588 filter!(self.span_utils, sub_span);
589 let span = self.span_from_span(sub_span);
590 Some(Data::RefData(Ref {
591 kind: RefKind::Function,
595 .map(|id| id_from_def_id(id))
596 .unwrap_or_else(|| null_id()),
599 ast::ExprKind::Path(_, ref path) => {
600 self.get_path_data(expr.id, path).map(|d| Data::RefData(d))
609 pub fn get_path_res(&self, id: NodeId) -> Res {
610 let hir_id = self.tcx.hir().node_to_hir_id(id);
611 match self.tcx.hir().get(hir_id) {
612 Node::TraitRef(tr) => tr.path.res,
614 Node::Item(&hir::Item {
615 kind: hir::ItemKind::Use(ref path, _),
618 Node::Visibility(&Spanned {
619 node: hir::VisibilityKind::Restricted { ref path, .. }, .. }) => path.res,
621 Node::PathSegment(seg) => {
623 Some(res) if res != Res::Err => res,
625 let parent_node = self.tcx.hir().get_parent_node(hir_id);
626 self.get_path_res(self.tcx.hir().hir_to_node_id(parent_node))
631 Node::Expr(&hir::Expr {
632 kind: hir::ExprKind::Struct(ref qpath, ..),
635 self.tables.qpath_res(qpath, hir_id)
638 Node::Expr(&hir::Expr {
639 kind: hir::ExprKind::Path(ref qpath),
642 Node::Pat(&hir::Pat {
643 kind: hir::PatKind::Path(ref qpath),
646 Node::Pat(&hir::Pat {
647 kind: hir::PatKind::Struct(ref qpath, ..),
650 Node::Pat(&hir::Pat {
651 kind: hir::PatKind::TupleStruct(ref qpath, ..),
655 kind: hir::TyKind::Path(ref qpath),
658 self.tables.qpath_res(qpath, hir_id)
661 Node::Binding(&hir::Pat {
662 kind: hir::PatKind::Binding(_, canonical_id, ..),
664 }) => Res::Local(canonical_id),
670 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Ref> {
674 self.get_path_segment_data(seg)
675 .or_else(|| self.get_path_segment_data_with_id(seg, id))
679 pub fn get_path_segment_data(&self, path_seg: &ast::PathSegment) -> Option<Ref> {
680 self.get_path_segment_data_with_id(path_seg, path_seg.id)
683 fn get_path_segment_data_with_id(
685 path_seg: &ast::PathSegment,
688 // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
689 fn fn_type(seg: &ast::PathSegment) -> bool {
690 if let Some(ref generic_args) = seg.args {
691 if let ast::GenericArgs::Parenthesized(_) = **generic_args {
698 if id == DUMMY_NODE_ID {
702 let res = self.get_path_res(id);
703 let span = path_seg.ident.span;
704 filter!(self.span_utils, span);
705 let span = self.span_from_span(span);
710 kind: RefKind::Variable,
712 ref_id: id_from_node_id(self.tcx.hir().hir_to_node_id(id), self),
715 Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
719 ref_id: id_from_def_id(def_id),
722 Res::Def(HirDefKind::Struct, def_id) |
723 Res::Def(HirDefKind::Variant, def_id) |
724 Res::Def(HirDefKind::Union, def_id) |
725 Res::Def(HirDefKind::Enum, def_id) |
726 Res::Def(HirDefKind::TyAlias, def_id) |
727 Res::Def(HirDefKind::ForeignTy, def_id) |
728 Res::Def(HirDefKind::TraitAlias, def_id) |
729 Res::Def(HirDefKind::AssocOpaqueTy, def_id) |
730 Res::Def(HirDefKind::AssocTy, def_id) |
731 Res::Def(HirDefKind::Trait, def_id) |
732 Res::Def(HirDefKind::OpaqueTy, def_id) |
733 Res::Def(HirDefKind::TyParam, def_id) => {
737 ref_id: id_from_def_id(def_id),
740 Res::Def(HirDefKind::ConstParam, def_id) => {
742 kind: RefKind::Variable,
744 ref_id: id_from_def_id(def_id),
747 Res::Def(HirDefKind::Ctor(CtorOf::Struct, ..), def_id) => {
748 // This is a reference to a tuple struct where the def_id points
749 // to an invisible constructor function. That is not a very useful
750 // def, so adjust to point to the tuple struct itself.
751 let parent_def_id = self.tcx.parent(def_id).unwrap();
755 ref_id: id_from_def_id(parent_def_id),
758 Res::Def(HirDefKind::Static, _) |
759 Res::Def(HirDefKind::Const, _) |
760 Res::Def(HirDefKind::AssocConst, _) |
761 Res::Def(HirDefKind::Ctor(..), _) => {
763 kind: RefKind::Variable,
765 ref_id: id_from_def_id(res.def_id()),
768 Res::Def(HirDefKind::Method, decl_id) => {
769 let def_id = if decl_id.is_local() {
770 let ti = self.tcx.associated_item(decl_id);
772 .associated_items(ti.container.id())
773 .find(|item| item.ident.name == ti.ident.name &&
774 item.defaultness.has_value())
775 .map(|item| item.def_id)
780 kind: RefKind::Function,
782 ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
785 Res::Def(HirDefKind::Fn, def_id) => {
787 kind: RefKind::Function,
789 ref_id: id_from_def_id(def_id),
792 Res::Def(HirDefKind::Mod, def_id) => {
796 ref_id: id_from_def_id(def_id),
801 Res::Def(HirDefKind::Macro(..), _) |
803 Res::NonMacroAttr(..) |
809 pub fn get_field_ref_data(
811 field_ref: &ast::Field,
812 variant: &ty::VariantDef,
814 filter!(self.span_utils, field_ref.ident.span);
815 self.tcx.find_field_index(field_ref.ident, variant).map(|index| {
816 let span = self.span_from_span(field_ref.ident.span);
818 kind: RefKind::Variable,
820 ref_id: id_from_def_id(variant.fields[index].did),
825 /// Attempt to return MacroRef for any AST node.
827 /// For a given piece of AST defined by the supplied Span and NodeId,
828 /// returns `None` if the node is not macro-generated or the span is malformed,
829 /// else uses the expansion callsite and callee to return some MacroRef.
830 pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
831 if !generated_code(span) {
834 // Note we take care to use the source callsite/callee, to handle
835 // nested expansions and ensure we only generate data for source-visible
837 let callsite = span.source_callsite();
838 let callsite_span = self.span_from_span(callsite);
839 let callee = span.source_callee()?;
841 // Ignore attribute macros, their spans are usually mangled
842 if let ExpnKind::Macro(MacroKind::Attr, _) |
843 ExpnKind::Macro(MacroKind::Derive, _) = callee.kind {
847 // If the callee is an imported macro from an external crate, need to get
848 // the source span and name from the session, as their spans are localized
849 // when read in, and no longer correspond to the source.
850 if let Some(mac) = self.tcx
852 .imported_macro_spans
854 .get(&callee.def_site)
856 let &(ref mac_name, mac_span) = mac;
857 let mac_span = self.span_from_span(mac_span);
858 return Some(MacroRef {
860 qualname: mac_name.clone(), // FIXME: generate the real qualname
861 callee_span: mac_span,
865 let callee_span = self.span_from_span(callee.def_site);
868 qualname: callee.kind.descr().to_string(), // FIXME: generate the real qualname
873 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
874 match self.get_path_res(ref_id) {
875 Res::PrimTy(_) | Res::SelfTy(..) | Res::Err => None,
876 def => Some(def.def_id()),
880 fn docs_for_attrs(&self, attrs: &[Attribute]) -> String {
881 let mut result = String::new();
884 if attr.check_name(sym::doc) {
885 if let Some(val) = attr.value_str() {
886 if attr.is_sugared_doc {
887 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
889 result.push_str(&val.as_str());
892 } else if let Some(meta_list) = attr.meta_item_list() {
893 meta_list.into_iter()
894 .filter(|it| it.check_name(sym::include))
895 .filter_map(|it| it.meta_item_list().map(|l| l.to_owned()))
897 .filter(|meta| meta.check_name(sym::contents))
898 .filter_map(|meta| meta.value_str())
900 result.push_str(&val.as_str());
907 if !self.config.full_docs {
908 if let Some(index) = result.find("\n\n") {
909 result.truncate(index);
916 fn next_impl_id(&self) -> u32 {
917 let next = self.impl_counter.get();
918 self.impl_counter.set(next + 1);
923 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
924 let mut sig = "fn ".to_owned();
925 if !generics.params.is_empty() {
927 sig.push_str(&generics
930 .map(|param| param.ident.to_string())
936 sig.push_str(&decl.inputs
938 .map(param_to_string)
943 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
944 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
950 // An AST visitor for collecting paths (e.g., the names of structs) and formal
951 // variables (idents) from patterns.
952 struct PathCollector<'l> {
953 collected_paths: Vec<(NodeId, &'l ast::Path)>,
954 collected_idents: Vec<(NodeId, ast::Ident, ast::Mutability)>,
957 impl<'l> PathCollector<'l> {
958 fn new() -> PathCollector<'l> {
960 collected_paths: vec![],
961 collected_idents: vec![],
966 impl<'l> Visitor<'l> for PathCollector<'l> {
967 fn visit_pat(&mut self, p: &'l ast::Pat) {
969 PatKind::Struct(ref path, ..) => {
970 self.collected_paths.push((p.id, path));
972 PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => {
973 self.collected_paths.push((p.id, path));
975 PatKind::Ident(bm, ident, _) => {
977 "PathCollector, visit ident in pat {}: {:?} {:?}",
982 let immut = match bm {
983 // Even if the ref is mut, you can't change the ref, only
984 // the data pointed at, so showing the initialising expression
985 // is still worthwhile.
986 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
987 ast::BindingMode::ByValue(mt) => mt,
989 self.collected_idents
990 .push((p.id, ident, immut));
994 visit::walk_pat(self, p);
998 /// Defines what to do with the results of saving the analysis.
999 pub trait SaveHandler {
1002 save_ctxt: &SaveContext<'_, '_>,
1003 analysis: &Analysis,
1007 /// Dump the save-analysis results to a file.
1008 pub struct DumpHandler<'a> {
1009 odir: Option<&'a Path>,
1013 impl<'a> DumpHandler<'a> {
1014 pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
1017 cratename: cratename.to_owned(),
1021 fn output_file(&self, ctx: &SaveContext<'_, '_>) -> (BufWriter<File>, PathBuf) {
1022 let sess = &ctx.tcx.sess;
1023 let file_name = match ctx.config.output_file {
1024 Some(ref s) => PathBuf::from(s),
1026 let mut root_path = match self.odir {
1027 Some(val) => val.join("save-analysis"),
1028 None => PathBuf::from("save-analysis-temp"),
1031 if let Err(e) = std::fs::create_dir_all(&root_path) {
1032 error!("Could not create directory {}: {}", root_path.display(), e);
1035 let executable = sess.crate_types
1038 .any(|ct| *ct == CrateType::Executable);
1039 let mut out_name = if executable {
1044 out_name.push_str(&self.cratename);
1045 out_name.push_str(&sess.opts.cg.extra_filename);
1046 out_name.push_str(".json");
1047 root_path.push(&out_name);
1053 info!("Writing output to {}", file_name.display());
1055 let output_file = BufWriter::new(File::create(&file_name).unwrap_or_else(
1056 |e| sess.fatal(&format!("Could not open {}: {}", file_name.display(), e)),
1059 (output_file, file_name)
1063 impl SaveHandler for DumpHandler<'_> {
1066 save_ctxt: &SaveContext<'_, '_>,
1067 analysis: &Analysis,
1069 let sess = &save_ctxt.tcx.sess;
1070 let (output, file_name) = self.output_file(&save_ctxt);
1071 if let Err(e) = serde_json::to_writer(output, &analysis) {
1072 error!("Can't serialize save-analysis: {:?}", e);
1075 if sess.opts.json_artifact_notifications {
1076 sess.parse_sess.span_diagnostic
1077 .emit_artifact_notification(&file_name, "save-analysis");
1082 /// Call a callback with the results of save-analysis.
1083 pub struct CallbackHandler<'b> {
1084 pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
1087 impl SaveHandler for CallbackHandler<'_> {
1090 _: &SaveContext<'_, '_>,
1091 analysis: &Analysis,
1093 (self.callback)(analysis)
1097 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
1102 config: Option<Config>,
1105 tcx.dep_graph.with_ignore(|| {
1106 info!("Dumping crate {}", cratename);
1108 // Privacy checking requires and is done after type checking; use a
1109 // fallback in case the access levels couldn't have been correctly computed.
1110 let access_levels = match tcx.sess.compile_status() {
1111 Ok(..) => tcx.privacy_access_levels(LOCAL_CRATE),
1112 Err(..) => tcx.arena.alloc(AccessLevels::default()),
1115 let save_ctxt = SaveContext {
1117 tables: &ty::TypeckTables::empty(None),
1118 access_levels: &access_levels,
1119 span_utils: SpanUtils::new(&tcx.sess),
1120 config: find_config(config),
1121 impl_counter: Cell::new(0),
1124 let mut visitor = DumpVisitor::new(save_ctxt);
1126 visitor.dump_crate_info(cratename, krate);
1127 visitor.dump_compilation_options(input, cratename);
1128 visit::walk_crate(&mut visitor, krate);
1130 handler.save(&visitor.save_ctxt, &visitor.analysis())
1134 fn find_config(supplied: Option<Config>) -> Config {
1135 if let Some(config) = supplied {
1139 match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
1140 None => Config::default(),
1141 Some(config) => config.to_str()
1143 .map_err(|_| error!("`RUST_SAVE_ANALYSIS_CONFIG` isn't UTF-8"))
1144 .and_then(|cfg| serde_json::from_str(cfg)
1145 .map_err(|_| error!("Could not deserialize save-analysis config"))
1146 ).unwrap_or_default()
1150 // Utility functions for the module.
1152 // Helper function to escape quotes in a string
1153 fn escape(s: String) -> String {
1154 s.replace("\"", "\"\"")
1157 // Helper function to determine if a span came from a
1158 // macro expansion or syntax extension.
1159 fn generated_code(span: Span) -> bool {
1160 span.from_expansion() || span.is_dummy()
1163 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
1164 // we use our own Id which is the same, but without the newtype.
1165 fn id_from_def_id(id: DefId) -> rls_data::Id {
1167 krate: id.krate.as_u32(),
1168 index: id.index.as_u32(),
1172 fn id_from_node_id(id: NodeId, scx: &SaveContext<'_, '_>) -> rls_data::Id {
1173 let def_id = scx.tcx.hir().opt_local_def_id_from_node_id(id);
1174 def_id.map(|id| id_from_def_id(id)).unwrap_or_else(|| {
1175 // Create a *fake* `DefId` out of a `NodeId` by subtracting the `NodeId`
1176 // out of the maximum u32 value. This will work unless you have *billions*
1177 // of definitions in a single crate (very unlikely to actually happen).
1179 krate: LOCAL_CRATE.as_u32(),
1180 index: !id.as_u32(),
1185 fn null_id() -> rls_data::Id {
1187 krate: u32::max_value(),
1188 index: u32::max_value(),
1192 fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext<'_, '_>) -> Vec<rls_data::Attribute> {
1194 // Only retain real attributes. Doc comments are lowered separately.
1195 .filter(|attr| attr.path != sym::doc)
1197 // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
1198 // attribute. First normalize all inner attribute (#![..]) to outer
1199 // ones (#[..]), then remove the two leading and the one trailing character.
1200 attr.style = ast::AttrStyle::Outer;
1201 let value = pprust::attribute_to_string(&attr);
1202 // This str slicing works correctly, because the leading and trailing characters
1203 // are in the ASCII range and thus exactly one byte each.
1204 let value = value[2..value.len()-1].to_string();
1206 rls_data::Attribute {
1208 span: scx.span_from_span(attr.span),