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 }
381 }
382
383 let (item, parent_pushed) = match item.kind {
385 clean::TraitItem(..)
386 | clean::EnumItem(..)
387 | clean::ForeignTypeItem
388 | clean::StructItem(..)
389 | clean::UnionItem(..)
390 | clean::VariantItem(..)
391 | clean::TypeAliasItem(..)
392 | clean::ImplItem(..) => {
393 self.cache.parent_stack.push(ParentStackItem::new(&item));
394 (self.fold_item_recur(item), true)
395 }
396 _ => (self.fold_item_recur(item), false),
397 };
398
399 let ret = if let clean::Item {
402 inner: box clean::ItemInner { kind: clean::ImplItem(ref i), .. },
403 } = item
404 {
405 let mut dids = FxIndexSet::default();
409 match i.for_ {
410 clean::Type::Path { ref path }
411 | clean::BorrowedRef { type_: box clean::Type::Path { ref path }, .. } => {
412 dids.insert(path.def_id());
413 if let Some(generics) = path.generics()
414 && let ty::Adt(adt, _) =
415 self.tcx.type_of(path.def_id()).instantiate_identity().kind()
416 && adt.is_fundamental()
417 {
418 for ty in generics {
419 dids.extend(ty.def_id(self.cache));
420 }
421 }
422 }
423 clean::DynTrait(ref bounds, _)
424 | clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
425 dids.insert(bounds[0].trait_.def_id());
426 }
427 ref t => {
428 let did = t
429 .primitive_type()
430 .and_then(|t| self.cache.primitive_locations.get(&t).cloned());
431
432 dids.extend(did);
433 }
434 }
435
436 if let Some(trait_) = &i.trait_
437 && let Some(generics) = trait_.generics()
438 {
439 for bound in generics {
440 dids.extend(bound.def_id(self.cache));
441 }
442 }
443 let impl_item = Impl { impl_item: item };
444 let impl_did = impl_item.def_id();
445 let trait_did = impl_item.trait_did();
446 if trait_did.is_none_or(|d| self.cache.traits.contains_key(&d)) {
447 for did in dids {
448 if self.impl_ids.entry(did).or_default().insert(impl_did) {
449 self.cache.impls.entry(did).or_default().push(impl_item.clone());
450 }
451 }
452 } else {
453 let trait_did = trait_did.expect("no trait did");
454 self.cache.orphan_trait_impls.push((trait_did, dids, impl_item));
455 }
456 None
457 } else {
458 Some(item)
459 };
460
461 if pushed {
462 self.cache.stack.pop().expect("stack already empty");
463 }
464 if parent_pushed {
465 self.cache.parent_stack.pop().expect("parent stack already empty");
466 }
467 self.cache.stripped_mod = orig_stripped_mod;
468 ret
469 }
470}
471
472fn add_item_to_search_index(tcx: TyCtxt<'_>, cache: &mut Cache, item: &clean::Item, name: Symbol) {
473 let item_def_id = item.item_id.as_def_id().unwrap();
475 let (parent_did, parent_path) = match item.kind {
476 clean::StrippedItem(..) => return,
477 clean::ProvidedAssocConstItem(..)
478 | clean::ImplAssocConstItem(..)
479 | clean::AssocTypeItem(..)
480 if cache.parent_stack.last().is_some_and(|parent| parent.is_trait_impl()) =>
481 {
482 return;
484 }
485 clean::RequiredMethodItem(..)
486 | clean::RequiredAssocConstItem(..)
487 | clean::RequiredAssocTypeItem(..)
488 | clean::StructFieldItem(..)
489 | clean::VariantItem(..) => {
490 if cache.stripped_mod
493 || item.type_() == ItemType::StructField
494 && name.as_str().chars().all(|c| c.is_ascii_digit())
495 {
496 return;
497 }
498 let parent_did =
499 cache.parent_stack.last().expect("parent_stack is empty").item_id().expect_def_id();
500 let parent_path = &cache.stack[..cache.stack.len() - 1];
501 (Some(parent_did), parent_path)
502 }
503 clean::MethodItem(..)
504 | clean::ProvidedAssocConstItem(..)
505 | clean::ImplAssocConstItem(..)
506 | clean::AssocTypeItem(..) => {
507 let last = cache.parent_stack.last().expect("parent_stack is empty 2");
508 let parent_did = match last {
509 ParentStackItem::Impl { for_: clean::Type::BorrowedRef { type_, .. }, .. } => {
516 type_.def_id(cache)
517 }
518 ParentStackItem::Impl { for_, .. } => for_.def_id(cache),
519 ParentStackItem::Type(item_id) => item_id.as_def_id(),
520 };
521 let Some(parent_did) = parent_did else { return };
522 match cache.paths.get(&parent_did) {
547 Some((fqp, _)) => (Some(parent_did), &fqp[..fqp.len() - 1]),
548 None => {
549 handle_orphan_impl_child(cache, item, parent_did);
550 return;
551 }
552 }
553 }
554 _ => {
555 if item_def_id.is_crate_root() || cache.stripped_mod {
558 return;
559 }
560 (None, &*cache.stack)
561 }
562 };
563
564 debug_assert!(!item.is_stripped());
565
566 let desc = short_markdown_summary(&item.doc_value(), &item.link_names(cache));
567 let defid = match &item.kind {
573 clean::ItemKind::ImportItem(import) => import.source.did.unwrap_or(item_def_id),
574 _ => item_def_id,
575 };
576 let impl_id = if let Some(ParentStackItem::Impl { item_id, .. }) = cache.parent_stack.last() {
577 item_id.as_def_id()
578 } else {
579 None
580 };
581 let search_type = get_function_type_for_search(
582 item,
583 tcx,
584 clean_impl_generics(cache.parent_stack.last()).as_ref(),
585 parent_did,
586 cache,
587 );
588 let aliases = item.attrs.get_doc_aliases();
589 let deprecation = item.deprecation(tcx);
590 let index_item = IndexItem {
591 ty: item.type_(),
592 defid: Some(defid),
593 name,
594 module_path: parent_path.to_vec(),
595 desc,
596 parent: parent_did,
597 parent_idx: None,
598 exact_module_path: None,
599 impl_id,
600 search_type,
601 aliases,
602 deprecation,
603 };
604 cache.search_index.push(index_item);
605}
606
607fn handle_orphan_impl_child(cache: &mut Cache, item: &clean::Item, parent_did: DefId) {
611 let impl_generics = clean_impl_generics(cache.parent_stack.last());
612 let impl_id = if let Some(ParentStackItem::Impl { item_id, .. }) = cache.parent_stack.last() {
613 item_id.as_def_id()
614 } else {
615 None
616 };
617 let orphan_item =
618 OrphanImplItem { parent: parent_did, item: item.clone(), impl_generics, impl_id };
619 cache.orphan_impl_items.push(orphan_item);
620}
621
622pub(crate) struct OrphanImplItem {
623 pub(crate) parent: DefId,
624 pub(crate) impl_id: Option<DefId>,
625 pub(crate) item: clean::Item,
626 pub(crate) impl_generics: Option<(clean::Type, clean::Generics)>,
627}
628
629enum ParentStackItem {
636 Impl {
637 for_: clean::Type,
638 trait_: Option<clean::Path>,
639 generics: clean::Generics,
640 kind: clean::ImplKind,
641 item_id: ItemId,
642 },
643 Type(ItemId),
644}
645
646impl ParentStackItem {
647 fn new(item: &clean::Item) -> Self {
648 match &item.kind {
649 clean::ItemKind::ImplItem(box clean::Impl { for_, trait_, generics, kind, .. }) => {
650 ParentStackItem::Impl {
651 for_: for_.clone(),
652 trait_: trait_.clone(),
653 generics: generics.clone(),
654 kind: kind.clone(),
655 item_id: item.item_id,
656 }
657 }
658 _ => ParentStackItem::Type(item.item_id),
659 }
660 }
661 fn is_trait_impl(&self) -> bool {
662 matches!(self, ParentStackItem::Impl { trait_: Some(..), .. })
663 }
664 fn item_id(&self) -> ItemId {
665 match self {
666 ParentStackItem::Impl { item_id, .. } => *item_id,
667 ParentStackItem::Type(item_id) => *item_id,
668 }
669 }
670}
671
672fn clean_impl_generics(item: Option<&ParentStackItem>) -> Option<(clean::Type, clean::Generics)> {
673 if let Some(ParentStackItem::Impl { for_, generics, kind: clean::ImplKind::Normal, .. }) = item
674 {
675 Some((for_.clone(), generics.clone()))
676 } else {
677 None
678 }
679}