1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
3 #![deny(rust_2018_idioms)]
5 #![allow(unused_attributes)]
7 #![recursion_limit="256"]
17 use rustc::hir::def::{CtorOf, Res, DefKind as HirDefKind};
19 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
20 use rustc::middle::privacy::AccessLevels;
21 use rustc::middle::cstore::ExternCrate;
22 use rustc::session::config::{CrateType, Input, OutputType};
23 use rustc::ty::{self, DefIdTree, TyCtxt};
24 use rustc::{bug, span_bug};
25 use rustc_codegen_utils::link::{filename_for_metadata, out_filename};
28 use std::default::Default;
31 use std::path::{Path, PathBuf};
33 use syntax::ast::{self, Attribute, DUMMY_NODE_ID, NodeId, PatKind};
34 use syntax::source_map::Spanned;
35 use syntax::parse::lexer::comments::strip_doc_comment_decoration;
36 use syntax::print::pprust;
37 use syntax::visit::{self, Visitor};
38 use syntax::print::pprust::{arg_to_string, ty_to_string};
39 use syntax::source_map::MacroAttribute;
42 use json_dumper::JsonDumper;
43 use dump_visitor::DumpVisitor;
44 use span_utils::SpanUtils;
46 use rls_data::{Def, DefKind, ExternalCrateData, GlobalCrateId, MacroRef, Ref, RefKind, Relation,
47 RelationKind, SpanData, Impl, ImplKind};
48 use rls_data::config::Config;
50 use log::{debug, error, info};
53 pub struct SaveContext<'l, 'tcx: 'l> {
54 tcx: TyCtxt<'l, 'tcx, 'tcx>,
55 tables: &'l ty::TypeckTables<'tcx>,
56 access_levels: &'l AccessLevels,
57 span_utils: SpanUtils<'tcx>,
59 impl_counter: Cell<u32>,
66 RelationData(Relation, Impl),
69 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
70 fn span_from_span(&self, span: Span) -> SpanData {
71 use rls_span::{Column, Row};
73 let cm = self.tcx.sess.source_map();
74 let start = cm.lookup_char_pos(span.lo());
75 let end = cm.lookup_char_pos(span.hi());
78 file_name: start.file.name.to_string().into(),
79 byte_start: span.lo().0,
80 byte_end: span.hi().0,
81 line_start: Row::new_one_indexed(start.line as u32),
82 line_end: Row::new_one_indexed(end.line as u32),
83 column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
84 column_end: Column::new_one_indexed(end.col.0 as u32 + 1),
88 // Returns path to the compilation output (e.g., libfoo-12345678.rmeta)
89 pub fn compilation_output(&self, crate_name: &str) -> PathBuf {
90 let sess = &self.tcx.sess;
91 // Save-analysis is emitted per whole session, not per each crate type
92 let crate_type = sess.crate_types.borrow()[0];
93 let outputs = &*self.tcx.output_filenames(LOCAL_CRATE);
95 if outputs.outputs.contains_key(&OutputType::Metadata) {
96 filename_for_metadata(sess, crate_name, outputs)
97 } else if outputs.outputs.should_codegen() {
98 out_filename(sess, crate_type, outputs, crate_name)
100 // Otherwise it's only a DepInfo, in which case we return early and
101 // not even reach the analysis stage.
106 // List external crates used by the current crate.
107 pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
108 let mut result = Vec::with_capacity(self.tcx.crates().len());
110 for &n in self.tcx.crates().iter() {
111 let span = match self.tcx.extern_crate(n.as_def_id()) {
112 Some(&ExternCrate { span, .. }) => span,
114 debug!("Skipping crate {}, no data", n);
118 let lo_loc = self.span_utils.sess.source_map().lookup_char_pos(span.lo());
119 result.push(ExternalCrateData {
120 // FIXME: change file_name field to PathBuf in rls-data
121 // https://github.com/nrc/rls-data/issues/7
122 file_name: self.span_utils.make_filename_string(&lo_loc.file),
125 name: self.tcx.crate_name(n).to_string(),
126 disambiguator: self.tcx.crate_disambiguator(n).to_fingerprint().as_value(),
134 pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
135 let qualname = format!("::{}",
136 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
138 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
139 filter!(self.span_utils, item.ident.span);
141 Some(Data::DefData(Def {
142 kind: DefKind::ForeignFunction,
143 id: id_from_node_id(item.id, self),
144 span: self.span_from_span(item.ident.span),
145 name: item.ident.to_string(),
147 value: make_signature(decl, generics),
151 docs: self.docs_for_attrs(&item.attrs),
152 sig: sig::foreign_item_signature(item, self),
153 attributes: lower_attributes(item.attrs.clone(), self),
156 ast::ForeignItemKind::Static(ref ty, _) => {
157 filter!(self.span_utils, item.ident.span);
159 let id = id_from_node_id(item.id, self);
160 let span = self.span_from_span(item.ident.span);
162 Some(Data::DefData(Def {
163 kind: DefKind::ForeignStatic,
166 name: item.ident.to_string(),
168 value: ty_to_string(ty),
172 docs: self.docs_for_attrs(&item.attrs),
173 sig: sig::foreign_item_signature(item, self),
174 attributes: lower_attributes(item.attrs.clone(), self),
177 // FIXME(plietar): needs a new DefKind in rls-data
178 ast::ForeignItemKind::Ty => None,
179 ast::ForeignItemKind::Macro(..) => None,
183 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
185 ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
186 let qualname = format!("::{}",
187 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
188 filter!(self.span_utils, item.ident.span);
189 Some(Data::DefData(Def {
190 kind: DefKind::Function,
191 id: id_from_node_id(item.id, self),
192 span: self.span_from_span(item.ident.span),
193 name: item.ident.to_string(),
195 value: make_signature(decl, generics),
199 docs: self.docs_for_attrs(&item.attrs),
200 sig: sig::item_signature(item, self),
201 attributes: lower_attributes(item.attrs.clone(), self),
204 ast::ItemKind::Static(ref typ, ..) => {
205 let qualname = format!("::{}",
206 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
208 filter!(self.span_utils, item.ident.span);
210 let id = id_from_node_id(item.id, self);
211 let span = self.span_from_span(item.ident.span);
213 Some(Data::DefData(Def {
214 kind: DefKind::Static,
217 name: item.ident.to_string(),
219 value: ty_to_string(&typ),
223 docs: self.docs_for_attrs(&item.attrs),
224 sig: sig::item_signature(item, self),
225 attributes: lower_attributes(item.attrs.clone(), self),
228 ast::ItemKind::Const(ref typ, _) => {
229 let qualname = format!("::{}",
230 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
231 filter!(self.span_utils, item.ident.span);
233 let id = id_from_node_id(item.id, self);
234 let span = self.span_from_span(item.ident.span);
236 Some(Data::DefData(Def {
237 kind: DefKind::Const,
240 name: item.ident.to_string(),
242 value: ty_to_string(typ),
246 docs: self.docs_for_attrs(&item.attrs),
247 sig: sig::item_signature(item, self),
248 attributes: lower_attributes(item.attrs.clone(), self),
251 ast::ItemKind::Mod(ref m) => {
252 let qualname = format!("::{}",
253 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
255 let cm = self.tcx.sess.source_map();
256 let filename = cm.span_to_filename(m.inner);
258 filter!(self.span_utils, item.ident.span);
260 Some(Data::DefData(Def {
262 id: id_from_node_id(item.id, self),
263 name: item.ident.to_string(),
265 span: self.span_from_span(item.ident.span),
266 value: filename.to_string(),
270 .map(|i| id_from_node_id(i.id, self))
273 docs: self.docs_for_attrs(&item.attrs),
274 sig: sig::item_signature(item, self),
275 attributes: lower_attributes(item.attrs.clone(), self),
278 ast::ItemKind::Enum(ref def, _) => {
279 let name = item.ident.to_string();
280 let qualname = format!("::{}",
281 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
282 filter!(self.span_utils, item.ident.span);
283 let variants_str = def.variants
285 .map(|v| v.node.ident.to_string())
288 let value = format!("{}::{{{}}}", name, variants_str);
289 Some(Data::DefData(Def {
291 id: id_from_node_id(item.id, self),
292 span: self.span_from_span(item.ident.span),
297 children: def.variants
299 .map(|v| id_from_node_id(v.node.id, self))
302 docs: self.docs_for_attrs(&item.attrs),
303 sig: sig::item_signature(item, self),
304 attributes: lower_attributes(item.attrs.clone(), self),
307 ast::ItemKind::Impl(.., ref trait_ref, ref typ, ref impls) => {
308 if let ast::TyKind::Path(None, ref path) = typ.node {
309 // Common case impl for a struct or something basic.
310 if generated_code(path.span) {
313 let sub_span = path.segments.last().unwrap().ident.span;
314 filter!(self.span_utils, sub_span);
316 let impl_id = self.next_impl_id();
317 let span = self.span_from_span(sub_span);
319 let type_data = self.lookup_ref_id(typ.id);
320 type_data.map(|type_data| {
321 Data::RelationData(Relation {
322 kind: RelationKind::Impl {
326 from: id_from_def_id(type_data),
329 .and_then(|t| self.lookup_ref_id(t.ref_id))
331 .unwrap_or_else(|| null_id()),
335 kind: match *trait_ref {
336 Some(_) => ImplKind::Direct,
337 None => ImplKind::Inherent,
340 value: String::new(),
344 .map(|i| id_from_node_id(i.id, self))
362 pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<Def> {
363 if let Some(ident) = field.ident {
364 let name = ident.to_string();
365 let qualname = format!("::{}::{}",
366 self.tcx.def_path_str(self.tcx.hir().local_def_id(scope)),
368 filter!(self.span_utils, ident.span);
369 let def_id = self.tcx.hir().local_def_id(field.id);
370 let typ = self.tcx.type_of(def_id).to_string();
373 let id = id_from_node_id(field.id, self);
374 let span = self.span_from_span(ident.span);
377 kind: DefKind::Field,
383 parent: Some(id_from_node_id(scope, self)),
386 docs: self.docs_for_attrs(&field.attrs),
387 sig: sig::field_signature(field, self),
388 attributes: lower_attributes(field.attrs.clone(), self),
395 // FIXME would be nice to take a MethodItem here, but the ast provides both
396 // trait and impl flavours, so the caller must do the disassembly.
397 pub fn get_method_data(&self, id: ast::NodeId, ident: ast::Ident, span: Span) -> Option<Def> {
398 // The qualname for a method is the trait name or name of the struct in an impl in
399 // which the method is declared in, followed by the method's name.
400 let (qualname, parent_scope, decl_id, docs, attributes) =
401 match self.tcx.impl_of_method(self.tcx.hir().local_def_id(id)) {
402 Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) {
403 Some(Node::Item(item)) => match item.node {
404 hir::ItemKind::Impl(.., ref ty, _) => {
405 let mut qualname = String::from("<");
406 qualname.push_str(&self.tcx.hir().hir_to_pretty_string(ty.hir_id));
408 let trait_id = self.tcx.trait_id_of_impl(impl_id);
409 let mut decl_id = None;
410 let mut docs = String::new();
411 let mut attrs = vec![];
412 if let Some(Node::ImplItem(item)) = self.tcx.hir().find(id) {
413 docs = self.docs_for_attrs(&item.attrs);
414 attrs = item.attrs.to_vec();
417 if let Some(def_id) = trait_id {
418 // A method in a trait impl.
419 qualname.push_str(" as ");
420 qualname.push_str(&self.tcx.def_path_str(def_id));
422 .associated_items(def_id)
423 .find(|item| item.ident.name == ident.name)
424 .map(|item| decl_id = Some(item.def_id));
426 qualname.push_str(">");
428 (qualname, trait_id, decl_id, docs, attrs)
433 "Container {:?} for method {} not an impl?",
442 "Container {:?} for method {} is not a node item {:?}",
449 None => match self.tcx.trait_of_item(self.tcx.hir().local_def_id(id)) {
451 let mut docs = String::new();
452 let mut attrs = vec![];
454 if let Some(Node::TraitItem(item)) = self.tcx.hir().find(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_ref_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 hir_node = self.tcx.hir().expect_expr(expr.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 hir_node = match self.tcx.hir().find(sub_ex.id) {
523 Some(Node::Expr(expr)) => expr,
526 "Missing or weird node for sub-expression {} in {:?}",
533 match self.tables.expr_ty_adjusted(&hir_node).sty {
534 ty::Adt(def, _) if !def.is_enum() => {
535 let variant = &def.non_enum_variant();
536 let index = self.tcx.find_field_index(ident, variant).unwrap();
537 filter!(self.span_utils, ident.span);
538 let span = self.span_from_span(ident.span);
539 return Some(Data::RefData(Ref {
540 kind: RefKind::Variable,
542 ref_id: id_from_def_id(variant.fields[index].did),
545 ty::Tuple(..) => None,
547 debug!("Expected struct or union type, found {:?}", ty);
552 ast::ExprKind::Struct(ref path, ..) => {
553 match self.tables.expr_ty_adjusted(&hir_node).sty {
554 ty::Adt(def, _) if !def.is_enum() => {
555 let sub_span = path.segments.last().unwrap().ident.span;
556 filter!(self.span_utils, sub_span);
557 let span = self.span_from_span(sub_span);
558 Some(Data::RefData(Ref {
561 ref_id: id_from_def_id(def.did),
565 // FIXME ty could legitimately be an enum, but then we will fail
566 // later if we try to look up the fields.
567 debug!("expected struct or union, found {:?}", ty);
572 ast::ExprKind::MethodCall(ref seg, ..) => {
573 let expr_hir_id = self.tcx.hir().definitions().node_to_hir_id(expr.id);
574 let method_id = match self.tables.type_dependent_def_id(expr_hir_id) {
577 debug!("Could not resolve method id for {:?}", expr);
581 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
582 ty::ImplContainer(_) => (Some(method_id), None),
583 ty::TraitContainer(_) => (None, Some(method_id)),
585 let sub_span = seg.ident.span;
586 filter!(self.span_utils, sub_span);
587 let span = self.span_from_span(sub_span);
588 Some(Data::RefData(Ref {
589 kind: RefKind::Function,
593 .map(|id| id_from_def_id(id))
594 .unwrap_or_else(|| null_id()),
597 ast::ExprKind::Path(_, ref path) => {
598 self.get_path_data(expr.id, path).map(|d| Data::RefData(d))
607 pub fn get_path_res(&self, id: NodeId) -> Res {
608 match self.tcx.hir().get(id) {
609 Node::TraitRef(tr) => tr.path.res,
611 Node::Item(&hir::Item {
612 node: hir::ItemKind::Use(ref path, _),
615 Node::Visibility(&Spanned {
616 node: hir::VisibilityKind::Restricted { ref path, .. }, .. }) => path.res,
618 Node::PathSegment(seg) => {
620 Some(res) if res != Res::Err => res,
621 _ => self.get_path_res(self.tcx.hir().get_parent_node(id)),
625 Node::Expr(&hir::Expr {
626 node: hir::ExprKind::Struct(ref qpath, ..),
629 let hir_id = self.tcx.hir().node_to_hir_id(id);
630 self.tables.qpath_res(qpath, hir_id)
633 Node::Expr(&hir::Expr {
634 node: hir::ExprKind::Path(ref qpath),
637 Node::Pat(&hir::Pat {
638 node: hir::PatKind::Path(ref qpath),
641 Node::Pat(&hir::Pat {
642 node: hir::PatKind::Struct(ref qpath, ..),
645 Node::Pat(&hir::Pat {
646 node: hir::PatKind::TupleStruct(ref qpath, ..),
650 node: hir::TyKind::Path(ref qpath),
653 let hir_id = self.tcx.hir().node_to_hir_id(id);
654 self.tables.qpath_res(qpath, hir_id)
657 Node::Binding(&hir::Pat {
658 node: hir::PatKind::Binding(_, canonical_id, ..),
660 }) => Res::Local(canonical_id),
666 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Ref> {
670 self.get_path_segment_data(seg)
671 .or_else(|| self.get_path_segment_data_with_id(seg, id))
675 pub fn get_path_segment_data(&self, path_seg: &ast::PathSegment) -> Option<Ref> {
676 self.get_path_segment_data_with_id(path_seg, path_seg.id)
679 fn get_path_segment_data_with_id(
681 path_seg: &ast::PathSegment,
684 // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
685 fn fn_type(seg: &ast::PathSegment) -> bool {
686 if let Some(ref generic_args) = seg.args {
687 if let ast::GenericArgs::Parenthesized(_) = **generic_args {
694 if id == DUMMY_NODE_ID {
698 let res = self.get_path_res(id);
699 let span = path_seg.ident.span;
700 filter!(self.span_utils, span);
701 let span = self.span_from_span(span);
706 kind: RefKind::Variable,
708 ref_id: id_from_node_id(self.tcx.hir().hir_to_node_id(id), self),
711 Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
715 ref_id: id_from_def_id(def_id),
718 Res::Def(HirDefKind::Struct, def_id) |
719 Res::Def(HirDefKind::Variant, def_id) |
720 Res::Def(HirDefKind::Union, def_id) |
721 Res::Def(HirDefKind::Enum, def_id) |
722 Res::Def(HirDefKind::TyAlias, def_id) |
723 Res::Def(HirDefKind::ForeignTy, def_id) |
724 Res::Def(HirDefKind::TraitAlias, def_id) |
725 Res::Def(HirDefKind::AssocExistential, def_id) |
726 Res::Def(HirDefKind::AssocTy, def_id) |
727 Res::Def(HirDefKind::Trait, def_id) |
728 Res::Def(HirDefKind::Existential, def_id) |
729 Res::Def(HirDefKind::TyParam, def_id) => {
733 ref_id: id_from_def_id(def_id),
736 Res::Def(HirDefKind::ConstParam, def_id) => {
738 kind: RefKind::Variable,
740 ref_id: id_from_def_id(def_id),
743 Res::Def(HirDefKind::Ctor(CtorOf::Struct, ..), def_id) => {
744 // This is a reference to a tuple struct where the def_id points
745 // to an invisible constructor function. That is not a very useful
746 // def, so adjust to point to the tuple struct itself.
747 let parent_def_id = self.tcx.parent(def_id).unwrap();
751 ref_id: id_from_def_id(parent_def_id),
754 Res::Def(HirDefKind::Static, _) |
755 Res::Def(HirDefKind::Const, _) |
756 Res::Def(HirDefKind::AssocConst, _) |
757 Res::Def(HirDefKind::Ctor(..), _) => {
759 kind: RefKind::Variable,
761 ref_id: id_from_def_id(res.def_id()),
764 Res::Def(HirDefKind::Method, decl_id) => {
765 let def_id = if decl_id.is_local() {
766 let ti = self.tcx.associated_item(decl_id);
768 .associated_items(ti.container.id())
769 .find(|item| item.ident.name == ti.ident.name &&
770 item.defaultness.has_value())
771 .map(|item| item.def_id)
776 kind: RefKind::Function,
778 ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
781 Res::Def(HirDefKind::Fn, def_id) => {
783 kind: RefKind::Function,
785 ref_id: id_from_def_id(def_id),
788 Res::Def(HirDefKind::Mod, def_id) => {
792 ref_id: id_from_def_id(def_id),
797 Res::Def(HirDefKind::Macro(..), _) |
799 Res::NonMacroAttr(..) |
805 pub fn get_field_ref_data(
807 field_ref: &ast::Field,
808 variant: &ty::VariantDef,
810 filter!(self.span_utils, field_ref.ident.span);
811 self.tcx.find_field_index(field_ref.ident, variant).map(|index| {
812 let span = self.span_from_span(field_ref.ident.span);
814 kind: RefKind::Variable,
816 ref_id: id_from_def_id(variant.fields[index].did),
821 /// Attempt to return MacroRef for any AST node.
823 /// For a given piece of AST defined by the supplied Span and NodeId,
824 /// returns `None` if the node is not macro-generated or the span is malformed,
825 /// else uses the expansion callsite and callee to return some MacroRef.
826 pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
827 if !generated_code(span) {
830 // Note we take care to use the source callsite/callee, to handle
831 // nested expansions and ensure we only generate data for source-visible
833 let callsite = span.source_callsite();
834 let callsite_span = self.span_from_span(callsite);
835 let callee = span.source_callee()?;
836 let callee_span = callee.def_site?;
838 // Ignore attribute macros, their spans are usually mangled
839 if let MacroAttribute(_) = callee.format {
843 // If the callee is an imported macro from an external crate, need to get
844 // the source span and name from the session, as their spans are localized
845 // when read in, and no longer correspond to the source.
846 if let Some(mac) = self.tcx
848 .imported_macro_spans
852 let &(ref mac_name, mac_span) = mac;
853 let mac_span = self.span_from_span(mac_span);
854 return Some(MacroRef {
856 qualname: mac_name.clone(), // FIXME: generate the real qualname
857 callee_span: mac_span,
861 let callee_span = self.span_from_span(callee_span);
864 qualname: callee.format.name().to_string(), // FIXME: generate the real qualname
869 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
870 match self.get_path_res(ref_id) {
871 Res::PrimTy(_) | Res::SelfTy(..) | Res::Err => None,
872 def => Some(def.def_id()),
876 fn docs_for_attrs(&self, attrs: &[Attribute]) -> String {
877 let mut result = String::new();
880 if attr.check_name(sym::doc) {
881 if let Some(val) = attr.value_str() {
882 if attr.is_sugared_doc {
883 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
885 result.push_str(&val.as_str());
888 } else if let Some(meta_list) = attr.meta_item_list() {
889 meta_list.into_iter()
890 .filter(|it| it.check_name(sym::include))
891 .filter_map(|it| it.meta_item_list().map(|l| l.to_owned()))
893 .filter(|meta| meta.check_name(sym::contents))
894 .filter_map(|meta| meta.value_str())
896 result.push_str(&val.as_str());
903 if !self.config.full_docs {
904 if let Some(index) = result.find("\n\n") {
905 result.truncate(index);
912 fn next_impl_id(&self) -> u32 {
913 let next = self.impl_counter.get();
914 self.impl_counter.set(next + 1);
919 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
920 let mut sig = "fn ".to_owned();
921 if !generics.params.is_empty() {
923 sig.push_str(&generics
926 .map(|param| param.ident.to_string())
932 sig.push_str(&decl.inputs
939 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
940 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
946 // An AST visitor for collecting paths (e.g., the names of structs) and formal
947 // variables (idents) from patterns.
948 struct PathCollector<'l> {
949 collected_paths: Vec<(NodeId, &'l ast::Path)>,
950 collected_idents: Vec<(NodeId, ast::Ident, ast::Mutability)>,
953 impl<'l> PathCollector<'l> {
954 fn new() -> PathCollector<'l> {
956 collected_paths: vec![],
957 collected_idents: vec![],
962 impl<'l, 'a: 'l> Visitor<'a> for PathCollector<'l> {
963 fn visit_pat(&mut self, p: &'a ast::Pat) {
965 PatKind::Struct(ref path, ..) => {
966 self.collected_paths.push((p.id, path));
968 PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => {
969 self.collected_paths.push((p.id, path));
971 PatKind::Ident(bm, ident, _) => {
973 "PathCollector, visit ident in pat {}: {:?} {:?}",
978 let immut = match bm {
979 // Even if the ref is mut, you can't change the ref, only
980 // the data pointed at, so showing the initialising expression
981 // is still worthwhile.
982 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
983 ast::BindingMode::ByValue(mt) => mt,
985 self.collected_idents
986 .push((p.id, ident, immut));
990 visit::walk_pat(self, p);
994 /// Defines what to do with the results of saving the analysis.
995 pub trait SaveHandler {
998 save_ctxt: SaveContext<'l, 'tcx>,
1005 /// Dump the save-analysis results to a file.
1006 pub struct DumpHandler<'a> {
1007 odir: Option<&'a Path>,
1011 impl<'a> DumpHandler<'a> {
1012 pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
1015 cratename: cratename.to_owned(),
1019 fn output_file(&self, ctx: &SaveContext<'_, '_>) -> File {
1020 let sess = &ctx.tcx.sess;
1021 let file_name = match ctx.config.output_file {
1022 Some(ref s) => PathBuf::from(s),
1024 let mut root_path = match self.odir {
1025 Some(val) => val.join("save-analysis"),
1026 None => PathBuf::from("save-analysis-temp"),
1029 if let Err(e) = std::fs::create_dir_all(&root_path) {
1030 error!("Could not create directory {}: {}", root_path.display(), e);
1033 let executable = sess.crate_types
1036 .any(|ct| *ct == CrateType::Executable);
1037 let mut out_name = if executable {
1042 out_name.push_str(&self.cratename);
1043 out_name.push_str(&sess.opts.cg.extra_filename);
1044 out_name.push_str(".json");
1045 root_path.push(&out_name);
1051 info!("Writing output to {}", file_name.display());
1053 let output_file = File::create(&file_name).unwrap_or_else(
1054 |e| sess.fatal(&format!("Could not open {}: {}", file_name.display(), e)),
1061 impl<'a> SaveHandler for DumpHandler<'a> {
1064 save_ctxt: SaveContext<'l, 'tcx>,
1069 let output = &mut self.output_file(&save_ctxt);
1070 let mut dumper = JsonDumper::new(output, save_ctxt.config.clone());
1071 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1073 visitor.dump_crate_info(cratename, krate);
1074 visitor.dump_compilation_options(input, cratename);
1075 visit::walk_crate(&mut visitor, krate);
1079 /// Call a callback with the results of save-analysis.
1080 pub struct CallbackHandler<'b> {
1081 pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
1084 impl<'b> SaveHandler for CallbackHandler<'b> {
1087 save_ctxt: SaveContext<'l, 'tcx>,
1092 // We're using the JsonDumper here because it has the format of the
1093 // save-analysis results that we will pass to the callback. IOW, we are
1094 // using the JsonDumper to collect the save-analysis results, but not
1095 // actually to dump them to a file. This is all a bit convoluted and
1096 // there is certainly a simpler design here trying to get out (FIXME).
1097 let mut dumper = JsonDumper::with_callback(self.callback, save_ctxt.config.clone());
1098 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1100 visitor.dump_crate_info(cratename, krate);
1101 visitor.dump_compilation_options(input, cratename);
1102 visit::walk_crate(&mut visitor, krate);
1106 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
1107 tcx: TyCtxt<'l, 'tcx, 'tcx>,
1111 config: Option<Config>,
1114 tcx.dep_graph.with_ignore(|| {
1115 info!("Dumping crate {}", cratename);
1117 // Privacy checking requires and is done after type checking; use a
1118 // fallback in case the access levels couldn't have been correctly computed.
1119 let access_levels = match tcx.sess.compile_status() {
1120 Ok(..) => tcx.privacy_access_levels(LOCAL_CRATE),
1121 Err(..) => tcx.arena.alloc(AccessLevels::default()),
1124 let save_ctxt = SaveContext {
1126 tables: &ty::TypeckTables::empty(None),
1127 access_levels: &access_levels,
1128 span_utils: SpanUtils::new(&tcx.sess),
1129 config: find_config(config),
1130 impl_counter: Cell::new(0),
1133 handler.save(save_ctxt, krate, cratename, input)
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.ctxt() != NO_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(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),