1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
3 #![feature(or_patterns)]
4 #![recursion_limit = "256"]
12 use rustc_ast::ast::{self};
13 use rustc_ast::util::comments::strip_doc_comment_decoration;
14 use rustc_ast_pretty::pprust::attribute_to_string;
16 use rustc_hir::def::{CtorOf, DefKind as HirDefKind, Res};
17 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
18 use rustc_hir::intravisit::{self, Visitor};
20 use rustc_hir_pretty::ty_to_string;
21 use rustc_middle::hir::map::Map;
22 use rustc_middle::middle::cstore::ExternCrate;
23 use rustc_middle::middle::privacy::AccessLevels;
24 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
25 use rustc_middle::{bug, span_bug};
26 use rustc_session::config::{CrateType, Input, OutputType};
27 use rustc_session::output::{filename_for_metadata, out_filename};
28 use rustc_span::source_map::Spanned;
29 use rustc_span::symbol::Ident;
33 use std::default::Default;
36 use std::io::BufWriter;
37 use std::path::{Path, PathBuf};
39 use dump_visitor::DumpVisitor;
40 use span_utils::SpanUtils;
42 use rls_data::config::Config;
44 Analysis, Def, DefKind, ExternalCrateData, GlobalCrateId, Impl, ImplKind, MacroRef, Ref,
45 RefKind, Relation, RelationKind, SpanData,
48 use log::{debug, error, info};
50 pub struct SaveContext<'l, 'tcx> {
52 tables: &'l ty::TypeckTables<'tcx>,
53 /// Used as a fallback when nesting the typeck tables during item processing
54 /// (if these are not available for that item, e.g. don't own a body)
55 empty_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> SaveContext<'l, 'tcx> {
70 fn span_from_span(&self, span: Span) -> SpanData {
71 use rls_span::{Column, Row};
73 let sm = self.tcx.sess.source_map();
74 let start = sm.lookup_char_pos(span.lo());
75 let end = sm.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()[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: &hir::ForeignItem<'_>) -> Option<Data> {
135 let def_id = self.tcx.hir().local_def_id(item.hir_id).to_def_id();
136 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
138 hir::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_def_id(def_id),
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.to_vec(), self),
156 hir::ForeignItemKind::Static(ref ty, _) => {
157 filter!(self.span_utils, item.ident.span);
159 let id = id_from_def_id(def_id);
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.to_vec(), self),
177 // FIXME(plietar): needs a new DefKind in rls-data
178 hir::ForeignItemKind::Type => None,
182 pub fn get_item_data(&self, item: &hir::Item<'_>) -> Option<Data> {
183 let def_id = self.tcx.hir().local_def_id(item.hir_id).to_def_id();
185 hir::ItemKind::Fn(ref sig, ref generics, _) => {
186 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
187 filter!(self.span_utils, item.ident.span);
188 Some(Data::DefData(Def {
189 kind: DefKind::Function,
190 id: id_from_def_id(def_id),
191 span: self.span_from_span(item.ident.span),
192 name: item.ident.to_string(),
194 value: make_signature(&sig.decl, generics),
198 docs: self.docs_for_attrs(&item.attrs),
199 sig: sig::item_signature(item, self),
200 attributes: lower_attributes(item.attrs.to_vec(), self),
203 hir::ItemKind::Static(ref typ, ..) => {
204 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
206 filter!(self.span_utils, item.ident.span);
208 let id = id_from_def_id(def_id);
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.to_vec(), self),
226 hir::ItemKind::Const(ref typ, _) => {
227 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
228 filter!(self.span_utils, item.ident.span);
230 let id = id_from_def_id(def_id);
231 let span = self.span_from_span(item.ident.span);
233 Some(Data::DefData(Def {
234 kind: DefKind::Const,
237 name: item.ident.to_string(),
239 value: ty_to_string(typ),
243 docs: self.docs_for_attrs(&item.attrs),
244 sig: sig::item_signature(item, self),
245 attributes: lower_attributes(item.attrs.to_vec(), self),
248 hir::ItemKind::Mod(ref m) => {
249 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
251 let sm = self.tcx.sess.source_map();
252 let filename = sm.span_to_filename(m.inner);
254 filter!(self.span_utils, item.ident.span);
256 Some(Data::DefData(Def {
258 id: id_from_def_id(def_id),
259 name: item.ident.to_string(),
261 span: self.span_from_span(item.ident.span),
262 value: filename.to_string(),
264 children: m.item_ids.iter().map(|i| id_from_hir_id(i.id, self)).collect(),
266 docs: self.docs_for_attrs(&item.attrs),
267 sig: sig::item_signature(item, self),
268 attributes: lower_attributes(item.attrs.to_vec(), self),
271 hir::ItemKind::Enum(ref def, _) => {
272 let name = item.ident.to_string();
273 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
274 filter!(self.span_utils, item.ident.span);
276 def.variants.iter().map(|v| v.ident.to_string()).collect::<Vec<_>>().join(", ");
277 let value = format!("{}::{{{}}}", name, variants_str);
278 Some(Data::DefData(Def {
280 id: id_from_def_id(def_id),
281 span: self.span_from_span(item.ident.span),
286 children: def.variants.iter().map(|v| id_from_hir_id(v.id, self)).collect(),
288 docs: self.docs_for_attrs(&item.attrs),
289 sig: sig::item_signature(item, self),
290 attributes: lower_attributes(item.attrs.to_vec(), self),
293 hir::ItemKind::Impl { ref of_trait, ref self_ty, ref items, .. } => {
294 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = self_ty.kind {
295 // Common case impl for a struct or something basic.
296 if generated_code(path.span) {
299 let sub_span = path.segments.last().unwrap().ident.span;
300 filter!(self.span_utils, sub_span);
302 let impl_id = self.next_impl_id();
303 let span = self.span_from_span(sub_span);
305 let type_data = self.lookup_def_id(self_ty.hir_id);
306 type_data.map(|type_data| {
309 kind: RelationKind::Impl { id: impl_id },
311 from: id_from_def_id(type_data),
314 .and_then(|t| self.lookup_def_id(t.hir_ref_id))
316 .unwrap_or_else(null_id),
320 kind: match *of_trait {
321 Some(_) => ImplKind::Direct,
322 None => ImplKind::Inherent,
325 value: String::new(),
329 .map(|i| id_from_hir_id(i.id.hir_id, self))
348 pub fn get_field_data(&self, field: &hir::StructField<'_>, scope: hir::HirId) -> Option<Def> {
349 let name = field.ident.to_string();
350 let scope_def_id = self.tcx.hir().local_def_id(scope).to_def_id();
351 let qualname = format!("::{}::{}", self.tcx.def_path_str(scope_def_id), field.ident);
352 filter!(self.span_utils, field.ident.span);
353 let field_def_id = self.tcx.hir().local_def_id(field.hir_id).to_def_id();
354 let typ = self.tcx.type_of(field_def_id).to_string();
356 let id = id_from_def_id(field_def_id);
357 let span = self.span_from_span(field.ident.span);
360 kind: DefKind::Field,
366 parent: Some(id_from_def_id(scope_def_id)),
369 docs: self.docs_for_attrs(&field.attrs),
370 sig: sig::field_signature(field, self),
371 attributes: lower_attributes(field.attrs.to_vec(), self),
375 // FIXME would be nice to take a MethodItem here, but the ast provides both
376 // trait and impl flavours, so the caller must do the disassembly.
377 pub fn get_method_data(&self, hir_id: hir::HirId, ident: Ident, span: Span) -> Option<Def> {
378 // The qualname for a method is the trait name or name of the struct in an impl in
379 // which the method is declared in, followed by the method's name.
380 let def_id = self.tcx.hir().local_def_id(hir_id).to_def_id();
381 let (qualname, parent_scope, decl_id, docs, attributes) =
382 match self.tcx.impl_of_method(def_id) {
383 Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) {
384 Some(Node::Item(item)) => match item.kind {
385 hir::ItemKind::Impl { ref self_ty, .. } => {
386 let hir = self.tcx.hir();
388 let mut qualname = String::from("<");
390 .push_str(&rustc_hir_pretty::id_to_string(&hir, self_ty.hir_id));
392 let trait_id = self.tcx.trait_id_of_impl(impl_id);
393 let mut docs = String::new();
394 let mut attrs = vec![];
395 if let Some(Node::ImplItem(item)) = hir.find(hir_id) {
396 docs = self.docs_for_attrs(&item.attrs);
397 attrs = item.attrs.to_vec();
400 let mut decl_id = None;
401 if let Some(def_id) = trait_id {
402 // A method in a trait impl.
403 qualname.push_str(" as ");
404 qualname.push_str(&self.tcx.def_path_str(def_id));
408 .associated_items(def_id)
409 .filter_by_name_unhygienic(ident.name)
411 .map(|item| item.def_id);
413 qualname.push_str(">");
415 (qualname, trait_id, decl_id, docs, attrs)
420 "Container {:?} for method {} not an impl?",
429 "Container {:?} for method {} is not a node item {:?}",
436 None => match self.tcx.trait_of_item(def_id) {
438 let mut docs = String::new();
439 let mut attrs = vec![];
441 if let Some(Node::TraitItem(item)) = self.tcx.hir().find(hir_id) {
442 docs = self.docs_for_attrs(&item.attrs);
443 attrs = item.attrs.to_vec();
447 format!("::{}", self.tcx.def_path_str(def_id)),
455 debug!("could not find container for method {} at {:?}", hir_id, span);
456 // This is not necessarily a bug, if there was a compilation error,
457 // the tables we need might not exist.
463 let qualname = format!("{}::{}", qualname, ident.name);
465 filter!(self.span_utils, ident.span);
468 kind: DefKind::Method,
469 id: id_from_def_id(def_id),
470 span: self.span_from_span(ident.span),
471 name: ident.name.to_string(),
473 // FIXME you get better data here by using the visitor.
474 value: String::new(),
475 parent: parent_scope.map(id_from_def_id),
477 decl_id: decl_id.map(id_from_def_id),
480 attributes: lower_attributes(attributes, self),
484 pub fn get_trait_ref_data(&self, trait_ref: &hir::TraitRef<'_>) -> Option<Ref> {
485 self.lookup_def_id(trait_ref.hir_ref_id).and_then(|def_id| {
486 let span = trait_ref.path.span;
487 if generated_code(span) {
490 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
491 filter!(self.span_utils, sub_span);
492 let span = self.span_from_span(sub_span);
493 Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(def_id) })
497 pub fn get_expr_data(&self, expr: &hir::Expr<'_>) -> Option<Data> {
498 let hir_node = self.tcx.hir().expect_expr(expr.hir_id);
499 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
500 if ty.is_none() || ty.unwrap().kind == ty::Error {
504 hir::ExprKind::Field(ref sub_ex, ident) => {
505 let hir_node = match self.tcx.hir().find(sub_ex.hir_id) {
506 Some(Node::Expr(expr)) => expr,
509 "Missing or weird node for sub-expression {} in {:?}",
515 match self.tables.expr_ty_adjusted(&hir_node).kind {
516 ty::Adt(def, _) if !def.is_enum() => {
517 let variant = &def.non_enum_variant();
518 filter!(self.span_utils, ident.span);
519 let span = self.span_from_span(ident.span);
520 Some(Data::RefData(Ref {
521 kind: RefKind::Variable,
525 .find_field_index(ident, variant)
526 .map(|index| id_from_def_id(variant.fields[index].did))
527 .unwrap_or_else(null_id),
530 ty::Tuple(..) => None,
532 debug!("expected struct or union type, found {:?}", ty);
537 hir::ExprKind::Struct(qpath, ..) => {
538 let segment = match qpath {
539 hir::QPath::Resolved(_, path) => path.segments.last().unwrap(),
540 hir::QPath::TypeRelative(_, segment) => segment,
542 match self.tables.expr_ty_adjusted(&hir_node).kind {
543 ty::Adt(def, _) if !def.is_enum() => {
544 let sub_span = segment.ident.span;
545 filter!(self.span_utils, sub_span);
546 let span = self.span_from_span(sub_span);
547 Some(Data::RefData(Ref {
550 ref_id: id_from_def_id(def.did),
554 // FIXME ty could legitimately be an enum, but then we will fail
555 // later if we try to look up the fields.
556 debug!("expected struct or union, found {:?}", ty);
561 hir::ExprKind::MethodCall(ref seg, ..) => {
562 let method_id = match self.tables.type_dependent_def_id(expr.hir_id) {
565 debug!("could not resolve method id for {:?}", expr);
569 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
570 ty::ImplContainer(_) => (Some(method_id), None),
571 ty::TraitContainer(_) => (None, Some(method_id)),
573 let sub_span = seg.ident.span;
574 filter!(self.span_utils, sub_span);
575 let span = self.span_from_span(sub_span);
576 Some(Data::RefData(Ref {
577 kind: RefKind::Function,
579 ref_id: def_id.or(decl_id).map(id_from_def_id).unwrap_or_else(null_id),
582 hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => {
583 self.get_path_data(expr.hir_id, path).map(Data::RefData)
587 bug!("invalid expression: {:?}", expr);
592 pub fn get_path_res(&self, hir_id: hir::HirId) -> Res {
593 match self.tcx.hir().get(hir_id) {
594 Node::TraitRef(tr) => tr.path.res,
596 Node::Item(&hir::Item { kind: hir::ItemKind::Use(path, _), .. }) => path.res,
597 Node::Visibility(&Spanned {
598 node: hir::VisibilityKind::Restricted { ref path, .. },
602 Node::PathSegment(seg) => match seg.res {
603 Some(res) if res != Res::Err => res,
605 let parent_node = self.tcx.hir().get_parent_node(hir_id);
606 self.get_path_res(parent_node)
610 Node::Expr(&hir::Expr { kind: hir::ExprKind::Struct(ref qpath, ..), .. }) => {
611 self.tables.qpath_res(qpath, hir_id)
614 Node::Expr(&hir::Expr { kind: hir::ExprKind::Path(ref qpath), .. })
615 | Node::Pat(&hir::Pat {
617 hir::PatKind::Path(ref qpath)
618 | hir::PatKind::Struct(ref qpath, ..)
619 | hir::PatKind::TupleStruct(ref qpath, ..),
622 | Node::Ty(&hir::Ty { kind: hir::TyKind::Path(ref qpath), .. }) => {
623 self.tables.qpath_res(qpath, hir_id)
626 Node::Binding(&hir::Pat {
627 kind: hir::PatKind::Binding(_, canonical_id, ..), ..
628 }) => Res::Local(canonical_id),
634 pub fn get_path_data(&self, id: hir::HirId, path: &hir::Path<'_>) -> Option<Ref> {
635 path.segments.last().and_then(|seg| {
636 self.get_path_segment_data(seg).or_else(|| self.get_path_segment_data_with_id(seg, id))
640 pub fn get_path_segment_data(&self, path_seg: &hir::PathSegment<'_>) -> Option<Ref> {
641 self.get_path_segment_data_with_id(path_seg, path_seg.hir_id?)
644 pub fn get_path_segment_data_with_id(
646 path_seg: &hir::PathSegment<'_>,
649 // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
650 fn fn_type(seg: &hir::PathSegment<'_>) -> bool {
651 seg.args.map(|args| args.parenthesized).unwrap_or(false)
654 let res = self.get_path_res(id);
655 let span = path_seg.ident.span;
656 filter!(self.span_utils, span);
657 let span = self.span_from_span(span);
661 Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_hir_id(id, self) })
663 Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
664 Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(def_id) })
668 | HirDefKind::Variant
671 | HirDefKind::TyAlias
672 | HirDefKind::ForeignTy
673 | HirDefKind::TraitAlias
674 | HirDefKind::AssocOpaqueTy
675 | HirDefKind::AssocTy
677 | HirDefKind::OpaqueTy
678 | HirDefKind::TyParam,
680 ) => Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(def_id) }),
681 Res::Def(HirDefKind::ConstParam, def_id) => {
682 Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_def_id(def_id) })
684 Res::Def(HirDefKind::Ctor(CtorOf::Struct, ..), def_id) => {
685 // This is a reference to a tuple struct where the def_id points
686 // to an invisible constructor function. That is not a very useful
687 // def, so adjust to point to the tuple struct itself.
688 let parent_def_id = self.tcx.parent(def_id).unwrap();
689 Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(parent_def_id) })
694 | HirDefKind::AssocConst
695 | HirDefKind::Ctor(..),
697 ) => Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_def_id(res.def_id()) }),
698 Res::Def(HirDefKind::AssocFn, decl_id) => {
699 let def_id = if decl_id.is_local() {
700 let ti = self.tcx.associated_item(decl_id);
703 .associated_items(ti.container.id())
704 .filter_by_name_unhygienic(ti.ident.name)
705 .find(|item| item.defaultness.has_value())
706 .map(|item| item.def_id)
711 kind: RefKind::Function,
713 ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
716 Res::Def(HirDefKind::Fn, def_id) => {
717 Some(Ref { kind: RefKind::Function, span, ref_id: id_from_def_id(def_id) })
719 Res::Def(HirDefKind::Mod, def_id) => {
720 Some(Ref { kind: RefKind::Mod, span, ref_id: id_from_def_id(def_id) })
724 HirDefKind::Macro(..)
725 | HirDefKind::ExternCrate
726 | HirDefKind::ForeignMod
727 | HirDefKind::LifetimeParam
728 | HirDefKind::AnonConst
731 | HirDefKind::GlobalAsm
733 | HirDefKind::Closure
734 | HirDefKind::Generator,
740 | Res::NonMacroAttr(..)
746 pub fn get_field_ref_data(
748 field_ref: &hir::Field<'_>,
749 variant: &ty::VariantDef,
751 filter!(self.span_utils, field_ref.ident.span);
752 self.tcx.find_field_index(field_ref.ident, variant).map(|index| {
753 let span = self.span_from_span(field_ref.ident.span);
754 Ref { kind: RefKind::Variable, span, ref_id: id_from_def_id(variant.fields[index].did) }
758 /// Attempt to return MacroRef for any AST node.
760 /// For a given piece of AST defined by the supplied Span and NodeId,
761 /// returns `None` if the node is not macro-generated or the span is malformed,
762 /// else uses the expansion callsite and callee to return some MacroRef.
763 pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
764 if !generated_code(span) {
767 // Note we take care to use the source callsite/callee, to handle
768 // nested expansions and ensure we only generate data for source-visible
770 let callsite = span.source_callsite();
771 let callsite_span = self.span_from_span(callsite);
772 let callee = span.source_callee()?;
774 let mac_name = match callee.kind {
775 ExpnKind::Macro(mac_kind, name) => match mac_kind {
776 MacroKind::Bang => name,
778 // Ignore attribute macros, their spans are usually mangled
779 // FIXME(eddyb) is this really the case anymore?
780 MacroKind::Attr | MacroKind::Derive => return None,
783 // These are not macros.
784 // FIXME(eddyb) maybe there is a way to handle them usefully?
785 ExpnKind::Root | ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => return None,
788 let callee_span = self.span_from_span(callee.def_site);
791 qualname: mac_name.to_string(), // FIXME: generate the real qualname
796 fn lookup_def_id(&self, ref_id: hir::HirId) -> Option<DefId> {
797 match self.get_path_res(ref_id) {
798 Res::PrimTy(_) | Res::SelfTy(..) | Res::Err => None,
799 def => def.opt_def_id(),
803 fn docs_for_attrs(&self, attrs: &[ast::Attribute]) -> String {
804 let mut result = String::new();
807 if let Some(val) = attr.doc_str() {
808 if attr.is_doc_comment() {
809 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
811 result.push_str(&val.as_str());
814 } else if attr.check_name(sym::doc) {
815 if let Some(meta_list) = attr.meta_item_list() {
818 .filter(|it| it.check_name(sym::include))
819 .filter_map(|it| it.meta_item_list().map(|l| l.to_owned()))
821 .filter(|meta| meta.check_name(sym::contents))
822 .filter_map(|meta| meta.value_str())
824 result.push_str(&val.as_str());
831 if !self.config.full_docs {
832 if let Some(index) = result.find("\n\n") {
833 result.truncate(index);
840 fn next_impl_id(&self) -> u32 {
841 let next = self.impl_counter.get();
842 self.impl_counter.set(next + 1);
847 fn make_signature(decl: &hir::FnDecl<'_>, generics: &hir::Generics<'_>) -> String {
848 let mut sig = "fn ".to_owned();
849 if !generics.params.is_empty() {
855 .map(|param| param.name.ident().to_string())
862 sig.push_str(&decl.inputs.iter().map(ty_to_string).collect::<Vec<_>>().join(", "));
865 hir::FnRetTy::DefaultReturn(_) => sig.push_str(" -> ()"),
866 hir::FnRetTy::Return(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
872 // An AST visitor for collecting paths (e.g., the names of structs) and formal
873 // variables (idents) from patterns.
874 struct PathCollector<'l> {
876 collected_paths: Vec<(hir::HirId, &'l hir::QPath<'l>)>,
877 collected_idents: Vec<(hir::HirId, Ident, hir::Mutability)>,
880 impl<'l> PathCollector<'l> {
881 fn new(tcx: TyCtxt<'l>) -> PathCollector<'l> {
882 PathCollector { tcx, collected_paths: vec![], collected_idents: vec![] }
886 impl<'l> Visitor<'l> for PathCollector<'l> {
889 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
890 intravisit::NestedVisitorMap::All(self.tcx.hir())
893 fn visit_pat(&mut self, p: &'l hir::Pat<'l>) {
895 hir::PatKind::Struct(ref path, ..) => {
896 self.collected_paths.push((p.hir_id, path));
898 hir::PatKind::TupleStruct(ref path, ..) | hir::PatKind::Path(ref path) => {
899 self.collected_paths.push((p.hir_id, path));
901 hir::PatKind::Binding(bm, _, ident, _) => {
903 "PathCollector, visit ident in pat {}: {:?} {:?}",
904 ident, p.span, ident.span
906 let immut = match bm {
907 // Even if the ref is mut, you can't change the ref, only
908 // the data pointed at, so showing the initialising expression
909 // is still worthwhile.
910 hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Ref => {
913 hir::BindingAnnotation::Mutable | hir::BindingAnnotation::RefMut => {
917 self.collected_idents.push((p.hir_id, ident, immut));
921 intravisit::walk_pat(self, p);
925 /// Defines what to do with the results of saving the analysis.
926 pub trait SaveHandler {
927 fn save(&mut self, save_ctxt: &SaveContext<'_, '_>, analysis: &Analysis);
930 /// Dump the save-analysis results to a file.
931 pub struct DumpHandler<'a> {
932 odir: Option<&'a Path>,
936 impl<'a> DumpHandler<'a> {
937 pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
938 DumpHandler { odir, cratename: cratename.to_owned() }
941 fn output_file(&self, ctx: &SaveContext<'_, '_>) -> (BufWriter<File>, PathBuf) {
942 let sess = &ctx.tcx.sess;
943 let file_name = match ctx.config.output_file {
944 Some(ref s) => PathBuf::from(s),
946 let mut root_path = match self.odir {
947 Some(val) => val.join("save-analysis"),
948 None => PathBuf::from("save-analysis-temp"),
951 if let Err(e) = std::fs::create_dir_all(&root_path) {
952 error!("Could not create directory {}: {}", root_path.display(), e);
955 let executable = sess.crate_types().iter().any(|ct| *ct == CrateType::Executable);
956 let mut out_name = if executable { String::new() } else { "lib".to_owned() };
957 out_name.push_str(&self.cratename);
958 out_name.push_str(&sess.opts.cg.extra_filename);
959 out_name.push_str(".json");
960 root_path.push(&out_name);
966 info!("Writing output to {}", file_name.display());
968 let output_file = BufWriter::new(File::create(&file_name).unwrap_or_else(|e| {
969 sess.fatal(&format!("Could not open {}: {}", file_name.display(), e))
972 (output_file, file_name)
976 impl SaveHandler for DumpHandler<'_> {
977 fn save(&mut self, save_ctxt: &SaveContext<'_, '_>, analysis: &Analysis) {
978 let sess = &save_ctxt.tcx.sess;
979 let (output, file_name) = self.output_file(&save_ctxt);
980 if let Err(e) = serde_json::to_writer(output, &analysis) {
981 error!("Can't serialize save-analysis: {:?}", e);
984 if sess.opts.json_artifact_notifications {
985 sess.parse_sess.span_diagnostic.emit_artifact_notification(&file_name, "save-analysis");
990 /// Call a callback with the results of save-analysis.
991 pub struct CallbackHandler<'b> {
992 pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
995 impl SaveHandler for CallbackHandler<'_> {
996 fn save(&mut self, _: &SaveContext<'_, '_>, analysis: &Analysis) {
997 (self.callback)(analysis)
1001 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
1005 config: Option<Config>,
1008 tcx.dep_graph.with_ignore(|| {
1009 info!("Dumping crate {}", cratename);
1011 // Privacy checking requires and is done after type checking; use a
1012 // fallback in case the access levels couldn't have been correctly computed.
1013 let access_levels = match tcx.sess.compile_status() {
1014 Ok(..) => tcx.privacy_access_levels(LOCAL_CRATE),
1015 Err(..) => tcx.arena.alloc(AccessLevels::default()),
1018 let save_ctxt = SaveContext {
1020 tables: &ty::TypeckTables::empty(None),
1021 empty_tables: &ty::TypeckTables::empty(None),
1022 access_levels: &access_levels,
1023 span_utils: SpanUtils::new(&tcx.sess),
1024 config: find_config(config),
1025 impl_counter: Cell::new(0),
1028 let mut visitor = DumpVisitor::new(save_ctxt);
1030 visitor.dump_crate_info(cratename, tcx.hir().krate());
1031 visitor.dump_compilation_options(input, cratename);
1032 visitor.process_crate(tcx.hir().krate());
1034 handler.save(&visitor.save_ctxt, &visitor.analysis())
1038 fn find_config(supplied: Option<Config>) -> Config {
1039 if let Some(config) = supplied {
1043 match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
1044 None => Config::default(),
1045 Some(config) => config
1048 .map_err(|_| error!("`RUST_SAVE_ANALYSIS_CONFIG` isn't UTF-8"))
1050 serde_json::from_str(cfg)
1051 .map_err(|_| error!("Could not deserialize save-analysis config"))
1053 .unwrap_or_default(),
1057 // Utility functions for the module.
1059 // Helper function to escape quotes in a string
1060 fn escape(s: String) -> String {
1061 s.replace("\"", "\"\"")
1064 // Helper function to determine if a span came from a
1065 // macro expansion or syntax extension.
1066 fn generated_code(span: Span) -> bool {
1067 span.from_expansion() || span.is_dummy()
1070 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
1071 // we use our own Id which is the same, but without the newtype.
1072 fn id_from_def_id(id: DefId) -> rls_data::Id {
1073 rls_data::Id { krate: id.krate.as_u32(), index: id.index.as_u32() }
1076 fn id_from_hir_id(id: hir::HirId, scx: &SaveContext<'_, '_>) -> rls_data::Id {
1077 let def_id = scx.tcx.hir().opt_local_def_id(id);
1078 def_id.map(|id| id_from_def_id(id.to_def_id())).unwrap_or_else(|| {
1079 // Create a *fake* `DefId` out of a `HirId` by combining the owner
1080 // `local_def_index` and the `local_id`.
1081 // This will work unless you have *billions* of definitions in a single
1082 // crate (very unlikely to actually happen).
1084 krate: LOCAL_CRATE.as_u32(),
1085 index: id.owner.local_def_index.as_u32() | id.local_id.as_u32().reverse_bits(),
1090 fn null_id() -> rls_data::Id {
1091 rls_data::Id { krate: u32::max_value(), index: u32::max_value() }
1094 fn lower_attributes(
1095 attrs: Vec<ast::Attribute>,
1096 scx: &SaveContext<'_, '_>,
1097 ) -> Vec<rls_data::Attribute> {
1100 // Only retain real attributes. Doc comments are lowered separately.
1101 .filter(|attr| !attr.has_name(sym::doc))
1103 // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
1104 // attribute. First normalize all inner attribute (#![..]) to outer
1105 // ones (#[..]), then remove the two leading and the one trailing character.
1106 attr.style = ast::AttrStyle::Outer;
1107 let value = attribute_to_string(&attr);
1108 // This str slicing works correctly, because the leading and trailing characters
1109 // are in the ASCII range and thus exactly one byte each.
1110 let value = value[2..value.len() - 1].to_string();
1112 rls_data::Attribute { value, span: scx.span_from_span(attr.span) }