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, ExternalCrate, ItemId, PrimitiveType};
10 use crate::config::RenderOptions;
11 use crate::core::DocContext;
12 use crate::fold::DocFolder;
13 use crate::formats::item_type::ItemType;
14 use crate::formats::Impl;
15 use crate::html::markdown::short_markdown_summary;
16 use crate::html::render::cache::{get_index_search_type, ExternalLocation};
17 use crate::html::render::IndexItem;
18 use crate::visit_lib::LibEmbargoVisitor;
20 /// This cache is used to store information about the [`clean::Crate`] being
21 /// rendered in order to provide more useful documentation. This contains
22 /// information like all implementors of a trait, all traits a type implements,
23 /// documentation for all known traits, etc.
25 /// This structure purposefully does not implement `Clone` because it's intended
26 /// to be a fairly large and expensive structure to clone. Instead this adheres
27 /// to `Send` so it may be stored in an `Arc` instance and shared among the various
28 /// rendering threads.
31 /// Maps a type ID to all known implementations for that type. This is only
32 /// recognized for intra-crate `ResolvedPath` types, and is used to print
33 /// out extra documentation on the page of an enum/struct.
35 /// The values of the map are a list of implementations and documentation
36 /// found on that implementation.
37 crate impls: FxHashMap<DefId, Vec<Impl>>,
39 /// Maintains a mapping of local crate `DefId`s to the fully qualified name
40 /// and "short type description" of that node. This is used when generating
41 /// URLs when a type is being linked to. External paths are not located in
42 /// this map because the `External` type itself has all the information
44 crate paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
46 /// Similar to `paths`, but only holds external paths. This is only used for
47 /// generating explicit hyperlinks to other crates.
48 crate external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
50 /// Maps local `DefId`s of exported types to fully qualified paths.
51 /// Unlike 'paths', this mapping ignores any renames that occur
52 /// due to 'use' statements.
54 /// This map is used when writing out the special 'implementors'
55 /// javascript file. By using the exact path that the type
56 /// is declared with, we ensure that each path will be identical
57 /// to the path used if the corresponding type is inlined. By
58 /// doing this, we can detect duplicate impls on a trait page, and only display
59 /// the impl for the inlined type.
60 crate exact_paths: FxHashMap<DefId, Vec<String>>,
62 /// This map contains information about all known traits of this crate.
63 /// Implementations of a crate should inherit the documentation of the
64 /// parent trait if no extra documentation is specified, and default methods
65 /// should show up in documentation about trait implementations.
66 crate traits: FxHashMap<DefId, clean::TraitWithExtraInfo>,
68 /// When rendering traits, it's often useful to be able to list all
69 /// implementors of the trait, and this mapping is exactly, that: a mapping
70 /// of trait ids to the list of known implementors of the trait
71 crate implementors: FxHashMap<DefId, Vec<Impl>>,
73 /// Cache of where external crate documentation can be found.
74 crate extern_locations: FxHashMap<CrateNum, ExternalLocation>,
76 /// Cache of where documentation for primitives can be found.
77 crate primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
79 // Note that external items for which `doc(hidden)` applies to are shown as
80 // non-reachable while local items aren't. This is because we're reusing
81 // the access levels from the privacy check pass.
82 crate access_levels: AccessLevels<DefId>,
84 /// The version of the crate being documented, if given from the `--crate-version` flag.
85 crate crate_version: Option<String>,
87 /// Whether to document private items.
88 /// This is stored in `Cache` so it doesn't need to be passed through all rustdoc functions.
89 crate document_private: bool,
91 /// Crates marked with [`#[doc(masked)]`][doc_masked].
93 /// [doc_masked]: https://doc.rust-lang.org/nightly/unstable-book/language-features/doc-masked.html
94 crate masked_crates: FxHashSet<CrateNum>,
96 // Private fields only used when initially crawling a crate to build a cache
98 parent_stack: Vec<DefId>,
99 parent_is_trait_impl: bool,
102 crate search_index: Vec<IndexItem>,
104 // In rare case where a structure is defined in one module but implemented
105 // in another, if the implementing module is parsed before defining module,
106 // then the fully qualified name of the structure isn't presented in `paths`
107 // yet when its implementation methods are being indexed. Caches such methods
108 // and their parent id here and indexes them at the end of crate parsing.
109 crate orphan_impl_items: Vec<(DefId, clean::Item)>,
111 // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
112 // even though the trait itself is not exported. This can happen if a trait
113 // was defined in function/expression scope, since the impl will be picked
114 // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
115 // crawl. In order to prevent crashes when looking for notable traits or
116 // when gathering trait documentation on a type, hold impls here while
117 // folding and add them to the cache later on if we find the trait.
118 orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
120 /// All intra-doc links resolved so far.
122 /// Links are indexed by the DefId of the item they document.
123 crate intra_doc_links: FxHashMap<ItemId, Vec<clean::ItemLink>>,
124 /// Cfg that have been hidden via #![doc(cfg_hide(...))]
125 crate hidden_cfg: FxHashSet<clean::cfg::Cfg>,
128 /// This struct is used to wrap the `cache` and `tcx` in order to run `DocFolder`.
129 struct CacheBuilder<'a, 'tcx> {
130 cache: &'a mut Cache,
135 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 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 let mut externs = Vec::new();
149 for &cnum in cx.tcx.crates(()) {
150 externs.push(ExternalCrate { crate_num: cnum });
151 // Analyze doc-reachability for extern items
152 LibEmbargoVisitor::new(cx).visit_lib(cnum);
155 let RenderOptions { extern_html_root_takes_precedence, output: dst, .. } =
158 // Cache where all our extern crates are located
159 // FIXME: this part is specific to HTML so it'd be nice to remove it from the common code
161 let name = e.name(tcx);
163 cx.render_options.extern_html_root_urls.get(&*name.as_str()).map(|u| &**u);
164 let location = e.location(extern_url, *extern_html_root_takes_precedence, dst, tcx);
165 cx.cache.extern_locations.insert(e.crate_num, location);
166 cx.cache.external_paths.insert(e.def_id(), (vec![name.to_string()], ItemType::Module));
169 // FIXME: avoid this clone (requires implementing Default manually)
170 cx.cache.primitive_locations = PrimitiveType::primitive_locations(tcx).clone();
171 for (prim, &def_id) in &cx.cache.primitive_locations {
172 let crate_name = tcx.crate_name(def_id.krate);
173 // Recall that we only allow primitive modules to be at the root-level of the crate.
174 // If that restriction is ever lifted, this will have to include the relative paths instead.
175 cx.cache.external_paths.insert(
177 (vec![crate_name.to_string(), prim.as_sym().to_string()], ItemType::Primitive),
181 krate = CacheBuilder { tcx, cache: &mut cx.cache }.fold_crate(krate);
183 for (trait_did, dids, impl_) in cx.cache.orphan_trait_impls.drain(..) {
184 if cx.cache.traits.contains_key(&trait_did) {
186 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.def_id.is_local() {
198 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_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.def_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.def_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 {
251 let (parent, is_inherent_impl_item) = match *item.kind {
252 clean::StrippedItem(..) => ((None, None), false),
253 clean::AssocConstItem(..) | clean::TypedefItem(_, true)
254 if self.cache.parent_is_trait_impl =>
256 // skip associated items in trait impls
257 ((None, None), false)
259 clean::AssocTypeItem(..)
260 | clean::TyMethodItem(..)
261 | clean::StructFieldItem(..)
262 | clean::VariantItem(..) => (
264 Some(*self.cache.parent_stack.last().expect("parent_stack is empty")),
265 Some(&self.cache.stack[..self.cache.stack.len() - 1]),
269 clean::MethodItem(..) | clean::AssocConstItem(..) => {
270 if self.cache.parent_stack.is_empty() {
271 ((None, None), false)
273 let last = self.cache.parent_stack.last().expect("parent_stack is empty 2");
275 let path = match self.cache.paths.get(&did) {
276 // The current stack not necessarily has correlation
277 // for where the type was defined. On the other
278 // hand, `paths` always has the right
279 // information if present.
286 )) => Some(&fqp[..fqp.len() - 1]),
287 Some(..) => Some(&*self.cache.stack),
290 ((Some(*last), path), true)
293 _ => ((None, Some(&*self.cache.stack)), false),
297 (parent, Some(path)) if is_inherent_impl_item || !self.cache.stripped_mod => {
298 debug_assert!(!item.is_stripped());
300 // A crate has a module at its root, containing all items,
301 // which should not be indexed. The crate-item itself is
302 // inserted later on when serializing the search-index.
303 if item.def_id.index().map_or(false, |idx| idx != CRATE_DEF_INDEX) {
304 let desc = item.doc_value().map_or_else(String::new, |x| {
305 short_markdown_summary(x.as_str(), &item.link_names(self.cache))
307 self.cache.search_index.push(IndexItem {
310 path: path.join("::"),
314 search_type: get_index_search_type(&item, self.tcx, self.cache),
315 aliases: item.attrs.get_doc_aliases(),
319 (Some(parent), None) if is_inherent_impl_item => {
320 // We have a parent, but we don't know where they're
321 // defined yet. Wait for later to index this item.
322 self.cache.orphan_impl_items.push((parent, item.clone()));
328 // Keep track of the fully qualified path for this item.
329 let pushed = match item.name {
330 Some(n) if !n.is_empty() => {
331 self.cache.stack.push(n.to_string());
338 clean::StructItem(..)
339 | clean::EnumItem(..)
340 | clean::TypedefItem(..)
341 | clean::TraitItem(..)
342 | clean::TraitAliasItem(..)
343 | clean::FunctionItem(..)
344 | clean::ModuleItem(..)
345 | clean::ForeignFunctionItem(..)
346 | clean::ForeignStaticItem(..)
347 | clean::ConstantItem(..)
348 | clean::StaticItem(..)
349 | clean::UnionItem(..)
350 | clean::ForeignTypeItem
351 | clean::MacroItem(..)
352 | clean::ProcMacroItem(..)
353 | clean::VariantItem(..) => {
354 if !self.cache.stripped_mod {
355 // Re-exported items mean that the same id can show up twice
356 // in the rustdoc ast that we're looking at. We know,
357 // however, that a re-exported item doesn't show up in the
358 // `public_items` map, so we can skip inserting into the
359 // paths map if there was already an entry present and we're
360 // not a public item.
361 if !self.cache.paths.contains_key(&item.def_id.expect_def_id())
362 || self.cache.access_levels.is_public(item.def_id.expect_def_id())
364 self.cache.paths.insert(
365 item.def_id.expect_def_id(),
366 (self.cache.stack.clone(), item.type_()),
371 clean::PrimitiveItem(..) => {
374 .insert(item.def_id.expect_def_id(), (self.cache.stack.clone(), item.type_()));
377 clean::ExternCrateItem { .. }
378 | clean::ImportItem(..)
379 | clean::OpaqueTyItem(..)
380 | clean::ImplItem(..)
381 | clean::TyMethodItem(..)
382 | clean::MethodItem(..)
383 | clean::StructFieldItem(..)
384 | clean::AssocConstItem(..)
385 | clean::AssocTypeItem(..)
386 | clean::StrippedItem(..)
387 | clean::KeywordItem(..) => {
388 // FIXME: Do these need handling?
389 // The person writing this comment doesn't know.
390 // So would rather leave them to an expert,
391 // as at least the list is better than `_ => {}`.
395 // Maintain the parent stack
396 let orig_parent_is_trait_impl = self.cache.parent_is_trait_impl;
397 let parent_pushed = match *item.kind {
399 | clean::EnumItem(..)
400 | clean::ForeignTypeItem
401 | clean::StructItem(..)
402 | clean::UnionItem(..)
403 | clean::VariantItem(..) => {
404 self.cache.parent_stack.push(item.def_id.expect_def_id());
405 self.cache.parent_is_trait_impl = false;
408 clean::ImplItem(ref i) => {
409 self.cache.parent_is_trait_impl = i.trait_.is_some();
411 clean::ResolvedPath { did, .. } => {
412 self.cache.parent_stack.push(did);
415 clean::DynTrait(ref bounds, _)
416 | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
417 self.cache.parent_stack.push(bounds[0].trait_.def_id());
423 .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
426 self.cache.parent_stack.push(did);
437 // Once we've recursively found all the generics, hoard off all the
438 // implementations elsewhere.
439 let item = self.fold_item_recur(item);
440 let ret = if let clean::Item { kind: box clean::ImplItem(ref i), .. } = item {
441 // Figure out the id of this impl. This may map to a
442 // primitive rather than always to a struct/enum.
443 // Note: matching twice to restrict the lifetime of the `i` borrow.
444 let mut dids = FxHashSet::default();
446 clean::ResolvedPath { did, .. }
447 | clean::BorrowedRef { type_: box clean::ResolvedPath { did, .. }, .. } => {
450 clean::DynTrait(ref bounds, _)
451 | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
452 dids.insert(bounds[0].trait_.def_id());
457 .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
459 if let Some(did) = did {
465 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
466 for bound in generics {
467 if let Some(did) = bound.def_id(self.cache) {
472 let impl_item = Impl { impl_item: item };
473 if impl_item.trait_did().map_or(true, |d| self.cache.traits.contains_key(&d)) {
475 self.cache.impls.entry(did).or_insert_with(Vec::new).push(impl_item.clone());
478 let trait_did = impl_item.trait_did().expect("no trait did");
479 self.cache.orphan_trait_impls.push((trait_did, dids, impl_item));
487 self.cache.stack.pop().expect("stack already empty");
490 self.cache.parent_stack.pop().expect("parent stack already empty");
492 self.cache.stripped_mod = orig_stripped_mod;
493 self.cache.parent_is_trait_impl = orig_parent_is_trait_impl;