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::io::BufWriter;
33 use std::path::{Path, PathBuf};
35 use syntax::ast::{self, Attribute, DUMMY_NODE_ID, NodeId, PatKind};
36 use syntax::source_map::Spanned;
37 use syntax::parse::lexer::comments::strip_doc_comment_decoration;
38 use syntax::print::pprust;
39 use syntax::visit::{self, Visitor};
40 use syntax::print::pprust::{arg_to_string, ty_to_string};
41 use syntax::source_map::MacroAttribute;
44 use json_dumper::JsonDumper;
45 use dump_visitor::DumpVisitor;
46 use span_utils::SpanUtils;
48 use rls_data::{Def, DefKind, ExternalCrateData, GlobalCrateId, MacroRef, Ref, RefKind, Relation,
49 RelationKind, SpanData, Impl, ImplKind};
50 use rls_data::config::Config;
52 use log::{debug, error, info};
55 pub struct SaveContext<'l, 'tcx> {
57 tables: &'l ty::TypeckTables<'tcx>,
58 access_levels: &'l AccessLevels,
59 span_utils: SpanUtils<'tcx>,
61 impl_counter: Cell<u32>,
68 RelationData(Relation, Impl),
71 impl<'l, 'tcx> SaveContext<'l, 'tcx> {
72 fn span_from_span(&self, span: Span) -> SpanData {
73 use rls_span::{Column, Row};
75 let cm = self.tcx.sess.source_map();
76 let start = cm.lookup_char_pos(span.lo());
77 let end = cm.lookup_char_pos(span.hi());
80 file_name: start.file.name.to_string().into(),
81 byte_start: span.lo().0,
82 byte_end: span.hi().0,
83 line_start: Row::new_one_indexed(start.line as u32),
84 line_end: Row::new_one_indexed(end.line as u32),
85 column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
86 column_end: Column::new_one_indexed(end.col.0 as u32 + 1),
90 // Returns path to the compilation output (e.g., libfoo-12345678.rmeta)
91 pub fn compilation_output(&self, crate_name: &str) -> PathBuf {
92 let sess = &self.tcx.sess;
93 // Save-analysis is emitted per whole session, not per each crate type
94 let crate_type = sess.crate_types.borrow()[0];
95 let outputs = &*self.tcx.output_filenames(LOCAL_CRATE);
97 if outputs.outputs.contains_key(&OutputType::Metadata) {
98 filename_for_metadata(sess, crate_name, outputs)
99 } else if outputs.outputs.should_codegen() {
100 out_filename(sess, crate_type, outputs, crate_name)
102 // Otherwise it's only a DepInfo, in which case we return early and
103 // not even reach the analysis stage.
108 // List external crates used by the current crate.
109 pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
110 let mut result = Vec::with_capacity(self.tcx.crates().len());
112 for &n in self.tcx.crates().iter() {
113 let span = match self.tcx.extern_crate(n.as_def_id()) {
114 Some(&ExternCrate { span, .. }) => span,
116 debug!("Skipping crate {}, no data", n);
120 let lo_loc = self.span_utils.sess.source_map().lookup_char_pos(span.lo());
121 result.push(ExternalCrateData {
122 // FIXME: change file_name field to PathBuf in rls-data
123 // https://github.com/nrc/rls-data/issues/7
124 file_name: self.span_utils.make_filename_string(&lo_loc.file),
127 name: self.tcx.crate_name(n).to_string(),
128 disambiguator: self.tcx.crate_disambiguator(n).to_fingerprint().as_value(),
136 pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
137 let qualname = format!("::{}",
138 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
140 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
141 filter!(self.span_utils, item.ident.span);
143 Some(Data::DefData(Def {
144 kind: DefKind::ForeignFunction,
145 id: id_from_node_id(item.id, self),
146 span: self.span_from_span(item.ident.span),
147 name: item.ident.to_string(),
149 value: make_signature(decl, generics),
153 docs: self.docs_for_attrs(&item.attrs),
154 sig: sig::foreign_item_signature(item, self),
155 attributes: lower_attributes(item.attrs.clone(), self),
158 ast::ForeignItemKind::Static(ref ty, _) => {
159 filter!(self.span_utils, item.ident.span);
161 let id = id_from_node_id(item.id, self);
162 let span = self.span_from_span(item.ident.span);
164 Some(Data::DefData(Def {
165 kind: DefKind::ForeignStatic,
168 name: item.ident.to_string(),
170 value: ty_to_string(ty),
174 docs: self.docs_for_attrs(&item.attrs),
175 sig: sig::foreign_item_signature(item, self),
176 attributes: lower_attributes(item.attrs.clone(), self),
179 // FIXME(plietar): needs a new DefKind in rls-data
180 ast::ForeignItemKind::Ty => None,
181 ast::ForeignItemKind::Macro(..) => None,
185 pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
187 ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
188 let qualname = format!("::{}",
189 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
190 filter!(self.span_utils, item.ident.span);
191 Some(Data::DefData(Def {
192 kind: DefKind::Function,
193 id: id_from_node_id(item.id, self),
194 span: self.span_from_span(item.ident.span),
195 name: item.ident.to_string(),
197 value: make_signature(decl, generics),
201 docs: self.docs_for_attrs(&item.attrs),
202 sig: sig::item_signature(item, self),
203 attributes: lower_attributes(item.attrs.clone(), self),
206 ast::ItemKind::Static(ref typ, ..) => {
207 let qualname = format!("::{}",
208 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
210 filter!(self.span_utils, item.ident.span);
212 let id = id_from_node_id(item.id, self);
213 let span = self.span_from_span(item.ident.span);
215 Some(Data::DefData(Def {
216 kind: DefKind::Static,
219 name: item.ident.to_string(),
221 value: ty_to_string(&typ),
225 docs: self.docs_for_attrs(&item.attrs),
226 sig: sig::item_signature(item, self),
227 attributes: lower_attributes(item.attrs.clone(), self),
230 ast::ItemKind::Const(ref typ, _) => {
231 let qualname = format!("::{}",
232 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
233 filter!(self.span_utils, item.ident.span);
235 let id = id_from_node_id(item.id, self);
236 let span = self.span_from_span(item.ident.span);
238 Some(Data::DefData(Def {
239 kind: DefKind::Const,
242 name: item.ident.to_string(),
244 value: ty_to_string(typ),
248 docs: self.docs_for_attrs(&item.attrs),
249 sig: sig::item_signature(item, self),
250 attributes: lower_attributes(item.attrs.clone(), self),
253 ast::ItemKind::Mod(ref m) => {
254 let qualname = format!("::{}",
255 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
257 let cm = self.tcx.sess.source_map();
258 let filename = cm.span_to_filename(m.inner);
260 filter!(self.span_utils, item.ident.span);
262 Some(Data::DefData(Def {
264 id: id_from_node_id(item.id, self),
265 name: item.ident.to_string(),
267 span: self.span_from_span(item.ident.span),
268 value: filename.to_string(),
272 .map(|i| id_from_node_id(i.id, self))
275 docs: self.docs_for_attrs(&item.attrs),
276 sig: sig::item_signature(item, self),
277 attributes: lower_attributes(item.attrs.clone(), self),
280 ast::ItemKind::Enum(ref def, _) => {
281 let name = item.ident.to_string();
282 let qualname = format!("::{}",
283 self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
284 filter!(self.span_utils, item.ident.span);
285 let variants_str = def.variants
287 .map(|v| v.node.ident.to_string())
290 let value = format!("{}::{{{}}}", name, variants_str);
291 Some(Data::DefData(Def {
293 id: id_from_node_id(item.id, self),
294 span: self.span_from_span(item.ident.span),
299 children: def.variants
301 .map(|v| id_from_node_id(v.node.id, self))
304 docs: self.docs_for_attrs(&item.attrs),
305 sig: sig::item_signature(item, self),
306 attributes: lower_attributes(item.attrs.clone(), self),
309 ast::ItemKind::Impl(.., ref trait_ref, ref typ, ref impls) => {
310 if let ast::TyKind::Path(None, ref path) = typ.node {
311 // Common case impl for a struct or something basic.
312 if generated_code(path.span) {
315 let sub_span = path.segments.last().unwrap().ident.span;
316 filter!(self.span_utils, sub_span);
318 let impl_id = self.next_impl_id();
319 let span = self.span_from_span(sub_span);
321 let type_data = self.lookup_ref_id(typ.id);
322 type_data.map(|type_data| {
323 Data::RelationData(Relation {
324 kind: RelationKind::Impl {
328 from: id_from_def_id(type_data),
331 .and_then(|t| self.lookup_ref_id(t.ref_id))
333 .unwrap_or_else(|| null_id()),
337 kind: match *trait_ref {
338 Some(_) => ImplKind::Direct,
339 None => ImplKind::Inherent,
342 value: String::new(),
346 .map(|i| id_from_node_id(i.id, self))
364 pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<Def> {
365 if let Some(ident) = field.ident {
366 let name = ident.to_string();
367 let qualname = format!("::{}::{}",
368 self.tcx.def_path_str(self.tcx.hir().local_def_id(scope)),
370 filter!(self.span_utils, ident.span);
371 let def_id = self.tcx.hir().local_def_id(field.id);
372 let typ = self.tcx.type_of(def_id).to_string();
375 let id = id_from_node_id(field.id, self);
376 let span = self.span_from_span(ident.span);
379 kind: DefKind::Field,
385 parent: Some(id_from_node_id(scope, self)),
388 docs: self.docs_for_attrs(&field.attrs),
389 sig: sig::field_signature(field, self),
390 attributes: lower_attributes(field.attrs.clone(), self),
397 // FIXME would be nice to take a MethodItem here, but the ast provides both
398 // trait and impl flavours, so the caller must do the disassembly.
399 pub fn get_method_data(&self, id: ast::NodeId, ident: ast::Ident, span: Span) -> Option<Def> {
400 // The qualname for a method is the trait name or name of the struct in an impl in
401 // which the method is declared in, followed by the method's name.
402 let (qualname, parent_scope, decl_id, docs, attributes) =
403 match self.tcx.impl_of_method(self.tcx.hir().local_def_id(id)) {
404 Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) {
405 Some(Node::Item(item)) => match item.node {
406 hir::ItemKind::Impl(.., ref ty, _) => {
407 let mut qualname = String::from("<");
408 qualname.push_str(&self.tcx.hir().hir_to_pretty_string(ty.hir_id));
410 let trait_id = self.tcx.trait_id_of_impl(impl_id);
411 let mut decl_id = None;
412 let mut docs = String::new();
413 let mut attrs = vec![];
414 let hir_id = self.tcx.hir().node_to_hir_id(id);
415 if let Some(Node::ImplItem(item)) =
416 self.tcx.hir().find(hir_id)
418 docs = self.docs_for_attrs(&item.attrs);
419 attrs = item.attrs.to_vec();
422 if let Some(def_id) = trait_id {
423 // A method in a trait impl.
424 qualname.push_str(" as ");
425 qualname.push_str(&self.tcx.def_path_str(def_id));
427 .associated_items(def_id)
428 .find(|item| item.ident.name == ident.name)
429 .map(|item| decl_id = Some(item.def_id));
431 qualname.push_str(">");
433 (qualname, trait_id, decl_id, docs, attrs)
438 "Container {:?} for method {} not an impl?",
447 "Container {:?} for method {} is not a node item {:?}",
454 None => match self.tcx.trait_of_item(self.tcx.hir().local_def_id(id)) {
456 let mut docs = String::new();
457 let mut attrs = vec![];
458 let hir_id = self.tcx.hir().node_to_hir_id(id);
460 if let Some(Node::TraitItem(item)) = self.tcx.hir().find(hir_id) {
461 docs = self.docs_for_attrs(&item.attrs);
462 attrs = item.attrs.to_vec();
466 format!("::{}", self.tcx.def_path_str(def_id)),
474 debug!("Could not find container for method {} at {:?}", id, span);
475 // This is not necessarily a bug, if there was a compilation error,
476 // the tables we need might not exist.
482 let qualname = format!("{}::{}", qualname, ident.name);
484 filter!(self.span_utils, ident.span);
487 kind: DefKind::Method,
488 id: id_from_node_id(id, self),
489 span: self.span_from_span(ident.span),
490 name: ident.name.to_string(),
492 // FIXME you get better data here by using the visitor.
493 value: String::new(),
494 parent: parent_scope.map(|id| id_from_def_id(id)),
496 decl_id: decl_id.map(|id| id_from_def_id(id)),
499 attributes: lower_attributes(attributes, self),
503 pub fn get_trait_ref_data(&self, trait_ref: &ast::TraitRef) -> Option<Ref> {
504 self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
505 let span = trait_ref.path.span;
506 if generated_code(span) {
509 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
510 filter!(self.span_utils, sub_span);
511 let span = self.span_from_span(sub_span);
515 ref_id: id_from_def_id(def_id),
520 pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
521 let expr_hir_id = self.tcx.hir().node_to_hir_id(expr.id);
522 let hir_node = self.tcx.hir().expect_expr(expr_hir_id);
523 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
524 if ty.is_none() || ty.unwrap().sty == ty::Error {
528 ast::ExprKind::Field(ref sub_ex, ident) => {
529 let sub_ex_hir_id = self.tcx.hir().node_to_hir_id(sub_ex.id);
530 let hir_node = match self.tcx.hir().find(sub_ex_hir_id) {
531 Some(Node::Expr(expr)) => expr,
534 "Missing or weird node for sub-expression {} in {:?}",
541 match self.tables.expr_ty_adjusted(&hir_node).sty {
542 ty::Adt(def, _) if !def.is_enum() => {
543 let variant = &def.non_enum_variant();
544 let index = self.tcx.find_field_index(ident, variant).unwrap();
545 filter!(self.span_utils, ident.span);
546 let span = self.span_from_span(ident.span);
547 return Some(Data::RefData(Ref {
548 kind: RefKind::Variable,
550 ref_id: id_from_def_id(variant.fields[index].did),
553 ty::Tuple(..) => None,
555 debug!("Expected struct or union type, found {:?}", ty);
560 ast::ExprKind::Struct(ref path, ..) => {
561 match self.tables.expr_ty_adjusted(&hir_node).sty {
562 ty::Adt(def, _) if !def.is_enum() => {
563 let sub_span = path.segments.last().unwrap().ident.span;
564 filter!(self.span_utils, sub_span);
565 let span = self.span_from_span(sub_span);
566 Some(Data::RefData(Ref {
569 ref_id: id_from_def_id(def.did),
573 // FIXME ty could legitimately be an enum, but then we will fail
574 // later if we try to look up the fields.
575 debug!("expected struct or union, found {:?}", ty);
580 ast::ExprKind::MethodCall(ref seg, ..) => {
581 let expr_hir_id = self.tcx.hir().definitions().node_to_hir_id(expr.id);
582 let method_id = match self.tables.type_dependent_def_id(expr_hir_id) {
585 debug!("Could not resolve method id for {:?}", expr);
589 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
590 ty::ImplContainer(_) => (Some(method_id), None),
591 ty::TraitContainer(_) => (None, Some(method_id)),
593 let sub_span = seg.ident.span;
594 filter!(self.span_utils, sub_span);
595 let span = self.span_from_span(sub_span);
596 Some(Data::RefData(Ref {
597 kind: RefKind::Function,
601 .map(|id| id_from_def_id(id))
602 .unwrap_or_else(|| null_id()),
605 ast::ExprKind::Path(_, ref path) => {
606 self.get_path_data(expr.id, path).map(|d| Data::RefData(d))
615 pub fn get_path_res(&self, id: NodeId) -> Res {
616 let hir_id = self.tcx.hir().node_to_hir_id(id);
617 match self.tcx.hir().get(hir_id) {
618 Node::TraitRef(tr) => tr.path.res,
620 Node::Item(&hir::Item {
621 node: hir::ItemKind::Use(ref path, _),
624 Node::Visibility(&Spanned {
625 node: hir::VisibilityKind::Restricted { ref path, .. }, .. }) => path.res,
627 Node::PathSegment(seg) => {
629 Some(res) if res != Res::Err => res,
631 let parent_node = self.tcx.hir().get_parent_node(hir_id);
632 self.get_path_res(self.tcx.hir().hir_to_node_id(parent_node))
637 Node::Expr(&hir::Expr {
638 node: hir::ExprKind::Struct(ref qpath, ..),
641 self.tables.qpath_res(qpath, hir_id)
644 Node::Expr(&hir::Expr {
645 node: hir::ExprKind::Path(ref qpath),
648 Node::Pat(&hir::Pat {
649 node: hir::PatKind::Path(ref qpath),
652 Node::Pat(&hir::Pat {
653 node: hir::PatKind::Struct(ref qpath, ..),
656 Node::Pat(&hir::Pat {
657 node: hir::PatKind::TupleStruct(ref qpath, ..),
661 node: hir::TyKind::Path(ref qpath),
664 self.tables.qpath_res(qpath, hir_id)
667 Node::Binding(&hir::Pat {
668 node: hir::PatKind::Binding(_, canonical_id, ..),
670 }) => Res::Local(canonical_id),
676 pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Ref> {
680 self.get_path_segment_data(seg)
681 .or_else(|| self.get_path_segment_data_with_id(seg, id))
685 pub fn get_path_segment_data(&self, path_seg: &ast::PathSegment) -> Option<Ref> {
686 self.get_path_segment_data_with_id(path_seg, path_seg.id)
689 fn get_path_segment_data_with_id(
691 path_seg: &ast::PathSegment,
694 // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
695 fn fn_type(seg: &ast::PathSegment) -> bool {
696 if let Some(ref generic_args) = seg.args {
697 if let ast::GenericArgs::Parenthesized(_) = **generic_args {
704 if id == DUMMY_NODE_ID {
708 let res = self.get_path_res(id);
709 let span = path_seg.ident.span;
710 filter!(self.span_utils, span);
711 let span = self.span_from_span(span);
716 kind: RefKind::Variable,
718 ref_id: id_from_node_id(self.tcx.hir().hir_to_node_id(id), self),
721 Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
725 ref_id: id_from_def_id(def_id),
728 Res::Def(HirDefKind::Struct, def_id) |
729 Res::Def(HirDefKind::Variant, def_id) |
730 Res::Def(HirDefKind::Union, def_id) |
731 Res::Def(HirDefKind::Enum, def_id) |
732 Res::Def(HirDefKind::TyAlias, def_id) |
733 Res::Def(HirDefKind::ForeignTy, def_id) |
734 Res::Def(HirDefKind::TraitAlias, def_id) |
735 Res::Def(HirDefKind::AssocExistential, def_id) |
736 Res::Def(HirDefKind::AssocTy, def_id) |
737 Res::Def(HirDefKind::Trait, def_id) |
738 Res::Def(HirDefKind::Existential, def_id) |
739 Res::Def(HirDefKind::TyParam, def_id) => {
743 ref_id: id_from_def_id(def_id),
746 Res::Def(HirDefKind::ConstParam, def_id) => {
748 kind: RefKind::Variable,
750 ref_id: id_from_def_id(def_id),
753 Res::Def(HirDefKind::Ctor(CtorOf::Struct, ..), def_id) => {
754 // This is a reference to a tuple struct where the def_id points
755 // to an invisible constructor function. That is not a very useful
756 // def, so adjust to point to the tuple struct itself.
757 let parent_def_id = self.tcx.parent(def_id).unwrap();
761 ref_id: id_from_def_id(parent_def_id),
764 Res::Def(HirDefKind::Static, _) |
765 Res::Def(HirDefKind::Const, _) |
766 Res::Def(HirDefKind::AssocConst, _) |
767 Res::Def(HirDefKind::Ctor(..), _) => {
769 kind: RefKind::Variable,
771 ref_id: id_from_def_id(res.def_id()),
774 Res::Def(HirDefKind::Method, decl_id) => {
775 let def_id = if decl_id.is_local() {
776 let ti = self.tcx.associated_item(decl_id);
778 .associated_items(ti.container.id())
779 .find(|item| item.ident.name == ti.ident.name &&
780 item.defaultness.has_value())
781 .map(|item| item.def_id)
786 kind: RefKind::Function,
788 ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
791 Res::Def(HirDefKind::Fn, def_id) => {
793 kind: RefKind::Function,
795 ref_id: id_from_def_id(def_id),
798 Res::Def(HirDefKind::Mod, def_id) => {
802 ref_id: id_from_def_id(def_id),
807 Res::Def(HirDefKind::Macro(..), _) |
809 Res::NonMacroAttr(..) |
815 pub fn get_field_ref_data(
817 field_ref: &ast::Field,
818 variant: &ty::VariantDef,
820 filter!(self.span_utils, field_ref.ident.span);
821 self.tcx.find_field_index(field_ref.ident, variant).map(|index| {
822 let span = self.span_from_span(field_ref.ident.span);
824 kind: RefKind::Variable,
826 ref_id: id_from_def_id(variant.fields[index].did),
831 /// Attempt to return MacroRef for any AST node.
833 /// For a given piece of AST defined by the supplied Span and NodeId,
834 /// returns `None` if the node is not macro-generated or the span is malformed,
835 /// else uses the expansion callsite and callee to return some MacroRef.
836 pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
837 if !generated_code(span) {
840 // Note we take care to use the source callsite/callee, to handle
841 // nested expansions and ensure we only generate data for source-visible
843 let callsite = span.source_callsite();
844 let callsite_span = self.span_from_span(callsite);
845 let callee = span.source_callee()?;
846 let callee_span = callee.def_site?;
848 // Ignore attribute macros, their spans are usually mangled
849 if let MacroAttribute(_) = callee.format {
853 // If the callee is an imported macro from an external crate, need to get
854 // the source span and name from the session, as their spans are localized
855 // when read in, and no longer correspond to the source.
856 if let Some(mac) = self.tcx
858 .imported_macro_spans
862 let &(ref mac_name, mac_span) = mac;
863 let mac_span = self.span_from_span(mac_span);
864 return Some(MacroRef {
866 qualname: mac_name.clone(), // FIXME: generate the real qualname
867 callee_span: mac_span,
871 let callee_span = self.span_from_span(callee_span);
874 qualname: callee.format.name().to_string(), // FIXME: generate the real qualname
879 fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
880 match self.get_path_res(ref_id) {
881 Res::PrimTy(_) | Res::SelfTy(..) | Res::Err => None,
882 def => Some(def.def_id()),
886 fn docs_for_attrs(&self, attrs: &[Attribute]) -> String {
887 let mut result = String::new();
890 if attr.check_name(sym::doc) {
891 if let Some(val) = attr.value_str() {
892 if attr.is_sugared_doc {
893 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
895 result.push_str(&val.as_str());
898 } else if let Some(meta_list) = attr.meta_item_list() {
899 meta_list.into_iter()
900 .filter(|it| it.check_name(sym::include))
901 .filter_map(|it| it.meta_item_list().map(|l| l.to_owned()))
903 .filter(|meta| meta.check_name(sym::contents))
904 .filter_map(|meta| meta.value_str())
906 result.push_str(&val.as_str());
913 if !self.config.full_docs {
914 if let Some(index) = result.find("\n\n") {
915 result.truncate(index);
922 fn next_impl_id(&self) -> u32 {
923 let next = self.impl_counter.get();
924 self.impl_counter.set(next + 1);
929 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
930 let mut sig = "fn ".to_owned();
931 if !generics.params.is_empty() {
933 sig.push_str(&generics
936 .map(|param| param.ident.to_string())
942 sig.push_str(&decl.inputs
949 ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
950 ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
956 // An AST visitor for collecting paths (e.g., the names of structs) and formal
957 // variables (idents) from patterns.
958 struct PathCollector<'l> {
959 collected_paths: Vec<(NodeId, &'l ast::Path)>,
960 collected_idents: Vec<(NodeId, ast::Ident, ast::Mutability)>,
963 impl<'l> PathCollector<'l> {
964 fn new() -> PathCollector<'l> {
966 collected_paths: vec![],
967 collected_idents: vec![],
972 impl<'l> Visitor<'l> for PathCollector<'l> {
973 fn visit_pat(&mut self, p: &'l ast::Pat) {
975 PatKind::Struct(ref path, ..) => {
976 self.collected_paths.push((p.id, path));
978 PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => {
979 self.collected_paths.push((p.id, path));
981 PatKind::Ident(bm, ident, _) => {
983 "PathCollector, visit ident in pat {}: {:?} {:?}",
988 let immut = match bm {
989 // Even if the ref is mut, you can't change the ref, only
990 // the data pointed at, so showing the initialising expression
991 // is still worthwhile.
992 ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
993 ast::BindingMode::ByValue(mt) => mt,
995 self.collected_idents
996 .push((p.id, ident, immut));
1000 visit::walk_pat(self, p);
1004 /// Defines what to do with the results of saving the analysis.
1005 pub trait SaveHandler {
1008 save_ctxt: SaveContext<'l, 'tcx>,
1015 /// Dump the save-analysis results to a file.
1016 pub struct DumpHandler<'a> {
1017 odir: Option<&'a Path>,
1021 impl<'a> DumpHandler<'a> {
1022 pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
1025 cratename: cratename.to_owned(),
1029 fn output_file(&self, ctx: &SaveContext<'_, '_>) -> (BufWriter<File>, PathBuf) {
1030 let sess = &ctx.tcx.sess;
1031 let file_name = match ctx.config.output_file {
1032 Some(ref s) => PathBuf::from(s),
1034 let mut root_path = match self.odir {
1035 Some(val) => val.join("save-analysis"),
1036 None => PathBuf::from("save-analysis-temp"),
1039 if let Err(e) = std::fs::create_dir_all(&root_path) {
1040 error!("Could not create directory {}: {}", root_path.display(), e);
1043 let executable = sess.crate_types
1046 .any(|ct| *ct == CrateType::Executable);
1047 let mut out_name = if executable {
1052 out_name.push_str(&self.cratename);
1053 out_name.push_str(&sess.opts.cg.extra_filename);
1054 out_name.push_str(".json");
1055 root_path.push(&out_name);
1061 info!("Writing output to {}", file_name.display());
1063 let output_file = BufWriter::new(File::create(&file_name).unwrap_or_else(
1064 |e| sess.fatal(&format!("Could not open {}: {}", file_name.display(), e)),
1067 (output_file, file_name)
1071 impl<'a> SaveHandler for DumpHandler<'a> {
1074 save_ctxt: SaveContext<'l, 'tcx>,
1079 let sess = &save_ctxt.tcx.sess;
1081 let (mut output, file_name) = self.output_file(&save_ctxt);
1082 let mut dumper = JsonDumper::new(&mut output, save_ctxt.config.clone());
1083 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1085 visitor.dump_crate_info(cratename, krate);
1086 visitor.dump_compilation_options(input, cratename);
1087 visit::walk_crate(&mut visitor, krate);
1092 if sess.opts.debugging_opts.emit_artifact_notifications {
1093 sess.parse_sess.span_diagnostic
1094 .emit_artifact_notification(&file_name, "save-analysis");
1099 /// Call a callback with the results of save-analysis.
1100 pub struct CallbackHandler<'b> {
1101 pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
1104 impl<'b> SaveHandler for CallbackHandler<'b> {
1107 save_ctxt: SaveContext<'l, 'tcx>,
1112 // We're using the JsonDumper here because it has the format of the
1113 // save-analysis results that we will pass to the callback. IOW, we are
1114 // using the JsonDumper to collect the save-analysis results, but not
1115 // actually to dump them to a file. This is all a bit convoluted and
1116 // there is certainly a simpler design here trying to get out (FIXME).
1117 let mut dumper = JsonDumper::with_callback(self.callback, save_ctxt.config.clone());
1118 let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1120 visitor.dump_crate_info(cratename, krate);
1121 visitor.dump_compilation_options(input, cratename);
1122 visit::walk_crate(&mut visitor, krate);
1126 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
1131 config: Option<Config>,
1134 tcx.dep_graph.with_ignore(|| {
1135 info!("Dumping crate {}", cratename);
1137 // Privacy checking requires and is done after type checking; use a
1138 // fallback in case the access levels couldn't have been correctly computed.
1139 let access_levels = match tcx.sess.compile_status() {
1140 Ok(..) => tcx.privacy_access_levels(LOCAL_CRATE),
1141 Err(..) => tcx.arena.alloc(AccessLevels::default()),
1144 let save_ctxt = SaveContext {
1146 tables: &ty::TypeckTables::empty(None),
1147 access_levels: &access_levels,
1148 span_utils: SpanUtils::new(&tcx.sess),
1149 config: find_config(config),
1150 impl_counter: Cell::new(0),
1153 handler.save(save_ctxt, krate, cratename, input)
1157 fn find_config(supplied: Option<Config>) -> Config {
1158 if let Some(config) = supplied {
1162 match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
1163 None => Config::default(),
1164 Some(config) => config.to_str()
1166 .map_err(|_| error!("`RUST_SAVE_ANALYSIS_CONFIG` isn't UTF-8"))
1167 .and_then(|cfg| serde_json::from_str(cfg)
1168 .map_err(|_| error!("Could not deserialize save-analysis config"))
1169 ).unwrap_or_default()
1173 // Utility functions for the module.
1175 // Helper function to escape quotes in a string
1176 fn escape(s: String) -> String {
1177 s.replace("\"", "\"\"")
1180 // Helper function to determine if a span came from a
1181 // macro expansion or syntax extension.
1182 fn generated_code(span: Span) -> bool {
1183 span.ctxt() != NO_EXPANSION || span.is_dummy()
1186 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
1187 // we use our own Id which is the same, but without the newtype.
1188 fn id_from_def_id(id: DefId) -> rls_data::Id {
1190 krate: id.krate.as_u32(),
1191 index: id.index.as_u32(),
1195 fn id_from_node_id(id: NodeId, scx: &SaveContext<'_, '_>) -> rls_data::Id {
1196 let def_id = scx.tcx.hir().opt_local_def_id(id);
1197 def_id.map(|id| id_from_def_id(id)).unwrap_or_else(|| {
1198 // Create a *fake* `DefId` out of a `NodeId` by subtracting the `NodeId`
1199 // out of the maximum u32 value. This will work unless you have *billions*
1200 // of definitions in a single crate (very unlikely to actually happen).
1202 krate: LOCAL_CRATE.as_u32(),
1203 index: !id.as_u32(),
1208 fn null_id() -> rls_data::Id {
1210 krate: u32::max_value(),
1211 index: u32::max_value(),
1215 fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext<'_, '_>) -> Vec<rls_data::Attribute> {
1217 // Only retain real attributes. Doc comments are lowered separately.
1218 .filter(|attr| attr.path != sym::doc)
1220 // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
1221 // attribute. First normalize all inner attribute (#![..]) to outer
1222 // ones (#[..]), then remove the two leading and the one trailing character.
1223 attr.style = ast::AttrStyle::Outer;
1224 let value = pprust::attribute_to_string(&attr);
1225 // This str slicing works correctly, because the leading and trailing characters
1226 // are in the ASCII range and thus exactly one byte each.
1227 let value = value[2..value.len()-1].to_string();
1229 rls_data::Attribute {
1231 span: scx.span_from_span(attr.span),