3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
5 use rustc_middle::middle::privacy::AccessLevels;
6 use rustc_middle::ty::TyCtxt;
7 use rustc_span::symbol::sym;
9 use crate::clean::{self, ItemId, PrimitiveType};
10 use crate::config::RenderOptions;
11 use crate::fold::DocFolder;
12 use crate::formats::item_type::ItemType;
13 use crate::formats::Impl;
14 use crate::html::markdown::short_markdown_summary;
15 use crate::html::render::cache::{get_index_search_type, ExternalLocation};
16 use crate::html::render::IndexItem;
18 /// This cache is used to store information about the [`clean::Crate`] being
19 /// rendered in order to provide more useful documentation. This contains
20 /// information like all implementors of a trait, all traits a type implements,
21 /// documentation for all known traits, etc.
23 /// This structure purposefully does not implement `Clone` because it's intended
24 /// to be a fairly large and expensive structure to clone. Instead this adheres
25 /// to `Send` so it may be stored in an `Arc` instance and shared among the various
26 /// rendering threads.
29 /// Maps a type ID to all known implementations for that type. This is only
30 /// recognized for intra-crate `ResolvedPath` types, and is used to print
31 /// out extra documentation on the page of an enum/struct.
33 /// The values of the map are a list of implementations and documentation
34 /// found on that implementation.
35 crate impls: FxHashMap<DefId, Vec<Impl>>,
37 /// Maintains a mapping of local crate `DefId`s to the fully qualified name
38 /// and "short type description" of that node. This is used when generating
39 /// URLs when a type is being linked to. External paths are not located in
40 /// this map because the `External` type itself has all the information
42 crate paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
44 /// Similar to `paths`, but only holds external paths. This is only used for
45 /// generating explicit hyperlinks to other crates.
46 crate external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
48 /// Maps local `DefId`s of exported types to fully qualified paths.
49 /// Unlike 'paths', this mapping ignores any renames that occur
50 /// due to 'use' statements.
52 /// This map is used when writing out the special 'implementors'
53 /// javascript file. By using the exact path that the type
54 /// is declared with, we ensure that each path will be identical
55 /// to the path used if the corresponding type is inlined. By
56 /// doing this, we can detect duplicate impls on a trait page, and only display
57 /// the impl for the inlined type.
58 crate exact_paths: FxHashMap<DefId, Vec<String>>,
60 /// This map contains information about all known traits of this crate.
61 /// Implementations of a crate should inherit the documentation of the
62 /// parent trait if no extra documentation is specified, and default methods
63 /// should show up in documentation about trait implementations.
64 crate traits: FxHashMap<DefId, clean::TraitWithExtraInfo>,
66 /// When rendering traits, it's often useful to be able to list all
67 /// implementors of the trait, and this mapping is exactly, that: a mapping
68 /// of trait ids to the list of known implementors of the trait
69 crate implementors: FxHashMap<DefId, Vec<Impl>>,
71 /// Cache of where external crate documentation can be found.
72 crate extern_locations: FxHashMap<CrateNum, ExternalLocation>,
74 /// Cache of where documentation for primitives can be found.
75 crate primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
77 // Note that external items for which `doc(hidden)` applies to are shown as
78 // non-reachable while local items aren't. This is because we're reusing
79 // the access levels from the privacy check pass.
80 crate access_levels: AccessLevels<DefId>,
82 /// The version of the crate being documented, if given from the `--crate-version` flag.
83 crate crate_version: Option<String>,
85 /// Whether to document private items.
86 /// This is stored in `Cache` so it doesn't need to be passed through all rustdoc functions.
87 crate document_private: bool,
89 /// Crates marked with [`#[doc(masked)]`][doc_masked].
91 /// [doc_masked]: https://doc.rust-lang.org/nightly/unstable-book/language-features/doc-masked.html
92 crate masked_crates: FxHashSet<CrateNum>,
94 // Private fields only used when initially crawling a crate to build a cache
96 parent_stack: Vec<DefId>,
97 parent_is_trait_impl: bool,
100 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 crate orphan_impl_items: Vec<(DefId, clean::Item)>,
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 crate intra_doc_links: FxHashMap<ItemId, Vec<clean::ItemLink>>,
122 /// Cfg that have been hidden via #![doc(cfg_hide(...))]
123 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,
133 crate fn new(access_levels: AccessLevels<DefId>, document_private: bool) -> Self {
134 Cache { access_levels, document_private, ..Cache::default() }
137 /// Populates the `Cache` with more data. The returned `Crate` will be missing some data that was
138 /// in `krate` due to the data being moved into the `Cache`.
141 mut krate: clean::Crate,
143 render_options: &RenderOptions,
145 // Crawl the crate to build various caches used for the output
146 debug!(?self.crate_version);
147 self.traits = krate.external_traits.take();
148 let RenderOptions { extern_html_root_takes_precedence, output: dst, .. } = render_options;
150 // Cache where all our extern crates are located
151 // FIXME: this part is specific to HTML so it'd be nice to remove it from the common code
152 for &e in &krate.externs {
153 let name = e.name(tcx);
155 render_options.extern_html_root_urls.get(&*name.as_str()).map(|u| &**u);
156 let location = e.location(extern_url, *extern_html_root_takes_precedence, dst, tcx);
157 self.extern_locations.insert(e.crate_num, location);
158 self.external_paths.insert(e.def_id(), (vec![name.to_string()], ItemType::Module));
161 // FIXME: avoid this clone (requires implementing Default manually)
162 self.primitive_locations = PrimitiveType::primitive_locations(tcx).clone();
163 for (prim, &def_id) in &self.primitive_locations {
164 let crate_name = tcx.crate_name(def_id.krate);
165 // Recall that we only allow primitive modules to be at the root-level of the crate.
166 // If that restriction is ever lifted, this will have to include the relative paths instead.
167 self.external_paths.insert(
169 (vec![crate_name.to_string(), prim.as_sym().to_string()], ItemType::Primitive),
173 krate = CacheBuilder { tcx, cache: self }.fold_crate(krate);
175 for (trait_did, dids, impl_) in self.orphan_trait_impls.drain(..) {
176 if self.traits.contains_key(&trait_did) {
178 self.impls.entry(did).or_default().push(impl_.clone());
187 impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> {
188 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
189 if item.def_id.is_local() {
190 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
193 // If this is a stripped module,
194 // we don't want it or its children in the search index.
195 let orig_stripped_mod = match *item.kind {
196 clean::StrippedItem(box clean::ModuleItem(..)) => {
197 mem::replace(&mut self.cache.stripped_mod, true)
199 _ => self.cache.stripped_mod,
202 // If the impl is from a masked crate or references something from a
203 // masked crate then remove it completely.
204 if let clean::ImplItem(ref i) = *item.kind {
205 if self.cache.masked_crates.contains(&item.def_id.krate())
208 .map_or(false, |t| self.cache.masked_crates.contains(&t.def_id().krate))
211 .map_or(false, |d| self.cache.masked_crates.contains(&d.krate))
217 // Propagate a trait method's documentation to all implementors of the
219 if let clean::TraitItem(ref t) = *item.kind {
220 self.cache.traits.entry(item.def_id.expect_def_id()).or_insert_with(|| {
221 clean::TraitWithExtraInfo {
223 is_notable: item.attrs.has_doc_flag(sym::notable_trait),
228 // Collect all the implementors of traits.
229 if let clean::ImplItem(ref i) = *item.kind {
230 if let Some(trait_) = &i.trait_ {
231 if i.blanket_impl.is_none() {
234 .entry(trait_.def_id())
236 .push(Impl { impl_item: item.clone() });
241 // Index this method for searching later on.
242 if let Some(ref s) = item.name {
243 let (parent, is_inherent_impl_item) = match *item.kind {
244 clean::StrippedItem(..) => ((None, None), false),
245 clean::AssocConstItem(..) | clean::TypedefItem(_, true)
246 if self.cache.parent_is_trait_impl =>
248 // skip associated items in trait impls
249 ((None, None), false)
251 clean::AssocTypeItem(..)
252 | clean::TyMethodItem(..)
253 | clean::StructFieldItem(..)
254 | clean::VariantItem(..) => (
256 Some(*self.cache.parent_stack.last().expect("parent_stack is empty")),
257 Some(&self.cache.stack[..self.cache.stack.len() - 1]),
261 clean::MethodItem(..) | clean::AssocConstItem(..) => {
262 if self.cache.parent_stack.is_empty() {
263 ((None, None), false)
265 let last = self.cache.parent_stack.last().expect("parent_stack is empty 2");
267 let path = match self.cache.paths.get(&did) {
268 // The current stack not necessarily has correlation
269 // for where the type was defined. On the other
270 // hand, `paths` always has the right
271 // information if present.
278 )) => Some(&fqp[..fqp.len() - 1]),
279 Some(..) => Some(&*self.cache.stack),
282 ((Some(*last), path), true)
285 _ => ((None, Some(&*self.cache.stack)), false),
289 (parent, Some(path)) if is_inherent_impl_item || !self.cache.stripped_mod => {
290 debug_assert!(!item.is_stripped());
292 // A crate has a module at its root, containing all items,
293 // which should not be indexed. The crate-item itself is
294 // inserted later on when serializing the search-index.
295 if item.def_id.index().map_or(false, |idx| idx != CRATE_DEF_INDEX) {
296 let desc = item.doc_value().map_or_else(String::new, |x| {
297 short_markdown_summary(x.as_str(), &item.link_names(self.cache))
299 self.cache.search_index.push(IndexItem {
302 path: path.join("::"),
306 search_type: get_index_search_type(&item, self.tcx),
307 aliases: item.attrs.get_doc_aliases(),
311 (Some(parent), None) if is_inherent_impl_item => {
312 // We have a parent, but we don't know where they're
313 // defined yet. Wait for later to index this item.
314 self.cache.orphan_impl_items.push((parent, item.clone()));
320 // Keep track of the fully qualified path for this item.
321 let pushed = match item.name {
322 Some(n) if !n.is_empty() => {
323 self.cache.stack.push(n.to_string());
330 clean::StructItem(..)
331 | clean::EnumItem(..)
332 | clean::TypedefItem(..)
333 | clean::TraitItem(..)
334 | clean::TraitAliasItem(..)
335 | clean::FunctionItem(..)
336 | clean::ModuleItem(..)
337 | clean::ForeignFunctionItem(..)
338 | clean::ForeignStaticItem(..)
339 | clean::ConstantItem(..)
340 | clean::StaticItem(..)
341 | clean::UnionItem(..)
342 | clean::ForeignTypeItem
343 | clean::MacroItem(..)
344 | clean::ProcMacroItem(..)
345 | clean::VariantItem(..) => {
346 if !self.cache.stripped_mod {
347 // Re-exported items mean that the same id can show up twice
348 // in the rustdoc ast that we're looking at. We know,
349 // however, that a re-exported item doesn't show up in the
350 // `public_items` map, so we can skip inserting into the
351 // paths map if there was already an entry present and we're
352 // not a public item.
353 if !self.cache.paths.contains_key(&item.def_id.expect_def_id())
354 || self.cache.access_levels.is_public(item.def_id.expect_def_id())
356 self.cache.paths.insert(
357 item.def_id.expect_def_id(),
358 (self.cache.stack.clone(), item.type_()),
363 clean::PrimitiveItem(..) => {
366 .insert(item.def_id.expect_def_id(), (self.cache.stack.clone(), item.type_()));
369 clean::ExternCrateItem { .. }
370 | clean::ImportItem(..)
371 | clean::OpaqueTyItem(..)
372 | clean::ImplItem(..)
373 | clean::TyMethodItem(..)
374 | clean::MethodItem(..)
375 | clean::StructFieldItem(..)
376 | clean::AssocConstItem(..)
377 | clean::AssocTypeItem(..)
378 | clean::StrippedItem(..)
379 | clean::KeywordItem(..) => {
380 // FIXME: Do these need handling?
381 // The person writing this comment doesn't know.
382 // So would rather leave them to an expert,
383 // as at least the list is better than `_ => {}`.
387 // Maintain the parent stack
388 let orig_parent_is_trait_impl = self.cache.parent_is_trait_impl;
389 let parent_pushed = match *item.kind {
391 | clean::EnumItem(..)
392 | clean::ForeignTypeItem
393 | clean::StructItem(..)
394 | clean::UnionItem(..)
395 | clean::VariantItem(..) => {
396 self.cache.parent_stack.push(item.def_id.expect_def_id());
397 self.cache.parent_is_trait_impl = false;
400 clean::ImplItem(ref i) => {
401 self.cache.parent_is_trait_impl = i.trait_.is_some();
403 clean::ResolvedPath { did, .. } => {
404 self.cache.parent_stack.push(did);
407 clean::DynTrait(ref bounds, _)
408 | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
409 self.cache.parent_stack.push(bounds[0].trait_.def_id());
415 .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
418 self.cache.parent_stack.push(did);
429 // Once we've recursively found all the generics, hoard off all the
430 // implementations elsewhere.
431 let item = self.fold_item_recur(item);
432 let ret = if let clean::Item { kind: box clean::ImplItem(ref i), .. } = item {
433 // Figure out the id of this impl. This may map to a
434 // primitive rather than always to a struct/enum.
435 // Note: matching twice to restrict the lifetime of the `i` borrow.
436 let mut dids = FxHashSet::default();
438 clean::ResolvedPath { did, .. }
439 | clean::BorrowedRef { type_: box clean::ResolvedPath { did, .. }, .. } => {
442 clean::DynTrait(ref bounds, _)
443 | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
444 dids.insert(bounds[0].trait_.def_id());
449 .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
451 if let Some(did) = did {
457 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
458 for bound in generics {
459 if let Some(did) = bound.def_id(self.cache) {
464 let impl_item = Impl { impl_item: item };
465 if impl_item.trait_did().map_or(true, |d| self.cache.traits.contains_key(&d)) {
467 self.cache.impls.entry(did).or_insert_with(Vec::new).push(impl_item.clone());
470 let trait_did = impl_item.trait_did().expect("no trait did");
471 self.cache.orphan_trait_impls.push((trait_did, dids, impl_item));
479 self.cache.stack.pop().expect("stack already empty");
482 self.cache.parent_stack.pop().expect("parent stack already empty");
484 self.cache.stripped_mod = orig_stripped_mod;
485 self.cache.parent_is_trait_impl = orig_parent_is_trait_impl;