1 use std::cell::RefCell;
2 use std::collections::BTreeMap;
4 use std::path::{Path, PathBuf};
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
9 use rustc_middle::middle::privacy::AccessLevels;
10 use rustc_span::source_map::FileName;
12 use crate::clean::{self, GetDefId};
13 use crate::config::RenderInfo;
14 use crate::fold::DocFolder;
15 use crate::formats::item_type::ItemType;
16 use crate::formats::Impl;
17 use crate::html::markdown::short_markdown_summary;
18 use crate::html::render::cache::{extern_location, get_index_search_type, ExternalLocation};
19 use crate::html::render::IndexItem;
21 thread_local!(crate static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
23 /// This cache is used to store information about the [`clean::Crate`] being
24 /// rendered in order to provide more useful documentation. This contains
25 /// information like all implementors of a trait, all traits a type implements,
26 /// documentation for all known traits, etc.
28 /// This structure purposefully does not implement `Clone` because it's intended
29 /// to be a fairly large and expensive structure to clone. Instead this adheres
30 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
31 /// rendering threads.
34 /// Maps a type ID to all known implementations for that type. This is only
35 /// recognized for intra-crate `ResolvedPath` types, and is used to print
36 /// out extra documentation on the page of an enum/struct.
38 /// The values of the map are a list of implementations and documentation
39 /// found on that implementation.
40 crate impls: FxHashMap<DefId, Vec<Impl>>,
42 /// Maintains a mapping of local crate `DefId`s to the fully qualified name
43 /// and "short type description" of that node. This is used when generating
44 /// URLs when a type is being linked to. External paths are not located in
45 /// this map because the `External` type itself has all the information
47 crate paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
49 /// Similar to `paths`, but only holds external paths. This is only used for
50 /// generating explicit hyperlinks to other crates.
51 crate external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
53 /// Maps local `DefId`s of exported types to fully qualified paths.
54 /// Unlike 'paths', this mapping ignores any renames that occur
55 /// due to 'use' statements.
57 /// This map is used when writing out the special 'implementors'
58 /// javascript file. By using the exact path that the type
59 /// is declared with, we ensure that each path will be identical
60 /// to the path used if the corresponding type is inlined. By
61 /// doing this, we can detect duplicate impls on a trait page, and only display
62 /// the impl for the inlined type.
63 crate exact_paths: FxHashMap<DefId, Vec<String>>,
65 /// This map contains information about all known traits of this crate.
66 /// Implementations of a crate should inherit the documentation of the
67 /// parent trait if no extra documentation is specified, and default methods
68 /// should show up in documentation about trait implementations.
69 crate traits: FxHashMap<DefId, clean::Trait>,
71 /// When rendering traits, it's often useful to be able to list all
72 /// implementors of the trait, and this mapping is exactly, that: a mapping
73 /// of trait ids to the list of known implementors of the trait
74 crate implementors: FxHashMap<DefId, Vec<Impl>>,
76 /// Cache of where external crate documentation can be found.
77 crate extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
79 /// Cache of where documentation for primitives can be found.
80 crate primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
82 // Note that external items for which `doc(hidden)` applies to are shown as
83 // non-reachable while local items aren't. This is because we're reusing
84 // the access levels from the privacy check pass.
85 crate access_levels: AccessLevels<DefId>,
87 /// The version of the crate being documented, if given from the `--crate-version` flag.
88 crate crate_version: Option<String>,
90 /// Whether to document private items.
91 /// This is stored in `Cache` so it doesn't need to be passed through all rustdoc functions.
92 crate document_private: bool,
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,
99 masked_crates: FxHashSet<CrateNum>,
101 crate search_index: Vec<IndexItem>,
102 crate deref_trait_did: Option<DefId>,
103 crate deref_mut_trait_did: Option<DefId>,
104 crate owned_box_did: Option<DefId>,
106 // In rare case where a structure is defined in one module but implemented
107 // in another, if the implementing module is parsed before defining module,
108 // then the fully qualified name of the structure isn't presented in `paths`
109 // yet when its implementation methods are being indexed. Caches such methods
110 // and their parent id here and indexes them at the end of crate parsing.
111 crate orphan_impl_items: Vec<(DefId, clean::Item)>,
113 // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
114 // even though the trait itself is not exported. This can happen if a trait
115 // was defined in function/expression scope, since the impl will be picked
116 // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
117 // crawl. In order to prevent crashes when looking for spotlight traits or
118 // when gathering trait documentation on a type, hold impls here while
119 // folding and add them to the cache later on if we find the trait.
120 orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
122 /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
123 /// we need the alias element to have an array of items.
124 crate aliases: BTreeMap<String, Vec<usize>>,
129 render_info: RenderInfo,
130 document_private: bool,
131 extern_html_root_urls: &BTreeMap<String, String>,
133 mut krate: clean::Crate,
134 ) -> (clean::Crate, Cache) {
135 // Crawl the crate to build various caches used for the output
148 external_paths.into_iter().map(|(k, (v, t))| (k, (v, ItemType::from(t)))).collect();
150 let mut cache = Cache {
153 parent_is_trait_impl: false,
156 crate_version: krate.version.take(),
158 traits: krate.external_traits.replace(Default::default()),
162 masked_crates: mem::take(&mut krate.masked_crates),
166 // Cache where all our extern crates are located
167 // FIXME: this part is specific to HTML so it'd be nice to remove it from the common code
168 for &(n, ref e) in &krate.externs {
169 let src_root = match e.src {
170 FileName::Real(ref p) => match p.local_path().parent() {
171 Some(p) => p.to_path_buf(),
172 None => PathBuf::new(),
176 let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
179 .insert(n, (e.name.clone(), src_root, extern_location(e, extern_url, &dst)));
181 let did = DefId { krate: n, index: CRATE_DEF_INDEX };
182 cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
185 // Cache where all known primitives have their documentation located.
187 // Favor linking to as local extern as possible, so iterate all crates in
188 // reverse topological order.
189 for &(_, ref e) in krate.externs.iter().rev() {
190 for &(def_id, prim) in &e.primitives {
191 cache.primitive_locations.insert(prim, def_id);
194 for &(def_id, prim) in &krate.primitives {
195 cache.primitive_locations.insert(prim, def_id);
198 cache.stack.push(krate.name.clone());
199 krate = cache.fold_crate(krate);
201 for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
202 if cache.traits.contains_key(&trait_did) {
204 cache.impls.entry(did).or_default().push(impl_.clone());
213 impl DocFolder for Cache {
214 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
215 if item.def_id.is_local() {
216 debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
219 // If this is a stripped module,
220 // we don't want it or its children in the search index.
221 let orig_stripped_mod = match item.kind {
222 clean::StrippedItem(box clean::ModuleItem(..)) => {
223 mem::replace(&mut self.stripped_mod, true)
225 _ => self.stripped_mod,
228 // If the impl is from a masked crate or references something from a
229 // masked crate then remove it completely.
230 if let clean::ImplItem(ref i) = item.kind {
231 if self.masked_crates.contains(&item.def_id.krate)
232 || i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate))
233 || i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate))
239 // Propagate a trait method's documentation to all implementors of the
241 if let clean::TraitItem(ref t) = item.kind {
242 self.traits.entry(item.def_id).or_insert_with(|| t.clone());
245 // Collect all the implementors of traits.
246 if let clean::ImplItem(ref i) = item.kind {
247 if let Some(did) = i.trait_.def_id() {
248 if i.blanket_impl.is_none() {
252 .push(Impl { impl_item: item.clone() });
257 // Index this method for searching later on.
258 if let Some(ref s) = item.name {
259 let (parent, is_inherent_impl_item) = match item.kind {
260 clean::StrippedItem(..) => ((None, None), false),
261 clean::AssocConstItem(..) | clean::TypedefItem(_, true)
262 if self.parent_is_trait_impl =>
264 // skip associated items in trait impls
265 ((None, None), false)
267 clean::AssocTypeItem(..)
268 | clean::TyMethodItem(..)
269 | clean::StructFieldItem(..)
270 | clean::VariantItem(..) => (
272 Some(*self.parent_stack.last().expect("parent_stack is empty")),
273 Some(&self.stack[..self.stack.len() - 1]),
277 clean::MethodItem(..) | clean::AssocConstItem(..) => {
278 if self.parent_stack.is_empty() {
279 ((None, None), false)
281 let last = self.parent_stack.last().expect("parent_stack is empty 2");
283 let path = match self.paths.get(&did) {
284 // The current stack not necessarily has correlation
285 // for where the type was defined. On the other
286 // hand, `paths` always has the right
287 // information if present.
294 )) => Some(&fqp[..fqp.len() - 1]),
295 Some(..) => Some(&*self.stack),
298 ((Some(*last), path), true)
301 _ => ((None, Some(&*self.stack)), false),
305 (parent, Some(path)) if is_inherent_impl_item || !self.stripped_mod => {
306 debug_assert!(!item.is_stripped());
308 // A crate has a module at its root, containing all items,
309 // which should not be indexed. The crate-item itself is
310 // inserted later on when serializing the search-index.
311 if item.def_id.index != CRATE_DEF_INDEX {
312 self.search_index.push(IndexItem {
315 path: path.join("::"),
318 .map_or_else(|| String::new(), short_markdown_summary),
321 search_type: get_index_search_type(&item),
324 for alias in item.attrs.get_doc_aliases() {
326 .entry(alias.to_lowercase())
327 .or_insert(Vec::new())
328 .push(self.search_index.len() - 1);
332 (Some(parent), None) if is_inherent_impl_item => {
333 // We have a parent, but we don't know where they're
334 // defined yet. Wait for later to index this item.
335 self.orphan_impl_items.push((parent, item.clone()));
341 // Keep track of the fully qualified path for this item.
342 let pushed = match item.name {
343 Some(ref n) if !n.is_empty() => {
344 self.stack.push(n.to_string());
351 clean::StructItem(..)
352 | clean::EnumItem(..)
353 | clean::TypedefItem(..)
354 | clean::TraitItem(..)
355 | clean::FunctionItem(..)
356 | clean::ModuleItem(..)
357 | clean::ForeignFunctionItem(..)
358 | clean::ForeignStaticItem(..)
359 | clean::ConstantItem(..)
360 | clean::StaticItem(..)
361 | clean::UnionItem(..)
362 | clean::ForeignTypeItem
363 | clean::MacroItem(..)
364 | clean::ProcMacroItem(..)
365 | clean::VariantItem(..)
366 if !self.stripped_mod =>
368 // Re-exported items mean that the same id can show up twice
369 // in the rustdoc ast that we're looking at. We know,
370 // however, that a re-exported item doesn't show up in the
371 // `public_items` map, so we can skip inserting into the
372 // paths map if there was already an entry present and we're
373 // not a public item.
374 if !self.paths.contains_key(&item.def_id)
375 || self.access_levels.is_public(item.def_id)
377 self.paths.insert(item.def_id, (self.stack.clone(), item.type_()));
380 clean::PrimitiveItem(..) => {
381 self.paths.insert(item.def_id, (self.stack.clone(), item.type_()));
387 // Maintain the parent stack
388 let orig_parent_is_trait_impl = self.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.parent_stack.push(item.def_id);
397 self.parent_is_trait_impl = false;
400 clean::ImplItem(ref i) => {
401 self.parent_is_trait_impl = i.trait_.is_some();
403 clean::ResolvedPath { did, .. } => {
404 self.parent_stack.push(did);
410 .and_then(|t| self.primitive_locations.get(&t).cloned());
413 self.parent_stack.push(did);
424 // Once we've recursively found all the generics, hoard off all the
425 // implementations elsewhere.
426 let item = self.fold_item_recur(item);
427 let ret = if let clean::Item { kind: clean::ImplItem(_), .. } = item {
428 // Figure out the id of this impl. This may map to a
429 // primitive rather than always to a struct/enum.
430 // Note: matching twice to restrict the lifetime of the `i` borrow.
431 let mut dids = FxHashSet::default();
432 if let clean::Item { kind: clean::ImplItem(ref i), .. } = item {
434 clean::ResolvedPath { did, .. }
435 | clean::BorrowedRef { type_: box clean::ResolvedPath { did, .. }, .. } => {
441 .and_then(|t| self.primitive_locations.get(&t).cloned());
443 if let Some(did) = did {
449 if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
450 for bound in generics {
451 if let Some(did) = bound.def_id() {
459 let impl_item = Impl { impl_item: item };
460 if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
462 self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
465 let trait_did = impl_item.trait_did().expect("no trait did");
466 self.orphan_trait_impls.push((trait_did, dids, impl_item));
474 self.stack.pop().expect("stack already empty");
477 self.parent_stack.pop().expect("parent stack already empty");
479 self.stripped_mod = orig_stripped_mod;
480 self.parent_is_trait_impl = orig_parent_is_trait_impl;
485 crate fn cache() -> Arc<Cache> {
486 CACHE_KEY.with(|c| c.borrow().clone())