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