]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/formats/cache.rs
Rollup merge of #89255 - FabianWolff:issue-88806, r=cjgillot
[rust.git] / src / librustdoc / formats / cache.rs
1 use std::mem;
2
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;
8
9 use crate::clean::{self, GetDefId, 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;
17
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.
22 ///
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.
27 #[derive(Default)]
28 crate struct Cache {
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.
32     ///
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>>,
36
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
41     /// necessary.
42     crate paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
43
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)>,
47
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.
51     ///
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>>,
59
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>,
65
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>>,
70
71     /// Cache of where external crate documentation can be found.
72     crate extern_locations: FxHashMap<CrateNum, ExternalLocation>,
73
74     /// Cache of where documentation for primitives can be found.
75     crate primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
76
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>,
81
82     /// The version of the crate being documented, if given from the `--crate-version` flag.
83     crate crate_version: Option<String>,
84
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,
88
89     /// Crates marked with [`#[doc(masked)]`][doc_masked].
90     ///
91     /// [doc_masked]: https://doc.rust-lang.org/nightly/unstable-book/language-features/doc-masked.html
92     crate masked_crates: FxHashSet<CrateNum>,
93
94     // Private fields only used when initially crawling a crate to build a cache
95     stack: Vec<String>,
96     parent_stack: Vec<DefId>,
97     parent_is_trait_impl: bool,
98     stripped_mod: bool,
99
100     crate search_index: Vec<IndexItem>,
101
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)>,
108
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)>,
117
118     /// All intra-doc links resolved so far.
119     ///
120     /// Links are indexed by the DefId of the item they document.
121     crate intra_doc_links: FxHashMap<ItemId, Vec<clean::ItemLink>>,
122 }
123
124 /// This struct is used to wrap the `cache` and `tcx` in order to run `DocFolder`.
125 struct CacheBuilder<'a, 'tcx> {
126     cache: &'a mut Cache,
127     tcx: TyCtxt<'tcx>,
128 }
129
130 impl Cache {
131     crate fn new(access_levels: AccessLevels<DefId>, document_private: bool) -> Self {
132         Cache { access_levels, document_private, ..Cache::default() }
133     }
134
135     /// Populates the `Cache` with more data. The returned `Crate` will be missing some data that was
136     /// in `krate` due to the data being moved into the `Cache`.
137     crate fn populate(
138         &mut self,
139         mut krate: clean::Crate,
140         tcx: TyCtxt<'_>,
141         render_options: &RenderOptions,
142     ) -> clean::Crate {
143         // Crawl the crate to build various caches used for the output
144         debug!(?self.crate_version);
145         self.traits = krate.external_traits.take();
146         let RenderOptions { extern_html_root_takes_precedence, output: dst, .. } = render_options;
147
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 &e in &krate.externs {
151             let name = e.name(tcx);
152             let extern_url =
153                 render_options.extern_html_root_urls.get(&*name.as_str()).map(|u| &**u);
154             let location = e.location(extern_url, *extern_html_root_takes_precedence, dst, tcx);
155             self.extern_locations.insert(e.crate_num, location);
156             self.external_paths.insert(e.def_id(), (vec![name.to_string()], ItemType::Module));
157         }
158
159         // FIXME: avoid this clone (requires implementing Default manually)
160         self.primitive_locations = PrimitiveType::primitive_locations(tcx).clone();
161         for (prim, &def_id) in &self.primitive_locations {
162             let crate_name = tcx.crate_name(def_id.krate);
163             // Recall that we only allow primitive modules to be at the root-level of the crate.
164             // If that restriction is ever lifted, this will have to include the relative paths instead.
165             self.external_paths.insert(
166                 def_id,
167                 (vec![crate_name.to_string(), prim.as_sym().to_string()], ItemType::Primitive),
168             );
169         }
170
171         krate = CacheBuilder { tcx, cache: self }.fold_crate(krate);
172
173         for (trait_did, dids, impl_) in self.orphan_trait_impls.drain(..) {
174             if self.traits.contains_key(&trait_did) {
175                 for did in dids {
176                     self.impls.entry(did).or_default().push(impl_.clone());
177                 }
178             }
179         }
180
181         krate
182     }
183 }
184
185 impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> {
186     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
187         if item.def_id.is_local() {
188             debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
189         }
190
191         // If this is a stripped module,
192         // we don't want it or its children in the search index.
193         let orig_stripped_mod = match *item.kind {
194             clean::StrippedItem(box clean::ModuleItem(..)) => {
195                 mem::replace(&mut self.cache.stripped_mod, true)
196             }
197             _ => self.cache.stripped_mod,
198         };
199
200         // If the impl is from a masked crate or references something from a
201         // masked crate then remove it completely.
202         if let clean::ImplItem(ref i) = *item.kind {
203             if self.cache.masked_crates.contains(&item.def_id.krate())
204                 || i.trait_.def_id().map_or(false, |d| self.cache.masked_crates.contains(&d.krate))
205                 || i.for_.def_id().map_or(false, |d| self.cache.masked_crates.contains(&d.krate))
206             {
207                 return None;
208             }
209         }
210
211         // Propagate a trait method's documentation to all implementors of the
212         // trait.
213         if let clean::TraitItem(ref t) = *item.kind {
214             self.cache.traits.entry(item.def_id.expect_def_id()).or_insert_with(|| {
215                 clean::TraitWithExtraInfo {
216                     trait_: t.clone(),
217                     is_notable: item.attrs.has_doc_flag(sym::notable_trait),
218                 }
219             });
220         }
221
222         // Collect all the implementors of traits.
223         if let clean::ImplItem(ref i) = *item.kind {
224             if let Some(did) = i.trait_.def_id() {
225                 if i.blanket_impl.is_none() {
226                     self.cache
227                         .implementors
228                         .entry(did)
229                         .or_default()
230                         .push(Impl { impl_item: item.clone() });
231                 }
232             }
233         }
234
235         // Index this method for searching later on.
236         if let Some(ref s) = item.name {
237             let (parent, is_inherent_impl_item) = match *item.kind {
238                 clean::StrippedItem(..) => ((None, None), false),
239                 clean::AssocConstItem(..) | clean::TypedefItem(_, true)
240                     if self.cache.parent_is_trait_impl =>
241                 {
242                     // skip associated items in trait impls
243                     ((None, None), false)
244                 }
245                 clean::AssocTypeItem(..)
246                 | clean::TyMethodItem(..)
247                 | clean::StructFieldItem(..)
248                 | clean::VariantItem(..) => (
249                     (
250                         Some(*self.cache.parent_stack.last().expect("parent_stack is empty")),
251                         Some(&self.cache.stack[..self.cache.stack.len() - 1]),
252                     ),
253                     false,
254                 ),
255                 clean::MethodItem(..) | clean::AssocConstItem(..) => {
256                     if self.cache.parent_stack.is_empty() {
257                         ((None, None), false)
258                     } else {
259                         let last = self.cache.parent_stack.last().expect("parent_stack is empty 2");
260                         let did = *last;
261                         let path = match self.cache.paths.get(&did) {
262                             // The current stack not necessarily has correlation
263                             // for where the type was defined. On the other
264                             // hand, `paths` always has the right
265                             // information if present.
266                             Some(&(
267                                 ref fqp,
268                                 ItemType::Trait
269                                 | ItemType::Struct
270                                 | ItemType::Union
271                                 | ItemType::Enum,
272                             )) => Some(&fqp[..fqp.len() - 1]),
273                             Some(..) => Some(&*self.cache.stack),
274                             None => None,
275                         };
276                         ((Some(*last), path), true)
277                     }
278                 }
279                 _ => ((None, Some(&*self.cache.stack)), false),
280             };
281
282             match parent {
283                 (parent, Some(path)) if is_inherent_impl_item || !self.cache.stripped_mod => {
284                     debug_assert!(!item.is_stripped());
285
286                     // A crate has a module at its root, containing all items,
287                     // which should not be indexed. The crate-item itself is
288                     // inserted later on when serializing the search-index.
289                     if item.def_id.index().map_or(false, |idx| idx != CRATE_DEF_INDEX) {
290                         let desc = item.doc_value().map_or_else(String::new, |x| {
291                             short_markdown_summary(&x.as_str(), &item.link_names(&self.cache))
292                         });
293                         self.cache.search_index.push(IndexItem {
294                             ty: item.type_(),
295                             name: s.to_string(),
296                             path: path.join("::"),
297                             desc,
298                             parent,
299                             parent_idx: None,
300                             search_type: get_index_search_type(&item, self.tcx),
301                             aliases: item.attrs.get_doc_aliases(),
302                         });
303                     }
304                 }
305                 (Some(parent), None) if is_inherent_impl_item => {
306                     // We have a parent, but we don't know where they're
307                     // defined yet. Wait for later to index this item.
308                     self.cache.orphan_impl_items.push((parent, item.clone()));
309                 }
310                 _ => {}
311             }
312         }
313
314         // Keep track of the fully qualified path for this item.
315         let pushed = match item.name {
316             Some(n) if !n.is_empty() => {
317                 self.cache.stack.push(n.to_string());
318                 true
319             }
320             _ => false,
321         };
322
323         match *item.kind {
324             clean::StructItem(..)
325             | clean::EnumItem(..)
326             | clean::TypedefItem(..)
327             | clean::TraitItem(..)
328             | clean::TraitAliasItem(..)
329             | clean::FunctionItem(..)
330             | clean::ModuleItem(..)
331             | clean::ForeignFunctionItem(..)
332             | clean::ForeignStaticItem(..)
333             | clean::ConstantItem(..)
334             | clean::StaticItem(..)
335             | clean::UnionItem(..)
336             | clean::ForeignTypeItem
337             | clean::MacroItem(..)
338             | clean::ProcMacroItem(..)
339             | clean::VariantItem(..) => {
340                 if !self.cache.stripped_mod {
341                     // Re-exported items mean that the same id can show up twice
342                     // in the rustdoc ast that we're looking at. We know,
343                     // however, that a re-exported item doesn't show up in the
344                     // `public_items` map, so we can skip inserting into the
345                     // paths map if there was already an entry present and we're
346                     // not a public item.
347                     if !self.cache.paths.contains_key(&item.def_id.expect_def_id())
348                         || self.cache.access_levels.is_public(item.def_id.expect_def_id())
349                     {
350                         self.cache.paths.insert(
351                             item.def_id.expect_def_id(),
352                             (self.cache.stack.clone(), item.type_()),
353                         );
354                     }
355                 }
356             }
357             clean::PrimitiveItem(..) => {
358                 self.cache
359                     .paths
360                     .insert(item.def_id.expect_def_id(), (self.cache.stack.clone(), item.type_()));
361             }
362
363             clean::ExternCrateItem { .. }
364             | clean::ImportItem(..)
365             | clean::OpaqueTyItem(..)
366             | clean::ImplItem(..)
367             | clean::TyMethodItem(..)
368             | clean::MethodItem(..)
369             | clean::StructFieldItem(..)
370             | clean::AssocConstItem(..)
371             | clean::AssocTypeItem(..)
372             | clean::StrippedItem(..)
373             | clean::KeywordItem(..) => {
374                 // FIXME: Do these need handling?
375                 // The person writing this comment doesn't know.
376                 // So would rather leave them to an expert,
377                 // as at least the list is better than `_ => {}`.
378             }
379         }
380
381         // Maintain the parent stack
382         let orig_parent_is_trait_impl = self.cache.parent_is_trait_impl;
383         let parent_pushed = match *item.kind {
384             clean::TraitItem(..)
385             | clean::EnumItem(..)
386             | clean::ForeignTypeItem
387             | clean::StructItem(..)
388             | clean::UnionItem(..)
389             | clean::VariantItem(..) => {
390                 self.cache.parent_stack.push(item.def_id.expect_def_id());
391                 self.cache.parent_is_trait_impl = false;
392                 true
393             }
394             clean::ImplItem(ref i) => {
395                 self.cache.parent_is_trait_impl = i.trait_.is_some();
396                 match i.for_ {
397                     clean::ResolvedPath { did, .. } => {
398                         self.cache.parent_stack.push(did);
399                         true
400                     }
401                     clean::DynTrait(ref bounds, _)
402                     | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
403                         if let Some(did) = bounds[0].trait_.def_id() {
404                             self.cache.parent_stack.push(did);
405                             true
406                         } else {
407                             false
408                         }
409                     }
410                     ref t => {
411                         let prim_did = t
412                             .primitive_type()
413                             .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
414                         match prim_did {
415                             Some(did) => {
416                                 self.cache.parent_stack.push(did);
417                                 true
418                             }
419                             None => false,
420                         }
421                     }
422                 }
423             }
424             _ => false,
425         };
426
427         // Once we've recursively found all the generics, hoard off all the
428         // implementations elsewhere.
429         let item = self.fold_item_recur(item);
430         let ret = if let clean::Item { kind: box clean::ImplItem(ref i), .. } = item {
431             // Figure out the id of this impl. This may map to a
432             // primitive rather than always to a struct/enum.
433             // Note: matching twice to restrict the lifetime of the `i` borrow.
434             let mut dids = FxHashSet::default();
435             match i.for_ {
436                 clean::ResolvedPath { did, .. }
437                 | clean::BorrowedRef { type_: box clean::ResolvedPath { did, .. }, .. } => {
438                     dids.insert(did);
439                 }
440                 clean::DynTrait(ref bounds, _)
441                 | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
442                     if let Some(did) = bounds[0].trait_.def_id() {
443                         dids.insert(did);
444                     }
445                 }
446                 ref t => {
447                     let did = t
448                         .primitive_type()
449                         .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
450
451                     if let Some(did) = did {
452                         dids.insert(did);
453                     }
454                 }
455             }
456
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() {
460                         dids.insert(did);
461                     }
462                 }
463             }
464             let impl_item = Impl { impl_item: item };
465             if impl_item.trait_did().map_or(true, |d| self.cache.traits.contains_key(&d)) {
466                 for did in dids {
467                     self.cache.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
468                 }
469             } else {
470                 let trait_did = impl_item.trait_did().expect("no trait did");
471                 self.cache.orphan_trait_impls.push((trait_did, dids, impl_item));
472             }
473             None
474         } else {
475             Some(item)
476         };
477
478         if pushed {
479             self.cache.stack.pop().expect("stack already empty");
480         }
481         if parent_pushed {
482             self.cache.parent_stack.pop().expect("parent stack already empty");
483         }
484         self.cache.stripped_mod = orig_stripped_mod;
485         self.cache.parent_is_trait_impl = orig_parent_is_trait_impl;
486         ret
487     }
488 }