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