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::{sym, 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::TraitWithExtraInfo>,
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(|| {
229 clean::TraitWithExtraInfo {
231 is_notable: item.attrs.has_doc_flag(sym::notable_trait),
236 // Collect all the implementors of traits.
237 if let clean::ImplItem(ref i) = *item.kind {
238 if let Some(trait_) = &i.trait_ {
239 if !i.kind.is_blanket() {
242 .entry(trait_.def_id())
244 .push(Impl { impl_item: item.clone() });
249 // Index this method for searching later on.
250 if let Some(ref s) = item.name.or_else(|| {
251 if item.is_stripped() {
253 } else if let clean::ImportItem(ref i) = *item.kind &&
254 let clean::ImportKind::Simple(s) = i.kind {
260 let (parent, is_inherent_impl_item) = match *item.kind {
261 clean::StrippedItem(..) => ((None, None), false),
262 clean::AssocConstItem(..) | clean::AssocTypeItem(..)
267 .map_or(false, |parent| parent.is_trait_impl()) =>
269 // skip associated items in trait impls
270 ((None, None), false)
272 clean::TyMethodItem(..)
273 | clean::TyAssocConstItem(..)
274 | clean::TyAssocTypeItem(..)
275 | clean::StructFieldItem(..)
276 | clean::VariantItem(..) => (
282 .expect("parent_stack is empty")
286 Some(&self.cache.stack[..self.cache.stack.len() - 1]),
290 clean::MethodItem(..) | clean::AssocConstItem(..) | clean::AssocTypeItem(..) => {
291 if self.cache.parent_stack.is_empty() {
292 ((None, None), false)
294 let last = self.cache.parent_stack.last().expect("parent_stack is empty 2");
295 let did = match &*last {
296 ParentStackItem::Impl { for_, .. } => for_.def_id(&self.cache),
297 ParentStackItem::Type(item_id) => item_id.as_def_id(),
299 let path = match did.and_then(|did| self.cache.paths.get(&did)) {
300 // The current stack not necessarily has correlation
301 // for where the type was defined. On the other
302 // hand, `paths` always has the right
303 // information if present.
304 Some(&(ref fqp, _)) => Some(&fqp[..fqp.len() - 1]),
310 _ => ((None, Some(&*self.cache.stack)), false),
314 (parent, Some(path)) if is_inherent_impl_item || !self.cache.stripped_mod => {
315 debug_assert!(!item.is_stripped());
317 // A crate has a module at its root, containing all items,
318 // which should not be indexed. The crate-item itself is
319 // inserted later on when serializing the search-index.
320 if item.item_id.as_def_id().map_or(false, |idx| !idx.is_crate_root()) {
321 let desc = item.doc_value().map_or_else(String::new, |x| {
322 short_markdown_summary(x.as_str(), &item.link_names(self.cache))
324 self.cache.search_index.push(IndexItem {
327 path: join_with_double_colon(path),
331 search_type: get_function_type_for_search(
334 clean_impl_generics(self.cache.parent_stack.last()).as_ref(),
337 aliases: item.attrs.get_doc_aliases(),
341 (Some(parent), None) if is_inherent_impl_item => {
342 // We have a parent, but we don't know where they're
343 // defined yet. Wait for later to index this item.
344 let impl_generics = clean_impl_generics(self.cache.parent_stack.last());
345 self.cache.orphan_impl_items.push(OrphanImplItem {
355 // Keep track of the fully qualified path for this item.
356 let pushed = match item.name {
357 Some(n) if !n.is_empty() => {
358 self.cache.stack.push(n);
365 clean::StructItem(..)
366 | clean::EnumItem(..)
367 | clean::TypedefItem(..)
368 | clean::TraitItem(..)
369 | clean::TraitAliasItem(..)
370 | clean::FunctionItem(..)
371 | clean::ModuleItem(..)
372 | clean::ForeignFunctionItem(..)
373 | clean::ForeignStaticItem(..)
374 | clean::ConstantItem(..)
375 | clean::StaticItem(..)
376 | clean::UnionItem(..)
377 | clean::ForeignTypeItem
378 | clean::MacroItem(..)
379 | clean::ProcMacroItem(..)
380 | clean::VariantItem(..) => {
381 if !self.cache.stripped_mod {
382 // Re-exported items mean that the same id can show up twice
383 // in the rustdoc ast that we're looking at. We know,
384 // however, that a re-exported item doesn't show up in the
385 // `public_items` map, so we can skip inserting into the
386 // paths map if there was already an entry present and we're
387 // not a public item.
388 if !self.cache.paths.contains_key(&item.item_id.expect_def_id())
389 || self.cache.access_levels.is_public(item.item_id.expect_def_id())
391 self.cache.paths.insert(
392 item.item_id.expect_def_id(),
393 (self.cache.stack.clone(), item.type_()),
398 clean::PrimitiveItem(..) => {
401 .insert(item.item_id.expect_def_id(), (self.cache.stack.clone(), item.type_()));
404 clean::ExternCrateItem { .. }
405 | clean::ImportItem(..)
406 | clean::OpaqueTyItem(..)
407 | clean::ImplItem(..)
408 | clean::TyMethodItem(..)
409 | clean::MethodItem(..)
410 | clean::StructFieldItem(..)
411 | clean::TyAssocConstItem(..)
412 | clean::AssocConstItem(..)
413 | clean::TyAssocTypeItem(..)
414 | clean::AssocTypeItem(..)
415 | clean::StrippedItem(..)
416 | clean::KeywordItem => {
417 // FIXME: Do these need handling?
418 // The person writing this comment doesn't know.
419 // So would rather leave them to an expert,
420 // as at least the list is better than `_ => {}`.
424 // Maintain the parent stack.
425 let (item, parent_pushed) = match *item.kind {
427 | clean::EnumItem(..)
428 | clean::ForeignTypeItem
429 | clean::StructItem(..)
430 | clean::UnionItem(..)
431 | clean::VariantItem(..)
432 | clean::ImplItem(..) => {
433 self.cache.parent_stack.push(ParentStackItem::new(&item));
434 (self.fold_item_recur(item), true)
436 _ => (self.fold_item_recur(item), false),
439 // Once we've recursively found all the generics, hoard off all the
440 // implementations elsewhere.
441 let ret = if let clean::Item { kind: box clean::ImplItem(ref i), .. } = item {
442 // Figure out the id of this impl. This may map to a
443 // primitive rather than always to a struct/enum.
444 // Note: matching twice to restrict the lifetime of the `i` borrow.
445 let mut dids = FxHashSet::default();
447 clean::Type::Path { ref path }
448 | clean::BorrowedRef { type_: box clean::Type::Path { ref path }, .. } => {
449 dids.insert(path.def_id());
450 if let Some(generics) = path.generics() &&
451 let ty::Adt(adt, _) = self.tcx.type_of(path.def_id()).kind() &&
452 adt.is_fundamental() {
454 if let Some(did) = ty.def_id(self.cache) {
460 clean::DynTrait(ref bounds, _)
461 | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
462 dids.insert(bounds[0].trait_.def_id());
467 .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
469 if let Some(did) = did {
475 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
476 for bound in generics {
477 if let Some(did) = bound.def_id(self.cache) {
482 let impl_item = Impl { impl_item: item };
483 if impl_item.trait_did().map_or(true, |d| self.cache.traits.contains_key(&d)) {
485 if self.impl_ids.entry(did).or_default().insert(impl_item.def_id()) {
489 .or_insert_with(Vec::new)
490 .push(impl_item.clone());
494 let trait_did = impl_item.trait_did().expect("no trait did");
495 self.cache.orphan_trait_impls.push((trait_did, dids, impl_item));
503 self.cache.stack.pop().expect("stack already empty");
506 self.cache.parent_stack.pop().expect("parent stack already empty");
508 self.cache.stripped_mod = orig_stripped_mod;
513 pub(crate) struct OrphanImplItem {
514 pub(crate) parent: DefId,
515 pub(crate) item: clean::Item,
516 pub(crate) impl_generics: Option<(clean::Type, clean::Generics)>,
519 /// Information about trait and type parents is tracked while traversing the item tree to build
522 /// We don't just store `Item` in there, because `Item` contains the list of children being
523 /// traversed and it would be wasteful to clone all that. We also need the item id, so just
524 /// storing `ItemKind` won't work, either.
525 enum ParentStackItem {
528 trait_: Option<clean::Path>,
529 generics: clean::Generics,
530 kind: clean::ImplKind,
536 impl ParentStackItem {
537 fn new(item: &clean::Item) -> Self {
539 clean::ItemKind::ImplItem(box clean::Impl { for_, trait_, generics, kind, .. }) => {
540 ParentStackItem::Impl {
542 trait_: trait_.clone(),
543 generics: generics.clone(),
545 item_id: item.item_id,
548 _ => ParentStackItem::Type(item.item_id),
551 fn is_trait_impl(&self) -> bool {
552 matches!(self, ParentStackItem::Impl { trait_: Some(..), .. })
554 fn item_id(&self) -> ItemId {
556 ParentStackItem::Impl { item_id, .. } => *item_id,
557 ParentStackItem::Type(item_id) => *item_id,
562 fn clean_impl_generics(item: Option<&ParentStackItem>) -> Option<(clean::Type, clean::Generics)> {
563 if let Some(ParentStackItem::Impl { for_, generics, kind: clean::ImplKind::Normal, .. }) = item
565 Some((for_.clone(), generics.clone()))