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::core::DocContext;
14use crate::fold::DocFolder;
15use crate::formats::Impl;
16use crate::formats::item_type::ItemType;
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: FxIndexMap<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        let render_options = &cx.render_options;
162        let extern_url_takes_precedence = render_options.extern_html_root_takes_precedence;
163        let dst = &render_options.output;
164
165        // Make `--extern-html-root-url` support the same names as `--extern` whenever possible
166        let cstore = CStore::from_tcx(tcx);
167        for (name, extern_url) in &render_options.extern_html_root_urls {
168            if let Some(crate_num) = cstore.resolved_extern_crate(Symbol::intern(name)) {
169                let e = ExternalCrate { crate_num };
170                let location = e.location(Some(extern_url), extern_url_takes_precedence, dst, tcx);
171                cx.cache.extern_locations.insert(e.crate_num, location);
172            }
173        }
174
175        // Cache where all our extern crates are located
176        // This is also used in the JSON output.
177        for &crate_num in tcx.crates(()) {
178            let e = ExternalCrate { crate_num };
179
180            let name = e.name(tcx);
181            cx.cache.extern_locations.entry(e.crate_num).or_insert_with(|| {
182                // falls back to matching by crates' own names, because
183                // transitive dependencies and injected crates may be loaded without `--extern`
184                let extern_url =
185                    render_options.extern_html_root_urls.get(name.as_str()).map(|u| &**u);
186                e.location(extern_url, extern_url_takes_precedence, dst, tcx)
187            });
188            cx.cache.external_paths.insert(e.def_id(), (vec![name], ItemType::Module));
189        }
190
191        // FIXME: avoid this clone (requires implementing Default manually)
192        cx.cache.primitive_locations = PrimitiveType::primitive_locations(tcx).clone();
193        for (prim, &def_id) in &cx.cache.primitive_locations {
194            let crate_name = tcx.crate_name(def_id.krate);
195            // Recall that we only allow primitive modules to be at the root-level of the crate.
196            // If that restriction is ever lifted, this will have to include the relative paths instead.
197            cx.cache
198                .external_paths
199                .insert(def_id, (vec![crate_name, prim.as_sym()], ItemType::Primitive));
200        }
201
202        let (krate, mut impl_ids) = {
203            let is_json_output = cx.is_json_output();
204            let mut cache_builder = CacheBuilder {
205                tcx,
206                cache: &mut cx.cache,
207                impl_ids: Default::default(),
208                is_json_output,
209            };
210            krate = cache_builder.fold_crate(krate);
211            (krate, cache_builder.impl_ids)
212        };
213
214        for (trait_did, dids, impl_) in cx.cache.orphan_trait_impls.drain(..) {
215            if cx.cache.traits.contains_key(&trait_did) {
216                for did in dids {
217                    if impl_ids.entry(did).or_default().insert(impl_.def_id()) {
218                        cx.cache.impls.entry(did).or_default().push(impl_.clone());
219                    }
220                }
221            }
222        }
223
224        krate
225    }
226}
227
228impl DocFolder for CacheBuilder<'_, '_> {
229    fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
230        if item.item_id.is_local() {
231            debug!(
232                "folding {} (stripped: {:?}) \"{:?}\", id {:?}",
233                item.type_(),
234                item.is_stripped(),
235                item.name,
236                item.item_id
237            );
238        }
239
240        // If this is a stripped module,
241        // we don't want it or its children in the search index.
242        let orig_stripped_mod = match item.kind {
243            clean::StrippedItem(box clean::ModuleItem(..)) => {
244                mem::replace(&mut self.cache.stripped_mod, true)
245            }
246            _ => self.cache.stripped_mod,
247        };
248
249        #[inline]
250        fn is_from_private_dep(tcx: TyCtxt<'_>, cache: &Cache, def_id: DefId) -> bool {
251            let krate = def_id.krate;
252
253            cache.masked_crates.contains(&krate) || tcx.is_private_dep(krate)
254        }
255
256        // If the impl is from a masked crate or references something from a
257        // masked crate then remove it completely.
258        if let clean::ImplItem(ref i) = item.kind
259            && (self.cache.masked_crates.contains(&item.item_id.krate())
260                || i.trait_
261                    .as_ref()
262                    .is_some_and(|t| is_from_private_dep(self.tcx, self.cache, t.def_id()))
263                || i.for_
264                    .def_id(self.cache)
265                    .is_some_and(|d| is_from_private_dep(self.tcx, self.cache, d)))
266        {
267            return None;
268        }
269
270        // Propagate a trait method's documentation to all implementors of the
271        // trait.
272        if let clean::TraitItem(ref t) = item.kind {
273            self.cache.traits.entry(item.item_id.expect_def_id()).or_insert_with(|| (**t).clone());
274        } else if let clean::ImplItem(ref i) = item.kind
275            && let Some(trait_) = &i.trait_
276            && !i.kind.is_blanket()
277        {
278            // Collect all the implementors of traits.
279            self.cache
280                .implementors
281                .entry(trait_.def_id())
282                .or_default()
283                .push(Impl { impl_item: item.clone() });
284        }
285
286        // Index this method for searching later on.
287        let search_name = if !item.is_stripped() {
288            item.name.or_else(|| {
289                if let clean::ImportItem(ref i) = item.kind
290                    && let clean::ImportKind::Simple(s) = i.kind
291                {
292                    Some(s)
293                } else {
294                    None
295                }
296            })
297        } else {
298            None
299        };
300        if let Some(name) = search_name {
301            add_item_to_search_index(self.tcx, self.cache, &item, name)
302        }
303
304        // Keep track of the fully qualified path for this item.
305        let pushed = match item.name {
306            Some(n) => {
307                self.cache.stack.push(n);
308                true
309            }
310            _ => false,
311        };
312
313        match item.kind {
314            clean::StructItem(..)
315            | clean::EnumItem(..)
316            | clean::TypeAliasItem(..)
317            | clean::TraitItem(..)
318            | clean::TraitAliasItem(..)
319            | clean::FunctionItem(..)
320            | clean::ModuleItem(..)
321            | clean::ForeignFunctionItem(..)
322            | clean::ForeignStaticItem(..)
323            | clean::ConstantItem(..)
324            | clean::StaticItem(..)
325            | clean::UnionItem(..)
326            | clean::ForeignTypeItem
327            | clean::MacroItem(..)
328            | clean::ProcMacroItem(..)
329            | clean::VariantItem(..) => {
330                use rustc_data_structures::fx::IndexEntry as Entry;
331
332                let skip_because_unstable = matches!(
333                    item.stability.map(|stab| stab.level),
334                    Some(StabilityLevel::Stable { allowed_through_unstable_modules: Some(_), .. })
335                );
336
337                if (!self.cache.stripped_mod && !skip_because_unstable) || self.is_json_output {
338                    // Re-exported items mean that the same id can show up twice
339                    // in the rustdoc ast that we're looking at. We know,
340                    // however, that a re-exported item doesn't show up in the
341                    // `public_items` map, so we can skip inserting into the
342                    // paths map if there was already an entry present and we're
343                    // not a public item.
344                    let item_def_id = item.item_id.expect_def_id();
345                    match self.cache.paths.entry(item_def_id) {
346                        Entry::Vacant(entry) => {
347                            entry.insert((self.cache.stack.clone(), item.type_()));
348                        }
349                        Entry::Occupied(mut entry) => {
350                            if entry.get().0.len() > self.cache.stack.len() {
351                                entry.insert((self.cache.stack.clone(), item.type_()));
352                            }
353                        }
354                    }
355                }
356            }
357            clean::PrimitiveItem(..) => {
358                self.cache
359                    .paths
360                    .insert(item.item_id.expect_def_id(), (self.cache.stack.clone(), item.type_()));
361            }
362
363            clean::ExternCrateItem { .. }
364            | clean::ImportItem(..)
365            | clean::ImplItem(..)
366            | clean::RequiredMethodItem(..)
367            | clean::MethodItem(..)
368            | clean::StructFieldItem(..)
369            | clean::RequiredAssocConstItem(..)
370            | clean::ProvidedAssocConstItem(..)
371            | clean::ImplAssocConstItem(..)
372            | clean::RequiredAssocTypeItem(..)
373            | clean::AssocTypeItem(..)
374            | clean::StrippedItem(..)
375            | clean::KeywordItem => {
376                // FIXME: Do these need handling?
377                // The person writing this comment doesn't know.
378                // So would rather leave them to an expert,
379                // as at least the list is better than `_ => {}`.
380            }
381        }
382
383        // Maintain the parent stack.
384        let (item, parent_pushed) = match item.kind {
385            clean::TraitItem(..)
386            | clean::EnumItem(..)
387            | clean::ForeignTypeItem
388            | clean::StructItem(..)
389            | clean::UnionItem(..)
390            | clean::VariantItem(..)
391            | clean::TypeAliasItem(..)
392            | clean::ImplItem(..) => {
393                self.cache.parent_stack.push(ParentStackItem::new(&item));
394                (self.fold_item_recur(item), true)
395            }
396            _ => (self.fold_item_recur(item), false),
397        };
398
399        // Once we've recursively found all the generics, hoard off all the
400        // implementations elsewhere.
401        let ret = if let clean::Item {
402            inner: box clean::ItemInner { kind: clean::ImplItem(ref i), .. },
403        } = item
404        {
405            // Figure out the id of this impl. This may map to a
406            // primitive rather than always to a struct/enum.
407            // Note: matching twice to restrict the lifetime of the `i` borrow.
408            let mut dids = FxIndexSet::default();
409            match i.for_ {
410                clean::Type::Path { ref path }
411                | clean::BorrowedRef { type_: box clean::Type::Path { ref path }, .. } => {
412                    dids.insert(path.def_id());
413                    if let Some(generics) = path.generics()
414                        && let ty::Adt(adt, _) =
415                            self.tcx.type_of(path.def_id()).instantiate_identity().kind()
416                        && adt.is_fundamental()
417                    {
418                        for ty in generics {
419                            dids.extend(ty.def_id(self.cache));
420                        }
421                    }
422                }
423                clean::DynTrait(ref bounds, _)
424                | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
425                    dids.insert(bounds[0].trait_.def_id());
426                }
427                ref t => {
428                    let did = t
429                        .primitive_type()
430                        .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
431
432                    dids.extend(did);
433                }
434            }
435
436            if let Some(trait_) = &i.trait_
437                && let Some(generics) = trait_.generics()
438            {
439                for bound in generics {
440                    dids.extend(bound.def_id(self.cache));
441                }
442            }
443            let impl_item = Impl { impl_item: item };
444            let impl_did = impl_item.def_id();
445            let trait_did = impl_item.trait_did();
446            if trait_did.is_none_or(|d| self.cache.traits.contains_key(&d)) {
447                for did in dids {
448                    if self.impl_ids.entry(did).or_default().insert(impl_did) {
449                        self.cache.impls.entry(did).or_default().push(impl_item.clone());
450                    }
451                }
452            } else {
453                let trait_did = trait_did.expect("no trait did");
454                self.cache.orphan_trait_impls.push((trait_did, dids, impl_item));
455            }
456            None
457        } else {
458            Some(item)
459        };
460
461        if pushed {
462            self.cache.stack.pop().expect("stack already empty");
463        }
464        if parent_pushed {
465            self.cache.parent_stack.pop().expect("parent stack already empty");
466        }
467        self.cache.stripped_mod = orig_stripped_mod;
468        ret
469    }
470}
471
472fn add_item_to_search_index(tcx: TyCtxt<'_>, cache: &mut Cache, item: &clean::Item, name: Symbol) {
473    // Item has a name, so it must also have a DefId (can't be an impl, let alone a blanket or auto impl).
474    let item_def_id = item.item_id.as_def_id().unwrap();
475    let (parent_did, parent_path) = match item.kind {
476        clean::StrippedItem(..) => return,
477        clean::ProvidedAssocConstItem(..)
478        | clean::ImplAssocConstItem(..)
479        | clean::AssocTypeItem(..)
480            if cache.parent_stack.last().is_some_and(|parent| parent.is_trait_impl()) =>
481        {
482            // skip associated items in trait impls
483            return;
484        }
485        clean::RequiredMethodItem(..)
486        | clean::RequiredAssocConstItem(..)
487        | clean::RequiredAssocTypeItem(..)
488        | clean::StructFieldItem(..)
489        | clean::VariantItem(..) => {
490            // Don't index if containing module is stripped (i.e., private),
491            // or if item is tuple struct/variant field (name is a number -> not useful for search).
492            if cache.stripped_mod
493                || item.type_() == ItemType::StructField
494                    && name.as_str().chars().all(|c| c.is_ascii_digit())
495            {
496                return;
497            }
498            let parent_did =
499                cache.parent_stack.last().expect("parent_stack is empty").item_id().expect_def_id();
500            let parent_path = &cache.stack[..cache.stack.len() - 1];
501            (Some(parent_did), parent_path)
502        }
503        clean::MethodItem(..)
504        | clean::ProvidedAssocConstItem(..)
505        | clean::ImplAssocConstItem(..)
506        | clean::AssocTypeItem(..) => {
507            let last = cache.parent_stack.last().expect("parent_stack is empty 2");
508            let parent_did = match last {
509                // impl Trait for &T { fn method(self); }
510                //
511                // When generating a function index with the above shape, we want it
512                // associated with `T`, not with the primitive reference type. It should
513                // show up as `T::method`, rather than `reference::method`, in the search
514                // results page.
515                ParentStackItem::Impl { for_: clean::Type::BorrowedRef { type_, .. }, .. } => {
516                    type_.def_id(cache)
517                }
518                ParentStackItem::Impl { for_, .. } => for_.def_id(cache),
519                ParentStackItem::Type(item_id) => item_id.as_def_id(),
520            };
521            let Some(parent_did) = parent_did else { return };
522            // The current stack reflects the CacheBuilder's recursive
523            // walk over HIR. For associated items, this is the module
524            // where the `impl` block is defined. That's an implementation
525            // detail that we don't want to affect the search engine.
526            //
527            // In particular, you can arrange things like this:
528            //
529            //     #![crate_name="me"]
530            //     mod private_mod {
531            //         impl Clone for MyThing { fn clone(&self) -> MyThing { MyThing } }
532            //     }
533            //     pub struct MyThing;
534            //
535            // When that happens, we need to:
536            // - ignore the `cache.stripped_mod` flag, since the Clone impl is actually
537            //   part of the public API even though it's defined in a private module
538            // - present the method as `me::MyThing::clone`, its publicly-visible path
539            // - deal with the fact that the recursive walk hasn't actually reached `MyThing`
540            //   until it's already past `private_mod`, since that's first, and doesn't know
541            //   yet if `MyThing` will actually be public or not (it could be re-exported)
542            //
543            // We accomplish the last two points by recording children of "orphan impls"
544            // in a field of the cache whose elements are added to the search index later,
545            // after cache building is complete (see `handle_orphan_impl_child`).
546            match cache.paths.get(&parent_did) {
547                Some((fqp, _)) => (Some(parent_did), &fqp[..fqp.len() - 1]),
548                None => {
549                    handle_orphan_impl_child(cache, item, parent_did);
550                    return;
551                }
552            }
553        }
554        _ => {
555            // Don't index if item is crate root, which is inserted later on when serializing the index.
556            // Don't index if containing module is stripped (i.e., private),
557            if item_def_id.is_crate_root() || cache.stripped_mod {
558                return;
559            }
560            (None, &*cache.stack)
561        }
562    };
563
564    debug_assert!(!item.is_stripped());
565
566    let desc = short_markdown_summary(&item.doc_value(), &item.link_names(cache));
567    // For searching purposes, a re-export is a duplicate if:
568    //
569    // - It's either an inline, or a true re-export
570    // - It's got the same name
571    // - Both of them have the same exact path
572    let defid = match &item.kind {
573        clean::ItemKind::ImportItem(import) => import.source.did.unwrap_or(item_def_id),
574        _ => item_def_id,
575    };
576    let impl_id = if let Some(ParentStackItem::Impl { item_id, .. }) = cache.parent_stack.last() {
577        item_id.as_def_id()
578    } else {
579        None
580    };
581    let search_type = get_function_type_for_search(
582        item,
583        tcx,
584        clean_impl_generics(cache.parent_stack.last()).as_ref(),
585        parent_did,
586        cache,
587    );
588    let aliases = item.attrs.get_doc_aliases();
589    let deprecation = item.deprecation(tcx);
590    let index_item = IndexItem {
591        ty: item.type_(),
592        defid: Some(defid),
593        name,
594        module_path: parent_path.to_vec(),
595        desc,
596        parent: parent_did,
597        parent_idx: None,
598        exact_module_path: None,
599        impl_id,
600        search_type,
601        aliases,
602        deprecation,
603    };
604    cache.search_index.push(index_item);
605}
606
607/// We have a parent, but we don't know where they're
608/// defined yet. Wait for later to index this item.
609/// See [`Cache::orphan_impl_items`].
610fn handle_orphan_impl_child(cache: &mut Cache, item: &clean::Item, parent_did: DefId) {
611    let impl_generics = clean_impl_generics(cache.parent_stack.last());
612    let impl_id = if let Some(ParentStackItem::Impl { item_id, .. }) = cache.parent_stack.last() {
613        item_id.as_def_id()
614    } else {
615        None
616    };
617    let orphan_item =
618        OrphanImplItem { parent: parent_did, item: item.clone(), impl_generics, impl_id };
619    cache.orphan_impl_items.push(orphan_item);
620}
621
622pub(crate) struct OrphanImplItem {
623    pub(crate) parent: DefId,
624    pub(crate) impl_id: Option<DefId>,
625    pub(crate) item: clean::Item,
626    pub(crate) impl_generics: Option<(clean::Type, clean::Generics)>,
627}
628
629/// Information about trait and type parents is tracked while traversing the item tree to build
630/// the cache.
631///
632/// We don't just store `Item` in there, because `Item` contains the list of children being
633/// traversed and it would be wasteful to clone all that. We also need the item id, so just
634/// storing `ItemKind` won't work, either.
635enum ParentStackItem {
636    Impl {
637        for_: clean::Type,
638        trait_: Option<clean::Path>,
639        generics: clean::Generics,
640        kind: clean::ImplKind,
641        item_id: ItemId,
642    },
643    Type(ItemId),
644}
645
646impl ParentStackItem {
647    fn new(item: &clean::Item) -> Self {
648        match &item.kind {
649            clean::ItemKind::ImplItem(box clean::Impl { for_, trait_, generics, kind, .. }) => {
650                ParentStackItem::Impl {
651                    for_: for_.clone(),
652                    trait_: trait_.clone(),
653                    generics: generics.clone(),
654                    kind: kind.clone(),
655                    item_id: item.item_id,
656                }
657            }
658            _ => ParentStackItem::Type(item.item_id),
659        }
660    }
661    fn is_trait_impl(&self) -> bool {
662        matches!(self, ParentStackItem::Impl { trait_: Some(..), .. })
663    }
664    fn item_id(&self) -> ItemId {
665        match self {
666            ParentStackItem::Impl { item_id, .. } => *item_id,
667            ParentStackItem::Type(item_id) => *item_id,
668        }
669    }
670}
671
672fn clean_impl_generics(item: Option<&ParentStackItem>) -> Option<(clean::Type, clean::Generics)> {
673    if let Some(ParentStackItem::Impl { for_, generics, kind: clean::ImplKind::Normal, .. }) = item
674    {
675        Some((for_.clone(), generics.clone()))
676    } else {
677        None
678    }
679}