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::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#[derive(Default)]
33pub(crate) struct Cache {
34 pub(crate) impls: DefIdMap<Vec<Impl>>,
41
42 pub(crate) paths: FxIndexMap<DefId, (Vec<Symbol>, ItemType)>,
48
49 pub(crate) external_paths: FxIndexMap<DefId, (Vec<Symbol>, ItemType)>,
52
53 pub(crate) exact_paths: DefIdMap<Vec<Symbol>>,
64
65 pub(crate) traits: FxIndexMap<DefId, clean::Trait>,
70
71 pub(crate) implementors: FxIndexMap<DefId, Vec<Impl>>,
75
76 pub(crate) extern_locations: FxIndexMap<CrateNum, ExternalLocation>,
78
79 pub(crate) primitive_locations: FxIndexMap<clean::PrimitiveType, DefId>,
81
82 pub(crate) effective_visibilities: RustdocEffectiveVisibilities,
86
87 pub(crate) crate_version: Option<String>,
89
90 pub(crate) document_private: bool,
93 pub(crate) document_hidden: bool,
96
97 pub(crate) masked_crates: FxHashSet<CrateNum>,
101
102 stack: Vec<Symbol>,
104 parent_stack: Vec<ParentStackItem>,
105 stripped_mod: bool,
106
107 pub(crate) search_index: Vec<IndexItem>,
108
109 pub(crate) orphan_impl_items: Vec<OrphanImplItem>,
115
116 orphan_trait_impls: Vec<(DefId, FxIndexSet<DefId>, Impl)>,
124
125 pub(crate) intra_doc_links: FxHashMap<ItemId, FxIndexSet<clean::ItemLink>>,
129
130 pub(crate) inlined_items: DefIdSet,
134}
135
136struct CacheBuilder<'a, 'tcx> {
138 cache: &'a mut Cache,
139 impl_ids: DefIdMap<DefIdSet>,
141 tcx: TyCtxt<'tcx>,
142 is_json_output: bool,
143}
144
145impl Cache {
146 pub(crate) fn new(document_private: bool, document_hidden: bool) -> Self {
147 Cache { document_private, document_hidden, ..Cache::default() }
148 }
149
150 fn parent_stack_last_impl_and_trait_id(&self) -> (Option<DefId>, Option<DefId>) {
151 if let Some(ParentStackItem::Impl { item_id, trait_, .. }) = self.parent_stack.last() {
152 (item_id.as_def_id(), trait_.as_ref().map(|tr| tr.def_id()))
153 } else {
154 (None, None)
155 }
156 }
157
158 pub(crate) fn populate(
161 cx: &mut DocContext<'_>,
162 mut krate: clean::Crate,
163 render_options: &RenderOptions,
164 ) -> clean::Crate {
165 let tcx = cx.tcx;
166
167 debug!(?cx.cache.crate_version);
169 assert!(cx.external_traits.is_empty());
170 cx.cache.traits = mem::take(&mut krate.external_traits);
171
172 let extern_url_takes_precedence = render_options.extern_html_root_takes_precedence;
173 let dst = &render_options.output;
174
175 let cstore = CStore::from_tcx(tcx);
177 for (name, extern_url) in &render_options.extern_html_root_urls {
178 if let Some(crate_num) = cstore.resolved_extern_crate(Symbol::intern(name)) {
179 let e = ExternalCrate { crate_num };
180 let location = e.location(Some(extern_url), extern_url_takes_precedence, dst, tcx);
181 cx.cache.extern_locations.insert(e.crate_num, location);
182 }
183 }
184
185 for &crate_num in tcx.crates(()) {
188 let e = ExternalCrate { crate_num };
189
190 let name = e.name(tcx);
191 cx.cache.extern_locations.entry(e.crate_num).or_insert_with(|| {
192 let extern_url =
195 render_options.extern_html_root_urls.get(name.as_str()).map(|u| &**u);
196 e.location(extern_url, extern_url_takes_precedence, dst, tcx)
197 });
198 cx.cache.external_paths.insert(e.def_id(), (vec![name], ItemType::Module));
199 }
200
201 cx.cache.primitive_locations = PrimitiveType::primitive_locations(tcx).clone();
203 for (prim, &def_id) in &cx.cache.primitive_locations {
204 let crate_name = tcx.crate_name(def_id.krate);
205 cx.cache
208 .external_paths
209 .insert(def_id, (vec![crate_name, prim.as_sym()], ItemType::Primitive));
210 }
211
212 let (krate, mut impl_ids) = {
213 let is_json_output = cx.is_json_output();
214 let mut cache_builder = CacheBuilder {
215 tcx,
216 cache: &mut cx.cache,
217 impl_ids: Default::default(),
218 is_json_output,
219 };
220 krate = cache_builder.fold_crate(krate);
221 (krate, cache_builder.impl_ids)
222 };
223
224 for (trait_did, dids, impl_) in cx.cache.orphan_trait_impls.drain(..) {
225 if cx.cache.traits.contains_key(&trait_did) {
226 for did in dids {
227 if impl_ids.entry(did).or_default().insert(impl_.def_id()) {
228 cx.cache.impls.entry(did).or_default().push(impl_.clone());
229 }
230 }
231 }
232 }
233
234 krate
235 }
236}
237
238impl DocFolder for CacheBuilder<'_, '_> {
239 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
240 if item.item_id.is_local() {
241 debug!(
242 "folding {} (stripped: {:?}) \"{:?}\", id {:?}",
243 item.type_(),
244 item.is_stripped(),
245 item.name,
246 item.item_id
247 );
248 }
249
250 let orig_stripped_mod = match item.kind {
253 clean::StrippedItem(box clean::ModuleItem(..)) => {
254 mem::replace(&mut self.cache.stripped_mod, true)
255 }
256 _ => self.cache.stripped_mod,
257 };
258
259 #[inline]
260 fn is_from_private_dep(tcx: TyCtxt<'_>, cache: &Cache, def_id: DefId) -> bool {
261 let krate = def_id.krate;
262
263 cache.masked_crates.contains(&krate) || tcx.is_private_dep(krate)
264 }
265
266 if let clean::ImplItem(ref i) = item.kind
269 && (self.cache.masked_crates.contains(&item.item_id.krate())
270 || i.trait_
271 .as_ref()
272 .is_some_and(|t| is_from_private_dep(self.tcx, self.cache, t.def_id()))
273 || i.for_
274 .def_id(self.cache)
275 .is_some_and(|d| is_from_private_dep(self.tcx, self.cache, d)))
276 {
277 return None;
278 }
279
280 if let clean::TraitItem(ref t) = item.kind {
283 self.cache.traits.entry(item.item_id.expect_def_id()).or_insert_with(|| (**t).clone());
284 } else if let clean::ImplItem(ref i) = item.kind
285 && let Some(trait_) = &i.trait_
286 && !i.kind.is_blanket()
287 {
288 self.cache
290 .implementors
291 .entry(trait_.def_id())
292 .or_default()
293 .push(Impl { impl_item: item.clone() });
294 }
295
296 let search_name = if !item.is_stripped() {
298 item.name.or_else(|| {
299 if let clean::ImportItem(ref i) = item.kind
300 && let clean::ImportKind::Simple(s) = i.kind
301 {
302 Some(s)
303 } else {
304 None
305 }
306 })
307 } else {
308 None
309 };
310 if let Some(name) = search_name {
311 add_item_to_search_index(self.tcx, self.cache, &item, name)
312 }
313
314 let pushed = match item.name {
316 Some(n) => {
317 self.cache.stack.push(n);
318 true
319 }
320 _ => false,
321 };
322
323 match item.kind {
324 clean::StructItem(..)
325 | clean::EnumItem(..)
326 | clean::TypeAliasItem(..)
327 | clean::TraitItem(..)
328 | clean::TraitAliasItem(..)
329 | clean::FunctionItem(..)
330 | clean::ModuleItem(..)
331 | clean::ForeignFunctionItem(..)
332 | clean::ForeignStaticItem(..)
333 | clean::ConstantItem(..)
334 | clean::StaticItem(..)
335 | clean::UnionItem(..)
336 | clean::ForeignTypeItem
337 | clean::MacroItem(..)
338 | clean::ProcMacroItem(..)
339 | clean::VariantItem(..) => {
340 use rustc_data_structures::fx::IndexEntry as Entry;
341
342 let skip_because_unstable = matches!(
343 item.stability.map(|stab| stab.level),
344 Some(StabilityLevel::Stable { allowed_through_unstable_modules: Some(_), .. })
345 );
346
347 if (!self.cache.stripped_mod && !skip_because_unstable) || self.is_json_output {
348 let item_def_id = item.item_id.expect_def_id();
355 match self.cache.paths.entry(item_def_id) {
356 Entry::Vacant(entry) => {
357 entry.insert((self.cache.stack.clone(), item.type_()));
358 }
359 Entry::Occupied(mut entry) => {
360 if entry.get().0.len() > self.cache.stack.len() {
361 entry.insert((self.cache.stack.clone(), item.type_()));
362 }
363 }
364 }
365 }
366 }
367 clean::PrimitiveItem(..) => {
368 self.cache
369 .paths
370 .insert(item.item_id.expect_def_id(), (self.cache.stack.clone(), item.type_()));
371 }
372
373 clean::ExternCrateItem { .. }
374 | clean::ImportItem(..)
375 | clean::ImplItem(..)
376 | clean::RequiredMethodItem(..)
377 | clean::MethodItem(..)
378 | clean::StructFieldItem(..)
379 | clean::RequiredAssocConstItem(..)
380 | clean::ProvidedAssocConstItem(..)
381 | clean::ImplAssocConstItem(..)
382 | clean::RequiredAssocTypeItem(..)
383 | clean::AssocTypeItem(..)
384 | clean::StrippedItem(..)
385 | clean::KeywordItem
386 | clean::AttributeItem => {
387 }
392 }
393
394 let (item, parent_pushed) = match item.kind {
396 clean::TraitItem(..)
397 | clean::EnumItem(..)
398 | clean::ForeignTypeItem
399 | clean::StructItem(..)
400 | clean::UnionItem(..)
401 | clean::VariantItem(..)
402 | clean::TypeAliasItem(..)
403 | clean::ImplItem(..) => {
404 self.cache.parent_stack.push(ParentStackItem::new(&item));
405 (self.fold_item_recur(item), true)
406 }
407 _ => (self.fold_item_recur(item), false),
408 };
409
410 let ret = if let clean::Item {
413 inner: box clean::ItemInner { kind: clean::ImplItem(ref i), .. },
414 } = item
415 {
416 let mut dids = FxIndexSet::default();
420 match i.for_ {
421 clean::Type::Path { ref path }
422 | clean::BorrowedRef { type_: box clean::Type::Path { ref path }, .. } => {
423 dids.insert(path.def_id());
424 if let Some(generics) = path.generics()
425 && let ty::Adt(adt, _) =
426 self.tcx.type_of(path.def_id()).instantiate_identity().kind()
427 && adt.is_fundamental()
428 {
429 for ty in generics {
430 dids.extend(ty.def_id(self.cache));
431 }
432 }
433 }
434 clean::DynTrait(ref bounds, _)
435 | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
436 dids.insert(bounds[0].trait_.def_id());
437 }
438 ref t => {
439 let did = t
440 .primitive_type()
441 .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
442
443 dids.extend(did);
444 }
445 }
446
447 if let Some(trait_) = &i.trait_
448 && let Some(generics) = trait_.generics()
449 {
450 for bound in generics {
451 dids.extend(bound.def_id(self.cache));
452 }
453 }
454 let impl_item = Impl { impl_item: item };
455 let impl_did = impl_item.def_id();
456 let trait_did = impl_item.trait_did();
457 if trait_did.is_none_or(|d| self.cache.traits.contains_key(&d)) {
458 for did in dids {
459 if self.impl_ids.entry(did).or_default().insert(impl_did) {
460 self.cache.impls.entry(did).or_default().push(impl_item.clone());
461 }
462 }
463 } else {
464 let trait_did = trait_did.expect("no trait did");
465 self.cache.orphan_trait_impls.push((trait_did, dids, impl_item));
466 }
467 None
468 } else {
469 Some(item)
470 };
471
472 if pushed {
473 self.cache.stack.pop().expect("stack already empty");
474 }
475 if parent_pushed {
476 self.cache.parent_stack.pop().expect("parent stack already empty");
477 }
478 self.cache.stripped_mod = orig_stripped_mod;
479 ret
480 }
481}
482
483fn add_item_to_search_index(tcx: TyCtxt<'_>, cache: &mut Cache, item: &clean::Item, name: Symbol) {
484 let item_def_id = item.item_id.as_def_id().unwrap();
486 let (parent_did, parent_path) = match item.kind {
487 clean::StrippedItem(..) => return,
488 clean::ProvidedAssocConstItem(..)
489 | clean::ImplAssocConstItem(..)
490 | clean::AssocTypeItem(..)
491 if cache.parent_stack.last().is_some_and(|parent| parent.is_trait_impl()) =>
492 {
493 return;
495 }
496 clean::RequiredMethodItem(..)
497 | clean::RequiredAssocConstItem(..)
498 | clean::RequiredAssocTypeItem(..)
499 | clean::StructFieldItem(..)
500 | clean::VariantItem(..) => {
501 if cache.stripped_mod
504 || item.type_() == ItemType::StructField
505 && name.as_str().chars().all(|c| c.is_ascii_digit())
506 {
507 return;
508 }
509 let parent_did =
510 cache.parent_stack.last().expect("parent_stack is empty").item_id().expect_def_id();
511 let parent_path = &cache.stack[..cache.stack.len() - 1];
512 (Some(parent_did), parent_path)
513 }
514 clean::MethodItem(..)
515 | clean::ProvidedAssocConstItem(..)
516 | clean::ImplAssocConstItem(..)
517 | clean::AssocTypeItem(..) => {
518 let last = cache.parent_stack.last().expect("parent_stack is empty 2");
519 let parent_did = match last {
520 ParentStackItem::Impl { for_: clean::Type::BorrowedRef { type_, .. }, .. } => {
527 type_.def_id(cache)
528 }
529 ParentStackItem::Impl { for_, .. } => for_.def_id(cache),
530 ParentStackItem::Type(item_id) => item_id.as_def_id(),
531 };
532 let Some(parent_did) = parent_did else { return };
533 match cache.paths.get(&parent_did) {
558 Some((fqp, _)) => (Some(parent_did), &fqp[..fqp.len() - 1]),
559 None => {
560 handle_orphan_impl_child(cache, item, parent_did);
561 return;
562 }
563 }
564 }
565 _ => {
566 if item_def_id.is_crate_root() || cache.stripped_mod {
569 return;
570 }
571 (None, &*cache.stack)
572 }
573 };
574
575 debug_assert!(!item.is_stripped());
576
577 let desc = short_markdown_summary(&item.doc_value(), &item.link_names(cache));
578 let defid = match &item.kind {
584 clean::ItemKind::ImportItem(import) => import.source.did.unwrap_or(item_def_id),
585 _ => item_def_id,
586 };
587 let (impl_id, trait_parent) = cache.parent_stack_last_impl_and_trait_id();
588 let search_type = get_function_type_for_search(
589 item,
590 tcx,
591 clean_impl_generics(cache.parent_stack.last()).as_ref(),
592 parent_did,
593 cache,
594 );
595 let aliases = item.attrs.get_doc_aliases();
596 let deprecation = item.deprecation(tcx);
597 let index_item = IndexItem {
598 ty: item.type_(),
599 defid: Some(defid),
600 name,
601 module_path: parent_path.to_vec(),
602 desc,
603 parent: parent_did,
604 parent_idx: None,
605 trait_parent,
606 trait_parent_idx: None,
607 exact_module_path: None,
608 impl_id,
609 search_type,
610 aliases,
611 deprecation,
612 };
613
614 cache.search_index.push(index_item);
615}
616
617fn handle_orphan_impl_child(cache: &mut Cache, item: &clean::Item, parent_did: DefId) {
621 let impl_generics = clean_impl_generics(cache.parent_stack.last());
622 let (impl_id, trait_parent) = cache.parent_stack_last_impl_and_trait_id();
623 let orphan_item = OrphanImplItem {
624 parent: parent_did,
625 trait_parent,
626 item: item.clone(),
627 impl_generics,
628 impl_id,
629 };
630 cache.orphan_impl_items.push(orphan_item);
631}
632
633pub(crate) struct OrphanImplItem {
634 pub(crate) parent: DefId,
635 pub(crate) impl_id: Option<DefId>,
636 pub(crate) trait_parent: Option<DefId>,
637 pub(crate) item: clean::Item,
638 pub(crate) impl_generics: Option<(clean::Type, clean::Generics)>,
639}
640
641enum ParentStackItem {
648 Impl {
649 for_: clean::Type,
650 trait_: Option<clean::Path>,
651 generics: clean::Generics,
652 kind: clean::ImplKind,
653 item_id: ItemId,
654 },
655 Type(ItemId),
656}
657
658impl ParentStackItem {
659 fn new(item: &clean::Item) -> Self {
660 match &item.kind {
661 clean::ItemKind::ImplItem(box clean::Impl { for_, trait_, generics, kind, .. }) => {
662 ParentStackItem::Impl {
663 for_: for_.clone(),
664 trait_: trait_.clone(),
665 generics: generics.clone(),
666 kind: kind.clone(),
667 item_id: item.item_id,
668 }
669 }
670 _ => ParentStackItem::Type(item.item_id),
671 }
672 }
673 fn is_trait_impl(&self) -> bool {
674 matches!(self, ParentStackItem::Impl { trait_: Some(..), .. })
675 }
676 fn item_id(&self) -> ItemId {
677 match self {
678 ParentStackItem::Impl { item_id, .. } => *item_id,
679 ParentStackItem::Type(item_id) => *item_id,
680 }
681 }
682}
683
684fn clean_impl_generics(item: Option<&ParentStackItem>) -> Option<(clean::Type, clean::Generics)> {
685 if let Some(ParentStackItem::Impl { for_, generics, kind: clean::ImplKind::Normal, .. }) = item
686 {
687 Some((for_.clone(), generics.clone()))
688 } else {
689 None
690 }
691}