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::{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::{enum_def_to_string, fn_to_string, 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, arg_names, 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(),
150 // functions in extern block are implicitly unsafe
151 unsafety: hir::Unsafety::Unsafe,
152 // functions in extern block cannot be const
153 constness: hir::Constness::NotConst,
154 abi: self.tcx.hir().get_foreign_abi(item.hir_id),
155 // functions in extern block cannot be async
156 asyncness: hir::IsAsync::NotAsync,
158 Some(item.ident.name),
167 docs: self.docs_for_attrs(&item.attrs),
168 sig: sig::foreign_item_signature(item, self),
169 attributes: lower_attributes(item.attrs.to_vec(), self),
172 hir::ForeignItemKind::Static(ref ty, _) => {
173 filter!(self.span_utils, item.ident.span);
175 let id = id_from_def_id(def_id);
176 let span = self.span_from_span(item.ident.span);
178 Some(Data::DefData(Def {
179 kind: DefKind::ForeignStatic,
182 name: item.ident.to_string(),
184 value: ty_to_string(ty),
188 docs: self.docs_for_attrs(&item.attrs),
189 sig: sig::foreign_item_signature(item, self),
190 attributes: lower_attributes(item.attrs.to_vec(), self),
193 // FIXME(plietar): needs a new DefKind in rls-data
194 hir::ForeignItemKind::Type => None,
198 pub fn get_item_data(&self, item: &hir::Item<'_>) -> Option<Data> {
199 let def_id = self.tcx.hir().local_def_id(item.hir_id).to_def_id();
201 hir::ItemKind::Fn(ref sig, ref generics, _) => {
202 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
203 filter!(self.span_utils, item.ident.span);
204 Some(Data::DefData(Def {
205 kind: DefKind::Function,
206 id: id_from_def_id(def_id),
207 span: self.span_from_span(item.ident.span),
208 name: item.ident.to_string(),
213 Some(item.ident.name),
222 docs: self.docs_for_attrs(&item.attrs),
223 sig: sig::item_signature(item, self),
224 attributes: lower_attributes(item.attrs.to_vec(), self),
227 hir::ItemKind::Static(ref typ, ..) => {
228 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
230 filter!(self.span_utils, item.ident.span);
232 let id = id_from_def_id(def_id);
233 let span = self.span_from_span(item.ident.span);
235 Some(Data::DefData(Def {
236 kind: DefKind::Static,
239 name: item.ident.to_string(),
241 value: ty_to_string(&typ),
245 docs: self.docs_for_attrs(&item.attrs),
246 sig: sig::item_signature(item, self),
247 attributes: lower_attributes(item.attrs.to_vec(), self),
250 hir::ItemKind::Const(ref typ, _) => {
251 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
252 filter!(self.span_utils, item.ident.span);
254 let id = id_from_def_id(def_id);
255 let span = self.span_from_span(item.ident.span);
257 Some(Data::DefData(Def {
258 kind: DefKind::Const,
261 name: item.ident.to_string(),
263 value: ty_to_string(typ),
267 docs: self.docs_for_attrs(&item.attrs),
268 sig: sig::item_signature(item, self),
269 attributes: lower_attributes(item.attrs.to_vec(), self),
272 hir::ItemKind::Mod(ref m) => {
273 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
275 let sm = self.tcx.sess.source_map();
276 let filename = sm.span_to_filename(m.inner);
278 filter!(self.span_utils, item.ident.span);
280 Some(Data::DefData(Def {
282 id: id_from_def_id(def_id),
283 name: item.ident.to_string(),
285 span: self.span_from_span(item.ident.span),
286 value: filename.to_string(),
288 children: m.item_ids.iter().map(|i| id_from_hir_id(i.id, self)).collect(),
290 docs: self.docs_for_attrs(&item.attrs),
291 sig: sig::item_signature(item, self),
292 attributes: lower_attributes(item.attrs.to_vec(), self),
295 hir::ItemKind::Enum(ref def, ref generics) => {
296 let name = item.ident.to_string();
297 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
298 filter!(self.span_utils, item.ident.span);
300 enum_def_to_string(def, generics, item.ident.name, item.span, &item.vis);
301 Some(Data::DefData(Def {
303 id: id_from_def_id(def_id),
304 span: self.span_from_span(item.ident.span),
309 children: def.variants.iter().map(|v| id_from_hir_id(v.id, self)).collect(),
311 docs: self.docs_for_attrs(&item.attrs),
312 sig: sig::item_signature(item, self),
313 attributes: lower_attributes(item.attrs.to_vec(), self),
316 hir::ItemKind::Impl { ref of_trait, ref self_ty, ref items, .. } => {
317 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = self_ty.kind {
318 // Common case impl for a struct or something basic.
319 if generated_code(path.span) {
322 let sub_span = path.segments.last().unwrap().ident.span;
323 filter!(self.span_utils, sub_span);
325 let impl_id = self.next_impl_id();
326 let span = self.span_from_span(sub_span);
328 let type_data = self.lookup_def_id(self_ty.hir_id);
329 type_data.map(|type_data| {
332 kind: RelationKind::Impl { id: impl_id },
334 from: id_from_def_id(type_data),
337 .and_then(|t| self.lookup_def_id(t.hir_ref_id))
339 .unwrap_or_else(null_id),
343 kind: match *of_trait {
344 Some(_) => ImplKind::Direct,
345 None => ImplKind::Inherent,
348 value: String::new(),
352 .map(|i| id_from_hir_id(i.id.hir_id, self))
371 pub fn get_field_data(&self, field: &hir::StructField<'_>, scope: hir::HirId) -> Option<Def> {
372 let name = field.ident.to_string();
373 let scope_def_id = self.tcx.hir().local_def_id(scope).to_def_id();
374 let qualname = format!("::{}::{}", self.tcx.def_path_str(scope_def_id), field.ident);
375 filter!(self.span_utils, field.ident.span);
376 let field_def_id = self.tcx.hir().local_def_id(field.hir_id).to_def_id();
377 let typ = self.tcx.type_of(field_def_id).to_string();
379 let id = id_from_def_id(field_def_id);
380 let span = self.span_from_span(field.ident.span);
383 kind: DefKind::Field,
389 parent: Some(id_from_def_id(scope_def_id)),
392 docs: self.docs_for_attrs(&field.attrs),
393 sig: sig::field_signature(field, self),
394 attributes: lower_attributes(field.attrs.to_vec(), self),
398 // FIXME would be nice to take a MethodItem here, but the ast provides both
399 // trait and impl flavours, so the caller must do the disassembly.
400 pub fn get_method_data(&self, hir_id: hir::HirId, ident: Ident, span: Span) -> Option<Def> {
401 // The qualname for a method is the trait name or name of the struct in an impl in
402 // which the method is declared in, followed by the method's name.
403 let def_id = self.tcx.hir().local_def_id(hir_id).to_def_id();
404 let (qualname, parent_scope, decl_id, docs, attributes) =
405 match self.tcx.impl_of_method(def_id) {
406 Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) {
407 Some(Node::Item(item)) => match item.kind {
408 hir::ItemKind::Impl { ref self_ty, .. } => {
409 let hir = self.tcx.hir();
411 let mut qualname = String::from("<");
413 .push_str(&rustc_hir_pretty::id_to_string(&hir, self_ty.hir_id));
415 let trait_id = self.tcx.trait_id_of_impl(impl_id);
416 let mut docs = String::new();
417 let mut attrs = vec![];
418 if let Some(Node::ImplItem(item)) = hir.find(hir_id) {
419 docs = self.docs_for_attrs(&item.attrs);
420 attrs = item.attrs.to_vec();
423 let mut decl_id = None;
424 if let Some(def_id) = trait_id {
425 // A method in a trait impl.
426 qualname.push_str(" as ");
427 qualname.push_str(&self.tcx.def_path_str(def_id));
431 .associated_items(def_id)
432 .filter_by_name_unhygienic(ident.name)
434 .map(|item| item.def_id);
436 qualname.push_str(">");
438 (qualname, trait_id, decl_id, docs, attrs)
443 "Container {:?} for method {} not an impl?",
452 "Container {:?} for method {} is not a node item {:?}",
459 None => match self.tcx.trait_of_item(def_id) {
461 let mut docs = String::new();
462 let mut attrs = vec![];
464 if let Some(Node::TraitItem(item)) = self.tcx.hir().find(hir_id) {
465 docs = self.docs_for_attrs(&item.attrs);
466 attrs = item.attrs.to_vec();
470 format!("::{}", self.tcx.def_path_str(def_id)),
478 debug!("could not find container for method {} at {:?}", hir_id, span);
479 // This is not necessarily a bug, if there was a compilation error,
480 // the tables we need might not exist.
486 let qualname = format!("{}::{}", qualname, ident.name);
488 filter!(self.span_utils, ident.span);
491 kind: DefKind::Method,
492 id: id_from_def_id(def_id),
493 span: self.span_from_span(ident.span),
494 name: ident.name.to_string(),
496 // FIXME you get better data here by using the visitor.
497 value: String::new(),
498 parent: parent_scope.map(id_from_def_id),
500 decl_id: decl_id.map(id_from_def_id),
503 attributes: lower_attributes(attributes, self),
507 pub fn get_trait_ref_data(&self, trait_ref: &hir::TraitRef<'_>) -> Option<Ref> {
508 self.lookup_def_id(trait_ref.hir_ref_id).and_then(|def_id| {
509 let span = trait_ref.path.span;
510 if generated_code(span) {
513 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
514 filter!(self.span_utils, sub_span);
515 let span = self.span_from_span(sub_span);
516 Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(def_id) })
520 pub fn get_expr_data(&self, expr: &hir::Expr<'_>) -> Option<Data> {
521 let hir_node = self.tcx.hir().expect_expr(expr.hir_id);
522 let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
523 if ty.is_none() || ty.unwrap().kind == ty::Error {
527 hir::ExprKind::Field(ref sub_ex, ident) => {
528 let hir_node = match self.tcx.hir().find(sub_ex.hir_id) {
529 Some(Node::Expr(expr)) => expr,
532 "Missing or weird node for sub-expression {} in {:?}",
538 match self.tables.expr_ty_adjusted(&hir_node).kind {
539 ty::Adt(def, _) if !def.is_enum() => {
540 let variant = &def.non_enum_variant();
541 filter!(self.span_utils, ident.span);
542 let span = self.span_from_span(ident.span);
543 Some(Data::RefData(Ref {
544 kind: RefKind::Variable,
548 .find_field_index(ident, variant)
549 .map(|index| id_from_def_id(variant.fields[index].did))
550 .unwrap_or_else(null_id),
553 ty::Tuple(..) => None,
555 debug!("expected struct or union type, found {:?}", ty);
560 hir::ExprKind::Struct(qpath, ..) => {
561 let segment = match qpath {
562 hir::QPath::Resolved(_, path) => path.segments.last().unwrap(),
563 hir::QPath::TypeRelative(_, segment) => segment,
565 match self.tables.expr_ty_adjusted(&hir_node).kind {
566 ty::Adt(def, _) if !def.is_enum() => {
567 let sub_span = segment.ident.span;
568 filter!(self.span_utils, sub_span);
569 let span = self.span_from_span(sub_span);
570 Some(Data::RefData(Ref {
573 ref_id: id_from_def_id(def.did),
577 // FIXME ty could legitimately be an enum, but then we will fail
578 // later if we try to look up the fields.
579 debug!("expected struct or union, found {:?}", ty);
584 hir::ExprKind::MethodCall(ref seg, ..) => {
585 let method_id = match self.tables.type_dependent_def_id(expr.hir_id) {
588 debug!("could not resolve method id for {:?}", expr);
592 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
593 ty::ImplContainer(_) => (Some(method_id), None),
594 ty::TraitContainer(_) => (None, Some(method_id)),
596 let sub_span = seg.ident.span;
597 filter!(self.span_utils, sub_span);
598 let span = self.span_from_span(sub_span);
599 Some(Data::RefData(Ref {
600 kind: RefKind::Function,
602 ref_id: def_id.or(decl_id).map(id_from_def_id).unwrap_or_else(null_id),
605 hir::ExprKind::Path(ref path) => {
606 self.get_path_data(expr.hir_id, path).map(Data::RefData)
610 bug!("invalid expression: {:?}", expr);
615 pub fn get_path_res(&self, hir_id: hir::HirId) -> Res {
616 match self.tcx.hir().get(hir_id) {
617 Node::TraitRef(tr) => tr.path.res,
619 Node::Item(&hir::Item { kind: hir::ItemKind::Use(path, _), .. }) => path.res,
620 Node::Visibility(&Spanned {
621 node: hir::VisibilityKind::Restricted { ref path, .. },
625 Node::PathSegment(seg) => match seg.res {
626 Some(res) if res != Res::Err => res,
628 let parent_node = self.tcx.hir().get_parent_node(hir_id);
629 self.get_path_res(parent_node)
633 Node::Expr(&hir::Expr { kind: hir::ExprKind::Struct(ref qpath, ..), .. }) => {
634 self.tables.qpath_res(qpath, hir_id)
637 Node::Expr(&hir::Expr { kind: hir::ExprKind::Path(ref qpath), .. })
638 | Node::Pat(&hir::Pat {
640 hir::PatKind::Path(ref qpath)
641 | hir::PatKind::Struct(ref qpath, ..)
642 | hir::PatKind::TupleStruct(ref qpath, ..),
645 | Node::Ty(&hir::Ty { kind: hir::TyKind::Path(ref qpath), .. }) => {
646 self.tables.qpath_res(qpath, hir_id)
649 Node::Binding(&hir::Pat {
650 kind: hir::PatKind::Binding(_, canonical_id, ..), ..
651 }) => Res::Local(canonical_id),
657 pub fn get_path_data(&self, id: hir::HirId, path: &hir::QPath<'_>) -> Option<Ref> {
658 let segment = match path {
659 hir::QPath::Resolved(_, path) => path.segments.last(),
660 hir::QPath::TypeRelative(_, segment) => Some(*segment),
662 segment.and_then(|seg| {
663 self.get_path_segment_data(seg).or_else(|| self.get_path_segment_data_with_id(seg, id))
667 pub fn get_path_segment_data(&self, path_seg: &hir::PathSegment<'_>) -> Option<Ref> {
668 self.get_path_segment_data_with_id(path_seg, path_seg.hir_id?)
671 pub fn get_path_segment_data_with_id(
673 path_seg: &hir::PathSegment<'_>,
676 // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
677 fn fn_type(seg: &hir::PathSegment<'_>) -> bool {
678 seg.args.map(|args| args.parenthesized).unwrap_or(false)
681 let res = self.get_path_res(id);
682 let span = path_seg.ident.span;
683 filter!(self.span_utils, span);
684 let span = self.span_from_span(span);
688 Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_hir_id(id, self) })
690 Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
691 Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(def_id) })
695 | HirDefKind::Variant
698 | HirDefKind::TyAlias
699 | HirDefKind::ForeignTy
700 | HirDefKind::TraitAlias
701 | HirDefKind::AssocTy
703 | HirDefKind::OpaqueTy
704 | HirDefKind::TyParam,
706 ) => Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(def_id) }),
707 Res::Def(HirDefKind::ConstParam, def_id) => {
708 Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_def_id(def_id) })
710 Res::Def(HirDefKind::Ctor(_, ..), def_id) => {
711 // This is a reference to a tuple struct or an enum variant where the def_id points
712 // to an invisible constructor function. That is not a very useful
713 // def, so adjust to point to the tuple struct or enum variant itself.
714 let parent_def_id = self.tcx.parent(def_id).unwrap();
715 Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(parent_def_id) })
717 Res::Def(HirDefKind::Static | HirDefKind::Const | HirDefKind::AssocConst, _) => {
718 Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_def_id(res.def_id()) })
720 Res::Def(HirDefKind::AssocFn, decl_id) => {
721 let def_id = if decl_id.is_local() {
722 let ti = self.tcx.associated_item(decl_id);
725 .associated_items(ti.container.id())
726 .filter_by_name_unhygienic(ti.ident.name)
727 .find(|item| item.defaultness.has_value())
728 .map(|item| item.def_id)
733 kind: RefKind::Function,
735 ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
738 Res::Def(HirDefKind::Fn, def_id) => {
739 Some(Ref { kind: RefKind::Function, span, ref_id: id_from_def_id(def_id) })
741 Res::Def(HirDefKind::Mod, def_id) => {
742 Some(Ref { kind: RefKind::Mod, span, ref_id: id_from_def_id(def_id) })
746 HirDefKind::Macro(..)
747 | HirDefKind::ExternCrate
748 | HirDefKind::ForeignMod
749 | HirDefKind::LifetimeParam
750 | HirDefKind::AnonConst
753 | HirDefKind::GlobalAsm
755 | HirDefKind::Closure
756 | HirDefKind::Generator,
762 | Res::NonMacroAttr(..)
768 pub fn get_field_ref_data(
770 field_ref: &hir::Field<'_>,
771 variant: &ty::VariantDef,
773 filter!(self.span_utils, field_ref.ident.span);
774 self.tcx.find_field_index(field_ref.ident, variant).map(|index| {
775 let span = self.span_from_span(field_ref.ident.span);
776 Ref { kind: RefKind::Variable, span, ref_id: id_from_def_id(variant.fields[index].did) }
780 /// Attempt to return MacroRef for any AST node.
782 /// For a given piece of AST defined by the supplied Span and NodeId,
783 /// returns `None` if the node is not macro-generated or the span is malformed,
784 /// else uses the expansion callsite and callee to return some MacroRef.
785 pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
786 if !generated_code(span) {
789 // Note we take care to use the source callsite/callee, to handle
790 // nested expansions and ensure we only generate data for source-visible
792 let callsite = span.source_callsite();
793 let callsite_span = self.span_from_span(callsite);
794 let callee = span.source_callee()?;
796 let mac_name = match callee.kind {
797 ExpnKind::Macro(mac_kind, name) => match mac_kind {
798 MacroKind::Bang => name,
800 // Ignore attribute macros, their spans are usually mangled
801 // FIXME(eddyb) is this really the case anymore?
802 MacroKind::Attr | MacroKind::Derive => return None,
805 // These are not macros.
806 // FIXME(eddyb) maybe there is a way to handle them usefully?
807 ExpnKind::Root | ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => return None,
810 let callee_span = self.span_from_span(callee.def_site);
813 qualname: mac_name.to_string(), // FIXME: generate the real qualname
818 fn lookup_def_id(&self, ref_id: hir::HirId) -> Option<DefId> {
819 match self.get_path_res(ref_id) {
820 Res::PrimTy(_) | Res::SelfTy(..) | Res::Err => None,
821 def => def.opt_def_id(),
825 fn docs_for_attrs(&self, attrs: &[ast::Attribute]) -> String {
826 let mut result = String::new();
829 if let Some(val) = attr.doc_str() {
830 if attr.is_doc_comment() {
831 result.push_str(&strip_doc_comment_decoration(&val.as_str()));
833 result.push_str(&val.as_str());
836 } else if attr.check_name(sym::doc) {
837 if let Some(meta_list) = attr.meta_item_list() {
840 .filter(|it| it.check_name(sym::include))
841 .filter_map(|it| it.meta_item_list().map(|l| l.to_owned()))
843 .filter(|meta| meta.check_name(sym::contents))
844 .filter_map(|meta| meta.value_str())
846 result.push_str(&val.as_str());
853 if !self.config.full_docs {
854 if let Some(index) = result.find("\n\n") {
855 result.truncate(index);
862 fn next_impl_id(&self) -> u32 {
863 let next = self.impl_counter.get();
864 self.impl_counter.set(next + 1);
869 // An AST visitor for collecting paths (e.g., the names of structs) and formal
870 // variables (idents) from patterns.
871 struct PathCollector<'l> {
873 collected_paths: Vec<(hir::HirId, &'l hir::QPath<'l>)>,
874 collected_idents: Vec<(hir::HirId, Ident, hir::Mutability)>,
877 impl<'l> PathCollector<'l> {
878 fn new(tcx: TyCtxt<'l>) -> PathCollector<'l> {
879 PathCollector { tcx, collected_paths: vec![], collected_idents: vec![] }
883 impl<'l> Visitor<'l> for PathCollector<'l> {
886 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
887 intravisit::NestedVisitorMap::All(self.tcx.hir())
890 fn visit_pat(&mut self, p: &'l hir::Pat<'l>) {
892 hir::PatKind::Struct(ref path, ..) => {
893 self.collected_paths.push((p.hir_id, path));
895 hir::PatKind::TupleStruct(ref path, ..) | hir::PatKind::Path(ref path) => {
896 self.collected_paths.push((p.hir_id, path));
898 hir::PatKind::Binding(bm, _, ident, _) => {
900 "PathCollector, visit ident in pat {}: {:?} {:?}",
901 ident, p.span, ident.span
903 let immut = match bm {
904 // Even if the ref is mut, you can't change the ref, only
905 // the data pointed at, so showing the initialising expression
906 // is still worthwhile.
907 hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Ref => {
910 hir::BindingAnnotation::Mutable | hir::BindingAnnotation::RefMut => {
914 self.collected_idents.push((p.hir_id, ident, immut));
918 intravisit::walk_pat(self, p);
922 /// Defines what to do with the results of saving the analysis.
923 pub trait SaveHandler {
924 fn save(&mut self, save_ctxt: &SaveContext<'_, '_>, analysis: &Analysis);
927 /// Dump the save-analysis results to a file.
928 pub struct DumpHandler<'a> {
929 odir: Option<&'a Path>,
933 impl<'a> DumpHandler<'a> {
934 pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
935 DumpHandler { odir, cratename: cratename.to_owned() }
938 fn output_file(&self, ctx: &SaveContext<'_, '_>) -> (BufWriter<File>, PathBuf) {
939 let sess = &ctx.tcx.sess;
940 let file_name = match ctx.config.output_file {
941 Some(ref s) => PathBuf::from(s),
943 let mut root_path = match self.odir {
944 Some(val) => val.join("save-analysis"),
945 None => PathBuf::from("save-analysis-temp"),
948 if let Err(e) = std::fs::create_dir_all(&root_path) {
949 error!("Could not create directory {}: {}", root_path.display(), e);
952 let executable = sess.crate_types().iter().any(|ct| *ct == CrateType::Executable);
953 let mut out_name = if executable { String::new() } else { "lib".to_owned() };
954 out_name.push_str(&self.cratename);
955 out_name.push_str(&sess.opts.cg.extra_filename);
956 out_name.push_str(".json");
957 root_path.push(&out_name);
963 info!("Writing output to {}", file_name.display());
965 let output_file = BufWriter::new(File::create(&file_name).unwrap_or_else(|e| {
966 sess.fatal(&format!("Could not open {}: {}", file_name.display(), e))
969 (output_file, file_name)
973 impl SaveHandler for DumpHandler<'_> {
974 fn save(&mut self, save_ctxt: &SaveContext<'_, '_>, analysis: &Analysis) {
975 let sess = &save_ctxt.tcx.sess;
976 let (output, file_name) = self.output_file(&save_ctxt);
977 if let Err(e) = serde_json::to_writer(output, &analysis) {
978 error!("Can't serialize save-analysis: {:?}", e);
981 if sess.opts.json_artifact_notifications {
982 sess.parse_sess.span_diagnostic.emit_artifact_notification(&file_name, "save-analysis");
987 /// Call a callback with the results of save-analysis.
988 pub struct CallbackHandler<'b> {
989 pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
992 impl SaveHandler for CallbackHandler<'_> {
993 fn save(&mut self, _: &SaveContext<'_, '_>, analysis: &Analysis) {
994 (self.callback)(analysis)
998 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
1002 config: Option<Config>,
1005 tcx.dep_graph.with_ignore(|| {
1006 info!("Dumping crate {}", cratename);
1008 // Privacy checking requires and is done after type checking; use a
1009 // fallback in case the access levels couldn't have been correctly computed.
1010 let access_levels = match tcx.sess.compile_status() {
1011 Ok(..) => tcx.privacy_access_levels(LOCAL_CRATE),
1012 Err(..) => tcx.arena.alloc(AccessLevels::default()),
1015 let save_ctxt = SaveContext {
1017 tables: &ty::TypeckTables::empty(None),
1018 empty_tables: &ty::TypeckTables::empty(None),
1019 access_levels: &access_levels,
1020 span_utils: SpanUtils::new(&tcx.sess),
1021 config: find_config(config),
1022 impl_counter: Cell::new(0),
1025 let mut visitor = DumpVisitor::new(save_ctxt);
1027 visitor.dump_crate_info(cratename, tcx.hir().krate());
1028 visitor.dump_compilation_options(input, cratename);
1029 visitor.process_crate(tcx.hir().krate());
1031 handler.save(&visitor.save_ctxt, &visitor.analysis())
1035 fn find_config(supplied: Option<Config>) -> Config {
1036 if let Some(config) = supplied {
1040 match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
1041 None => Config::default(),
1042 Some(config) => config
1045 .map_err(|_| error!("`RUST_SAVE_ANALYSIS_CONFIG` isn't UTF-8"))
1047 serde_json::from_str(cfg)
1048 .map_err(|_| error!("Could not deserialize save-analysis config"))
1050 .unwrap_or_default(),
1054 // Utility functions for the module.
1056 // Helper function to escape quotes in a string
1057 fn escape(s: String) -> String {
1058 s.replace("\"", "\"\"")
1061 // Helper function to determine if a span came from a
1062 // macro expansion or syntax extension.
1063 fn generated_code(span: Span) -> bool {
1064 span.from_expansion() || span.is_dummy()
1067 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
1068 // we use our own Id which is the same, but without the newtype.
1069 fn id_from_def_id(id: DefId) -> rls_data::Id {
1070 rls_data::Id { krate: id.krate.as_u32(), index: id.index.as_u32() }
1073 fn id_from_hir_id(id: hir::HirId, scx: &SaveContext<'_, '_>) -> rls_data::Id {
1074 let def_id = scx.tcx.hir().opt_local_def_id(id);
1075 def_id.map(|id| id_from_def_id(id.to_def_id())).unwrap_or_else(|| {
1076 // Create a *fake* `DefId` out of a `HirId` by combining the owner
1077 // `local_def_index` and the `local_id`.
1078 // This will work unless you have *billions* of definitions in a single
1079 // crate (very unlikely to actually happen).
1081 krate: LOCAL_CRATE.as_u32(),
1082 index: id.owner.local_def_index.as_u32() | id.local_id.as_u32().reverse_bits(),
1087 fn null_id() -> rls_data::Id {
1088 rls_data::Id { krate: u32::MAX, index: u32::MAX }
1091 fn lower_attributes(
1092 attrs: Vec<ast::Attribute>,
1093 scx: &SaveContext<'_, '_>,
1094 ) -> Vec<rls_data::Attribute> {
1097 // Only retain real attributes. Doc comments are lowered separately.
1098 .filter(|attr| !attr.has_name(sym::doc))
1100 // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
1101 // attribute. First normalize all inner attribute (#![..]) to outer
1102 // ones (#[..]), then remove the two leading and the one trailing character.
1103 attr.style = ast::AttrStyle::Outer;
1104 let value = attribute_to_string(&attr);
1105 // This str slicing works correctly, because the leading and trailing characters
1106 // are in the ASCII range and thus exactly one byte each.
1107 let value = value[2..value.len() - 1].to_string();
1109 rls_data::Attribute { value, span: scx.span_from_span(attr.span) }