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