1use std::mem;
2
3use rustc_ast::join_path_syms;
4use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
5use rustc_hir::StabilityLevel;
6use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet};
7use rustc_metadata::creader::CStore;
8use rustc_middle::ty::{self, TyCtxt};
9use rustc_span::Symbol;
10use tracing::debug;
11
12use crate::clean::types::ExternalLocation;
13use crate::clean::{self, ExternalCrate, ItemId, PrimitiveType};
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: FxHashMap<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 pub(crate) hidden_cfg: FxHashSet<clean::cfg::Cfg>,
131
132 pub(crate) inlined_items: DefIdSet,
136}
137
138struct CacheBuilder<'a, 'tcx> {
140 cache: &'a mut Cache,
141 impl_ids: DefIdMap<DefIdSet>,
143 tcx: TyCtxt<'tcx>,
144 is_json_output: bool,
145}
146
147impl Cache {
148 pub(crate) fn new(document_private: bool, document_hidden: bool) -> Self {
149 Cache { document_private, document_hidden, ..Cache::default() }
150 }
151
152 pub(crate) fn populate(cx: &mut DocContext<'_>, mut krate: clean::Crate) -> clean::Crate {
155 let tcx = cx.tcx;
156
157 debug!(?cx.cache.crate_version);
159 assert!(cx.external_traits.is_empty());
160 cx.cache.traits = mem::take(&mut krate.external_traits);
161
162 let render_options = &cx.render_options;
163 let extern_url_takes_precedence = render_options.extern_html_root_takes_precedence;
164 let dst = &render_options.output;
165
166 let cstore = CStore::from_tcx(tcx);
168 for (name, extern_url) in &render_options.extern_html_root_urls {
169 if let Some(crate_num) = cstore.resolved_extern_crate(Symbol::intern(name)) {
170 let e = ExternalCrate { crate_num };
171 let location = e.location(Some(extern_url), extern_url_takes_precedence, dst, tcx);
172 cx.cache.extern_locations.insert(e.crate_num, location);
173 }
174 }
175
176 for &crate_num in tcx.crates(()) {
179 let e = ExternalCrate { crate_num };
180
181 let name = e.name(tcx);
182 cx.cache.extern_locations.entry(e.crate_num).or_insert_with(|| {
183 let extern_url =
186 render_options.extern_html_root_urls.get(name.as_str()).map(|u| &**u);
187 e.location(extern_url, extern_url_takes_precedence, dst, tcx)
188 });
189 cx.cache.external_paths.insert(e.def_id(), (vec![name], ItemType::Module));
190 }
191
192 cx.cache.primitive_locations = PrimitiveType::primitive_locations(tcx).clone();
194 for (prim, &def_id) in &cx.cache.primitive_locations {
195 let crate_name = tcx.crate_name(def_id.krate);
196 cx.cache
199 .external_paths
200 .insert(def_id, (vec![crate_name, prim.as_sym()], ItemType::Primitive));
201 }
202
203 let (krate, mut impl_ids) = {
204 let is_json_output = cx.is_json_output();
205 let mut cache_builder = CacheBuilder {
206 tcx,
207 cache: &mut cx.cache,
208 impl_ids: Default::default(),
209 is_json_output,
210 };
211 krate = cache_builder.fold_crate(krate);
212 (krate, cache_builder.impl_ids)
213 };
214
215 for (trait_did, dids, impl_) in cx.cache.orphan_trait_impls.drain(..) {
216 if cx.cache.traits.contains_key(&trait_did) {
217 for did in dids {
218 if impl_ids.entry(did).or_default().insert(impl_.def_id()) {
219 cx.cache.impls.entry(did).or_default().push(impl_.clone());
220 }
221 }
222 }
223 }
224
225 krate
226 }
227}
228
229impl DocFolder for CacheBuilder<'_, '_> {
230 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
231 if item.item_id.is_local() {
232 debug!(
233 "folding {} (stripped: {:?}) \"{:?}\", id {:?}",
234 item.type_(),
235 item.is_stripped(),
236 item.name,
237 item.item_id
238 );
239 }
240
241 let orig_stripped_mod = match item.kind {
244 clean::StrippedItem(box clean::ModuleItem(..)) => {
245 mem::replace(&mut self.cache.stripped_mod, true)
246 }
247 _ => self.cache.stripped_mod,
248 };
249
250 #[inline]
251 fn is_from_private_dep(tcx: TyCtxt<'_>, cache: &Cache, def_id: DefId) -> bool {
252 let krate = def_id.krate;
253
254 cache.masked_crates.contains(&krate) || tcx.is_private_dep(krate)
255 }
256
257 if let clean::ImplItem(ref i) = item.kind
260 && (self.cache.masked_crates.contains(&item.item_id.krate())
261 || i.trait_
262 .as_ref()
263 .is_some_and(|t| is_from_private_dep(self.tcx, self.cache, t.def_id()))
264 || i.for_
265 .def_id(self.cache)
266 .is_some_and(|d| is_from_private_dep(self.tcx, self.cache, d)))
267 {
268 return None;
269 }
270
271 if let clean::TraitItem(ref t) = item.kind {
274 self.cache.traits.entry(item.item_id.expect_def_id()).or_insert_with(|| (**t).clone());
275 } else if let clean::ImplItem(ref i) = item.kind
276 && let Some(trait_) = &i.trait_
277 && !i.kind.is_blanket()
278 {
279 self.cache
281 .implementors
282 .entry(trait_.def_id())
283 .or_default()
284 .push(Impl { impl_item: item.clone() });
285 }
286
287 let search_name = if !item.is_stripped() {
289 item.name.or_else(|| {
290 if let clean::ImportItem(ref i) = item.kind
291 && let clean::ImportKind::Simple(s) = i.kind
292 {
293 Some(s)
294 } else {
295 None
296 }
297 })
298 } else {
299 None
300 };
301 if let Some(name) = search_name {
302 add_item_to_search_index(self.tcx, self.cache, &item, name)
303 }
304
305 let pushed = match item.name {
307 Some(n) => {
308 self.cache.stack.push(n);
309 true
310 }
311 _ => false,
312 };
313
314 match item.kind {
315 clean::StructItem(..)
316 | clean::EnumItem(..)
317 | clean::TypeAliasItem(..)
318 | clean::TraitItem(..)
319 | clean::TraitAliasItem(..)
320 | clean::FunctionItem(..)
321 | clean::ModuleItem(..)
322 | clean::ForeignFunctionItem(..)
323 | clean::ForeignStaticItem(..)
324 | clean::ConstantItem(..)
325 | clean::StaticItem(..)
326 | clean::UnionItem(..)
327 | clean::ForeignTypeItem
328 | clean::MacroItem(..)
329 | clean::ProcMacroItem(..)
330 | clean::VariantItem(..) => {
331 use rustc_data_structures::fx::IndexEntry as Entry;
332
333 let skip_because_unstable = matches!(
334 item.stability.map(|stab| stab.level),
335 Some(StabilityLevel::Stable { allowed_through_unstable_modules: Some(_), .. })
336 );
337
338 if (!self.cache.stripped_mod && !skip_because_unstable) || self.is_json_output {
339 let item_def_id = item.item_id.expect_def_id();
346 match self.cache.paths.entry(item_def_id) {
347 Entry::Vacant(entry) => {
348 entry.insert((self.cache.stack.clone(), item.type_()));
349 }
350 Entry::Occupied(mut entry) => {
351 if entry.get().0.len() > self.cache.stack.len() {
352 entry.insert((self.cache.stack.clone(), item.type_()));
353 }
354 }
355 }
356 }
357 }
358 clean::PrimitiveItem(..) => {
359 self.cache
360 .paths
361 .insert(item.item_id.expect_def_id(), (self.cache.stack.clone(), item.type_()));
362 }
363
364 clean::ExternCrateItem { .. }
365 | clean::ImportItem(..)
366 | clean::ImplItem(..)
367 | clean::RequiredMethodItem(..)
368 | clean::MethodItem(..)
369 | clean::StructFieldItem(..)
370 | clean::RequiredAssocConstItem(..)
371 | clean::ProvidedAssocConstItem(..)
372 | clean::ImplAssocConstItem(..)
373 | clean::RequiredAssocTypeItem(..)
374 | clean::AssocTypeItem(..)
375 | clean::StrippedItem(..)
376 | clean::KeywordItem => {
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 path = join_path_syms(parent_path);
578 let impl_id = if let Some(ParentStackItem::Impl { item_id, .. }) = cache.parent_stack.last() {
579 item_id.as_def_id()
580 } else {
581 None
582 };
583 let search_type = get_function_type_for_search(
584 item,
585 tcx,
586 clean_impl_generics(cache.parent_stack.last()).as_ref(),
587 parent_did,
588 cache,
589 );
590 let aliases = item.attrs.get_doc_aliases();
591 let deprecation = item.deprecation(tcx);
592 let index_item = IndexItem {
593 ty: item.type_(),
594 defid: Some(defid),
595 name,
596 path,
597 desc,
598 parent: parent_did,
599 parent_idx: None,
600 exact_path: None,
601 impl_id,
602 search_type,
603 aliases,
604 deprecation,
605 };
606 cache.search_index.push(index_item);
607}
608
609fn handle_orphan_impl_child(cache: &mut Cache, item: &clean::Item, parent_did: DefId) {
613 let impl_generics = clean_impl_generics(cache.parent_stack.last());
614 let impl_id = if let Some(ParentStackItem::Impl { item_id, .. }) = cache.parent_stack.last() {
615 item_id.as_def_id()
616 } else {
617 None
618 };
619 let orphan_item =
620 OrphanImplItem { parent: parent_did, item: item.clone(), impl_generics, impl_id };
621 cache.orphan_impl_items.push(orphan_item);
622}
623
624pub(crate) struct OrphanImplItem {
625 pub(crate) parent: DefId,
626 pub(crate) impl_id: Option<DefId>,
627 pub(crate) item: clean::Item,
628 pub(crate) impl_generics: Option<(clean::Type, clean::Generics)>,
629}
630
631enum ParentStackItem {
638 Impl {
639 for_: clean::Type,
640 trait_: Option<clean::Path>,
641 generics: clean::Generics,
642 kind: clean::ImplKind,
643 item_id: ItemId,
644 },
645 Type(ItemId),
646}
647
648impl ParentStackItem {
649 fn new(item: &clean::Item) -> Self {
650 match &item.kind {
651 clean::ItemKind::ImplItem(box clean::Impl { for_, trait_, generics, kind, .. }) => {
652 ParentStackItem::Impl {
653 for_: for_.clone(),
654 trait_: trait_.clone(),
655 generics: generics.clone(),
656 kind: kind.clone(),
657 item_id: item.item_id,
658 }
659 }
660 _ => ParentStackItem::Type(item.item_id),
661 }
662 }
663 fn is_trait_impl(&self) -> bool {
664 matches!(self, ParentStackItem::Impl { trait_: Some(..), .. })
665 }
666 fn item_id(&self) -> ItemId {
667 match self {
668 ParentStackItem::Impl { item_id, .. } => *item_id,
669 ParentStackItem::Type(item_id) => *item_id,
670 }
671 }
672}
673
674fn clean_impl_generics(item: Option<&ParentStackItem>) -> Option<(clean::Type, clean::Generics)> {
675 if let Some(ParentStackItem::Impl { for_, generics, kind: clean::ImplKind::Normal, .. }) = item
676 {
677 Some((for_.clone(), generics.clone()))
678 } else {
679 None
680 }
681}