3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_hir::def_id::{CrateNum, DefId};
5 use rustc_middle::middle::privacy::EffectiveVisibilities;
6 use rustc_middle::ty::{self, TyCtxt};
7 use rustc_span::Symbol;
9 use crate::clean::{self, types::ExternalLocation, ExternalCrate, ItemId, PrimitiveType};
10 use crate::core::DocContext;
11 use crate::fold::DocFolder;
12 use crate::formats::item_type::ItemType;
13 use crate::formats::Impl;
14 use crate::html::format::join_with_double_colon;
15 use crate::html::markdown::short_markdown_summary;
16 use crate::html::render::search_index::get_function_type_for_search;
17 use crate::html::render::IndexItem;
19 /// This cache is used to store information about the [`clean::Crate`] being
20 /// rendered in order to provide more useful documentation. This contains
21 /// information like all implementors of a trait, all traits a type implements,
22 /// documentation for all known traits, etc.
24 /// This structure purposefully does not implement `Clone` because it's intended
25 /// to be a fairly large and expensive structure to clone. Instead this adheres
26 /// to `Send` so it may be stored in an `Arc` instance and shared among the various
27 /// rendering threads.
29 pub(crate) struct Cache {
30 /// Maps a type ID to all known implementations for that type. This is only
31 /// recognized for intra-crate [`clean::Type::Path`]s, and is used to print
32 /// out extra documentation on the page of an enum/struct.
34 /// The values of the map are a list of implementations and documentation
35 /// found on that implementation.
36 pub(crate) impls: FxHashMap<DefId, Vec<Impl>>,
38 /// Maintains a mapping of local crate `DefId`s to the fully qualified name
39 /// and "short type description" of that node. This is used when generating
40 /// URLs when a type is being linked to. External paths are not located in
41 /// this map because the `External` type itself has all the information
43 pub(crate) paths: FxHashMap<DefId, (Vec<Symbol>, ItemType)>,
45 /// Similar to `paths`, but only holds external paths. This is only used for
46 /// generating explicit hyperlinks to other crates.
47 pub(crate) external_paths: FxHashMap<DefId, (Vec<Symbol>, ItemType)>,
49 /// Maps local `DefId`s of exported types to fully qualified paths.
50 /// Unlike 'paths', this mapping ignores any renames that occur
51 /// due to 'use' statements.
53 /// This map is used when writing out the special 'implementors'
54 /// javascript file. By using the exact path that the type
55 /// is declared with, we ensure that each path will be identical
56 /// to the path used if the corresponding type is inlined. By
57 /// doing this, we can detect duplicate impls on a trait page, and only display
58 /// the impl for the inlined type.
59 pub(crate) exact_paths: FxHashMap<DefId, Vec<Symbol>>,
61 /// This map contains information about all known traits of this crate.
62 /// Implementations of a crate should inherit the documentation of the
63 /// parent trait if no extra documentation is specified, and default methods
64 /// should show up in documentation about trait implementations.
65 pub(crate) traits: FxHashMap<DefId, clean::Trait>,
67 /// When rendering traits, it's often useful to be able to list all
68 /// implementors of the trait, and this mapping is exactly, that: a mapping
69 /// of trait ids to the list of known implementors of the trait
70 pub(crate) implementors: FxHashMap<DefId, Vec<Impl>>,
72 /// Cache of where external crate documentation can be found.
73 pub(crate) extern_locations: FxHashMap<CrateNum, ExternalLocation>,
75 /// Cache of where documentation for primitives can be found.
76 pub(crate) primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
78 // Note that external items for which `doc(hidden)` applies to are shown as
79 // non-reachable while local items aren't. This is because we're reusing
80 // the effective visibilities from the privacy check pass.
81 pub(crate) effective_visibilities: EffectiveVisibilities<DefId>,
83 /// The version of the crate being documented, if given from the `--crate-version` flag.
84 pub(crate) crate_version: Option<String>,
86 /// Whether to document private items.
87 /// This is stored in `Cache` so it doesn't need to be passed through all rustdoc functions.
88 pub(crate) document_private: bool,
90 /// Crates marked with [`#[doc(masked)]`][doc_masked].
92 /// [doc_masked]: https://doc.rust-lang.org/nightly/unstable-book/language-features/doc-masked.html
93 pub(crate) masked_crates: FxHashSet<CrateNum>,
95 // Private fields only used when initially crawling a crate to build a cache
97 parent_stack: Vec<ParentStackItem>,
100 pub(crate) search_index: Vec<IndexItem>,
102 // In rare case where a structure is defined in one module but implemented
103 // in another, if the implementing module is parsed before defining module,
104 // then the fully qualified name of the structure isn't presented in `paths`
105 // yet when its implementation methods are being indexed. Caches such methods
106 // and their parent id here and indexes them at the end of crate parsing.
107 pub(crate) orphan_impl_items: Vec<OrphanImplItem>,
109 // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
110 // even though the trait itself is not exported. This can happen if a trait
111 // was defined in function/expression scope, since the impl will be picked
112 // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
113 // crawl. In order to prevent crashes when looking for notable traits or
114 // when gathering trait documentation on a type, hold impls here while
115 // folding and add them to the cache later on if we find the trait.
116 orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
118 /// All intra-doc links resolved so far.
120 /// Links are indexed by the DefId of the item they document.
121 pub(crate) intra_doc_links: FxHashMap<ItemId, Vec<clean::ItemLink>>,
122 /// Cfg that have been hidden via #![doc(cfg_hide(...))]
123 pub(crate) hidden_cfg: FxHashSet<clean::cfg::Cfg>,
126 /// This struct is used to wrap the `cache` and `tcx` in order to run `DocFolder`.
127 struct CacheBuilder<'a, 'tcx> {
128 cache: &'a mut Cache,
129 /// This field is used to prevent duplicated impl blocks.
130 impl_ids: FxHashMap<DefId, FxHashSet<DefId>>,
136 effective_visibilities: EffectiveVisibilities<DefId>,
137 document_private: bool,
139 Cache { effective_visibilities, document_private, ..Cache::default() }
142 /// Populates the `Cache` with more data. The returned `Crate` will be missing some data that was
143 /// in `krate` due to the data being moved into the `Cache`.
144 pub(crate) fn populate(cx: &mut DocContext<'_>, mut krate: clean::Crate) -> clean::Crate {
147 // Crawl the crate to build various caches used for the output
148 debug!(?cx.cache.crate_version);
149 cx.cache.traits = krate.external_traits.take();
151 // Cache where all our extern crates are located
152 // FIXME: this part is specific to HTML so it'd be nice to remove it from the common code
153 for &crate_num in cx.tcx.crates(()) {
154 let e = ExternalCrate { crate_num };
156 let name = e.name(tcx);
157 let render_options = &cx.render_options;
158 let extern_url = render_options.extern_html_root_urls.get(name.as_str()).map(|u| &**u);
159 let extern_url_takes_precedence = render_options.extern_html_root_takes_precedence;
160 let dst = &render_options.output;
161 let location = e.location(extern_url, extern_url_takes_precedence, dst, tcx);
162 cx.cache.extern_locations.insert(e.crate_num, location);
163 cx.cache.external_paths.insert(e.def_id(), (vec![name], ItemType::Module));
166 // FIXME: avoid this clone (requires implementing Default manually)
167 cx.cache.primitive_locations = PrimitiveType::primitive_locations(tcx).clone();
168 for (prim, &def_id) in &cx.cache.primitive_locations {
169 let crate_name = tcx.crate_name(def_id.krate);
170 // Recall that we only allow primitive modules to be at the root-level of the crate.
171 // If that restriction is ever lifted, this will have to include the relative paths instead.
174 .insert(def_id, (vec![crate_name, prim.as_sym()], ItemType::Primitive));
177 let (krate, mut impl_ids) = {
178 let mut cache_builder =
179 CacheBuilder { tcx, cache: &mut cx.cache, impl_ids: FxHashMap::default() };
180 krate = cache_builder.fold_crate(krate);
181 (krate, cache_builder.impl_ids)
184 for (trait_did, dids, impl_) in cx.cache.orphan_trait_impls.drain(..) {
185 if cx.cache.traits.contains_key(&trait_did) {
187 if impl_ids.entry(did).or_default().insert(impl_.def_id()) {
188 cx.cache.impls.entry(did).or_default().push(impl_.clone());
198 impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> {
199 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
200 if item.item_id.is_local() {
201 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.item_id);
204 // If this is a stripped module,
205 // we don't want it or its children in the search index.
206 let orig_stripped_mod = match *item.kind {
207 clean::StrippedItem(box clean::ModuleItem(..)) => {
208 mem::replace(&mut self.cache.stripped_mod, true)
210 _ => self.cache.stripped_mod,
213 // If the impl is from a masked crate or references something from a
214 // masked crate then remove it completely.
215 if let clean::ImplItem(ref i) = *item.kind {
216 if self.cache.masked_crates.contains(&item.item_id.krate())
219 .map_or(false, |t| self.cache.masked_crates.contains(&t.def_id().krate))
222 .map_or(false, |d| self.cache.masked_crates.contains(&d.krate))
228 // Propagate a trait method's documentation to all implementors of the
230 if let clean::TraitItem(ref t) = *item.kind {
231 self.cache.traits.entry(item.item_id.expect_def_id()).or_insert_with(|| (**t).clone());
234 // Collect all the implementors of traits.
235 if let clean::ImplItem(ref i) = *item.kind {
236 if let Some(trait_) = &i.trait_ {
237 if !i.kind.is_blanket() {
240 .entry(trait_.def_id())
242 .push(Impl { impl_item: item.clone() });
247 // Index this method for searching later on.
248 if let Some(ref s) = item.name.or_else(|| {
249 if item.is_stripped() {
251 } else if let clean::ImportItem(ref i) = *item.kind &&
252 let clean::ImportKind::Simple(s) = i.kind {
258 let (parent, is_inherent_impl_item) = match *item.kind {
259 clean::StrippedItem(..) => ((None, None), false),
260 clean::AssocConstItem(..) | clean::AssocTypeItem(..)
265 .map_or(false, |parent| parent.is_trait_impl()) =>
267 // skip associated items in trait impls
268 ((None, None), false)
270 clean::TyMethodItem(..)
271 | clean::TyAssocConstItem(..)
272 | clean::TyAssocTypeItem(..)
273 | clean::StructFieldItem(..)
274 | clean::VariantItem(..) => (
280 .expect("parent_stack is empty")
284 Some(&self.cache.stack[..self.cache.stack.len() - 1]),
288 clean::MethodItem(..) | clean::AssocConstItem(..) | clean::AssocTypeItem(..) => {
289 if self.cache.parent_stack.is_empty() {
290 ((None, None), false)
292 let last = self.cache.parent_stack.last().expect("parent_stack is empty 2");
293 let did = match &*last {
294 ParentStackItem::Impl { for_, .. } => for_.def_id(&self.cache),
295 ParentStackItem::Type(item_id) => item_id.as_def_id(),
297 let path = match did.and_then(|did| self.cache.paths.get(&did)) {
298 // The current stack not necessarily has correlation
299 // for where the type was defined. On the other
300 // hand, `paths` always has the right
301 // information if present.
302 Some(&(ref fqp, _)) => Some(&fqp[..fqp.len() - 1]),
308 _ => ((None, Some(&*self.cache.stack)), false),
312 (parent, Some(path)) if is_inherent_impl_item || !self.cache.stripped_mod => {
313 debug_assert!(!item.is_stripped());
315 // A crate has a module at its root, containing all items,
316 // which should not be indexed. The crate-item itself is
317 // inserted later on when serializing the search-index.
318 if item.item_id.as_def_id().map_or(false, |idx| !idx.is_crate_root()) {
319 let desc = item.doc_value().map_or_else(String::new, |x| {
320 short_markdown_summary(x.as_str(), &item.link_names(self.cache))
322 self.cache.search_index.push(IndexItem {
325 path: join_with_double_colon(path),
329 search_type: get_function_type_for_search(
332 clean_impl_generics(self.cache.parent_stack.last()).as_ref(),
335 aliases: item.attrs.get_doc_aliases(),
339 (Some(parent), None) if is_inherent_impl_item => {
340 // We have a parent, but we don't know where they're
341 // defined yet. Wait for later to index this item.
342 let impl_generics = clean_impl_generics(self.cache.parent_stack.last());
343 self.cache.orphan_impl_items.push(OrphanImplItem {
353 // Keep track of the fully qualified path for this item.
354 let pushed = match item.name {
355 Some(n) if !n.is_empty() => {
356 self.cache.stack.push(n);
363 clean::StructItem(..)
364 | clean::EnumItem(..)
365 | clean::TypedefItem(..)
366 | clean::TraitItem(..)
367 | clean::TraitAliasItem(..)
368 | clean::FunctionItem(..)
369 | clean::ModuleItem(..)
370 | clean::ForeignFunctionItem(..)
371 | clean::ForeignStaticItem(..)
372 | clean::ConstantItem(..)
373 | clean::StaticItem(..)
374 | clean::UnionItem(..)
375 | clean::ForeignTypeItem
376 | clean::MacroItem(..)
377 | clean::ProcMacroItem(..)
378 | clean::VariantItem(..) => {
379 if !self.cache.stripped_mod {
380 // Re-exported items mean that the same id can show up twice
381 // in the rustdoc ast that we're looking at. We know,
382 // however, that a re-exported item doesn't show up in the
383 // `public_items` map, so we can skip inserting into the
384 // paths map if there was already an entry present and we're
385 // not a public item.
386 if !self.cache.paths.contains_key(&item.item_id.expect_def_id())
389 .effective_visibilities
390 .is_directly_public(item.item_id.expect_def_id())
392 self.cache.paths.insert(
393 item.item_id.expect_def_id(),
394 (self.cache.stack.clone(), item.type_()),
399 clean::PrimitiveItem(..) => {
402 .insert(item.item_id.expect_def_id(), (self.cache.stack.clone(), item.type_()));
405 clean::ExternCrateItem { .. }
406 | clean::ImportItem(..)
407 | clean::OpaqueTyItem(..)
408 | clean::ImplItem(..)
409 | clean::TyMethodItem(..)
410 | clean::MethodItem(..)
411 | clean::StructFieldItem(..)
412 | clean::TyAssocConstItem(..)
413 | clean::AssocConstItem(..)
414 | clean::TyAssocTypeItem(..)
415 | clean::AssocTypeItem(..)
416 | clean::StrippedItem(..)
417 | clean::KeywordItem => {
418 // FIXME: Do these need handling?
419 // The person writing this comment doesn't know.
420 // So would rather leave them to an expert,
421 // as at least the list is better than `_ => {}`.
425 // Maintain the parent stack.
426 let (item, parent_pushed) = match *item.kind {
428 | clean::EnumItem(..)
429 | clean::ForeignTypeItem
430 | clean::StructItem(..)
431 | clean::UnionItem(..)
432 | clean::VariantItem(..)
433 | clean::ImplItem(..) => {
434 self.cache.parent_stack.push(ParentStackItem::new(&item));
435 (self.fold_item_recur(item), true)
437 _ => (self.fold_item_recur(item), false),
440 // Once we've recursively found all the generics, hoard off all the
441 // implementations elsewhere.
442 let ret = if let clean::Item { kind: box clean::ImplItem(ref i), .. } = item {
443 // Figure out the id of this impl. This may map to a
444 // primitive rather than always to a struct/enum.
445 // Note: matching twice to restrict the lifetime of the `i` borrow.
446 let mut dids = FxHashSet::default();
448 clean::Type::Path { ref path }
449 | clean::BorrowedRef { type_: box clean::Type::Path { ref path }, .. } => {
450 dids.insert(path.def_id());
451 if let Some(generics) = path.generics() &&
452 let ty::Adt(adt, _) = self.tcx.type_of(path.def_id()).kind() &&
453 adt.is_fundamental() {
455 if let Some(did) = ty.def_id(self.cache) {
461 clean::DynTrait(ref bounds, _)
462 | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
463 dids.insert(bounds[0].trait_.def_id());
468 .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
470 if let Some(did) = did {
476 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
477 for bound in generics {
478 if let Some(did) = bound.def_id(self.cache) {
483 let impl_item = Impl { impl_item: item };
484 if impl_item.trait_did().map_or(true, |d| self.cache.traits.contains_key(&d)) {
486 if self.impl_ids.entry(did).or_default().insert(impl_item.def_id()) {
490 .or_insert_with(Vec::new)
491 .push(impl_item.clone());
495 let trait_did = impl_item.trait_did().expect("no trait did");
496 self.cache.orphan_trait_impls.push((trait_did, dids, impl_item));
504 self.cache.stack.pop().expect("stack already empty");
507 self.cache.parent_stack.pop().expect("parent stack already empty");
509 self.cache.stripped_mod = orig_stripped_mod;
514 pub(crate) struct OrphanImplItem {
515 pub(crate) parent: DefId,
516 pub(crate) item: clean::Item,
517 pub(crate) impl_generics: Option<(clean::Type, clean::Generics)>,
520 /// Information about trait and type parents is tracked while traversing the item tree to build
523 /// We don't just store `Item` in there, because `Item` contains the list of children being
524 /// traversed and it would be wasteful to clone all that. We also need the item id, so just
525 /// storing `ItemKind` won't work, either.
526 enum ParentStackItem {
529 trait_: Option<clean::Path>,
530 generics: clean::Generics,
531 kind: clean::ImplKind,
537 impl ParentStackItem {
538 fn new(item: &clean::Item) -> Self {
540 clean::ItemKind::ImplItem(box clean::Impl { for_, trait_, generics, kind, .. }) => {
541 ParentStackItem::Impl {
543 trait_: trait_.clone(),
544 generics: generics.clone(),
546 item_id: item.item_id,
549 _ => ParentStackItem::Type(item.item_id),
552 fn is_trait_impl(&self) -> bool {
553 matches!(self, ParentStackItem::Impl { trait_: Some(..), .. })
555 fn item_id(&self) -> ItemId {
557 ParentStackItem::Impl { item_id, .. } => *item_id,
558 ParentStackItem::Type(item_id) => *item_id,
563 fn clean_impl_generics(item: Option<&ParentStackItem>) -> Option<(clean::Type, clean::Generics)> {
564 if let Some(ParentStackItem::Impl { for_, generics, kind: clean::ImplKind::Normal, .. }) = item
566 Some((for_.clone(), generics.clone()))