rustdoc/formats/
cache.rs

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