1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
3 #![deny(rust_2018_idioms)]
5 #![deny(unused_lifetimes)]
6 #![allow(unused_attributes)]
8 #![recursion_limit="256"]
18 use rustc::hir::def::{CtorOf, Res, DefKind as HirDefKind};
20 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
21 use rustc::middle::privacy::AccessLevels;
22 use rustc::middle::cstore::ExternCrate;
23 use rustc::session::config::{CrateType, Input, OutputType};
24 use rustc::ty::{self, DefIdTree, TyCtxt};
25 use rustc::{bug, span_bug};
26 use rustc_codegen_utils::link::{filename_for_metadata, out_filename};
29 use std::default::Default;
32 use std::path::{Path, PathBuf};
34 use syntax::ast::{self, Attribute, DUMMY_NODE_ID, NodeId, PatKind};
35 use syntax::source_map::Spanned;
36 use syntax::parse::lexer::comments::strip_doc_comment_decoration;
37 use syntax::print::pprust;
38 use syntax::visit::{self, Visitor};
39 use syntax::print::pprust::{arg_to_string, ty_to_string};
40 use syntax::source_map::MacroAttribute;
43 use json_dumper::JsonDumper;
44 use dump_visitor::DumpVisitor;
45 use span_utils::SpanUtils;
47 use rls_data::{Def, DefKind, ExternalCrateData, GlobalCrateId, MacroRef, Ref, RefKind, Relation,
48 RelationKind, SpanData, Impl, ImplKind};
49 use rls_data::config::Config;
51 use log::{debug, error, info};
54 pub struct SaveContext<'l, 'tcx> {
56 tables: &'l ty::TypeckTables<'tcx>,
57 access_levels: &'l AccessLevels,
58 span_utils: SpanUtils<'tcx>,
60 impl_counter: Cell<u32>,
67 RelationData(Relation, Impl),
70 impl<'l, 'tcx> SaveContext<'l, 'tcx> {
71 fn span_from_span(&self, span: Span) -> SpanData {
72 use rls_span::{Column, Row};
74 let cm = self.tcx.sess.source_map();
75 let start = cm.lookup_char_pos(span.lo());
76 let end = cm.lookup_char_pos(span.hi());
79 file_name: start.file.name.to_string().into(),
80 byte_start: span.lo().0,
81 byte_end: span.hi().0,
82 line_start: Row::new_one_indexed(start.line as u32),
83 line_end: Row::new_one_indexed(end.line as u32),
84 column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
85 column_end: Column::new_one_indexed(end.col.0 as u32 + 1),
89 // Returns path to the compilation output (e.g., libfoo-12345678.rmeta)
90 pub fn compilation_output(&self, crate_name: &str) -> PathBuf {
91 let sess = &self.tcx.sess;
92 // Save-analysis is emitted per whole session, not per each crate type
93 let crate_type = sess.crate_types.borrow()[0];
94 let outputs = &*self.tcx.output_filenames(LOCAL_CRATE);
96 if outputs.outputs.contains_key(&OutputType::Metadata) {
97 filename_for_metadata(sess, crate_name, outputs)
98 } else if outputs.outputs.should_codegen() {
99 out_filename(sess, crate_type, outputs, crate_name)
101 // Otherwise it's only a DepInfo, in which case we return early and
102 // not even reach the analysis stage.
107 // List external crates used by the current crate.
108 pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
109 let mut result = Vec::with_capacity(self.tcx.crates().len());
111 for &n in self.tcx.crates().iter() {
112 let span = match self.tcx.extern_crate(n.as_def_id()) {
113 Some(&ExternCrate { span, .. }) => span,
115 debug!("Skipping crate {}, no data", n);
119 let lo_loc = self.span_utils.sess.source_map().lookup_char_pos(span.lo());
120 result.push(ExternalCrateData {
121 // FIXME: change file_name field to PathBuf in rls-data
122 // https://github.com/nrc/rls-data/issues/7
123 file_name: self.span_utils.make_filename_string(&lo_loc.file),
126 name: self.tcx.crate_name(n).to_string(),
127 disambiguator: self.tcx.crate_disambiguator(n).to_fingerprint().as_value(),
135 pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
136 let qualname = format!("::{}",
137 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
139 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
140 filter!(self.span_utils, item.ident.span);
142 Some(Data::DefData(Def {
143 kind: DefKind::ForeignFunction,
144 id: id_from_node_id(item.id, self),
145 span: self.span_from_span(item.ident.span),
146 name: item.ident.to_string(),
148 value: make_signature(decl, generics),
152 docs: self.docs_for_attrs(&item.attrs),
153 sig: sig::foreign_item_signature(item, self),
154 attributes: lower_attributes(item.attrs.clone(), self),
157 ast::ForeignItemKind::Static(ref ty, _) => {
158 filter!(self.span_utils, item.ident.span);
160 let id = id_from_node_id(item.id, self);
161 let span = self.span_from_span(item.ident.span);
163 Some(Data::DefData(Def {
164 kind: DefKind::ForeignStatic,
167 name: item.ident.to_string(),
169 value: ty_to_string(ty),
173 docs: self.docs_for_attrs(&item.attrs),
174 sig: sig::foreign_item_signature(item, self),
175 attributes: lower_attributes(item.attrs.clone(), self),
178 // FIXME(plietar): needs a new DefKind in rls-data
179 ast::ForeignItemKind::Ty => None,
180 ast::ForeignItemKind::Macro(..) => None,
184 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
186 ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
187 let qualname = format!("::{}",
188 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
189 filter!(self.span_utils, item.ident.span);
190 Some(Data::DefData(Def {
191 kind: DefKind::Function,
192 id: id_from_node_id(item.id, self),
193 span: self.span_from_span(item.ident.span),
194 name: item.ident.to_string(),
196 value: make_signature(decl, generics),
200 docs: self.docs_for_attrs(&item.attrs),
201 sig: sig::item_signature(item, self),
202 attributes: lower_attributes(item.attrs.clone(), self),
205 ast::ItemKind::Static(ref typ, ..) => {
206 let qualname = format!("::{}",
207 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
209 filter!(self.span_utils, item.ident.span);
211 let id = id_from_node_id(item.id, self);
212 let span = self.span_from_span(item.ident.span);
214 Some(Data::DefData(Def {
215 kind: DefKind::Static,
218 name: item.ident.to_string(),
220 value: ty_to_string(&typ),
224 docs: self.docs_for_attrs(&item.attrs),
225 sig: sig::item_signature(item, self),
226 attributes: lower_attributes(item.attrs.clone(), self),
229 ast::ItemKind::Const(ref typ, _) => {
230 let qualname = format!("::{}",
231 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
232 filter!(self.span_utils, item.ident.span);
234 let id = id_from_node_id(item.id, self);
235 let span = self.span_from_span(item.ident.span);
237 Some(Data::DefData(Def {
238 kind: DefKind::Const,
241 name: item.ident.to_string(),
243 value: ty_to_string(typ),
247 docs: self.docs_for_attrs(&item.attrs),
248 sig: sig::item_signature(item, self),
249 attributes: lower_attributes(item.attrs.clone(), self),
252 ast::ItemKind::Mod(ref m) => {
253 let qualname = format!("::{}",
254 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
256 let cm = self.tcx.sess.source_map();
257 let filename = cm.span_to_filename(m.inner);
259 filter!(self.span_utils, item.ident.span);
261 Some(Data::DefData(Def {
263 id: id_from_node_id(item.id, self),
264 name: item.ident.to_string(),
266 span: self.span_from_span(item.ident.span),
267 value: filename.to_string(),
271 .map(|i| id_from_node_id(i.id, self))
274 docs: self.docs_for_attrs(&item.attrs),
275 sig: sig::item_signature(item, self),
276 attributes: lower_attributes(item.attrs.clone(), self),
279 ast::ItemKind::Enum(ref def, _) => {
280 let name = item.ident.to_string();
281 let qualname = format!("::{}",
282 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
283 filter!(self.span_utils, item.ident.span);
284 let variants_str = def.variants
286 .map(|v| v.node.ident.to_string())
289 let value = format!("{}::{{{}}}", name, variants_str);
290 Some(Data::DefData(Def {
292 id: id_from_node_id(item.id, self),
293 span: self.span_from_span(item.ident.span),
298 children: def.variants
300 .map(|v| id_from_node_id(v.node.id, self))
303 docs: self.docs_for_attrs(&item.attrs),
304 sig: sig::item_signature(item, self),
305 attributes: lower_attributes(item.attrs.clone(), self),
308 ast::ItemKind::Impl(.., ref trait_ref, ref typ, ref impls) => {
309 if let ast::TyKind::Path(None, ref path) = typ.node {
310 // Common case impl for a struct or something basic.
311 if generated_code(path.span) {
314 let sub_span = path.segments.last().unwrap().ident.span;
315 filter!(self.span_utils, sub_span);
317 let impl_id = self.next_impl_id();
318 let span = self.span_from_span(sub_span);
320 let type_data = self.lookup_ref_id(typ.id);
321 type_data.map(|type_data| {
322 Data::RelationData(Relation {
323 kind: RelationKind::Impl {
327 from: id_from_def_id(type_data),
330 .and_then(|t| self.lookup_ref_id(t.ref_id))
332 .unwrap_or_else(|| null_id()),
336 kind: match *trait_ref {
337 Some(_) => ImplKind::Direct,
338 None => ImplKind::Inherent,
341 value: String::new(),
345 .map(|i| id_from_node_id(i.id, self))
363 pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<Def> {
364 if let Some(ident) = field.ident {
365 let name = ident.to_string();
366 let qualname = format!("::{}::{}",
367 self.tcx.def_path_str(self.tcx.hir().local_def_id(scope)),
369 filter!(self.span_utils, ident.span);
370 let def_id = self.tcx.hir().local_def_id(field.id);
371 let typ = self.tcx.type_of(def_id).to_string();
374 let id = id_from_node_id(field.id, self);
375 let span = self.span_from_span(ident.span);
378 kind: DefKind::Field,
384 parent: Some(id_from_node_id(scope, self)),
387 docs: self.docs_for_attrs(&field.attrs),
388 sig: sig::field_signature(field, self),
389 attributes: lower_attributes(field.attrs.clone(), self),
396 // FIXME would be nice to take a MethodItem here, but the ast provides both
397 // trait and impl flavours, so the caller must do the disassembly.
398 pub fn get_method_data(&self, id: ast::NodeId, ident: ast::Ident, span: Span) -> Option<Def> {
399 // The qualname for a method is the trait name or name of the struct in an impl in
400 // which the method is declared in, followed by the method's name.
401 let (qualname, parent_scope, decl_id, docs, attributes) =
402 match self.tcx.impl_of_method(self.tcx.hir().local_def_id(id)) {
403 Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) {
404 Some(Node::Item(item)) => match item.node {
405 hir::ItemKind::Impl(.., ref ty, _) => {
406 let mut qualname = String::from("<");
407 qualname.push_str(&self.tcx.hir().hir_to_pretty_string(ty.hir_id));
409 let trait_id = self.tcx.trait_id_of_impl(impl_id);
410 let mut decl_id = None;
411 let mut docs = String::new();
412 let mut attrs = vec![];
413 if let Some(Node::ImplItem(item)) = self.tcx.hir().find(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(id)) {
452 let mut docs = String::new();
453 let mut attrs = vec![];
455 if let Some(Node::TraitItem(item)) = self.tcx.hir().find(id) {
456 docs = self.docs_for_attrs(&item.attrs);
457 attrs = item.attrs.to_vec();
461 format!("::{}", self.tcx.def_path_str(def_id)),
469 debug!("Could not find container for method {} at {:?}", id, span);
470 // This is not necessarily a bug, if there was a compilation error,
471 // the tables we need might not exist.
477 let qualname = format!("{}::{}", qualname, ident.name);
479 filter!(self.span_utils, ident.span);
482 kind: DefKind::Method,
483 id: id_from_node_id(id, self),
484 span: self.span_from_span(ident.span),
485 name: ident.name.to_string(),
487 // FIXME you get better data here by using the visitor.
488 value: String::new(),
489 parent: parent_scope.map(|id| id_from_def_id(id)),
491 decl_id: decl_id.map(|id| id_from_def_id(id)),
494 attributes: lower_attributes(attributes, self),
498 pub fn get_trait_ref_data(&self, trait_ref: &ast::TraitRef) -> Option<Ref> {
499 self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
500 let span = trait_ref.path.span;
501 if generated_code(span) {
504 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
505 filter!(self.span_utils, sub_span);
506 let span = self.span_from_span(sub_span);
510 ref_id: id_from_def_id(def_id),
515 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
516 let expr_hir_id = self.tcx.hir().node_to_hir_id(expr.id);
517 let hir_node = self.tcx.hir().expect_expr(expr_hir_id);
518 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
519 if ty.is_none() || ty.unwrap().sty == ty::Error {
523 ast::ExprKind::Field(ref sub_ex, ident) => {
524 let hir_node = match self.tcx.hir().find(sub_ex.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).sty {
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).sty {
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 node: 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,
624 _ => self.get_path_res(self.tcx.hir().get_parent_node(id)),
628 Node::Expr(&hir::Expr {
629 node: hir::ExprKind::Struct(ref qpath, ..),
632 self.tables.qpath_res(qpath, hir_id)
635 Node::Expr(&hir::Expr {
636 node: hir::ExprKind::Path(ref qpath),
639 Node::Pat(&hir::Pat {
640 node: hir::PatKind::Path(ref qpath),
643 Node::Pat(&hir::Pat {
644 node: hir::PatKind::Struct(ref qpath, ..),
647 Node::Pat(&hir::Pat {
648 node: hir::PatKind::TupleStruct(ref qpath, ..),
652 node: hir::TyKind::Path(ref qpath),
655 self.tables.qpath_res(qpath, hir_id)
658 Node::Binding(&hir::Pat {
659 node: hir::PatKind::Binding(_, canonical_id, ..),
661 }) => Res::Local(canonical_id),
667 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Ref> {
671 self.get_path_segment_data(seg)
672 .or_else(|| self.get_path_segment_data_with_id(seg, id))
676 pub fn get_path_segment_data(&self, path_seg: &ast::PathSegment) -> Option<Ref> {
677 self.get_path_segment_data_with_id(path_seg, path_seg.id)
680 fn get_path_segment_data_with_id(
682 path_seg: &ast::PathSegment,
685 // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
686 fn fn_type(seg: &ast::PathSegment) -> bool {
687 if let Some(ref generic_args) = seg.args {
688 if let ast::GenericArgs::Parenthesized(_) = **generic_args {
695 if id == DUMMY_NODE_ID {
699 let res = self.get_path_res(id);
700 let span = path_seg.ident.span;
701 filter!(self.span_utils, span);
702 let span = self.span_from_span(span);
707 kind: RefKind::Variable,
709 ref_id: id_from_node_id(self.tcx.hir().hir_to_node_id(id), self),
712 Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
716 ref_id: id_from_def_id(def_id),
719 Res::Def(HirDefKind::Struct, def_id) |
720 Res::Def(HirDefKind::Variant, def_id) |
721 Res::Def(HirDefKind::Union, def_id) |
722 Res::Def(HirDefKind::Enum, def_id) |
723 Res::Def(HirDefKind::TyAlias, def_id) |
724 Res::Def(HirDefKind::ForeignTy, def_id) |
725 Res::Def(HirDefKind::TraitAlias, def_id) |
726 Res::Def(HirDefKind::AssocExistential, def_id) |
727 Res::Def(HirDefKind::AssocTy, def_id) |
728 Res::Def(HirDefKind::Trait, def_id) |
729 Res::Def(HirDefKind::Existential, def_id) |
730 Res::Def(HirDefKind::TyParam, def_id) => {
734 ref_id: id_from_def_id(def_id),
737 Res::Def(HirDefKind::ConstParam, def_id) => {
739 kind: RefKind::Variable,
741 ref_id: id_from_def_id(def_id),
744 Res::Def(HirDefKind::Ctor(CtorOf::Struct, ..), def_id) => {
745 // This is a reference to a tuple struct where the def_id points
746 // to an invisible constructor function. That is not a very useful
747 // def, so adjust to point to the tuple struct itself.
748 let parent_def_id = self.tcx.parent(def_id).unwrap();
752 ref_id: id_from_def_id(parent_def_id),
755 Res::Def(HirDefKind::Static, _) |
756 Res::Def(HirDefKind::Const, _) |
757 Res::Def(HirDefKind::AssocConst, _) |
758 Res::Def(HirDefKind::Ctor(..), _) => {
760 kind: RefKind::Variable,
762 ref_id: id_from_def_id(res.def_id()),
765 Res::Def(HirDefKind::Method, decl_id) => {
766 let def_id = if decl_id.is_local() {
767 let ti = self.tcx.associated_item(decl_id);
769 .associated_items(ti.container.id())
770 .find(|item| item.ident.name == ti.ident.name &&
771 item.defaultness.has_value())
772 .map(|item| item.def_id)
777 kind: RefKind::Function,
779 ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
782 Res::Def(HirDefKind::Fn, def_id) => {
784 kind: RefKind::Function,
786 ref_id: id_from_def_id(def_id),
789 Res::Def(HirDefKind::Mod, def_id) => {
793 ref_id: id_from_def_id(def_id),
798 Res::Def(HirDefKind::Macro(..), _) |
800 Res::NonMacroAttr(..) |
806 pub fn get_field_ref_data(
808 field_ref: &ast::Field,
809 variant: &ty::VariantDef,
811 filter!(self.span_utils, field_ref.ident.span);
812 self.tcx.find_field_index(field_ref.ident, variant).map(|index| {
813 let span = self.span_from_span(field_ref.ident.span);
815 kind: RefKind::Variable,
817 ref_id: id_from_def_id(variant.fields[index].did),
822 /// Attempt to return MacroRef for any AST node.
824 /// For a given piece of AST defined by the supplied Span and NodeId,
825 /// returns `None` if the node is not macro-generated or the span is malformed,
826 /// else uses the expansion callsite and callee to return some MacroRef.
827 pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
828 if !generated_code(span) {
831 // Note we take care to use the source callsite/callee, to handle
832 // nested expansions and ensure we only generate data for source-visible
834 let callsite = span.source_callsite();
835 let callsite_span = self.span_from_span(callsite);
836 let callee = span.source_callee()?;
837 let callee_span = callee.def_site?;
839 // Ignore attribute macros, their spans are usually mangled
840 if let MacroAttribute(_) = callee.format {
844 // If the callee is an imported macro from an external crate, need to get
845 // the source span and name from the session, as their spans are localized
846 // when read in, and no longer correspond to the source.
847 if let Some(mac) = self.tcx
849 .imported_macro_spans
853 let &(ref mac_name, mac_span) = mac;
854 let mac_span = self.span_from_span(mac_span);
855 return Some(MacroRef {
857 qualname: mac_name.clone(), // FIXME: generate the real qualname
858 callee_span: mac_span,
862 let callee_span = self.span_from_span(callee_span);
865 qualname: callee.format.name().to_string(), // FIXME: generate the real qualname
870 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
871 match self.get_path_res(ref_id) {
872 Res::PrimTy(_) | Res::SelfTy(..) | Res::Err => None,
873 def => Some(def.def_id()),
877 fn docs_for_attrs(&self, attrs: &[Attribute]) -> String {
878 let mut result = String::new();
881 if attr.check_name(sym::doc) {
882 if let Some(val) = attr.value_str() {
883 if attr.is_sugared_doc {
884 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
886 result.push_str(&val.as_str());
889 } else if let Some(meta_list) = attr.meta_item_list() {
890 meta_list.into_iter()
891 .filter(|it| it.check_name(sym::include))
892 .filter_map(|it| it.meta_item_list().map(|l| l.to_owned()))
894 .filter(|meta| meta.check_name(sym::contents))
895 .filter_map(|meta| meta.value_str())
897 result.push_str(&val.as_str());
904 if !self.config.full_docs {
905 if let Some(index) = result.find("\n\n") {
906 result.truncate(index);
913 fn next_impl_id(&self) -> u32 {
914 let next = self.impl_counter.get();
915 self.impl_counter.set(next + 1);
920 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
921 let mut sig = "fn ".to_owned();
922 if !generics.params.is_empty() {
924 sig.push_str(&generics
927 .map(|param| param.ident.to_string())
933 sig.push_str(&decl.inputs
940 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
941 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
947 // An AST visitor for collecting paths (e.g., the names of structs) and formal
948 // variables (idents) from patterns.
949 struct PathCollector<'l> {
950 collected_paths: Vec<(NodeId, &'l ast::Path)>,
951 collected_idents: Vec<(NodeId, ast::Ident, ast::Mutability)>,
954 impl<'l> PathCollector<'l> {
955 fn new() -> PathCollector<'l> {
957 collected_paths: vec![],
958 collected_idents: vec![],
963 impl<'l> Visitor<'l> for PathCollector<'l> {
964 fn visit_pat(&mut self, p: &'l ast::Pat) {
966 PatKind::Struct(ref path, ..) => {
967 self.collected_paths.push((p.id, path));
969 PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => {
970 self.collected_paths.push((p.id, path));
972 PatKind::Ident(bm, ident, _) => {
974 "PathCollector, visit ident in pat {}: {:?} {:?}",
979 let immut = match bm {
980 // Even if the ref is mut, you can't change the ref, only
981 // the data pointed at, so showing the initialising expression
982 // is still worthwhile.
983 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
984 ast::BindingMode::ByValue(mt) => mt,
986 self.collected_idents
987 .push((p.id, ident, immut));
991 visit::walk_pat(self, p);
995 /// Defines what to do with the results of saving the analysis.
996 pub trait SaveHandler {
999 save_ctxt: SaveContext<'l, 'tcx>,
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<'_, '_>) -> (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 = 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<'a> SaveHandler for DumpHandler<'a> {
1065 save_ctxt: SaveContext<'l, 'tcx>,
1070 let sess = &save_ctxt.tcx.sess;
1072 let (mut output, file_name) = self.output_file(&save_ctxt);
1073 let mut dumper = JsonDumper::new(&mut output, save_ctxt.config.clone());
1074 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1076 visitor.dump_crate_info(cratename, krate);
1077 visitor.dump_compilation_options(input, cratename);
1078 visit::walk_crate(&mut visitor, krate);
1083 if sess.opts.debugging_opts.emit_artifact_notifications {
1084 sess.parse_sess.span_diagnostic
1085 .emit_artifact_notification(&file_name, "save-analysis");
1090 /// Call a callback with the results of save-analysis.
1091 pub struct CallbackHandler<'b> {
1092 pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
1095 impl<'b> SaveHandler for CallbackHandler<'b> {
1098 save_ctxt: SaveContext<'l, 'tcx>,
1103 // We're using the JsonDumper here because it has the format of the
1104 // save-analysis results that we will pass to the callback. IOW, we are
1105 // using the JsonDumper to collect the save-analysis results, but not
1106 // actually to dump them to a file. This is all a bit convoluted and
1107 // there is certainly a simpler design here trying to get out (FIXME).
1108 let mut dumper = JsonDumper::with_callback(self.callback, save_ctxt.config.clone());
1109 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1111 visitor.dump_crate_info(cratename, krate);
1112 visitor.dump_compilation_options(input, cratename);
1113 visit::walk_crate(&mut visitor, krate);
1117 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
1122 config: Option<Config>,
1125 tcx.dep_graph.with_ignore(|| {
1126 info!("Dumping crate {}", cratename);
1128 // Privacy checking requires and is done after type checking; use a
1129 // fallback in case the access levels couldn't have been correctly computed.
1130 let access_levels = match tcx.sess.compile_status() {
1131 Ok(..) => tcx.privacy_access_levels(LOCAL_CRATE),
1132 Err(..) => tcx.arena.alloc(AccessLevels::default()),
1135 let save_ctxt = SaveContext {
1137 tables: &ty::TypeckTables::empty(None),
1138 access_levels: &access_levels,
1139 span_utils: SpanUtils::new(&tcx.sess),
1140 config: find_config(config),
1141 impl_counter: Cell::new(0),
1144 handler.save(save_ctxt, krate, cratename, input)
1148 fn find_config(supplied: Option<Config>) -> Config {
1149 if let Some(config) = supplied {
1153 match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
1154 None => Config::default(),
1155 Some(config) => config.to_str()
1157 .map_err(|_| error!("`RUST_SAVE_ANALYSIS_CONFIG` isn't UTF-8"))
1158 .and_then(|cfg| serde_json::from_str(cfg)
1159 .map_err(|_| error!("Could not deserialize save-analysis config"))
1160 ).unwrap_or_default()
1164 // Utility functions for the module.
1166 // Helper function to escape quotes in a string
1167 fn escape(s: String) -> String {
1168 s.replace("\"", "\"\"")
1171 // Helper function to determine if a span came from a
1172 // macro expansion or syntax extension.
1173 fn generated_code(span: Span) -> bool {
1174 span.ctxt() != NO_EXPANSION || span.is_dummy()
1177 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
1178 // we use our own Id which is the same, but without the newtype.
1179 fn id_from_def_id(id: DefId) -> rls_data::Id {
1181 krate: id.krate.as_u32(),
1182 index: id.index.as_u32(),
1186 fn id_from_node_id(id: NodeId, scx: &SaveContext<'_, '_>) -> rls_data::Id {
1187 let def_id = scx.tcx.hir().opt_local_def_id(id);
1188 def_id.map(|id| id_from_def_id(id)).unwrap_or_else(|| {
1189 // Create a *fake* `DefId` out of a `NodeId` by subtracting the `NodeId`
1190 // out of the maximum u32 value. This will work unless you have *billions*
1191 // of definitions in a single crate (very unlikely to actually happen).
1193 krate: LOCAL_CRATE.as_u32(),
1194 index: !id.as_u32(),
1199 fn null_id() -> rls_data::Id {
1201 krate: u32::max_value(),
1202 index: u32::max_value(),
1206 fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext<'_, '_>) -> Vec<rls_data::Attribute> {
1208 // Only retain real attributes. Doc comments are lowered separately.
1209 .filter(|attr| attr.path != sym::doc)
1211 // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
1212 // attribute. First normalize all inner attribute (#![..]) to outer
1213 // ones (#[..]), then remove the two leading and the one trailing character.
1214 attr.style = ast::AttrStyle::Outer;
1215 let value = pprust::attribute_to_string(&attr);
1216 // This str slicing works correctly, because the leading and trailing characters
1217 // are in the ASCII range and thus exactly one byte each.
1218 let value = value[2..value.len()-1].to_string();
1220 rls_data::Attribute {
1222 span: scx.span_from_span(attr.span),