1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
2 #![feature(if_let_guard)]
3 #![recursion_limit = "256"]
4 #![allow(rustc::potential_query_instability)]
5 #![feature(never_type)]
6 #![deny(rustc::untranslatable_diagnostic)]
7 #![deny(rustc::diagnostic_outside_of_impl)]
20 use rustc_ast::util::comments::beautify_doc_string;
21 use rustc_ast_pretty::pprust::attribute_to_string;
23 use rustc_hir::def::{DefKind as HirDefKind, Res};
24 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
25 use rustc_hir::intravisit::{self, Visitor};
27 use rustc_hir_pretty::{enum_def_to_string, fn_to_string, ty_to_string};
28 use rustc_middle::hir::nested_filter;
29 use rustc_middle::middle::privacy::EffectiveVisibilities;
30 use rustc_middle::ty::{self, print::with_no_trimmed_paths, DefIdTree, TyCtxt};
31 use rustc_middle::{bug, span_bug};
32 use rustc_session::config::{CrateType, Input, OutputType};
33 use rustc_session::cstore::ExternCrate;
34 use rustc_session::output::{filename_for_metadata, out_filename};
35 use rustc_span::symbol::Ident;
41 use std::io::BufWriter;
42 use std::path::{Path, PathBuf};
44 use dump_visitor::DumpVisitor;
45 use span_utils::SpanUtils;
47 use rls_data::config::Config;
49 Analysis, Def, DefKind, ExternalCrateData, GlobalCrateId, Impl, ImplKind, MacroRef, Ref,
50 RefKind, Relation, RelationKind, SpanData,
53 pub struct SaveContext<'tcx> {
55 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
56 effective_visibilities: &'tcx EffectiveVisibilities,
57 span_utils: SpanUtils<'tcx>,
59 impl_counter: Cell<u32>,
66 RelationData(Relation, Impl),
69 impl<'tcx> SaveContext<'tcx> {
70 /// Gets the type-checking results for the current body.
71 /// As this will ICE if called outside bodies, only call when working with
72 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
74 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
75 self.maybe_typeck_results.expect("`SaveContext::typeck_results` called outside of body")
78 fn span_from_span(&self, span: Span) -> SpanData {
79 use rls_span::{Column, Row};
81 let sm = self.tcx.sess.source_map();
82 let start = sm.lookup_char_pos(span.lo());
83 let end = sm.lookup_char_pos(span.hi());
86 file_name: start.file.name.prefer_remapped().to_string().into(),
87 byte_start: span.lo().0,
88 byte_end: span.hi().0,
89 line_start: Row::new_one_indexed(start.line as u32),
90 line_end: Row::new_one_indexed(end.line as u32),
91 column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
92 column_end: Column::new_one_indexed(end.col.0 as u32 + 1),
96 /// Returns path to the compilation output (e.g., libfoo-12345678.rmeta)
97 pub fn compilation_output(&self, crate_name: Symbol) -> PathBuf {
98 let sess = &self.tcx.sess;
99 // Save-analysis is emitted per whole session, not per each crate type
100 let crate_type = sess.crate_types()[0];
101 let outputs = &*self.tcx.output_filenames(());
103 if outputs.outputs.contains_key(&OutputType::Metadata) {
104 filename_for_metadata(sess, crate_name, outputs)
105 } else if outputs.outputs.should_codegen() {
106 out_filename(sess, crate_type, outputs, crate_name)
108 // Otherwise it's only a DepInfo, in which case we return early and
109 // not even reach the analysis stage.
114 /// List external crates used by the current crate.
115 pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
116 let mut result = Vec::with_capacity(self.tcx.crates(()).len());
118 for &n in self.tcx.crates(()).iter() {
119 let Some(&ExternCrate { span, .. }) = self.tcx.extern_crate(n.as_def_id()) else {
120 debug!("skipping crate {}, no data", n);
123 let lo_loc = self.span_utils.sess.source_map().lookup_char_pos(span.lo());
124 result.push(ExternalCrateData {
125 // FIXME: change file_name field to PathBuf in rls-data
126 // https://github.com/nrc/rls-data/issues/7
127 file_name: self.span_utils.make_filename_string(&lo_loc.file),
130 name: self.tcx.crate_name(n).to_string(),
132 self.tcx.def_path_hash(n.as_def_id()).stable_crate_id().to_u64(),
142 pub fn get_extern_item_data(&self, item: &hir::ForeignItem<'_>) -> Option<Data> {
143 let def_id = item.owner_id.to_def_id();
144 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
145 let attrs = self.tcx.hir().attrs(item.hir_id());
147 hir::ForeignItemKind::Fn(ref decl, arg_names, ref generics) => {
148 filter!(self.span_utils, item.ident.span);
150 Some(Data::DefData(Def {
151 kind: DefKind::ForeignFunction,
152 id: id_from_def_id(def_id),
153 span: self.span_from_span(item.ident.span),
154 name: item.ident.to_string(),
159 // functions in extern block are implicitly unsafe
160 unsafety: hir::Unsafety::Unsafe,
161 // functions in extern block cannot be const
162 constness: hir::Constness::NotConst,
163 abi: self.tcx.hir().get_foreign_abi(item.hir_id()),
164 // functions in extern block cannot be async
165 asyncness: hir::IsAsync::NotAsync,
167 Some(item.ident.name),
175 docs: self.docs_for_attrs(attrs),
176 sig: sig::foreign_item_signature(item, self),
177 attributes: lower_attributes(attrs.to_vec(), self),
180 hir::ForeignItemKind::Static(ref ty, _) => {
181 filter!(self.span_utils, item.ident.span);
183 let id = id_from_def_id(def_id);
184 let span = self.span_from_span(item.ident.span);
186 Some(Data::DefData(Def {
187 kind: DefKind::ForeignStatic,
190 name: item.ident.to_string(),
192 value: ty_to_string(ty),
196 docs: self.docs_for_attrs(attrs),
197 sig: sig::foreign_item_signature(item, self),
198 attributes: lower_attributes(attrs.to_vec(), self),
201 // FIXME(plietar): needs a new DefKind in rls-data
202 hir::ForeignItemKind::Type => None,
206 pub fn get_item_data(&self, item: &hir::Item<'_>) -> Option<Data> {
207 let def_id = item.owner_id.to_def_id();
208 let attrs = self.tcx.hir().attrs(item.hir_id());
210 hir::ItemKind::Fn(ref sig, ref generics, _) => {
211 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
212 filter!(self.span_utils, item.ident.span);
213 Some(Data::DefData(Def {
214 kind: DefKind::Function,
215 id: id_from_def_id(def_id),
216 span: self.span_from_span(item.ident.span),
217 name: item.ident.to_string(),
222 Some(item.ident.name),
230 docs: self.docs_for_attrs(attrs),
231 sig: sig::item_signature(item, self),
232 attributes: lower_attributes(attrs.to_vec(), self),
235 hir::ItemKind::Static(ref typ, ..) => {
236 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
238 filter!(self.span_utils, item.ident.span);
240 let id = id_from_def_id(def_id);
241 let span = self.span_from_span(item.ident.span);
243 Some(Data::DefData(Def {
244 kind: DefKind::Static,
247 name: item.ident.to_string(),
249 value: ty_to_string(&typ),
253 docs: self.docs_for_attrs(attrs),
254 sig: sig::item_signature(item, self),
255 attributes: lower_attributes(attrs.to_vec(), self),
258 hir::ItemKind::Const(ref typ, _) => {
259 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
260 filter!(self.span_utils, item.ident.span);
262 let id = id_from_def_id(def_id);
263 let span = self.span_from_span(item.ident.span);
265 Some(Data::DefData(Def {
266 kind: DefKind::Const,
269 name: item.ident.to_string(),
271 value: ty_to_string(typ),
275 docs: self.docs_for_attrs(attrs),
276 sig: sig::item_signature(item, self),
277 attributes: lower_attributes(attrs.to_vec(), self),
280 hir::ItemKind::Mod(ref m) => {
281 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
283 let sm = self.tcx.sess.source_map();
284 let filename = sm.span_to_filename(m.spans.inner_span);
286 filter!(self.span_utils, item.ident.span);
288 Some(Data::DefData(Def {
290 id: id_from_def_id(def_id),
291 name: item.ident.to_string(),
293 span: self.span_from_span(item.ident.span),
294 value: filename.prefer_remapped().to_string(),
299 .map(|i| id_from_def_id(i.owner_id.to_def_id()))
302 docs: self.docs_for_attrs(attrs),
303 sig: sig::item_signature(item, self),
304 attributes: lower_attributes(attrs.to_vec(), self),
307 hir::ItemKind::Enum(ref def, ref generics) => {
308 let name = item.ident.to_string();
309 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
310 filter!(self.span_utils, item.ident.span);
312 enum_def_to_string(def, generics, item.ident.name, item.span);
313 Some(Data::DefData(Def {
315 id: id_from_def_id(def_id),
316 span: self.span_from_span(item.ident.span),
321 children: def.variants.iter().map(|v| id_from_hir_id(v.hir_id, self)).collect(),
323 docs: self.docs_for_attrs(attrs),
324 sig: sig::item_signature(item, self),
325 attributes: lower_attributes(attrs.to_vec(), self),
328 hir::ItemKind::Impl(hir::Impl { ref of_trait, ref self_ty, ref items, .. })
329 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = self_ty.kind =>
331 // Common case impl for a struct or something basic.
332 if generated_code(path.span) {
335 let sub_span = path.segments.last().unwrap().ident.span;
336 filter!(self.span_utils, sub_span);
338 let impl_id = self.next_impl_id();
339 let span = self.span_from_span(sub_span);
341 let type_data = self.lookup_def_id(self_ty.hir_id);
342 type_data.map(|type_data| {
345 kind: RelationKind::Impl { id: impl_id },
347 from: id_from_def_id(type_data),
350 .and_then(|t| self.lookup_def_id(t.hir_ref_id))
352 .unwrap_or_else(null_id),
356 kind: match *of_trait {
357 Some(_) => ImplKind::Direct,
358 None => ImplKind::Inherent,
361 value: String::new(),
365 .map(|i| id_from_def_id(i.id.owner_id.to_def_id()))
374 hir::ItemKind::Impl(_) => None,
382 pub fn get_field_data(&self, field: &hir::FieldDef<'_>, scope: hir::HirId) -> Option<Def> {
383 let name = field.ident.to_string();
384 let scope_def_id = self.tcx.hir().local_def_id(scope).to_def_id();
385 let qualname = format!("::{}::{}", self.tcx.def_path_str(scope_def_id), field.ident);
386 filter!(self.span_utils, field.ident.span);
387 let field_def_id = self.tcx.hir().local_def_id(field.hir_id).to_def_id();
388 let typ = self.tcx.type_of(field_def_id).to_string();
390 let id = id_from_def_id(field_def_id);
391 let span = self.span_from_span(field.ident.span);
392 let attrs = self.tcx.hir().attrs(field.hir_id);
395 kind: DefKind::Field,
401 parent: Some(id_from_def_id(scope_def_id)),
404 docs: self.docs_for_attrs(attrs),
405 sig: sig::field_signature(field, self),
406 attributes: lower_attributes(attrs.to_vec(), self),
410 // FIXME would be nice to take a MethodItem here, but the ast provides both
411 // trait and impl flavours, so the caller must do the disassembly.
412 pub fn get_method_data(&self, hir_id: hir::HirId, ident: Ident, span: Span) -> Option<Def> {
413 // The qualname for a method is the trait name or name of the struct in an impl in
414 // which the method is declared in, followed by the method's name.
415 let def_id = self.tcx.hir().local_def_id(hir_id).to_def_id();
416 let (qualname, parent_scope, decl_id, docs, attributes) =
417 match self.tcx.impl_of_method(def_id) {
418 Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) {
419 Some(Node::Item(item)) => match item.kind {
420 hir::ItemKind::Impl(hir::Impl { ref self_ty, .. }) => {
421 let hir = self.tcx.hir();
423 let mut qualname = String::from("<");
425 .push_str(&rustc_hir_pretty::id_to_string(&hir, self_ty.hir_id));
427 let trait_id = self.tcx.trait_id_of_impl(impl_id);
428 let mut docs = String::new();
429 let mut attrs = vec![];
430 if let Some(Node::ImplItem(_)) = hir.find(hir_id) {
431 attrs = self.tcx.hir().attrs(hir_id).to_vec();
432 docs = self.docs_for_attrs(&attrs);
435 let mut decl_id = None;
436 if let Some(def_id) = trait_id {
437 // A method in a trait impl.
438 qualname.push_str(" as ");
439 qualname.push_str(&self.tcx.def_path_str(def_id));
443 .associated_items(def_id)
444 .filter_by_name_unhygienic(ident.name)
446 .map(|item| item.def_id);
450 (qualname, trait_id, decl_id, docs, attrs)
455 "Container {:?} for method {} not an impl?",
464 "Container {:?} for method {} is not a node item {:?}",
471 None => match self.tcx.trait_of_item(def_id) {
473 let mut docs = String::new();
474 let mut attrs = vec![];
476 if let Some(Node::TraitItem(_)) = self.tcx.hir().find(hir_id) {
477 attrs = self.tcx.hir().attrs(hir_id).to_vec();
478 docs = self.docs_for_attrs(&attrs);
482 format!("::{}", self.tcx.def_path_str(def_id)),
490 debug!("could not find container for method {} at {:?}", hir_id, span);
491 // This is not necessarily a bug, if there was a compilation error,
492 // the typeck results we need might not exist.
498 let qualname = format!("{}::{}", qualname, ident.name);
500 filter!(self.span_utils, ident.span);
503 kind: DefKind::Method,
504 id: id_from_def_id(def_id),
505 span: self.span_from_span(ident.span),
506 name: ident.name.to_string(),
508 // FIXME you get better data here by using the visitor.
509 value: String::new(),
510 parent: parent_scope.map(id_from_def_id),
512 decl_id: decl_id.map(id_from_def_id),
515 attributes: lower_attributes(attributes, self),
519 pub fn get_expr_data(&self, expr: &hir::Expr<'_>) -> Option<Data> {
520 let ty = self.typeck_results().expr_ty_adjusted_opt(expr)?;
521 if matches!(ty.kind(), ty::Error(_)) {
525 hir::ExprKind::Field(ref sub_ex, ident) => {
526 match self.typeck_results().expr_ty_adjusted(&sub_ex).kind() {
527 ty::Adt(def, _) if !def.is_enum() => {
528 let variant = &def.non_enum_variant();
529 filter!(self.span_utils, ident.span);
530 let span = self.span_from_span(ident.span);
531 Some(Data::RefData(Ref {
532 kind: RefKind::Variable,
536 .find_field_index(ident, variant)
537 .map(|index| id_from_def_id(variant.fields[index].did))
538 .unwrap_or_else(null_id),
541 ty::Tuple(..) => None,
543 debug!("expected struct or union type, found {:?}", ty);
548 hir::ExprKind::Struct(qpath, ..) => match ty.kind() {
550 let sub_span = qpath.last_segment_span();
551 filter!(self.span_utils, sub_span);
552 let span = self.span_from_span(sub_span);
553 Some(Data::RefData(Ref {
556 ref_id: id_from_def_id(def.did()),
560 debug!("expected adt, found {:?}", ty);
564 hir::ExprKind::MethodCall(ref seg, ..) => {
565 let Some(method_id) = self.typeck_results().type_dependent_def_id(expr.hir_id) else {
566 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(ref 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, _), .. }) => {
597 path.res.get(0).copied().unwrap_or(Res::Err)
599 Node::PathSegment(seg) => {
600 if seg.res != Res::Err {
603 let parent_node = self.tcx.hir().get_parent_node(hir_id);
604 self.get_path_res(parent_node)
608 Node::Expr(&hir::Expr { kind: hir::ExprKind::Struct(ref qpath, ..), .. }) => {
609 self.typeck_results().qpath_res(qpath, hir_id)
612 Node::Expr(&hir::Expr { kind: hir::ExprKind::Path(ref qpath), .. })
613 | Node::Pat(&hir::Pat {
615 hir::PatKind::Path(ref qpath)
616 | hir::PatKind::Struct(ref qpath, ..)
617 | hir::PatKind::TupleStruct(ref qpath, ..),
620 | Node::Ty(&hir::Ty { kind: hir::TyKind::Path(ref qpath), .. }) => match qpath {
621 hir::QPath::Resolved(_, path) => path.res,
622 hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => {
623 // #75962: `self.typeck_results` may be different from the `hir_id`'s result.
624 if self.tcx.has_typeck_results(hir_id.owner.to_def_id()) {
625 self.tcx.typeck(hir_id.owner.def_id).qpath_res(qpath, hir_id)
632 Node::Pat(&hir::Pat { kind: hir::PatKind::Binding(_, canonical_id, ..), .. }) => {
633 Res::Local(canonical_id)
640 pub fn get_path_data(&self, id: hir::HirId, path: &hir::QPath<'_>) -> Option<Ref> {
641 let segment = match path {
642 hir::QPath::Resolved(_, path) => path.segments.last(),
643 hir::QPath::TypeRelative(_, segment) => Some(*segment),
644 hir::QPath::LangItem(..) => None,
646 segment.and_then(|seg| {
647 self.get_path_segment_data(seg).or_else(|| self.get_path_segment_data_with_id(seg, id))
651 pub fn get_path_segment_data(&self, path_seg: &hir::PathSegment<'_>) -> Option<Ref> {
652 self.get_path_segment_data_with_id(path_seg, path_seg.hir_id)
655 pub fn get_path_segment_data_with_id(
657 path_seg: &hir::PathSegment<'_>,
660 // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
661 fn fn_type(seg: &hir::PathSegment<'_>) -> bool {
662 seg.args.map_or(false, |args| args.parenthesized)
665 let res = self.get_path_res(id);
666 let span = path_seg.ident.span;
667 filter!(self.span_utils, span);
668 let span = self.span_from_span(span);
672 Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_hir_id(id, self) })
674 Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
675 Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(def_id) })
679 | HirDefKind::Variant
682 | HirDefKind::TyAlias
683 | HirDefKind::ForeignTy
684 | HirDefKind::TraitAlias
685 | HirDefKind::AssocTy
687 | HirDefKind::OpaqueTy
688 | HirDefKind::ImplTraitPlaceholder
689 | HirDefKind::TyParam,
691 ) => Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(def_id) }),
692 Res::Def(HirDefKind::ConstParam, def_id) => {
693 Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_def_id(def_id) })
695 Res::Def(HirDefKind::Ctor(..), def_id) => {
696 // This is a reference to a tuple struct or an enum variant where the def_id points
697 // to an invisible constructor function. That is not a very useful
698 // def, so adjust to point to the tuple struct or enum variant itself.
699 let parent_def_id = self.tcx.parent(def_id);
700 Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(parent_def_id) })
702 Res::Def(HirDefKind::Static(_) | HirDefKind::Const | HirDefKind::AssocConst, _) => {
703 Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_def_id(res.def_id()) })
705 Res::Def(HirDefKind::AssocFn, decl_id) => {
706 let def_id = if decl_id.is_local() {
707 if self.tcx.impl_defaultness(decl_id).has_value() {
716 kind: RefKind::Function,
718 ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
721 Res::Def(HirDefKind::Fn, def_id) => {
722 Some(Ref { kind: RefKind::Function, span, ref_id: id_from_def_id(def_id) })
724 Res::Def(HirDefKind::Mod, def_id) => {
725 Some(Ref { kind: RefKind::Mod, span, ref_id: id_from_def_id(def_id) })
729 HirDefKind::Macro(..)
730 | HirDefKind::ExternCrate
731 | HirDefKind::ForeignMod
732 | HirDefKind::LifetimeParam
733 | HirDefKind::AnonConst
734 | HirDefKind::InlineConst
737 | HirDefKind::GlobalAsm
739 | HirDefKind::Closure
740 | HirDefKind::Generator,
744 | Res::SelfTyParam { .. }
745 | Res::SelfTyAlias { .. }
747 | Res::NonMacroAttr(..)
753 pub fn get_field_ref_data(
755 field_ref: &hir::ExprField<'_>,
756 variant: &ty::VariantDef,
758 filter!(self.span_utils, field_ref.ident.span);
759 self.tcx.find_field_index(field_ref.ident, variant).map(|index| {
760 let span = self.span_from_span(field_ref.ident.span);
761 Ref { kind: RefKind::Variable, span, ref_id: id_from_def_id(variant.fields[index].did) }
765 /// Attempt to return MacroRef for any AST node.
767 /// For a given piece of AST defined by the supplied Span and NodeId,
768 /// returns `None` if the node is not macro-generated or the span is malformed,
769 /// else uses the expansion callsite and callee to return some MacroRef.
771 /// FIXME: [`DumpVisitor::process_macro_use`] should actually dump this data
773 fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
774 if !generated_code(span) {
777 // Note we take care to use the source callsite/callee, to handle
778 // nested expansions and ensure we only generate data for source-visible
780 let callsite = span.source_callsite();
781 let callsite_span = self.span_from_span(callsite);
782 let callee = span.source_callee()?;
784 let mac_name = match callee.kind {
785 ExpnKind::Macro(kind, name) => match kind {
786 MacroKind::Bang => name,
788 // Ignore attribute macros, their spans are usually mangled
789 // FIXME(eddyb) is this really the case anymore?
790 MacroKind::Attr | MacroKind::Derive => return None,
793 // These are not macros.
794 // FIXME(eddyb) maybe there is a way to handle them usefully?
795 ExpnKind::Inlined | ExpnKind::Root | ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => {
800 let callee_span = self.span_from_span(callee.def_site);
803 qualname: mac_name.to_string(), // FIXME: generate the real qualname
808 fn lookup_def_id(&self, ref_id: hir::HirId) -> Option<DefId> {
809 match self.get_path_res(ref_id) {
810 Res::PrimTy(_) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } | Res::Err => None,
811 def => def.opt_def_id(),
815 fn docs_for_attrs(&self, attrs: &[ast::Attribute]) -> String {
816 let mut result = String::new();
819 if let Some((val, kind)) = attr.doc_str_and_comment_kind() {
820 // FIXME: Should save-analysis beautify doc strings itself or leave it to users?
821 result.push_str(beautify_doc_string(val, kind).as_str());
826 if !self.config.full_docs {
827 if let Some(index) = result.find("\n\n") {
828 result.truncate(index);
835 fn next_impl_id(&self) -> u32 {
836 let next = self.impl_counter.get();
837 self.impl_counter.set(next + 1);
842 // An AST visitor for collecting paths (e.g., the names of structs) and formal
843 // variables (idents) from patterns.
844 struct PathCollector<'l> {
846 collected_paths: Vec<(hir::HirId, &'l hir::QPath<'l>)>,
847 collected_idents: Vec<(hir::HirId, Ident, hir::Mutability)>,
850 impl<'l> PathCollector<'l> {
851 fn new(tcx: TyCtxt<'l>) -> PathCollector<'l> {
852 PathCollector { tcx, collected_paths: vec![], collected_idents: vec![] }
856 impl<'l> Visitor<'l> for PathCollector<'l> {
857 type NestedFilter = nested_filter::All;
859 fn nested_visit_map(&mut self) -> Self::Map {
863 fn visit_pat(&mut self, p: &'l hir::Pat<'l>) {
865 hir::PatKind::Struct(ref path, ..) => {
866 self.collected_paths.push((p.hir_id, path));
868 hir::PatKind::TupleStruct(ref path, ..) | hir::PatKind::Path(ref path) => {
869 self.collected_paths.push((p.hir_id, path));
871 hir::PatKind::Binding(hir::BindingAnnotation(_, mutbl), _, ident, _) => {
873 "PathCollector, visit ident in pat {}: {:?} {:?}",
874 ident, p.span, ident.span
876 self.collected_idents.push((p.hir_id, ident, mutbl));
880 intravisit::walk_pat(self, p);
884 /// Defines what to do with the results of saving the analysis.
885 pub trait SaveHandler {
886 fn save(&mut self, save_ctxt: &SaveContext<'_>, analysis: &Analysis);
889 /// Dump the save-analysis results to a file.
890 pub struct DumpHandler<'a> {
891 odir: Option<&'a Path>,
895 impl<'a> DumpHandler<'a> {
896 pub fn new(odir: Option<&'a Path>, cratename: Symbol) -> DumpHandler<'a> {
897 DumpHandler { odir, cratename: cratename.to_string() }
900 fn output_file(&self, ctx: &SaveContext<'_>) -> (BufWriter<File>, PathBuf) {
901 let sess = &ctx.tcx.sess;
902 let file_name = match ctx.config.output_file {
903 Some(ref s) => PathBuf::from(s),
905 let mut root_path = match self.odir {
906 Some(val) => val.join("save-analysis"),
907 None => PathBuf::from("save-analysis-temp"),
910 if let Err(e) = std::fs::create_dir_all(&root_path) {
911 error!("Could not create directory {}: {}", root_path.display(), e);
914 let executable = sess.crate_types().iter().any(|ct| *ct == CrateType::Executable);
915 let mut out_name = if executable { String::new() } else { "lib".to_owned() };
916 out_name.push_str(&self.cratename);
917 out_name.push_str(&sess.opts.cg.extra_filename);
918 out_name.push_str(".json");
919 root_path.push(&out_name);
925 info!("Writing output to {}", file_name.display());
927 let output_file = BufWriter::new(File::create(&file_name).unwrap_or_else(|e| {
928 sess.emit_fatal(errors::CouldNotOpen { file_name: file_name.as_path(), err: e })
931 (output_file, file_name)
935 impl SaveHandler for DumpHandler<'_> {
936 fn save(&mut self, save_ctxt: &SaveContext<'_>, analysis: &Analysis) {
937 let sess = &save_ctxt.tcx.sess;
938 let (output, file_name) = self.output_file(&save_ctxt);
939 if let Err(e) = serde_json::to_writer(output, &analysis) {
940 error!("Can't serialize save-analysis: {:?}", e);
943 if sess.opts.json_artifact_notifications {
944 sess.parse_sess.span_diagnostic.emit_artifact_notification(&file_name, "save-analysis");
949 /// Call a callback with the results of save-analysis.
950 pub struct CallbackHandler<'b> {
951 pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
954 impl SaveHandler for CallbackHandler<'_> {
955 fn save(&mut self, _: &SaveContext<'_>, analysis: &Analysis) {
956 (self.callback)(analysis)
960 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
964 config: Option<Config>,
967 with_no_trimmed_paths!({
968 tcx.dep_graph.with_ignore(|| {
969 info!("Dumping crate {}", cratename);
971 // Privacy checking must be done outside of type inference; use a
972 // fallback in case effective visibilities couldn't have been correctly computed.
973 let effective_visibilities = match tcx.sess.compile_status() {
974 Ok(..) => tcx.effective_visibilities(()),
975 Err(..) => tcx.arena.alloc(EffectiveVisibilities::default()),
978 let save_ctxt = SaveContext {
980 maybe_typeck_results: None,
981 effective_visibilities: &effective_visibilities,
982 span_utils: SpanUtils::new(&tcx.sess),
983 config: find_config(config),
984 impl_counter: Cell::new(0),
987 let mut visitor = DumpVisitor::new(save_ctxt);
989 visitor.dump_crate_info(cratename);
990 visitor.dump_compilation_options(input, cratename);
991 visitor.process_crate();
993 handler.save(&visitor.save_ctxt, &visitor.analysis())
998 fn find_config(supplied: Option<Config>) -> Config {
999 if let Some(config) = supplied {
1003 match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
1004 None => Config::default(),
1005 Some(config) => config
1008 .map_err(|_| error!("`RUST_SAVE_ANALYSIS_CONFIG` isn't UTF-8"))
1010 serde_json::from_str(cfg)
1011 .map_err(|_| error!("Could not deserialize save-analysis config"))
1013 .unwrap_or_default(),
1017 // Utility functions for the module.
1019 // Helper function to escape quotes in a string
1020 fn escape(s: String) -> String {
1021 s.replace('\"', "\"\"")
1024 // Helper function to determine if a span came from a
1025 // macro expansion or syntax extension.
1026 fn generated_code(span: Span) -> bool {
1027 span.from_expansion() || span.is_dummy()
1030 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
1031 // we use our own Id which is the same, but without the newtype.
1032 fn id_from_def_id(id: DefId) -> rls_data::Id {
1033 rls_data::Id { krate: id.krate.as_u32(), index: id.index.as_u32() }
1036 fn id_from_hir_id(id: hir::HirId, scx: &SaveContext<'_>) -> rls_data::Id {
1037 let def_id = scx.tcx.hir().opt_local_def_id(id);
1038 def_id.map(|id| id_from_def_id(id.to_def_id())).unwrap_or_else(|| {
1039 // Create a *fake* `DefId` out of a `HirId` by combining the owner
1040 // `local_def_index` and the `local_id`.
1041 // This will work unless you have *billions* of definitions in a single
1042 // crate (very unlikely to actually happen).
1044 krate: LOCAL_CRATE.as_u32(),
1045 index: id.owner.def_id.local_def_index.as_u32() | id.local_id.as_u32().reverse_bits(),
1050 fn null_id() -> rls_data::Id {
1051 rls_data::Id { krate: u32::MAX, index: u32::MAX }
1054 fn lower_attributes(attrs: Vec<ast::Attribute>, scx: &SaveContext<'_>) -> Vec<rls_data::Attribute> {
1057 // Only retain real attributes. Doc comments are lowered separately.
1058 .filter(|attr| !attr.has_name(sym::doc))
1060 // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
1061 // attribute. First normalize all inner attribute (#![..]) to outer
1062 // ones (#[..]), then remove the two leading and the one trailing character.
1063 attr.style = ast::AttrStyle::Outer;
1064 let value = attribute_to_string(&attr);
1065 // This str slicing works correctly, because the leading and trailing characters
1066 // are in the ASCII range and thus exactly one byte each.
1067 let value = value[2..value.len() - 1].to_string();
1069 rls_data::Attribute { value, span: scx.span_from_span(attr.span) }