]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/formats/cache.rs
Merge commit '4f3ab69ea0a0908260944443c739426cc384ae1a' into clippyup
[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};
5 use rustc_middle::ty::{self, TyCtxt};
6 use rustc_span::Symbol;
7
8 use crate::clean::{self, types::ExternalLocation, ExternalCrate, ItemId, PrimitiveType};
9 use crate::core::DocContext;
10 use crate::fold::DocFolder;
11 use crate::formats::item_type::ItemType;
12 use crate::formats::Impl;
13 use crate::html::format::join_with_double_colon;
14 use crate::html::markdown::short_markdown_summary;
15 use crate::html::render::search_index::get_function_type_for_search;
16 use crate::html::render::IndexItem;
17 use crate::visit_lib::RustdocEffectiveVisibilities;
18
19 /// This cache is used to store information about the [`clean::Crate`] being
20 /// rendered in order to provide more useful documentation. This contains
21 /// information like all implementors of a trait, all traits a type implements,
22 /// documentation for all known traits, etc.
23 ///
24 /// This structure purposefully does not implement `Clone` because it's intended
25 /// to be a fairly large and expensive structure to clone. Instead this adheres
26 /// to `Send` so it may be stored in an `Arc` instance and shared among the various
27 /// rendering threads.
28 #[derive(Default)]
29 pub(crate) struct Cache {
30     /// Maps a type ID to all known implementations for that type. This is only
31     /// recognized for intra-crate [`clean::Type::Path`]s, and is used to print
32     /// out extra documentation on the page of an enum/struct.
33     ///
34     /// The values of the map are a list of implementations and documentation
35     /// found on that implementation.
36     pub(crate) impls: FxHashMap<DefId, Vec<Impl>>,
37
38     /// Maintains a mapping of local crate `DefId`s to the fully qualified name
39     /// and "short type description" of that node. This is used when generating
40     /// URLs when a type is being linked to. External paths are not located in
41     /// this map because the `External` type itself has all the information
42     /// necessary.
43     pub(crate) paths: FxHashMap<DefId, (Vec<Symbol>, ItemType)>,
44
45     /// Similar to `paths`, but only holds external paths. This is only used for
46     /// generating explicit hyperlinks to other crates.
47     pub(crate) external_paths: FxHashMap<DefId, (Vec<Symbol>, ItemType)>,
48
49     /// Maps local `DefId`s of exported types to fully qualified paths.
50     /// Unlike 'paths', this mapping ignores any renames that occur
51     /// due to 'use' statements.
52     ///
53     /// This map is used when writing out the special 'implementors'
54     /// javascript file. By using the exact path that the type
55     /// is declared with, we ensure that each path will be identical
56     /// to the path used if the corresponding type is inlined. By
57     /// doing this, we can detect duplicate impls on a trait page, and only display
58     /// the impl for the inlined type.
59     pub(crate) exact_paths: FxHashMap<DefId, Vec<Symbol>>,
60
61     /// This map contains information about all known traits of this crate.
62     /// Implementations of a crate should inherit the documentation of the
63     /// parent trait if no extra documentation is specified, and default methods
64     /// should show up in documentation about trait implementations.
65     pub(crate) traits: FxHashMap<DefId, clean::Trait>,
66
67     /// When rendering traits, it's often useful to be able to list all
68     /// implementors of the trait, and this mapping is exactly, that: a mapping
69     /// of trait ids to the list of known implementors of the trait
70     pub(crate) implementors: FxHashMap<DefId, Vec<Impl>>,
71
72     /// Cache of where external crate documentation can be found.
73     pub(crate) extern_locations: FxHashMap<CrateNum, ExternalLocation>,
74
75     /// Cache of where documentation for primitives can be found.
76     pub(crate) primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
77
78     // Note that external items for which `doc(hidden)` applies to are shown as
79     // non-reachable while local items aren't. This is because we're reusing
80     // the effective visibilities from the privacy check pass.
81     pub(crate) effective_visibilities: RustdocEffectiveVisibilities,
82
83     /// The version of the crate being documented, if given from the `--crate-version` flag.
84     pub(crate) crate_version: Option<String>,
85
86     /// Whether to document private items.
87     /// This is stored in `Cache` so it doesn't need to be passed through all rustdoc functions.
88     pub(crate) document_private: bool,
89
90     /// Crates marked with [`#[doc(masked)]`][doc_masked].
91     ///
92     /// [doc_masked]: https://doc.rust-lang.org/nightly/unstable-book/language-features/doc-masked.html
93     pub(crate) masked_crates: FxHashSet<CrateNum>,
94
95     // Private fields only used when initially crawling a crate to build a cache
96     stack: Vec<Symbol>,
97     parent_stack: Vec<ParentStackItem>,
98     stripped_mod: bool,
99
100     pub(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     pub(crate) orphan_impl_items: Vec<OrphanImplItem>,
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     pub(crate) intra_doc_links: FxHashMap<ItemId, Vec<clean::ItemLink>>,
122     /// Cfg that have been hidden via #![doc(cfg_hide(...))]
123     pub(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     /// This field is used to prevent duplicated impl blocks.
130     impl_ids: FxHashMap<DefId, FxHashSet<DefId>>,
131     tcx: TyCtxt<'tcx>,
132 }
133
134 impl Cache {
135     pub(crate) fn new(document_private: bool) -> Self {
136         Cache { document_private, ..Cache::default() }
137     }
138
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     pub(crate) fn populate(cx: &mut DocContext<'_>, mut krate: clean::Crate) -> clean::Crate {
142         let tcx = cx.tcx;
143
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();
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 &crate_num in cx.tcx.crates(()) {
151             let e = ExternalCrate { crate_num };
152
153             let name = e.name(tcx);
154             let render_options = &cx.render_options;
155             let extern_url = render_options.extern_html_root_urls.get(name.as_str()).map(|u| &**u);
156             let extern_url_takes_precedence = render_options.extern_html_root_takes_precedence;
157             let dst = &render_options.output;
158             let location = e.location(extern_url, extern_url_takes_precedence, dst, tcx);
159             cx.cache.extern_locations.insert(e.crate_num, location);
160             cx.cache.external_paths.insert(e.def_id(), (vec![name], ItemType::Module));
161         }
162
163         // FIXME: avoid this clone (requires implementing Default manually)
164         cx.cache.primitive_locations = PrimitiveType::primitive_locations(tcx).clone();
165         for (prim, &def_id) in &cx.cache.primitive_locations {
166             let crate_name = tcx.crate_name(def_id.krate);
167             // Recall that we only allow primitive modules to be at the root-level of the crate.
168             // If that restriction is ever lifted, this will have to include the relative paths instead.
169             cx.cache
170                 .external_paths
171                 .insert(def_id, (vec![crate_name, prim.as_sym()], ItemType::Primitive));
172         }
173
174         let (krate, mut impl_ids) = {
175             let mut cache_builder =
176                 CacheBuilder { tcx, cache: &mut cx.cache, impl_ids: FxHashMap::default() };
177             krate = cache_builder.fold_crate(krate);
178             (krate, cache_builder.impl_ids)
179         };
180
181         for (trait_did, dids, impl_) in cx.cache.orphan_trait_impls.drain(..) {
182             if cx.cache.traits.contains_key(&trait_did) {
183                 for did in dids {
184                     if impl_ids.entry(did).or_default().insert(impl_.def_id()) {
185                         cx.cache.impls.entry(did).or_default().push(impl_.clone());
186                     }
187                 }
188             }
189         }
190
191         krate
192     }
193 }
194
195 impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> {
196     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
197         if item.item_id.is_local() {
198             debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.item_id);
199         }
200
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)
206             }
207             _ => self.cache.stripped_mod,
208         };
209
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.item_id.krate())
214                 || i.trait_
215                     .as_ref()
216                     .map_or(false, |t| self.cache.masked_crates.contains(&t.def_id().krate))
217                 || i.for_
218                     .def_id(self.cache)
219                     .map_or(false, |d| self.cache.masked_crates.contains(&d.krate))
220             {
221                 return None;
222             }
223         }
224
225         // Propagate a trait method's documentation to all implementors of the
226         // trait.
227         if let clean::TraitItem(ref t) = *item.kind {
228             self.cache.traits.entry(item.item_id.expect_def_id()).or_insert_with(|| (**t).clone());
229         }
230
231         // Collect all the implementors of traits.
232         if let clean::ImplItem(ref i) = *item.kind {
233             if let Some(trait_) = &i.trait_ {
234                 if !i.kind.is_blanket() {
235                     self.cache
236                         .implementors
237                         .entry(trait_.def_id())
238                         .or_default()
239                         .push(Impl { impl_item: item.clone() });
240                 }
241             }
242         }
243
244         // Index this method for searching later on.
245         if let Some(ref s) = item.name.or_else(|| {
246             if item.is_stripped() {
247                 None
248             } else if let clean::ImportItem(ref i) = *item.kind &&
249                 let clean::ImportKind::Simple(s) = i.kind {
250                 Some(s)
251             } else {
252                 None
253             }
254         }) {
255             let (parent, is_inherent_impl_item) = match *item.kind {
256                 clean::StrippedItem(..) => ((None, None), false),
257                 clean::AssocConstItem(..) | clean::AssocTypeItem(..)
258                     if self
259                         .cache
260                         .parent_stack
261                         .last()
262                         .map_or(false, |parent| parent.is_trait_impl()) =>
263                 {
264                     // skip associated items in trait impls
265                     ((None, None), false)
266                 }
267                 clean::TyMethodItem(..)
268                 | clean::TyAssocConstItem(..)
269                 | clean::TyAssocTypeItem(..)
270                 | clean::StructFieldItem(..)
271                 | clean::VariantItem(..) => (
272                     (
273                         Some(
274                             self.cache
275                                 .parent_stack
276                                 .last()
277                                 .expect("parent_stack is empty")
278                                 .item_id()
279                                 .expect_def_id(),
280                         ),
281                         Some(&self.cache.stack[..self.cache.stack.len() - 1]),
282                     ),
283                     false,
284                 ),
285                 clean::MethodItem(..) | clean::AssocConstItem(..) | clean::AssocTypeItem(..) => {
286                     if self.cache.parent_stack.is_empty() {
287                         ((None, None), false)
288                     } else {
289                         let last = self.cache.parent_stack.last().expect("parent_stack is empty 2");
290                         let did = match &*last {
291                             ParentStackItem::Impl { for_, .. } => for_.def_id(&self.cache),
292                             ParentStackItem::Type(item_id) => item_id.as_def_id(),
293                         };
294                         let path = match did.and_then(|did| self.cache.paths.get(&did)) {
295                             // The current stack not necessarily has correlation
296                             // for where the type was defined. On the other
297                             // hand, `paths` always has the right
298                             // information if present.
299                             Some(&(ref fqp, _)) => Some(&fqp[..fqp.len() - 1]),
300                             None => None,
301                         };
302                         ((did, path), true)
303                     }
304                 }
305                 _ => ((None, Some(&*self.cache.stack)), false),
306             };
307
308             match parent {
309                 (parent, Some(path)) if is_inherent_impl_item || !self.cache.stripped_mod => {
310                     debug_assert!(!item.is_stripped());
311
312                     // A crate has a module at its root, containing all items,
313                     // which should not be indexed. The crate-item itself is
314                     // inserted later on when serializing the search-index.
315                     if item.item_id.as_def_id().map_or(false, |idx| !idx.is_crate_root()) {
316                         let desc = item.doc_value().map_or_else(String::new, |x| {
317                             short_markdown_summary(x.as_str(), &item.link_names(self.cache))
318                         });
319                         let ty = item.type_();
320                         let name = s.to_string();
321                         if ty != ItemType::StructField || u16::from_str_radix(&name, 10).is_err() {
322                             // In case this is a field from a tuple struct, we don't add it into
323                             // the search index because its name is something like "0", which is
324                             // not useful for rustdoc search.
325                             self.cache.search_index.push(IndexItem {
326                                 ty,
327                                 name,
328                                 path: join_with_double_colon(path),
329                                 desc,
330                                 parent,
331                                 parent_idx: None,
332                                 search_type: get_function_type_for_search(
333                                     &item,
334                                     self.tcx,
335                                     clean_impl_generics(self.cache.parent_stack.last()).as_ref(),
336                                     self.cache,
337                                 ),
338                                 aliases: item.attrs.get_doc_aliases(),
339                             });
340                         }
341                     }
342                 }
343                 (Some(parent), None) if is_inherent_impl_item => {
344                     // We have a parent, but we don't know where they're
345                     // defined yet. Wait for later to index this item.
346                     let impl_generics = clean_impl_generics(self.cache.parent_stack.last());
347                     self.cache.orphan_impl_items.push(OrphanImplItem {
348                         parent,
349                         item: item.clone(),
350                         impl_generics,
351                     });
352                 }
353                 _ => {}
354             }
355         }
356
357         // Keep track of the fully qualified path for this item.
358         let pushed = match item.name {
359             Some(n) if !n.is_empty() => {
360                 self.cache.stack.push(n);
361                 true
362             }
363             _ => false,
364         };
365
366         match *item.kind {
367             clean::StructItem(..)
368             | clean::EnumItem(..)
369             | clean::TypedefItem(..)
370             | clean::TraitItem(..)
371             | clean::TraitAliasItem(..)
372             | clean::FunctionItem(..)
373             | clean::ModuleItem(..)
374             | clean::ForeignFunctionItem(..)
375             | clean::ForeignStaticItem(..)
376             | clean::ConstantItem(..)
377             | clean::StaticItem(..)
378             | clean::UnionItem(..)
379             | clean::ForeignTypeItem
380             | clean::MacroItem(..)
381             | clean::ProcMacroItem(..)
382             | clean::VariantItem(..) => {
383                 if !self.cache.stripped_mod {
384                     // Re-exported items mean that the same id can show up twice
385                     // in the rustdoc ast that we're looking at. We know,
386                     // however, that a re-exported item doesn't show up in the
387                     // `public_items` map, so we can skip inserting into the
388                     // paths map if there was already an entry present and we're
389                     // not a public item.
390                     if !self.cache.paths.contains_key(&item.item_id.expect_def_id())
391                         || self
392                             .cache
393                             .effective_visibilities
394                             .is_directly_public(self.tcx, item.item_id.expect_def_id())
395                     {
396                         self.cache.paths.insert(
397                             item.item_id.expect_def_id(),
398                             (self.cache.stack.clone(), item.type_()),
399                         );
400                     }
401                 }
402             }
403             clean::PrimitiveItem(..) => {
404                 self.cache
405                     .paths
406                     .insert(item.item_id.expect_def_id(), (self.cache.stack.clone(), item.type_()));
407             }
408
409             clean::ExternCrateItem { .. }
410             | clean::ImportItem(..)
411             | clean::OpaqueTyItem(..)
412             | clean::ImplItem(..)
413             | clean::TyMethodItem(..)
414             | clean::MethodItem(..)
415             | clean::StructFieldItem(..)
416             | clean::TyAssocConstItem(..)
417             | clean::AssocConstItem(..)
418             | clean::TyAssocTypeItem(..)
419             | clean::AssocTypeItem(..)
420             | clean::StrippedItem(..)
421             | clean::KeywordItem => {
422                 // FIXME: Do these need handling?
423                 // The person writing this comment doesn't know.
424                 // So would rather leave them to an expert,
425                 // as at least the list is better than `_ => {}`.
426             }
427         }
428
429         // Maintain the parent stack.
430         let (item, parent_pushed) = match *item.kind {
431             clean::TraitItem(..)
432             | clean::EnumItem(..)
433             | clean::ForeignTypeItem
434             | clean::StructItem(..)
435             | clean::UnionItem(..)
436             | clean::VariantItem(..)
437             | clean::ImplItem(..) => {
438                 self.cache.parent_stack.push(ParentStackItem::new(&item));
439                 (self.fold_item_recur(item), true)
440             }
441             _ => (self.fold_item_recur(item), false),
442         };
443
444         // Once we've recursively found all the generics, hoard off all the
445         // implementations elsewhere.
446         let ret = if let clean::Item { kind: box clean::ImplItem(ref i), .. } = item {
447             // Figure out the id of this impl. This may map to a
448             // primitive rather than always to a struct/enum.
449             // Note: matching twice to restrict the lifetime of the `i` borrow.
450             let mut dids = FxHashSet::default();
451             match i.for_ {
452                 clean::Type::Path { ref path }
453                 | clean::BorrowedRef { type_: box clean::Type::Path { ref path }, .. } => {
454                     dids.insert(path.def_id());
455                     if let Some(generics) = path.generics() &&
456                         let ty::Adt(adt, _) = self.tcx.type_of(path.def_id()).kind() &&
457                         adt.is_fundamental() {
458                         for ty in generics {
459                             if let Some(did) = ty.def_id(self.cache) {
460                                 dids.insert(did);
461                             }
462                         }
463                     }
464                 }
465                 clean::DynTrait(ref bounds, _)
466                 | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
467                     dids.insert(bounds[0].trait_.def_id());
468                 }
469                 ref t => {
470                     let did = t
471                         .primitive_type()
472                         .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
473
474                     if let Some(did) = did {
475                         dids.insert(did);
476                     }
477                 }
478             }
479
480             if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
481                 for bound in generics {
482                     if let Some(did) = bound.def_id(self.cache) {
483                         dids.insert(did);
484                     }
485                 }
486             }
487             let impl_item = Impl { impl_item: item };
488             if impl_item.trait_did().map_or(true, |d| self.cache.traits.contains_key(&d)) {
489                 for did in dids {
490                     if self.impl_ids.entry(did).or_default().insert(impl_item.def_id()) {
491                         self.cache
492                             .impls
493                             .entry(did)
494                             .or_insert_with(Vec::new)
495                             .push(impl_item.clone());
496                     }
497                 }
498             } else {
499                 let trait_did = impl_item.trait_did().expect("no trait did");
500                 self.cache.orphan_trait_impls.push((trait_did, dids, impl_item));
501             }
502             None
503         } else {
504             Some(item)
505         };
506
507         if pushed {
508             self.cache.stack.pop().expect("stack already empty");
509         }
510         if parent_pushed {
511             self.cache.parent_stack.pop().expect("parent stack already empty");
512         }
513         self.cache.stripped_mod = orig_stripped_mod;
514         ret
515     }
516 }
517
518 pub(crate) struct OrphanImplItem {
519     pub(crate) parent: DefId,
520     pub(crate) item: clean::Item,
521     pub(crate) impl_generics: Option<(clean::Type, clean::Generics)>,
522 }
523
524 /// Information about trait and type parents is tracked while traversing the item tree to build
525 /// the cache.
526 ///
527 /// We don't just store `Item` in there, because `Item` contains the list of children being
528 /// traversed and it would be wasteful to clone all that. We also need the item id, so just
529 /// storing `ItemKind` won't work, either.
530 enum ParentStackItem {
531     Impl {
532         for_: clean::Type,
533         trait_: Option<clean::Path>,
534         generics: clean::Generics,
535         kind: clean::ImplKind,
536         item_id: ItemId,
537     },
538     Type(ItemId),
539 }
540
541 impl ParentStackItem {
542     fn new(item: &clean::Item) -> Self {
543         match &*item.kind {
544             clean::ItemKind::ImplItem(box clean::Impl { for_, trait_, generics, kind, .. }) => {
545                 ParentStackItem::Impl {
546                     for_: for_.clone(),
547                     trait_: trait_.clone(),
548                     generics: generics.clone(),
549                     kind: kind.clone(),
550                     item_id: item.item_id,
551                 }
552             }
553             _ => ParentStackItem::Type(item.item_id),
554         }
555     }
556     fn is_trait_impl(&self) -> bool {
557         matches!(self, ParentStackItem::Impl { trait_: Some(..), .. })
558     }
559     fn item_id(&self) -> ItemId {
560         match self {
561             ParentStackItem::Impl { item_id, .. } => *item_id,
562             ParentStackItem::Type(item_id) => *item_id,
563         }
564     }
565 }
566
567 fn clean_impl_generics(item: Option<&ParentStackItem>) -> Option<(clean::Type, clean::Generics)> {
568     if let Some(ParentStackItem::Impl { for_, generics, kind: clean::ImplKind::Normal, .. }) = item
569     {
570         Some((for_.clone(), generics.clone()))
571     } else {
572         None
573     }
574 }