rustdoc/formats/
cache.rs

1use std::mem;
2
3use rustc_attr_parsing::StabilityLevel;
4use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
5use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet};
6use rustc_middle::ty::{self, TyCtxt};
7use rustc_span::Symbol;
8use tracing::debug;
9
10use crate::clean::types::ExternalLocation;
11use crate::clean::{self, ExternalCrate, ItemId, PrimitiveType};
12use crate::core::DocContext;
13use crate::fold::DocFolder;
14use crate::formats::Impl;
15use crate::formats::item_type::ItemType;
16use crate::html::format::join_with_double_colon;
17use crate::html::markdown::short_markdown_summary;
18use crate::html::render::IndexItem;
19use crate::html::render::search_index::get_function_type_for_search;
20use crate::visit_lib::RustdocEffectiveVisibilities;
21
22/// This cache is used to store information about the [`clean::Crate`] being
23/// rendered in order to provide more useful documentation. This contains
24/// information like all implementors of a trait, all traits a type implements,
25/// documentation for all known traits, etc.
26///
27/// This structure purposefully does not implement `Clone` because it's intended
28/// to be a fairly large and expensive structure to clone. Instead this adheres
29/// to `Send` so it may be stored in an `Arc` instance and shared among the various
30/// rendering threads.
31#[derive(Default)]
32pub(crate) struct Cache {
33    /// Maps a type ID to all known implementations for that type. This is only
34    /// recognized for intra-crate [`clean::Type::Path`]s, and is used to print
35    /// out extra documentation on the page of an enum/struct.
36    ///
37    /// The values of the map are a list of implementations and documentation
38    /// found on that implementation.
39    pub(crate) impls: DefIdMap<Vec<Impl>>,
40
41    /// Maintains a mapping of local crate `DefId`s to the fully qualified name
42    /// and "short type description" of that node. This is used when generating
43    /// URLs when a type is being linked to. External paths are not located in
44    /// this map because the `External` type itself has all the information
45    /// necessary.
46    pub(crate) paths: FxIndexMap<DefId, (Vec<Symbol>, ItemType)>,
47
48    /// Similar to `paths`, but only holds external paths. This is only used for
49    /// generating explicit hyperlinks to other crates.
50    pub(crate) external_paths: FxHashMap<DefId, (Vec<Symbol>, ItemType)>,
51
52    /// Maps local `DefId`s of exported types to fully qualified paths.
53    /// Unlike 'paths', this mapping ignores any renames that occur
54    /// due to 'use' statements.
55    ///
56    /// This map is used when writing out the `impl.trait` and `impl.type`
57    /// javascript files. By using the exact path that the type
58    /// is declared with, we ensure that each path will be identical
59    /// to the path used if the corresponding type is inlined. By
60    /// doing this, we can detect duplicate impls on a trait page, and only display
61    /// the impl for the inlined type.
62    pub(crate) exact_paths: DefIdMap<Vec<Symbol>>,
63
64    /// This map contains information about all known traits of this crate.
65    /// Implementations of a crate should inherit the documentation of the
66    /// parent trait if no extra documentation is specified, and default methods
67    /// should show up in documentation about trait implementations.
68    pub(crate) traits: FxIndexMap<DefId, clean::Trait>,
69
70    /// When rendering traits, it's often useful to be able to list all
71    /// implementors of the trait, and this mapping is exactly, that: a mapping
72    /// of trait ids to the list of known implementors of the trait
73    pub(crate) implementors: FxIndexMap<DefId, Vec<Impl>>,
74
75    /// Cache of where external crate documentation can be found.
76    pub(crate) extern_locations: FxIndexMap<CrateNum, ExternalLocation>,
77
78    /// Cache of where documentation for primitives can be found.
79    pub(crate) primitive_locations: FxIndexMap<clean::PrimitiveType, DefId>,
80
81    // Note that external items for which `doc(hidden)` applies to are shown as
82    // non-reachable while local items aren't. This is because we're reusing
83    // the effective visibilities from the privacy check pass.
84    pub(crate) effective_visibilities: RustdocEffectiveVisibilities,
85
86    /// The version of the crate being documented, if given from the `--crate-version` flag.
87    pub(crate) crate_version: Option<String>,
88
89    /// Whether to document private items.
90    /// This is stored in `Cache` so it doesn't need to be passed through all rustdoc functions.
91    pub(crate) document_private: bool,
92    /// Whether to document hidden items.
93    /// This is stored in `Cache` so it doesn't need to be passed through all rustdoc functions.
94    pub(crate) document_hidden: bool,
95
96    /// Crates marked with [`#[doc(masked)]`][doc_masked].
97    ///
98    /// [doc_masked]: https://doc.rust-lang.org/nightly/unstable-book/language-features/doc-masked.html
99    pub(crate) masked_crates: FxHashSet<CrateNum>,
100
101    // Private fields only used when initially crawling a crate to build a cache
102    stack: Vec<Symbol>,
103    parent_stack: Vec<ParentStackItem>,
104    stripped_mod: bool,
105
106    pub(crate) search_index: Vec<IndexItem>,
107
108    // In rare case where a structure is defined in one module but implemented
109    // in another, if the implementing module is parsed before defining module,
110    // then the fully qualified name of the structure isn't presented in `paths`
111    // yet when its implementation methods are being indexed. Caches such methods
112    // and their parent id here and indexes them at the end of crate parsing.
113    pub(crate) orphan_impl_items: Vec<OrphanImplItem>,
114
115    // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
116    // even though the trait itself is not exported. This can happen if a trait
117    // was defined in function/expression scope, since the impl will be picked
118    // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
119    // crawl. In order to prevent crashes when looking for notable traits or
120    // when gathering trait documentation on a type, hold impls here while
121    // folding and add them to the cache later on if we find the trait.
122    orphan_trait_impls: Vec<(DefId, FxIndexSet<DefId>, Impl)>,
123
124    /// All intra-doc links resolved so far.
125    ///
126    /// Links are indexed by the DefId of the item they document.
127    pub(crate) intra_doc_links: FxHashMap<ItemId, FxIndexSet<clean::ItemLink>>,
128    /// Cfg that have been hidden via #![doc(cfg_hide(...))]
129    pub(crate) hidden_cfg: FxHashSet<clean::cfg::Cfg>,
130
131    /// Contains the list of `DefId`s which have been inlined. It is used when generating files
132    /// to check if a stripped item should get its file generated or not: if it's inside a
133    /// `#[doc(hidden)]` item or a private one and not inlined, it shouldn't get a file.
134    pub(crate) inlined_items: DefIdSet,
135}
136
137/// This struct is used to wrap the `cache` and `tcx` in order to run `DocFolder`.
138struct CacheBuilder<'a, 'tcx> {
139    cache: &'a mut Cache,
140    /// This field is used to prevent duplicated impl blocks.
141    impl_ids: DefIdMap<DefIdSet>,
142    tcx: TyCtxt<'tcx>,
143    is_json_output: bool,
144}
145
146impl Cache {
147    pub(crate) fn new(document_private: bool, document_hidden: bool) -> Self {
148        Cache { document_private, document_hidden, ..Cache::default() }
149    }
150
151    /// Populates the `Cache` with more data. The returned `Crate` will be missing some data that was
152    /// in `krate` due to the data being moved into the `Cache`.
153    pub(crate) fn populate(cx: &mut DocContext<'_>, mut krate: clean::Crate) -> clean::Crate {
154        let tcx = cx.tcx;
155
156        // Crawl the crate to build various caches used for the output
157        debug!(?cx.cache.crate_version);
158        assert!(cx.external_traits.is_empty());
159        cx.cache.traits = mem::take(&mut krate.external_traits);
160
161        // Cache where all our extern crates are located
162        // FIXME: this part is specific to HTML so it'd be nice to remove it from the common code
163        for &crate_num in tcx.crates(()) {
164            let e = ExternalCrate { crate_num };
165
166            let name = e.name(tcx);
167            let render_options = &cx.render_options;
168            let extern_url = render_options.extern_html_root_urls.get(name.as_str()).map(|u| &**u);
169            let extern_url_takes_precedence = render_options.extern_html_root_takes_precedence;
170            let dst = &render_options.output;
171            let location = e.location(extern_url, extern_url_takes_precedence, dst, tcx);
172            cx.cache.extern_locations.insert(e.crate_num, location);
173            cx.cache.external_paths.insert(e.def_id(), (vec![name], ItemType::Module));
174        }
175
176        // FIXME: avoid this clone (requires implementing Default manually)
177        cx.cache.primitive_locations = PrimitiveType::primitive_locations(tcx).clone();
178        for (prim, &def_id) in &cx.cache.primitive_locations {
179            let crate_name = tcx.crate_name(def_id.krate);
180            // Recall that we only allow primitive modules to be at the root-level of the crate.
181            // If that restriction is ever lifted, this will have to include the relative paths instead.
182            cx.cache
183                .external_paths
184                .insert(def_id, (vec![crate_name, prim.as_sym()], ItemType::Primitive));
185        }
186
187        let (krate, mut impl_ids) = {
188            let is_json_output = cx.is_json_output();
189            let mut cache_builder = CacheBuilder {
190                tcx,
191                cache: &mut cx.cache,
192                impl_ids: Default::default(),
193                is_json_output,
194            };
195            krate = cache_builder.fold_crate(krate);
196            (krate, cache_builder.impl_ids)
197        };
198
199        for (trait_did, dids, impl_) in cx.cache.orphan_trait_impls.drain(..) {
200            if cx.cache.traits.contains_key(&trait_did) {
201                for did in dids {
202                    if impl_ids.entry(did).or_default().insert(impl_.def_id()) {
203                        cx.cache.impls.entry(did).or_default().push(impl_.clone());
204                    }
205                }
206            }
207        }
208
209        krate
210    }
211}
212
213impl DocFolder for CacheBuilder<'_, '_> {
214    fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
215        if item.item_id.is_local() {
216            debug!(
217                "folding {} (stripped: {:?}) \"{:?}\", id {:?}",
218                item.type_(),
219                item.is_stripped(),
220                item.name,
221                item.item_id
222            );
223        }
224
225        // If this is a stripped module,
226        // we don't want it or its children in the search index.
227        let orig_stripped_mod = match item.kind {
228            clean::StrippedItem(box clean::ModuleItem(..)) => {
229                mem::replace(&mut self.cache.stripped_mod, true)
230            }
231            _ => self.cache.stripped_mod,
232        };
233
234        #[inline]
235        fn is_from_private_dep(tcx: TyCtxt<'_>, cache: &Cache, def_id: DefId) -> bool {
236            let krate = def_id.krate;
237
238            cache.masked_crates.contains(&krate) || tcx.is_private_dep(krate)
239        }
240
241        // If the impl is from a masked crate or references something from a
242        // masked crate then remove it completely.
243        if let clean::ImplItem(ref i) = item.kind
244            && (self.cache.masked_crates.contains(&item.item_id.krate())
245                || i.trait_
246                    .as_ref()
247                    .is_some_and(|t| is_from_private_dep(self.tcx, self.cache, t.def_id()))
248                || i.for_
249                    .def_id(self.cache)
250                    .is_some_and(|d| is_from_private_dep(self.tcx, self.cache, d)))
251        {
252            return None;
253        }
254
255        // Propagate a trait method's documentation to all implementors of the
256        // trait.
257        if let clean::TraitItem(ref t) = item.kind {
258            self.cache.traits.entry(item.item_id.expect_def_id()).or_insert_with(|| (**t).clone());
259        } else if let clean::ImplItem(ref i) = item.kind
260            && let Some(trait_) = &i.trait_
261            && !i.kind.is_blanket()
262        {
263            // Collect all the implementors of traits.
264            self.cache
265                .implementors
266                .entry(trait_.def_id())
267                .or_default()
268                .push(Impl { impl_item: item.clone() });
269        }
270
271        // Index this method for searching later on.
272        let search_name = if !item.is_stripped() {
273            item.name.or_else(|| {
274                if let clean::ImportItem(ref i) = item.kind
275                    && let clean::ImportKind::Simple(s) = i.kind
276                {
277                    Some(s)
278                } else {
279                    None
280                }
281            })
282        } else {
283            None
284        };
285        if let Some(name) = search_name {
286            add_item_to_search_index(self.tcx, self.cache, &item, name)
287        }
288
289        // Keep track of the fully qualified path for this item.
290        let pushed = match item.name {
291            Some(n) if !n.is_empty() => {
292                self.cache.stack.push(n);
293                true
294            }
295            _ => false,
296        };
297
298        match item.kind {
299            clean::StructItem(..)
300            | clean::EnumItem(..)
301            | clean::TypeAliasItem(..)
302            | clean::TraitItem(..)
303            | clean::TraitAliasItem(..)
304            | clean::FunctionItem(..)
305            | clean::ModuleItem(..)
306            | clean::ForeignFunctionItem(..)
307            | clean::ForeignStaticItem(..)
308            | clean::ConstantItem(..)
309            | clean::StaticItem(..)
310            | clean::UnionItem(..)
311            | clean::ForeignTypeItem
312            | clean::MacroItem(..)
313            | clean::ProcMacroItem(..)
314            | clean::VariantItem(..) => {
315                use rustc_data_structures::fx::IndexEntry as Entry;
316
317                let skip_because_unstable = matches!(
318                    item.stability.map(|stab| stab.level),
319                    Some(StabilityLevel::Stable { allowed_through_unstable_modules: Some(_), .. })
320                );
321
322                if (!self.cache.stripped_mod && !skip_because_unstable) || self.is_json_output {
323                    // Re-exported items mean that the same id can show up twice
324                    // in the rustdoc ast that we're looking at. We know,
325                    // however, that a re-exported item doesn't show up in the
326                    // `public_items` map, so we can skip inserting into the
327                    // paths map if there was already an entry present and we're
328                    // not a public item.
329                    let item_def_id = item.item_id.expect_def_id();
330                    match self.cache.paths.entry(item_def_id) {
331                        Entry::Vacant(entry) => {
332                            entry.insert((self.cache.stack.clone(), item.type_()));
333                        }
334                        Entry::Occupied(mut entry) => {
335                            if entry.get().0.len() > self.cache.stack.len() {
336                                entry.insert((self.cache.stack.clone(), item.type_()));
337                            }
338                        }
339                    }
340                }
341            }
342            clean::PrimitiveItem(..) => {
343                self.cache
344                    .paths
345                    .insert(item.item_id.expect_def_id(), (self.cache.stack.clone(), item.type_()));
346            }
347
348            clean::ExternCrateItem { .. }
349            | clean::ImportItem(..)
350            | clean::ImplItem(..)
351            | clean::RequiredMethodItem(..)
352            | clean::MethodItem(..)
353            | clean::StructFieldItem(..)
354            | clean::RequiredAssocConstItem(..)
355            | clean::ProvidedAssocConstItem(..)
356            | clean::ImplAssocConstItem(..)
357            | clean::RequiredAssocTypeItem(..)
358            | clean::AssocTypeItem(..)
359            | clean::StrippedItem(..)
360            | clean::KeywordItem => {
361                // FIXME: Do these need handling?
362                // The person writing this comment doesn't know.
363                // So would rather leave them to an expert,
364                // as at least the list is better than `_ => {}`.
365            }
366        }
367
368        // Maintain the parent stack.
369        let (item, parent_pushed) = match item.kind {
370            clean::TraitItem(..)
371            | clean::EnumItem(..)
372            | clean::ForeignTypeItem
373            | clean::StructItem(..)
374            | clean::UnionItem(..)
375            | clean::VariantItem(..)
376            | clean::TypeAliasItem(..)
377            | clean::ImplItem(..) => {
378                self.cache.parent_stack.push(ParentStackItem::new(&item));
379                (self.fold_item_recur(item), true)
380            }
381            _ => (self.fold_item_recur(item), false),
382        };
383
384        // Once we've recursively found all the generics, hoard off all the
385        // implementations elsewhere.
386        let ret = if let clean::Item {
387            inner: box clean::ItemInner { kind: clean::ImplItem(ref i), .. },
388            ..
389        } = item
390        {
391            // Figure out the id of this impl. This may map to a
392            // primitive rather than always to a struct/enum.
393            // Note: matching twice to restrict the lifetime of the `i` borrow.
394            let mut dids = FxIndexSet::default();
395            match i.for_ {
396                clean::Type::Path { ref path }
397                | clean::BorrowedRef { type_: box clean::Type::Path { ref path }, .. } => {
398                    dids.insert(path.def_id());
399                    if let Some(generics) = path.generics()
400                        && let ty::Adt(adt, _) =
401                            self.tcx.type_of(path.def_id()).instantiate_identity().kind()
402                        && adt.is_fundamental()
403                    {
404                        for ty in generics {
405                            dids.extend(ty.def_id(self.cache));
406                        }
407                    }
408                }
409                clean::DynTrait(ref bounds, _)
410                | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
411                    dids.insert(bounds[0].trait_.def_id());
412                }
413                ref t => {
414                    let did = t
415                        .primitive_type()
416                        .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
417
418                    dids.extend(did);
419                }
420            }
421
422            if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
423                for bound in generics {
424                    dids.extend(bound.def_id(self.cache));
425                }
426            }
427            let impl_item = Impl { impl_item: item };
428            let impl_did = impl_item.def_id();
429            let trait_did = impl_item.trait_did();
430            if trait_did.is_none_or(|d| self.cache.traits.contains_key(&d)) {
431                for did in dids {
432                    if self.impl_ids.entry(did).or_default().insert(impl_did) {
433                        self.cache.impls.entry(did).or_default().push(impl_item.clone());
434                    }
435                }
436            } else {
437                let trait_did = trait_did.expect("no trait did");
438                self.cache.orphan_trait_impls.push((trait_did, dids, impl_item));
439            }
440            None
441        } else {
442            Some(item)
443        };
444
445        if pushed {
446            self.cache.stack.pop().expect("stack already empty");
447        }
448        if parent_pushed {
449            self.cache.parent_stack.pop().expect("parent stack already empty");
450        }
451        self.cache.stripped_mod = orig_stripped_mod;
452        ret
453    }
454}
455
456fn add_item_to_search_index(tcx: TyCtxt<'_>, cache: &mut Cache, item: &clean::Item, name: Symbol) {
457    // Item has a name, so it must also have a DefId (can't be an impl, let alone a blanket or auto impl).
458    let item_def_id = item.item_id.as_def_id().unwrap();
459    let (parent_did, parent_path) = match item.kind {
460        clean::StrippedItem(..) => return,
461        clean::ProvidedAssocConstItem(..)
462        | clean::ImplAssocConstItem(..)
463        | clean::AssocTypeItem(..)
464            if cache.parent_stack.last().is_some_and(|parent| parent.is_trait_impl()) =>
465        {
466            // skip associated items in trait impls
467            return;
468        }
469        clean::RequiredMethodItem(..)
470        | clean::RequiredAssocConstItem(..)
471        | clean::RequiredAssocTypeItem(..)
472        | clean::StructFieldItem(..)
473        | clean::VariantItem(..) => {
474            // Don't index if containing module is stripped (i.e., private),
475            // or if item is tuple struct/variant field (name is a number -> not useful for search).
476            if cache.stripped_mod
477                || item.type_() == ItemType::StructField
478                    && name.as_str().chars().all(|c| c.is_ascii_digit())
479            {
480                return;
481            }
482            let parent_did =
483                cache.parent_stack.last().expect("parent_stack is empty").item_id().expect_def_id();
484            let parent_path = &cache.stack[..cache.stack.len() - 1];
485            (Some(parent_did), parent_path)
486        }
487        clean::MethodItem(..)
488        | clean::ProvidedAssocConstItem(..)
489        | clean::ImplAssocConstItem(..)
490        | clean::AssocTypeItem(..) => {
491            let last = cache.parent_stack.last().expect("parent_stack is empty 2");
492            let parent_did = match last {
493                // impl Trait for &T { fn method(self); }
494                //
495                // When generating a function index with the above shape, we want it
496                // associated with `T`, not with the primitive reference type. It should
497                // show up as `T::method`, rather than `reference::method`, in the search
498                // results page.
499                ParentStackItem::Impl { for_: clean::Type::BorrowedRef { type_, .. }, .. } => {
500                    type_.def_id(cache)
501                }
502                ParentStackItem::Impl { for_, .. } => for_.def_id(cache),
503                ParentStackItem::Type(item_id) => item_id.as_def_id(),
504            };
505            let Some(parent_did) = parent_did else { return };
506            // The current stack reflects the CacheBuilder's recursive
507            // walk over HIR. For associated items, this is the module
508            // where the `impl` block is defined. That's an implementation
509            // detail that we don't want to affect the search engine.
510            //
511            // In particular, you can arrange things like this:
512            //
513            //     #![crate_name="me"]
514            //     mod private_mod {
515            //         impl Clone for MyThing { fn clone(&self) -> MyThing { MyThing } }
516            //     }
517            //     pub struct MyThing;
518            //
519            // When that happens, we need to:
520            // - ignore the `cache.stripped_mod` flag, since the Clone impl is actually
521            //   part of the public API even though it's defined in a private module
522            // - present the method as `me::MyThing::clone`, its publicly-visible path
523            // - deal with the fact that the recursive walk hasn't actually reached `MyThing`
524            //   until it's already past `private_mod`, since that's first, and doesn't know
525            //   yet if `MyThing` will actually be public or not (it could be re-exported)
526            //
527            // We accomplish the last two points by recording children of "orphan impls"
528            // in a field of the cache whose elements are added to the search index later,
529            // after cache building is complete (see `handle_orphan_impl_child`).
530            match cache.paths.get(&parent_did) {
531                Some((fqp, _)) => (Some(parent_did), &fqp[..fqp.len() - 1]),
532                None => {
533                    handle_orphan_impl_child(cache, item, parent_did);
534                    return;
535                }
536            }
537        }
538        _ => {
539            // Don't index if item is crate root, which is inserted later on when serializing the index.
540            // Don't index if containing module is stripped (i.e., private),
541            if item_def_id.is_crate_root() || cache.stripped_mod {
542                return;
543            }
544            (None, &*cache.stack)
545        }
546    };
547
548    debug_assert!(!item.is_stripped());
549
550    let desc = short_markdown_summary(&item.doc_value(), &item.link_names(cache));
551    // For searching purposes, a re-export is a duplicate if:
552    //
553    // - It's either an inline, or a true re-export
554    // - It's got the same name
555    // - Both of them have the same exact path
556    let defid = match &item.kind {
557        clean::ItemKind::ImportItem(import) => import.source.did.unwrap_or(item_def_id),
558        _ => item_def_id,
559    };
560    let path = join_with_double_colon(parent_path);
561    let impl_id = if let Some(ParentStackItem::Impl { item_id, .. }) = cache.parent_stack.last() {
562        item_id.as_def_id()
563    } else {
564        None
565    };
566    let search_type = get_function_type_for_search(
567        item,
568        tcx,
569        clean_impl_generics(cache.parent_stack.last()).as_ref(),
570        parent_did,
571        cache,
572    );
573    let aliases = item.attrs.get_doc_aliases();
574    let deprecation = item.deprecation(tcx);
575    let index_item = IndexItem {
576        ty: item.type_(),
577        defid: Some(defid),
578        name,
579        path,
580        desc,
581        parent: parent_did,
582        parent_idx: None,
583        exact_path: None,
584        impl_id,
585        search_type,
586        aliases,
587        deprecation,
588    };
589    cache.search_index.push(index_item);
590}
591
592/// We have a parent, but we don't know where they're
593/// defined yet. Wait for later to index this item.
594/// See [`Cache::orphan_impl_items`].
595fn handle_orphan_impl_child(cache: &mut Cache, item: &clean::Item, parent_did: DefId) {
596    let impl_generics = clean_impl_generics(cache.parent_stack.last());
597    let impl_id = if let Some(ParentStackItem::Impl { item_id, .. }) = cache.parent_stack.last() {
598        item_id.as_def_id()
599    } else {
600        None
601    };
602    let orphan_item =
603        OrphanImplItem { parent: parent_did, item: item.clone(), impl_generics, impl_id };
604    cache.orphan_impl_items.push(orphan_item);
605}
606
607pub(crate) struct OrphanImplItem {
608    pub(crate) parent: DefId,
609    pub(crate) impl_id: Option<DefId>,
610    pub(crate) item: clean::Item,
611    pub(crate) impl_generics: Option<(clean::Type, clean::Generics)>,
612}
613
614/// Information about trait and type parents is tracked while traversing the item tree to build
615/// the cache.
616///
617/// We don't just store `Item` in there, because `Item` contains the list of children being
618/// traversed and it would be wasteful to clone all that. We also need the item id, so just
619/// storing `ItemKind` won't work, either.
620enum ParentStackItem {
621    Impl {
622        for_: clean::Type,
623        trait_: Option<clean::Path>,
624        generics: clean::Generics,
625        kind: clean::ImplKind,
626        item_id: ItemId,
627    },
628    Type(ItemId),
629}
630
631impl ParentStackItem {
632    fn new(item: &clean::Item) -> Self {
633        match &item.kind {
634            clean::ItemKind::ImplItem(box clean::Impl { for_, trait_, generics, kind, .. }) => {
635                ParentStackItem::Impl {
636                    for_: for_.clone(),
637                    trait_: trait_.clone(),
638                    generics: generics.clone(),
639                    kind: kind.clone(),
640                    item_id: item.item_id,
641                }
642            }
643            _ => ParentStackItem::Type(item.item_id),
644        }
645    }
646    fn is_trait_impl(&self) -> bool {
647        matches!(self, ParentStackItem::Impl { trait_: Some(..), .. })
648    }
649    fn item_id(&self) -> ItemId {
650        match self {
651            ParentStackItem::Impl { item_id, .. } => *item_id,
652            ParentStackItem::Type(item_id) => *item_id,
653        }
654    }
655}
656
657fn clean_impl_generics(item: Option<&ParentStackItem>) -> Option<(clean::Type, clean::Generics)> {
658    if let Some(ParentStackItem::Impl { for_, generics, kind: clean::ImplKind::Normal, .. }) = item
659    {
660        Some((for_.clone(), generics.clone()))
661    } else {
662        None
663    }
664}