Skip to main content

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