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::{param_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 /// Used as a fallback when nesting the typeck tables during item processing
52 /// (if these are not available for that item, e.g. don't own a body)
53 empty_tables: &'l ty::TypeckTables<'tcx>,
54 access_levels: &'l AccessLevels,
55 span_utils: SpanUtils<'tcx>,
57 impl_counter: Cell<u32>,
64 RelationData(Relation, Impl),
67 impl<'l, 'tcx> SaveContext<'l, 'tcx> {
68 fn span_from_span(&self, span: Span) -> SpanData {
69 use rls_span::{Column, Row};
71 let cm = self.tcx.sess.source_map();
72 let start = cm.lookup_char_pos(span.lo());
73 let end = cm.lookup_char_pos(span.hi());
76 file_name: start.file.name.to_string().into(),
77 byte_start: span.lo().0,
78 byte_end: span.hi().0,
79 line_start: Row::new_one_indexed(start.line as u32),
80 line_end: Row::new_one_indexed(end.line as u32),
81 column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
82 column_end: Column::new_one_indexed(end.col.0 as u32 + 1),
86 // Returns path to the compilation output (e.g., libfoo-12345678.rmeta)
87 pub fn compilation_output(&self, crate_name: &str) -> PathBuf {
88 let sess = &self.tcx.sess;
89 // Save-analysis is emitted per whole session, not per each crate type
90 let crate_type = sess.crate_types.borrow()[0];
91 let outputs = &*self.tcx.output_filenames(LOCAL_CRATE);
93 if outputs.outputs.contains_key(&OutputType::Metadata) {
94 filename_for_metadata(sess, crate_name, outputs)
95 } else if outputs.outputs.should_codegen() {
96 out_filename(sess, crate_type, outputs, crate_name)
98 // Otherwise it's only a DepInfo, in which case we return early and
99 // not even reach the analysis stage.
104 // List external crates used by the current crate.
105 pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
106 let mut result = Vec::with_capacity(self.tcx.crates().len());
108 for &n in self.tcx.crates().iter() {
109 let span = match self.tcx.extern_crate(n.as_def_id()) {
110 Some(&ExternCrate { span, .. }) => span,
112 debug!("skipping crate {}, no data", n);
116 let lo_loc = self.span_utils.sess.source_map().lookup_char_pos(span.lo());
117 result.push(ExternalCrateData {
118 // FIXME: change file_name field to PathBuf in rls-data
119 // https://github.com/nrc/rls-data/issues/7
120 file_name: self.span_utils.make_filename_string(&lo_loc.file),
123 name: self.tcx.crate_name(n).to_string(),
124 disambiguator: self.tcx.crate_disambiguator(n).to_fingerprint().as_value(),
132 pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
133 let qualname = format!("::{}",
134 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
136 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
137 filter!(self.span_utils, item.ident.span);
139 Some(Data::DefData(Def {
140 kind: DefKind::ForeignFunction,
141 id: id_from_node_id(item.id, self),
142 span: self.span_from_span(item.ident.span),
143 name: item.ident.to_string(),
145 value: make_signature(decl, generics),
149 docs: self.docs_for_attrs(&item.attrs),
150 sig: sig::foreign_item_signature(item, self),
151 attributes: lower_attributes(item.attrs.clone(), self),
154 ast::ForeignItemKind::Static(ref ty, _) => {
155 filter!(self.span_utils, item.ident.span);
157 let id = id_from_node_id(item.id, self);
158 let span = self.span_from_span(item.ident.span);
160 Some(Data::DefData(Def {
161 kind: DefKind::ForeignStatic,
164 name: item.ident.to_string(),
166 value: ty_to_string(ty),
170 docs: self.docs_for_attrs(&item.attrs),
171 sig: sig::foreign_item_signature(item, self),
172 attributes: lower_attributes(item.attrs.clone(), self),
175 // FIXME(plietar): needs a new DefKind in rls-data
176 ast::ForeignItemKind::Ty => None,
177 ast::ForeignItemKind::Macro(..) => None,
181 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
183 ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
184 let qualname = format!("::{}",
185 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
186 filter!(self.span_utils, item.ident.span);
187 Some(Data::DefData(Def {
188 kind: DefKind::Function,
189 id: id_from_node_id(item.id, self),
190 span: self.span_from_span(item.ident.span),
191 name: item.ident.to_string(),
193 value: make_signature(decl, generics),
197 docs: self.docs_for_attrs(&item.attrs),
198 sig: sig::item_signature(item, self),
199 attributes: lower_attributes(item.attrs.clone(), self),
202 ast::ItemKind::Static(ref typ, ..) => {
203 let qualname = format!("::{}",
204 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
206 filter!(self.span_utils, item.ident.span);
208 let id = id_from_node_id(item.id, self);
209 let span = self.span_from_span(item.ident.span);
211 Some(Data::DefData(Def {
212 kind: DefKind::Static,
215 name: item.ident.to_string(),
217 value: ty_to_string(&typ),
221 docs: self.docs_for_attrs(&item.attrs),
222 sig: sig::item_signature(item, self),
223 attributes: lower_attributes(item.attrs.clone(), self),
226 ast::ItemKind::Const(ref typ, _) => {
227 let qualname = format!("::{}",
228 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
229 filter!(self.span_utils, item.ident.span);
231 let id = id_from_node_id(item.id, self);
232 let span = self.span_from_span(item.ident.span);
234 Some(Data::DefData(Def {
235 kind: DefKind::Const,
238 name: item.ident.to_string(),
240 value: ty_to_string(typ),
244 docs: self.docs_for_attrs(&item.attrs),
245 sig: sig::item_signature(item, self),
246 attributes: lower_attributes(item.attrs.clone(), self),
249 ast::ItemKind::Mod(ref m) => {
250 let qualname = format!("::{}",
251 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
253 let cm = self.tcx.sess.source_map();
254 let filename = cm.span_to_filename(m.inner);
256 filter!(self.span_utils, item.ident.span);
258 Some(Data::DefData(Def {
260 id: id_from_node_id(item.id, self),
261 name: item.ident.to_string(),
263 span: self.span_from_span(item.ident.span),
264 value: filename.to_string(),
268 .map(|i| id_from_node_id(i.id, self))
271 docs: self.docs_for_attrs(&item.attrs),
272 sig: sig::item_signature(item, self),
273 attributes: lower_attributes(item.attrs.clone(), self),
276 ast::ItemKind::Enum(ref def, _) => {
277 let name = item.ident.to_string();
278 let qualname = format!("::{}",
279 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
280 filter!(self.span_utils, item.ident.span);
281 let variants_str = def.variants
283 .map(|v| v.ident.to_string())
286 let value = format!("{}::{{{}}}", name, variants_str);
287 Some(Data::DefData(Def {
289 id: id_from_node_id(item.id, self),
290 span: self.span_from_span(item.ident.span),
295 children: def.variants
297 .map(|v| id_from_node_id(v.id, self))
300 docs: self.docs_for_attrs(&item.attrs),
301 sig: sig::item_signature(item, self),
302 attributes: lower_attributes(item.attrs.clone(), self),
305 ast::ItemKind::Impl(.., ref trait_ref, ref typ, ref impls) => {
306 if let ast::TyKind::Path(None, ref path) = typ.kind {
307 // Common case impl for a struct or something basic.
308 if generated_code(path.span) {
311 let sub_span = path.segments.last().unwrap().ident.span;
312 filter!(self.span_utils, sub_span);
314 let impl_id = self.next_impl_id();
315 let span = self.span_from_span(sub_span);
317 let type_data = self.lookup_def_id(typ.id);
318 type_data.map(|type_data| {
319 Data::RelationData(Relation {
320 kind: RelationKind::Impl {
324 from: id_from_def_id(type_data),
327 .and_then(|t| self.lookup_def_id(t.ref_id))
329 .unwrap_or_else(|| null_id()),
333 kind: match *trait_ref {
334 Some(_) => ImplKind::Direct,
335 None => ImplKind::Inherent,
338 value: String::new(),
342 .map(|i| id_from_node_id(i.id, self))
360 pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<Def> {
361 if let Some(ident) = field.ident {
362 let name = ident.to_string();
363 let qualname = format!("::{}::{}",
364 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(scope)),
366 filter!(self.span_utils, ident.span);
367 let def_id = self.tcx.hir().local_def_id_from_node_id(field.id);
368 let typ = self.tcx.type_of(def_id).to_string();
371 let id = id_from_node_id(field.id, self);
372 let span = self.span_from_span(ident.span);
375 kind: DefKind::Field,
381 parent: Some(id_from_node_id(scope, self)),
384 docs: self.docs_for_attrs(&field.attrs),
385 sig: sig::field_signature(field, self),
386 attributes: lower_attributes(field.attrs.clone(), self),
393 // FIXME would be nice to take a MethodItem here, but the ast provides both
394 // trait and impl flavours, so the caller must do the disassembly.
395 pub fn get_method_data(&self, id: ast::NodeId, ident: ast::Ident, span: Span) -> Option<Def> {
396 // The qualname for a method is the trait name or name of the struct in an impl in
397 // which the method is declared in, followed by the method's name.
398 let (qualname, parent_scope, decl_id, docs, attributes) =
399 match self.tcx.impl_of_method(self.tcx.hir().local_def_id_from_node_id(id)) {
400 Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) {
401 Some(Node::Item(item)) => match item.kind {
402 hir::ItemKind::Impl(.., ref ty, _) => {
403 let mut qualname = String::from("<");
404 qualname.push_str(&self.tcx.hir().hir_to_pretty_string(ty.hir_id));
406 let trait_id = self.tcx.trait_id_of_impl(impl_id);
407 let mut decl_id = None;
408 let mut docs = String::new();
409 let mut attrs = vec![];
410 let hir_id = self.tcx.hir().node_to_hir_id(id);
411 if let Some(Node::ImplItem(item)) =
412 self.tcx.hir().find(hir_id)
414 docs = self.docs_for_attrs(&item.attrs);
415 attrs = item.attrs.to_vec();
418 if let Some(def_id) = trait_id {
419 // A method in a trait impl.
420 qualname.push_str(" as ");
421 qualname.push_str(&self.tcx.def_path_str(def_id));
423 .associated_items(def_id)
424 .find(|item| item.ident.name == ident.name)
425 .map(|item| decl_id = Some(item.def_id));
427 qualname.push_str(">");
429 (qualname, trait_id, decl_id, docs, attrs)
434 "Container {:?} for method {} not an impl?",
443 "Container {:?} for method {} is not a node item {:?}",
450 None => match self.tcx.trait_of_item(self.tcx.hir().local_def_id_from_node_id(id)) {
452 let mut docs = String::new();
453 let mut attrs = vec![];
454 let hir_id = self.tcx.hir().node_to_hir_id(id);
456 if let Some(Node::TraitItem(item)) = self.tcx.hir().find(hir_id) {
457 docs = self.docs_for_attrs(&item.attrs);
458 attrs = item.attrs.to_vec();
462 format!("::{}", self.tcx.def_path_str(def_id)),
470 debug!("could not find container for method {} at {:?}", id, span);
471 // This is not necessarily a bug, if there was a compilation error,
472 // the tables we need might not exist.
478 let qualname = format!("{}::{}", qualname, ident.name);
480 filter!(self.span_utils, ident.span);
483 kind: DefKind::Method,
484 id: id_from_node_id(id, self),
485 span: self.span_from_span(ident.span),
486 name: ident.name.to_string(),
488 // FIXME you get better data here by using the visitor.
489 value: String::new(),
490 parent: parent_scope.map(|id| id_from_def_id(id)),
492 decl_id: decl_id.map(|id| id_from_def_id(id)),
495 attributes: lower_attributes(attributes, self),
499 pub fn get_trait_ref_data(&self, trait_ref: &ast::TraitRef) -> Option<Ref> {
500 self.lookup_def_id(trait_ref.ref_id).and_then(|def_id| {
501 let span = trait_ref.path.span;
502 if generated_code(span) {
505 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
506 filter!(self.span_utils, sub_span);
507 let span = self.span_from_span(sub_span);
511 ref_id: id_from_def_id(def_id),
516 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
517 let expr_hir_id = self.tcx.hir().node_to_hir_id(expr.id);
518 let hir_node = self.tcx.hir().expect_expr(expr_hir_id);
519 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
520 if ty.is_none() || ty.unwrap().kind == ty::Error {
524 ast::ExprKind::Field(ref sub_ex, ident) => {
525 let sub_ex_hir_id = self.tcx.hir().node_to_hir_id(sub_ex.id);
526 let hir_node = match self.tcx.hir().find(sub_ex_hir_id) {
527 Some(Node::Expr(expr)) => expr,
530 "Missing or weird node for sub-expression {} in {:?}",
537 match self.tables.expr_ty_adjusted(&hir_node).kind {
538 ty::Adt(def, _) if !def.is_enum() => {
539 let variant = &def.non_enum_variant();
540 let index = self.tcx.find_field_index(ident, variant).unwrap();
541 filter!(self.span_utils, ident.span);
542 let span = self.span_from_span(ident.span);
543 return Some(Data::RefData(Ref {
544 kind: RefKind::Variable,
546 ref_id: id_from_def_id(variant.fields[index].did),
549 ty::Tuple(..) => None,
551 debug!("expected struct or union type, found {:?}", ty);
556 ast::ExprKind::Struct(ref path, ..) => {
557 match self.tables.expr_ty_adjusted(&hir_node).kind {
558 ty::Adt(def, _) if !def.is_enum() => {
559 let sub_span = path.segments.last().unwrap().ident.span;
560 filter!(self.span_utils, sub_span);
561 let span = self.span_from_span(sub_span);
562 Some(Data::RefData(Ref {
565 ref_id: id_from_def_id(def.did),
569 // FIXME ty could legitimately be an enum, but then we will fail
570 // later if we try to look up the fields.
571 debug!("expected struct or union, found {:?}", ty);
576 ast::ExprKind::MethodCall(ref seg, ..) => {
577 let expr_hir_id = self.tcx.hir().definitions().node_to_hir_id(expr.id);
578 let method_id = match self.tables.type_dependent_def_id(expr_hir_id) {
581 debug!("could not resolve method id for {:?}", expr);
585 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
586 ty::ImplContainer(_) => (Some(method_id), None),
587 ty::TraitContainer(_) => (None, Some(method_id)),
589 let sub_span = seg.ident.span;
590 filter!(self.span_utils, sub_span);
591 let span = self.span_from_span(sub_span);
592 Some(Data::RefData(Ref {
593 kind: RefKind::Function,
597 .map(|id| id_from_def_id(id))
598 .unwrap_or_else(|| null_id()),
601 ast::ExprKind::Path(_, ref path) => {
602 self.get_path_data(expr.id, path).map(|d| Data::RefData(d))
611 pub fn get_path_res(&self, id: NodeId) -> Res {
612 let hir_id = self.tcx.hir().node_to_hir_id(id);
613 match self.tcx.hir().get(hir_id) {
614 Node::TraitRef(tr) => tr.path.res,
616 Node::Item(&hir::Item {
617 kind: hir::ItemKind::Use(ref path, _),
620 Node::Visibility(&Spanned {
621 node: hir::VisibilityKind::Restricted { ref path, .. }, .. }) => path.res,
623 Node::PathSegment(seg) => {
625 Some(res) if res != Res::Err => res,
627 let parent_node = self.tcx.hir().get_parent_node(hir_id);
628 self.get_path_res(self.tcx.hir().hir_to_node_id(parent_node))
633 Node::Expr(&hir::Expr {
634 kind: hir::ExprKind::Struct(ref qpath, ..),
637 self.tables.qpath_res(qpath, hir_id)
640 Node::Expr(&hir::Expr {
641 kind: hir::ExprKind::Path(ref qpath),
644 Node::Pat(&hir::Pat {
645 kind: hir::PatKind::Path(ref qpath),
648 Node::Pat(&hir::Pat {
649 kind: hir::PatKind::Struct(ref qpath, ..),
652 Node::Pat(&hir::Pat {
653 kind: hir::PatKind::TupleStruct(ref qpath, ..),
657 kind: hir::TyKind::Path(ref qpath),
660 self.tables.qpath_res(qpath, hir_id)
663 Node::Binding(&hir::Pat {
664 kind: hir::PatKind::Binding(_, canonical_id, ..),
666 }) => Res::Local(canonical_id),
672 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Ref> {
676 self.get_path_segment_data(seg)
677 .or_else(|| self.get_path_segment_data_with_id(seg, id))
681 pub fn get_path_segment_data(&self, path_seg: &ast::PathSegment) -> Option<Ref> {
682 self.get_path_segment_data_with_id(path_seg, path_seg.id)
685 fn get_path_segment_data_with_id(
687 path_seg: &ast::PathSegment,
690 // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
691 fn fn_type(seg: &ast::PathSegment) -> bool {
692 if let Some(ref generic_args) = seg.args {
693 if let ast::GenericArgs::Parenthesized(_) = **generic_args {
700 if id == DUMMY_NODE_ID {
704 let res = self.get_path_res(id);
705 let span = path_seg.ident.span;
706 filter!(self.span_utils, span);
707 let span = self.span_from_span(span);
712 kind: RefKind::Variable,
714 ref_id: id_from_node_id(self.tcx.hir().hir_to_node_id(id), self),
717 Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
721 ref_id: id_from_def_id(def_id),
724 Res::Def(HirDefKind::Struct, def_id) |
725 Res::Def(HirDefKind::Variant, def_id) |
726 Res::Def(HirDefKind::Union, def_id) |
727 Res::Def(HirDefKind::Enum, def_id) |
728 Res::Def(HirDefKind::TyAlias, def_id) |
729 Res::Def(HirDefKind::ForeignTy, def_id) |
730 Res::Def(HirDefKind::TraitAlias, def_id) |
731 Res::Def(HirDefKind::AssocOpaqueTy, def_id) |
732 Res::Def(HirDefKind::AssocTy, def_id) |
733 Res::Def(HirDefKind::Trait, def_id) |
734 Res::Def(HirDefKind::OpaqueTy, def_id) |
735 Res::Def(HirDefKind::TyParam, def_id) => {
739 ref_id: id_from_def_id(def_id),
742 Res::Def(HirDefKind::ConstParam, def_id) => {
744 kind: RefKind::Variable,
746 ref_id: id_from_def_id(def_id),
749 Res::Def(HirDefKind::Ctor(CtorOf::Struct, ..), def_id) => {
750 // This is a reference to a tuple struct where the def_id points
751 // to an invisible constructor function. That is not a very useful
752 // def, so adjust to point to the tuple struct itself.
753 let parent_def_id = self.tcx.parent(def_id).unwrap();
757 ref_id: id_from_def_id(parent_def_id),
760 Res::Def(HirDefKind::Static, _) |
761 Res::Def(HirDefKind::Const, _) |
762 Res::Def(HirDefKind::AssocConst, _) |
763 Res::Def(HirDefKind::Ctor(..), _) => {
765 kind: RefKind::Variable,
767 ref_id: id_from_def_id(res.def_id()),
770 Res::Def(HirDefKind::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.ident.name == ti.ident.name &&
776 item.defaultness.has_value())
777 .map(|item| item.def_id)
782 kind: RefKind::Function,
784 ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
787 Res::Def(HirDefKind::Fn, def_id) => {
789 kind: RefKind::Function,
791 ref_id: id_from_def_id(def_id),
794 Res::Def(HirDefKind::Mod, def_id) => {
798 ref_id: id_from_def_id(def_id),
803 Res::Def(HirDefKind::Macro(..), _) |
805 Res::NonMacroAttr(..) |
811 pub fn get_field_ref_data(
813 field_ref: &ast::Field,
814 variant: &ty::VariantDef,
816 filter!(self.span_utils, field_ref.ident.span);
817 self.tcx.find_field_index(field_ref.ident, variant).map(|index| {
818 let span = self.span_from_span(field_ref.ident.span);
820 kind: RefKind::Variable,
822 ref_id: id_from_def_id(variant.fields[index].did),
827 /// Attempt to return MacroRef for any AST node.
829 /// For a given piece of AST defined by the supplied Span and NodeId,
830 /// returns `None` if the node is not macro-generated or the span is malformed,
831 /// else uses the expansion callsite and callee to return some MacroRef.
832 pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
833 if !generated_code(span) {
836 // Note we take care to use the source callsite/callee, to handle
837 // nested expansions and ensure we only generate data for source-visible
839 let callsite = span.source_callsite();
840 let callsite_span = self.span_from_span(callsite);
841 let callee = span.source_callee()?;
843 // Ignore attribute macros, their spans are usually mangled
844 if let ExpnKind::Macro(MacroKind::Attr, _) |
845 ExpnKind::Macro(MacroKind::Derive, _) = callee.kind {
849 // If the callee is an imported macro from an external crate, need to get
850 // the source span and name from the session, as their spans are localized
851 // when read in, and no longer correspond to the source.
852 if let Some(mac) = self.tcx
854 .imported_macro_spans
856 .get(&callee.def_site)
858 let &(ref mac_name, mac_span) = mac;
859 let mac_span = self.span_from_span(mac_span);
860 return Some(MacroRef {
862 qualname: mac_name.clone(), // FIXME: generate the real qualname
863 callee_span: mac_span,
867 let callee_span = self.span_from_span(callee.def_site);
870 qualname: callee.kind.descr().to_string(), // FIXME: generate the real qualname
875 fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
876 match self.get_path_res(ref_id) {
877 Res::PrimTy(_) | Res::SelfTy(..) | Res::Err => None,
878 def => Some(def.def_id()),
882 fn docs_for_attrs(&self, attrs: &[Attribute]) -> String {
883 let mut result = String::new();
886 if attr.check_name(sym::doc) {
887 if let Some(val) = attr.value_str() {
888 if attr.is_sugared_doc {
889 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
891 result.push_str(&val.as_str());
894 } else if let Some(meta_list) = attr.meta_item_list() {
895 meta_list.into_iter()
896 .filter(|it| it.check_name(sym::include))
897 .filter_map(|it| it.meta_item_list().map(|l| l.to_owned()))
899 .filter(|meta| meta.check_name(sym::contents))
900 .filter_map(|meta| meta.value_str())
902 result.push_str(&val.as_str());
909 if !self.config.full_docs {
910 if let Some(index) = result.find("\n\n") {
911 result.truncate(index);
918 fn next_impl_id(&self) -> u32 {
919 let next = self.impl_counter.get();
920 self.impl_counter.set(next + 1);
925 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
926 let mut sig = "fn ".to_owned();
927 if !generics.params.is_empty() {
929 sig.push_str(&generics
932 .map(|param| param.ident.to_string())
938 sig.push_str(&decl.inputs
940 .map(param_to_string)
945 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
946 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
952 // An AST visitor for collecting paths (e.g., the names of structs) and formal
953 // variables (idents) from patterns.
954 struct PathCollector<'l> {
955 collected_paths: Vec<(NodeId, &'l ast::Path)>,
956 collected_idents: Vec<(NodeId, ast::Ident, ast::Mutability)>,
959 impl<'l> PathCollector<'l> {
960 fn new() -> PathCollector<'l> {
962 collected_paths: vec![],
963 collected_idents: vec![],
968 impl<'l> Visitor<'l> for PathCollector<'l> {
969 fn visit_pat(&mut self, p: &'l ast::Pat) {
971 PatKind::Struct(ref path, ..) => {
972 self.collected_paths.push((p.id, path));
974 PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => {
975 self.collected_paths.push((p.id, path));
977 PatKind::Ident(bm, ident, _) => {
979 "PathCollector, visit ident in pat {}: {:?} {:?}",
984 let immut = match bm {
985 // Even if the ref is mut, you can't change the ref, only
986 // the data pointed at, so showing the initialising expression
987 // is still worthwhile.
988 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
989 ast::BindingMode::ByValue(mt) => mt,
991 self.collected_idents
992 .push((p.id, ident, immut));
996 visit::walk_pat(self, p);
1000 /// Defines what to do with the results of saving the analysis.
1001 pub trait SaveHandler {
1004 save_ctxt: &SaveContext<'_, '_>,
1005 analysis: &Analysis,
1009 /// Dump the save-analysis results to a file.
1010 pub struct DumpHandler<'a> {
1011 odir: Option<&'a Path>,
1015 impl<'a> DumpHandler<'a> {
1016 pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
1019 cratename: cratename.to_owned(),
1023 fn output_file(&self, ctx: &SaveContext<'_, '_>) -> (BufWriter<File>, PathBuf) {
1024 let sess = &ctx.tcx.sess;
1025 let file_name = match ctx.config.output_file {
1026 Some(ref s) => PathBuf::from(s),
1028 let mut root_path = match self.odir {
1029 Some(val) => val.join("save-analysis"),
1030 None => PathBuf::from("save-analysis-temp"),
1033 if let Err(e) = std::fs::create_dir_all(&root_path) {
1034 error!("Could not create directory {}: {}", root_path.display(), e);
1037 let executable = sess.crate_types
1040 .any(|ct| *ct == CrateType::Executable);
1041 let mut out_name = if executable {
1046 out_name.push_str(&self.cratename);
1047 out_name.push_str(&sess.opts.cg.extra_filename);
1048 out_name.push_str(".json");
1049 root_path.push(&out_name);
1055 info!("Writing output to {}", file_name.display());
1057 let output_file = BufWriter::new(File::create(&file_name).unwrap_or_else(
1058 |e| sess.fatal(&format!("Could not open {}: {}", file_name.display(), e)),
1061 (output_file, file_name)
1065 impl SaveHandler for DumpHandler<'_> {
1068 save_ctxt: &SaveContext<'_, '_>,
1069 analysis: &Analysis,
1071 let sess = &save_ctxt.tcx.sess;
1072 let (output, file_name) = self.output_file(&save_ctxt);
1073 if let Err(e) = serde_json::to_writer(output, &analysis) {
1074 error!("Can't serialize save-analysis: {:?}", e);
1077 if sess.opts.json_artifact_notifications {
1078 sess.parse_sess.span_diagnostic
1079 .emit_artifact_notification(&file_name, "save-analysis");
1084 /// Call a callback with the results of save-analysis.
1085 pub struct CallbackHandler<'b> {
1086 pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
1089 impl SaveHandler for CallbackHandler<'_> {
1092 _: &SaveContext<'_, '_>,
1093 analysis: &Analysis,
1095 (self.callback)(analysis)
1099 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
1104 config: Option<Config>,
1107 tcx.dep_graph.with_ignore(|| {
1108 info!("Dumping crate {}", cratename);
1110 // Privacy checking requires and is done after type checking; use a
1111 // fallback in case the access levels couldn't have been correctly computed.
1112 let access_levels = match tcx.sess.compile_status() {
1113 Ok(..) => tcx.privacy_access_levels(LOCAL_CRATE),
1114 Err(..) => tcx.arena.alloc(AccessLevels::default()),
1117 let save_ctxt = SaveContext {
1119 tables: &ty::TypeckTables::empty(None),
1120 empty_tables: &ty::TypeckTables::empty(None),
1121 access_levels: &access_levels,
1122 span_utils: SpanUtils::new(&tcx.sess),
1123 config: find_config(config),
1124 impl_counter: Cell::new(0),
1127 let mut visitor = DumpVisitor::new(save_ctxt);
1129 visitor.dump_crate_info(cratename, krate);
1130 visitor.dump_compilation_options(input, cratename);
1131 visit::walk_crate(&mut visitor, krate);
1133 handler.save(&visitor.save_ctxt, &visitor.analysis())
1137 fn find_config(supplied: Option<Config>) -> Config {
1138 if let Some(config) = supplied {
1142 match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
1143 None => Config::default(),
1144 Some(config) => config.to_str()
1146 .map_err(|_| error!("`RUST_SAVE_ANALYSIS_CONFIG` isn't UTF-8"))
1147 .and_then(|cfg| serde_json::from_str(cfg)
1148 .map_err(|_| error!("Could not deserialize save-analysis config"))
1149 ).unwrap_or_default()
1153 // Utility functions for the module.
1155 // Helper function to escape quotes in a string
1156 fn escape(s: String) -> String {
1157 s.replace("\"", "\"\"")
1160 // Helper function to determine if a span came from a
1161 // macro expansion or syntax extension.
1162 fn generated_code(span: Span) -> bool {
1163 span.from_expansion() || span.is_dummy()
1166 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
1167 // we use our own Id which is the same, but without the newtype.
1168 fn id_from_def_id(id: DefId) -> rls_data::Id {
1170 krate: id.krate.as_u32(),
1171 index: id.index.as_u32(),
1175 fn id_from_node_id(id: NodeId, scx: &SaveContext<'_, '_>) -> rls_data::Id {
1176 let def_id = scx.tcx.hir().opt_local_def_id_from_node_id(id);
1177 def_id.map(|id| id_from_def_id(id)).unwrap_or_else(|| {
1178 // Create a *fake* `DefId` out of a `NodeId` by subtracting the `NodeId`
1179 // out of the maximum u32 value. This will work unless you have *billions*
1180 // of definitions in a single crate (very unlikely to actually happen).
1182 krate: LOCAL_CRATE.as_u32(),
1183 index: !id.as_u32(),
1188 fn null_id() -> rls_data::Id {
1190 krate: u32::max_value(),
1191 index: u32::max_value(),
1195 fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext<'_, '_>) -> Vec<rls_data::Attribute> {
1197 // Only retain real attributes. Doc comments are lowered separately.
1198 .filter(|attr| attr.path != sym::doc)
1200 // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
1201 // attribute. First normalize all inner attribute (#![..]) to outer
1202 // ones (#[..]), then remove the two leading and the one trailing character.
1203 attr.style = ast::AttrStyle::Outer;
1204 let value = pprust::attribute_to_string(&attr);
1205 // This str slicing works correctly, because the leading and trailing characters
1206 // are in the ASCII range and thus exactly one byte each.
1207 let value = value[2..value.len()-1].to_string();
1209 rls_data::Attribute {
1211 span: scx.span_from_span(attr.span),