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::core::DocContext;
14use crate::fold::DocFolder;
15use crate::formats::Impl;
16use crate::formats::item_type::ItemType;
17use crate::html::markdown::short_markdown_summary;
18use crate::html::render::IndexItem;
19use crate::html::render::search_index::get_function_type_for_search;
20use crate::visit_lib::RustdocEffectiveVisibilities;
21
22#[derive(Default)]
32pub(crate) struct Cache {
33 pub(crate) impls: DefIdMap<Vec<Impl>>,
40
41 pub(crate) paths: FxIndexMap<DefId, (Vec<Symbol>, ItemType)>,
47
48 pub(crate) external_paths: FxIndexMap<DefId, (Vec<Symbol>, ItemType)>,
51
52 pub(crate) exact_paths: DefIdMap<Vec<Symbol>>,
63
64 pub(crate) traits: FxIndexMap<DefId, clean::Trait>,
69
70 pub(crate) implementors: FxIndexMap<DefId, Vec<Impl>>,
74
75 pub(crate) extern_locations: FxIndexMap<CrateNum, ExternalLocation>,
77
78 pub(crate) primitive_locations: FxIndexMap<clean::PrimitiveType, DefId>,
80
81 pub(crate) effective_visibilities: RustdocEffectiveVisibilities,
85
86 pub(crate) crate_version: Option<String>,
88
89 pub(crate) document_private: bool,
92 pub(crate) document_hidden: bool,
95
96 pub(crate) masked_crates: FxHashSet<CrateNum>,
100
101 stack: Vec<Symbol>,
103 parent_stack: Vec<ParentStackItem>,
104 stripped_mod: bool,
105
106 pub(crate) search_index: Vec<IndexItem>,
107
108 pub(crate) orphan_impl_items: Vec<OrphanImplItem>,
114
115 orphan_trait_impls: Vec<(DefId, FxIndexSet<DefId>, Impl)>,
123
124 pub(crate) intra_doc_links: FxHashMap<ItemId, FxIndexSet<clean::ItemLink>>,
128 pub(crate) hidden_cfg: FxHashSet<clean::cfg::Cfg>,
130
131 pub(crate) inlined_items: DefIdSet,
135}
136
137struct CacheBuilder<'a, 'tcx> {
139 cache: &'a mut Cache,
140 impl_ids: DefIdMap<DefIdSet>,
142 tcx: TyCtxt<'tcx>,
143 is_json_output: bool,
144}
145
146impl Cache {
147 pub(crate) fn new(document_private: bool, document_hidden: bool) -> Self {
148 Cache { document_private, document_hidden, ..Cache::default() }
149 }
150
151 pub(crate) fn populate(cx: &mut DocContext<'_>, mut krate: clean::Crate) -> clean::Crate {
154 let tcx = cx.tcx;
155
156 debug!(?cx.cache.crate_version);
158 assert!(cx.external_traits.is_empty());
159 cx.cache.traits = mem::take(&mut krate.external_traits);
160
161 let render_options = &cx.render_options;
162 let extern_url_takes_precedence = render_options.extern_html_root_takes_precedence;
163 let dst = &render_options.output;
164
165 let cstore = CStore::from_tcx(tcx);
167 for (name, extern_url) in &render_options.extern_html_root_urls {
168 if let Some(crate_num) = cstore.resolved_extern_crate(Symbol::intern(name)) {
169 let e = ExternalCrate { crate_num };
170 let location = e.location(Some(extern_url), extern_url_takes_precedence, dst, tcx);
171 cx.cache.extern_locations.insert(e.crate_num, location);
172 }
173 }
174
175 for &crate_num in tcx.crates(()) {
178 let e = ExternalCrate { crate_num };
179
180 let name = e.name(tcx);
181 cx.cache.extern_locations.entry(e.crate_num).or_insert_with(|| {
182 let extern_url =
185 render_options.extern_html_root_urls.get(name.as_str()).map(|u| &**u);
186 e.location(extern_url, extern_url_takes_precedence, dst, tcx)
187 });
188 cx.cache.external_paths.insert(e.def_id(), (vec![name], ItemType::Module));
189 }
190
191 cx.cache.primitive_locations = PrimitiveType::primitive_locations(tcx).clone();
193 for (prim, &def_id) in &cx.cache.primitive_locations {
194 let crate_name = tcx.crate_name(def_id.krate);
195 cx.cache
198 .external_paths
199 .insert(def_id, (vec![crate_name, prim.as_sym()], ItemType::Primitive));
200 }
201
202 let (krate, mut impl_ids) = {
203 let is_json_output = cx.is_json_output();
204 let mut cache_builder = CacheBuilder {
205 tcx,
206 cache: &mut cx.cache,
207 impl_ids: Default::default(),
208 is_json_output,
209 };
210 krate = cache_builder.fold_crate(krate);
211 (krate, cache_builder.impl_ids)
212 };
213
214 for (trait_did, dids, impl_) in cx.cache.orphan_trait_impls.drain(..) {
215 if cx.cache.traits.contains_key(&trait_did) {
216 for did in dids {
217 if impl_ids.entry(did).or_default().insert(impl_.def_id()) {
218 cx.cache.impls.entry(did).or_default().push(impl_.clone());
219 }
220 }
221 }
222 }
223
224 krate
225 }
226}
227
228impl DocFolder for CacheBuilder<'_, '_> {
229 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
230 if item.item_id.is_local() {
231 debug!(
232 "folding {} (stripped: {:?}) \"{:?}\", id {:?}",
233 item.type_(),
234 item.is_stripped(),
235 item.name,
236 item.item_id
237 );
238 }
239
240 let orig_stripped_mod = match item.kind {
243 clean::StrippedItem(box clean::ModuleItem(..)) => {
244 mem::replace(&mut self.cache.stripped_mod, true)
245 }
246 _ => self.cache.stripped_mod,
247 };
248
249 #[inline]
250 fn is_from_private_dep(tcx: TyCtxt<'_>, cache: &Cache, def_id: DefId) -> bool {
251 let krate = def_id.krate;
252
253 cache.masked_crates.contains(&krate) || tcx.is_private_dep(krate)
254 }
255
256 if let clean::ImplItem(ref i) = item.kind
259 && (self.cache.masked_crates.contains(&item.item_id.krate())
260 || i.trait_
261 .as_ref()
262 .is_some_and(|t| is_from_private_dep(self.tcx, self.cache, t.def_id()))
263 || i.for_
264 .def_id(self.cache)
265 .is_some_and(|d| is_from_private_dep(self.tcx, self.cache, d)))
266 {
267 return None;
268 }
269
270 if let clean::TraitItem(ref t) = item.kind {
273 self.cache.traits.entry(item.item_id.expect_def_id()).or_insert_with(|| (**t).clone());
274 } else if let clean::ImplItem(ref i) = item.kind
275 && let Some(trait_) = &i.trait_
276 && !i.kind.is_blanket()
277 {
278 self.cache
280 .implementors
281 .entry(trait_.def_id())
282 .or_default()
283 .push(Impl { impl_item: item.clone() });
284 }
285
286 let search_name = if !item.is_stripped() {
288 item.name.or_else(|| {
289 if let clean::ImportItem(ref i) = item.kind
290 && let clean::ImportKind::Simple(s) = i.kind
291 {
292 Some(s)
293 } else {
294 None
295 }
296 })
297 } else {
298 None
299 };
300 if let Some(name) = search_name {
301 add_item_to_search_index(self.tcx, self.cache, &item, name)
302 }
303
304 let pushed = match item.name {
306 Some(n) => {
307 self.cache.stack.push(n);
308 true
309 }
310 _ => false,
311 };
312
313 match item.kind {
314 clean::StructItem(..)
315 | clean::EnumItem(..)
316 | clean::TypeAliasItem(..)
317 | clean::TraitItem(..)
318 | clean::TraitAliasItem(..)
319 | clean::FunctionItem(..)
320 | clean::ModuleItem(..)
321 | clean::ForeignFunctionItem(..)
322 | clean::ForeignStaticItem(..)
323 | clean::ConstantItem(..)
324 | clean::StaticItem(..)
325 | clean::UnionItem(..)
326 | clean::ForeignTypeItem
327 | clean::MacroItem(..)
328 | clean::ProcMacroItem(..)
329 | clean::VariantItem(..) => {
330 use rustc_data_structures::fx::IndexEntry as Entry;
331
332 let skip_because_unstable = matches!(
333 item.stability.map(|stab| stab.level),
334 Some(StabilityLevel::Stable { allowed_through_unstable_modules: Some(_), .. })
335 );
336
337 if (!self.cache.stripped_mod && !skip_because_unstable) || self.is_json_output {
338 let item_def_id = item.item_id.expect_def_id();
345 match self.cache.paths.entry(item_def_id) {
346 Entry::Vacant(entry) => {
347 entry.insert((self.cache.stack.clone(), item.type_()));
348 }
349 Entry::Occupied(mut entry) => {
350 if entry.get().0.len() > self.cache.stack.len() {
351 entry.insert((self.cache.stack.clone(), item.type_()));
352 }
353 }
354 }
355 }
356 }
357 clean::PrimitiveItem(..) => {
358 self.cache
359 .paths
360 .insert(item.item_id.expect_def_id(), (self.cache.stack.clone(), item.type_()));
361 }
362
363 clean::ExternCrateItem { .. }
364 | clean::ImportItem(..)
365 | clean::ImplItem(..)
366 | clean::RequiredMethodItem(..)
367 | clean::MethodItem(..)
368 | clean::StructFieldItem(..)
369 | clean::RequiredAssocConstItem(..)
370 | clean::ProvidedAssocConstItem(..)
371 | clean::ImplAssocConstItem(..)
372 | clean::RequiredAssocTypeItem(..)
373 | clean::AssocTypeItem(..)
374 | clean::StrippedItem(..)
375 | clean::KeywordItem
376 | clean::AttributeItem => {
377 }
382 }
383
384 let (item, parent_pushed) = match item.kind {
386 clean::TraitItem(..)
387 | clean::EnumItem(..)
388 | clean::ForeignTypeItem
389 | clean::StructItem(..)
390 | clean::UnionItem(..)
391 | clean::VariantItem(..)
392 | clean::TypeAliasItem(..)
393 | clean::ImplItem(..) => {
394 self.cache.parent_stack.push(ParentStackItem::new(&item));
395 (self.fold_item_recur(item), true)
396 }
397 _ => (self.fold_item_recur(item), false),
398 };
399
400 let ret = if let clean::Item {
403 inner: box clean::ItemInner { kind: clean::ImplItem(ref i), .. },
404 } = item
405 {
406 let mut dids = FxIndexSet::default();
410 match i.for_ {
411 clean::Type::Path { ref path }
412 | clean::BorrowedRef { type_: box clean::Type::Path { ref path }, .. } => {
413 dids.insert(path.def_id());
414 if let Some(generics) = path.generics()
415 && let ty::Adt(adt, _) =
416 self.tcx.type_of(path.def_id()).instantiate_identity().kind()
417 && adt.is_fundamental()
418 {
419 for ty in generics {
420 dids.extend(ty.def_id(self.cache));
421 }
422 }
423 }
424 clean::DynTrait(ref bounds, _)
425 | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
426 dids.insert(bounds[0].trait_.def_id());
427 }
428 ref t => {
429 let did = t
430 .primitive_type()
431 .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
432
433 dids.extend(did);
434 }
435 }
436
437 if let Some(trait_) = &i.trait_
438 && let Some(generics) = trait_.generics()
439 {
440 for bound in generics {
441 dids.extend(bound.def_id(self.cache));
442 }
443 }
444 let impl_item = Impl { impl_item: item };
445 let impl_did = impl_item.def_id();
446 let trait_did = impl_item.trait_did();
447 if trait_did.is_none_or(|d| self.cache.traits.contains_key(&d)) {
448 for did in dids {
449 if self.impl_ids.entry(did).or_default().insert(impl_did) {
450 self.cache.impls.entry(did).or_default().push(impl_item.clone());
451 }
452 }
453 } else {
454 let trait_did = trait_did.expect("no trait did");
455 self.cache.orphan_trait_impls.push((trait_did, dids, impl_item));
456 }
457 None
458 } else {
459 Some(item)
460 };
461
462 if pushed {
463 self.cache.stack.pop().expect("stack already empty");
464 }
465 if parent_pushed {
466 self.cache.parent_stack.pop().expect("parent stack already empty");
467 }
468 self.cache.stripped_mod = orig_stripped_mod;
469 ret
470 }
471}
472
473fn add_item_to_search_index(tcx: TyCtxt<'_>, cache: &mut Cache, item: &clean::Item, name: Symbol) {
474 let item_def_id = item.item_id.as_def_id().unwrap();
476 let (parent_did, parent_path) = match item.kind {
477 clean::StrippedItem(..) => return,
478 clean::ProvidedAssocConstItem(..)
479 | clean::ImplAssocConstItem(..)
480 | clean::AssocTypeItem(..)
481 if cache.parent_stack.last().is_some_and(|parent| parent.is_trait_impl()) =>
482 {
483 return;
485 }
486 clean::RequiredMethodItem(..)
487 | clean::RequiredAssocConstItem(..)
488 | clean::RequiredAssocTypeItem(..)
489 | clean::StructFieldItem(..)
490 | clean::VariantItem(..) => {
491 if cache.stripped_mod
494 || item.type_() == ItemType::StructField
495 && name.as_str().chars().all(|c| c.is_ascii_digit())
496 {
497 return;
498 }
499 let parent_did =
500 cache.parent_stack.last().expect("parent_stack is empty").item_id().expect_def_id();
501 let parent_path = &cache.stack[..cache.stack.len() - 1];
502 (Some(parent_did), parent_path)
503 }
504 clean::MethodItem(..)
505 | clean::ProvidedAssocConstItem(..)
506 | clean::ImplAssocConstItem(..)
507 | clean::AssocTypeItem(..) => {
508 let last = cache.parent_stack.last().expect("parent_stack is empty 2");
509 let parent_did = match last {
510 ParentStackItem::Impl { for_: clean::Type::BorrowedRef { type_, .. }, .. } => {
517 type_.def_id(cache)
518 }
519 ParentStackItem::Impl { for_, .. } => for_.def_id(cache),
520 ParentStackItem::Type(item_id) => item_id.as_def_id(),
521 };
522 let Some(parent_did) = parent_did else { return };
523 match cache.paths.get(&parent_did) {
548 Some((fqp, _)) => (Some(parent_did), &fqp[..fqp.len() - 1]),
549 None => {
550 handle_orphan_impl_child(cache, item, parent_did);
551 return;
552 }
553 }
554 }
555 _ => {
556 if item_def_id.is_crate_root() || cache.stripped_mod {
559 return;
560 }
561 (None, &*cache.stack)
562 }
563 };
564
565 debug_assert!(!item.is_stripped());
566
567 let desc = short_markdown_summary(&item.doc_value(), &item.link_names(cache));
568 let defid = match &item.kind {
574 clean::ItemKind::ImportItem(import) => import.source.did.unwrap_or(item_def_id),
575 _ => item_def_id,
576 };
577 let impl_id = if let Some(ParentStackItem::Impl { item_id, .. }) = cache.parent_stack.last() {
578 item_id.as_def_id()
579 } else {
580 None
581 };
582 let search_type = get_function_type_for_search(
583 item,
584 tcx,
585 clean_impl_generics(cache.parent_stack.last()).as_ref(),
586 parent_did,
587 cache,
588 );
589 let aliases = item.attrs.get_doc_aliases();
590 let deprecation = item.deprecation(tcx);
591 let index_item = IndexItem {
592 ty: item.type_(),
593 defid: Some(defid),
594 name,
595 module_path: parent_path.to_vec(),
596 desc,
597 parent: parent_did,
598 parent_idx: None,
599 exact_module_path: None,
600 impl_id,
601 search_type,
602 aliases,
603 deprecation,
604 };
605 cache.search_index.push(index_item);
606}
607
608fn handle_orphan_impl_child(cache: &mut Cache, item: &clean::Item, parent_did: DefId) {
612 let impl_generics = clean_impl_generics(cache.parent_stack.last());
613 let impl_id = if let Some(ParentStackItem::Impl { item_id, .. }) = cache.parent_stack.last() {
614 item_id.as_def_id()
615 } else {
616 None
617 };
618 let orphan_item =
619 OrphanImplItem { parent: parent_did, item: item.clone(), impl_generics, impl_id };
620 cache.orphan_impl_items.push(orphan_item);
621}
622
623pub(crate) struct OrphanImplItem {
624 pub(crate) parent: DefId,
625 pub(crate) impl_id: Option<DefId>,
626 pub(crate) item: clean::Item,
627 pub(crate) impl_generics: Option<(clean::Type, clean::Generics)>,
628}
629
630enum ParentStackItem {
637 Impl {
638 for_: clean::Type,
639 trait_: Option<clean::Path>,
640 generics: clean::Generics,
641 kind: clean::ImplKind,
642 item_id: ItemId,
643 },
644 Type(ItemId),
645}
646
647impl ParentStackItem {
648 fn new(item: &clean::Item) -> Self {
649 match &item.kind {
650 clean::ItemKind::ImplItem(box clean::Impl { for_, trait_, generics, kind, .. }) => {
651 ParentStackItem::Impl {
652 for_: for_.clone(),
653 trait_: trait_.clone(),
654 generics: generics.clone(),
655 kind: kind.clone(),
656 item_id: item.item_id,
657 }
658 }
659 _ => ParentStackItem::Type(item.item_id),
660 }
661 }
662 fn is_trait_impl(&self) -> bool {
663 matches!(self, ParentStackItem::Impl { trait_: Some(..), .. })
664 }
665 fn item_id(&self) -> ItemId {
666 match self {
667 ParentStackItem::Impl { item_id, .. } => *item_id,
668 ParentStackItem::Type(item_id) => *item_id,
669 }
670 }
671}
672
673fn clean_impl_generics(item: Option<&ParentStackItem>) -> Option<(clean::Type, clean::Generics)> {
674 if let Some(ParentStackItem::Impl { for_, generics, kind: clean::ImplKind::Normal, .. }) = item
675 {
676 Some((for_.clone(), generics.clone()))
677 } else {
678 None
679 }
680}