rustdoc/formats/
cache.rs

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