3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_hir::def_id::{CrateNum, DefId};
5 use rustc_middle::middle::privacy::AccessLevels;
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 access levels from the privacy check pass.
81 pub(crate) access_levels: AccessLevels<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>>,
135 pub(crate) fn new(access_levels: AccessLevels<DefId>, document_private: bool) -> Self {
136 Cache { access_levels, document_private, ..Cache::default() }
139 /// Populates the `Cache` with more data. The returned `Crate` will be missing some data that was
140 /// in `krate` due to the data being moved into the `Cache`.
141 pub(crate) fn populate(cx: &mut DocContext<'_>, mut krate: clean::Crate) -> clean::Crate {
144 // Crawl the crate to build various caches used for the output
145 debug!(?cx.cache.crate_version);
146 cx.cache.traits = krate.external_traits.take();
148 // Cache where all our extern crates are located
149 // FIXME: this part is specific to HTML so it'd be nice to remove it from the common code
150 for &crate_num in cx.tcx.crates(()) {
151 let e = ExternalCrate { crate_num };
153 let name = e.name(tcx);
154 let render_options = &cx.render_options;
155 let extern_url = render_options.extern_html_root_urls.get(name.as_str()).map(|u| &**u);
156 let extern_url_takes_precedence = render_options.extern_html_root_takes_precedence;
157 let dst = &render_options.output;
158 let location = e.location(extern_url, extern_url_takes_precedence, dst, tcx);
159 cx.cache.extern_locations.insert(e.crate_num, location);
160 cx.cache.external_paths.insert(e.def_id(), (vec![name], ItemType::Module));
163 // FIXME: avoid this clone (requires implementing Default manually)
164 cx.cache.primitive_locations = PrimitiveType::primitive_locations(tcx).clone();
165 for (prim, &def_id) in &cx.cache.primitive_locations {
166 let crate_name = tcx.crate_name(def_id.krate);
167 // Recall that we only allow primitive modules to be at the root-level of the crate.
168 // If that restriction is ever lifted, this will have to include the relative paths instead.
171 .insert(def_id, (vec![crate_name, prim.as_sym()], ItemType::Primitive));
174 let (krate, mut impl_ids) = {
175 let mut cache_builder =
176 CacheBuilder { tcx, cache: &mut cx.cache, impl_ids: FxHashMap::default() };
177 krate = cache_builder.fold_crate(krate);
178 (krate, cache_builder.impl_ids)
181 for (trait_did, dids, impl_) in cx.cache.orphan_trait_impls.drain(..) {
182 if cx.cache.traits.contains_key(&trait_did) {
184 if impl_ids.entry(did).or_default().insert(impl_.def_id()) {
185 cx.cache.impls.entry(did).or_default().push(impl_.clone());
195 impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> {
196 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
197 if item.item_id.is_local() {
198 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.item_id);
201 // If this is a stripped module,
202 // we don't want it or its children in the search index.
203 let orig_stripped_mod = match *item.kind {
204 clean::StrippedItem(box clean::ModuleItem(..)) => {
205 mem::replace(&mut self.cache.stripped_mod, true)
207 _ => self.cache.stripped_mod,
210 // If the impl is from a masked crate or references something from a
211 // masked crate then remove it completely.
212 if let clean::ImplItem(ref i) = *item.kind {
213 if self.cache.masked_crates.contains(&item.item_id.krate())
216 .map_or(false, |t| self.cache.masked_crates.contains(&t.def_id().krate))
219 .map_or(false, |d| self.cache.masked_crates.contains(&d.krate))
225 // Propagate a trait method's documentation to all implementors of the
227 if let clean::TraitItem(ref t) = *item.kind {
228 self.cache.traits.entry(item.item_id.expect_def_id()).or_insert_with(|| (**t).clone());
231 // Collect all the implementors of traits.
232 if let clean::ImplItem(ref i) = *item.kind {
233 if let Some(trait_) = &i.trait_ {
234 if !i.kind.is_blanket() {
237 .entry(trait_.def_id())
239 .push(Impl { impl_item: item.clone() });
244 // Index this method for searching later on.
245 if let Some(ref s) = item.name.or_else(|| {
246 if item.is_stripped() {
248 } else if let clean::ImportItem(ref i) = *item.kind &&
249 let clean::ImportKind::Simple(s) = i.kind {
255 let (parent, is_inherent_impl_item) = match *item.kind {
256 clean::StrippedItem(..) => ((None, None), false),
257 clean::AssocConstItem(..) | clean::AssocTypeItem(..)
262 .map_or(false, |parent| parent.is_trait_impl()) =>
264 // skip associated items in trait impls
265 ((None, None), false)
267 clean::TyMethodItem(..)
268 | clean::TyAssocConstItem(..)
269 | clean::TyAssocTypeItem(..)
270 | clean::StructFieldItem(..)
271 | clean::VariantItem(..) => (
277 .expect("parent_stack is empty")
281 Some(&self.cache.stack[..self.cache.stack.len() - 1]),
285 clean::MethodItem(..) | clean::AssocConstItem(..) | clean::AssocTypeItem(..) => {
286 if self.cache.parent_stack.is_empty() {
287 ((None, None), false)
289 let last = self.cache.parent_stack.last().expect("parent_stack is empty 2");
290 let did = match &*last {
291 ParentStackItem::Impl { for_, .. } => for_.def_id(&self.cache),
292 ParentStackItem::Type(item_id) => item_id.as_def_id(),
294 let path = match did.and_then(|did| self.cache.paths.get(&did)) {
295 // The current stack not necessarily has correlation
296 // for where the type was defined. On the other
297 // hand, `paths` always has the right
298 // information if present.
299 Some(&(ref fqp, _)) => Some(&fqp[..fqp.len() - 1]),
305 _ => ((None, Some(&*self.cache.stack)), false),
309 (parent, Some(path)) if is_inherent_impl_item || !self.cache.stripped_mod => {
310 debug_assert!(!item.is_stripped());
312 // A crate has a module at its root, containing all items,
313 // which should not be indexed. The crate-item itself is
314 // inserted later on when serializing the search-index.
315 if item.item_id.as_def_id().map_or(false, |idx| !idx.is_crate_root()) {
316 let desc = item.doc_value().map_or_else(String::new, |x| {
317 short_markdown_summary(x.as_str(), &item.link_names(self.cache))
319 self.cache.search_index.push(IndexItem {
322 path: join_with_double_colon(path),
326 search_type: get_function_type_for_search(
329 clean_impl_generics(self.cache.parent_stack.last()).as_ref(),
332 aliases: item.attrs.get_doc_aliases(),
336 (Some(parent), None) if is_inherent_impl_item => {
337 // We have a parent, but we don't know where they're
338 // defined yet. Wait for later to index this item.
339 let impl_generics = clean_impl_generics(self.cache.parent_stack.last());
340 self.cache.orphan_impl_items.push(OrphanImplItem {
350 // Keep track of the fully qualified path for this item.
351 let pushed = match item.name {
352 Some(n) if !n.is_empty() => {
353 self.cache.stack.push(n);
360 clean::StructItem(..)
361 | clean::EnumItem(..)
362 | clean::TypedefItem(..)
363 | clean::TraitItem(..)
364 | clean::TraitAliasItem(..)
365 | clean::FunctionItem(..)
366 | clean::ModuleItem(..)
367 | clean::ForeignFunctionItem(..)
368 | clean::ForeignStaticItem(..)
369 | clean::ConstantItem(..)
370 | clean::StaticItem(..)
371 | clean::UnionItem(..)
372 | clean::ForeignTypeItem
373 | clean::MacroItem(..)
374 | clean::ProcMacroItem(..)
375 | clean::VariantItem(..) => {
376 if !self.cache.stripped_mod {
377 // Re-exported items mean that the same id can show up twice
378 // in the rustdoc ast that we're looking at. We know,
379 // however, that a re-exported item doesn't show up in the
380 // `public_items` map, so we can skip inserting into the
381 // paths map if there was already an entry present and we're
382 // not a public item.
383 if !self.cache.paths.contains_key(&item.item_id.expect_def_id())
384 || self.cache.access_levels.is_public(item.item_id.expect_def_id())
386 self.cache.paths.insert(
387 item.item_id.expect_def_id(),
388 (self.cache.stack.clone(), item.type_()),
393 clean::PrimitiveItem(..) => {
396 .insert(item.item_id.expect_def_id(), (self.cache.stack.clone(), item.type_()));
399 clean::ExternCrateItem { .. }
400 | clean::ImportItem(..)
401 | clean::OpaqueTyItem(..)
402 | clean::ImplItem(..)
403 | clean::TyMethodItem(..)
404 | clean::MethodItem(..)
405 | clean::StructFieldItem(..)
406 | clean::TyAssocConstItem(..)
407 | clean::AssocConstItem(..)
408 | clean::TyAssocTypeItem(..)
409 | clean::AssocTypeItem(..)
410 | clean::StrippedItem(..)
411 | clean::KeywordItem => {
412 // FIXME: Do these need handling?
413 // The person writing this comment doesn't know.
414 // So would rather leave them to an expert,
415 // as at least the list is better than `_ => {}`.
419 // Maintain the parent stack.
420 let (item, parent_pushed) = match *item.kind {
422 | clean::EnumItem(..)
423 | clean::ForeignTypeItem
424 | clean::StructItem(..)
425 | clean::UnionItem(..)
426 | clean::VariantItem(..)
427 | clean::ImplItem(..) => {
428 self.cache.parent_stack.push(ParentStackItem::new(&item));
429 (self.fold_item_recur(item), true)
431 _ => (self.fold_item_recur(item), false),
434 // Once we've recursively found all the generics, hoard off all the
435 // implementations elsewhere.
436 let ret = if let clean::Item { kind: box clean::ImplItem(ref i), .. } = item {
437 // Figure out the id of this impl. This may map to a
438 // primitive rather than always to a struct/enum.
439 // Note: matching twice to restrict the lifetime of the `i` borrow.
440 let mut dids = FxHashSet::default();
442 clean::Type::Path { ref path }
443 | clean::BorrowedRef { type_: box clean::Type::Path { ref path }, .. } => {
444 dids.insert(path.def_id());
445 if let Some(generics) = path.generics() &&
446 let ty::Adt(adt, _) = self.tcx.type_of(path.def_id()).kind() &&
447 adt.is_fundamental() {
449 if let Some(did) = ty.def_id(self.cache) {
455 clean::DynTrait(ref bounds, _)
456 | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
457 dids.insert(bounds[0].trait_.def_id());
462 .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
464 if let Some(did) = did {
470 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
471 for bound in generics {
472 if let Some(did) = bound.def_id(self.cache) {
477 let impl_item = Impl { impl_item: item };
478 if impl_item.trait_did().map_or(true, |d| self.cache.traits.contains_key(&d)) {
480 if self.impl_ids.entry(did).or_default().insert(impl_item.def_id()) {
484 .or_insert_with(Vec::new)
485 .push(impl_item.clone());
489 let trait_did = impl_item.trait_did().expect("no trait did");
490 self.cache.orphan_trait_impls.push((trait_did, dids, impl_item));
498 self.cache.stack.pop().expect("stack already empty");
501 self.cache.parent_stack.pop().expect("parent stack already empty");
503 self.cache.stripped_mod = orig_stripped_mod;
508 pub(crate) struct OrphanImplItem {
509 pub(crate) parent: DefId,
510 pub(crate) item: clean::Item,
511 pub(crate) impl_generics: Option<(clean::Type, clean::Generics)>,
514 /// Information about trait and type parents is tracked while traversing the item tree to build
517 /// We don't just store `Item` in there, because `Item` contains the list of children being
518 /// traversed and it would be wasteful to clone all that. We also need the item id, so just
519 /// storing `ItemKind` won't work, either.
520 enum ParentStackItem {
523 trait_: Option<clean::Path>,
524 generics: clean::Generics,
525 kind: clean::ImplKind,
531 impl ParentStackItem {
532 fn new(item: &clean::Item) -> Self {
534 clean::ItemKind::ImplItem(box clean::Impl { for_, trait_, generics, kind, .. }) => {
535 ParentStackItem::Impl {
537 trait_: trait_.clone(),
538 generics: generics.clone(),
540 item_id: item.item_id,
543 _ => ParentStackItem::Type(item.item_id),
546 fn is_trait_impl(&self) -> bool {
547 matches!(self, ParentStackItem::Impl { trait_: Some(..), .. })
549 fn item_id(&self) -> ItemId {
551 ParentStackItem::Impl { item_id, .. } => *item_id,
552 ParentStackItem::Type(item_id) => *item_id,
557 fn clean_impl_generics(item: Option<&ParentStackItem>) -> Option<(clean::Type, clean::Generics)> {
558 if let Some(ParentStackItem::Impl { for_, generics, kind: clean::ImplKind::Normal, .. }) = item
560 Some((for_.clone(), generics.clone()))