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