1use std::mem;
5
6use rustc_attr_ir::{DocInline, find_attr};
7use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
8use rustc_hir::def::{DefKind, MacroKinds, Res};
9use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId, LocalDefIdSet};
10use rustc_hir::intravisit::{Visitor, walk_body, walk_item};
11use rustc_hir::{self as hir, HirId, Node};
12use rustc_middle::hir::nested_filter;
13use rustc_middle::ty::TyCtxt;
14use rustc_span::Span;
15use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalModId};
16use rustc_span::symbol::{Symbol, kw};
17use tracing::{debug, instrument, trace};
18
19use crate::clean::reexport_chain;
20use crate::clean::utils::{inherits_doc_hidden, should_ignore_res};
21use crate::core;
22
23#[derive(Debug)]
26pub(crate) struct Module<'hir> {
27 pub(crate) name: Symbol,
28 pub(crate) where_inner: Span,
29 pub(crate) mods: Vec<Module<'hir>>,
30 pub(crate) def_id: LocalDefId,
31 pub(crate) renamed: Option<Symbol>,
32 pub(crate) import_id: Option<LocalDefId>,
33 pub(crate) items: FxIndexMap<(LocalDefId, Option<Symbol>), ItemEntry<'hir>>,
53
54 pub(crate) inlined_foreigns: FxIndexMap<(DefId, Option<Symbol>), InlinedForeign>,
63 pub(crate) foreigns: Vec<Foreign<'hir>>,
65}
66
67#[derive(Debug)]
68pub(crate) struct ItemEntry<'hir> {
69 pub(crate) item: &'hir hir::Item<'hir>,
70 pub(crate) renamed: Option<Symbol>,
71 pub(crate) import_ids: Vec<LocalDefId>,
72}
73
74#[derive(Debug)]
75pub(crate) struct InlinedForeign {
76 pub(crate) res: Res,
77 pub(crate) import_id: LocalDefId,
78}
79
80#[derive(Debug)]
81pub(crate) struct Foreign<'hir> {
82 pub(crate) item: &'hir hir::ForeignItem<'hir>,
83 pub(crate) renamed: Option<Symbol>,
84 pub(crate) import_id: Option<LocalDefId>,
85}
86
87impl Module<'_> {
88 pub(crate) fn new(
89 name: Symbol,
90 def_id: LocalDefId,
91 where_inner: Span,
92 renamed: Option<Symbol>,
93 import_id: Option<LocalDefId>,
94 ) -> Self {
95 Module {
96 name,
97 def_id,
98 where_inner,
99 renamed,
100 import_id,
101 mods: Vec::new(),
102 items: FxIndexMap::default(),
103 inlined_foreigns: FxIndexMap::default(),
104 foreigns: Vec::new(),
105 }
106 }
107
108 pub(crate) fn where_outer(&self, tcx: TyCtxt<'_>) -> Span {
109 tcx.def_span(self.def_id)
110 }
111}
112
113fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<Symbol> {
115 let crate_name = tcx.crate_name(did.krate);
116 let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| elem.data.get_opt_name());
117 std::iter::once(crate_name).chain(relative).collect()
118}
119
120#[derive(Copy, Clone)]
121enum GlobMode {
122 Everything,
124 NoGlob,
126 Only,
128}
129
130pub(crate) struct RustdocVisitor<'a, 'tcx> {
131 cx: &'a mut core::DocContext<'tcx>,
132 view_item_stack: LocalDefIdSet,
133 inlining: bool,
134 inside_public_path: bool,
136 exact_paths: DefIdMap<Vec<Symbol>>,
137 modules: Vec<Module<'tcx>>,
138 is_importable_from_parent: bool,
139 inside_body: bool,
140 glob_mode: GlobMode,
141}
142
143impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
144 pub(crate) fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
145 let mut stack = LocalDefIdSet::default();
147 stack.insert(CRATE_DEF_ID);
148 let om = Module::new(
149 cx.tcx.crate_name(LOCAL_CRATE),
150 CRATE_DEF_ID,
151 cx.tcx.hir_root_module().spans.inner_span,
152 None,
153 None,
154 );
155
156 RustdocVisitor {
157 cx,
158 view_item_stack: stack,
159 inlining: false,
160 inside_public_path: true,
161 exact_paths: Default::default(),
162 modules: vec![om],
163 is_importable_from_parent: true,
164 inside_body: false,
165 glob_mode: GlobMode::Everything,
166 }
167 }
168
169 fn store_path(&mut self, did: DefId) {
170 let tcx = self.cx.tcx;
171 self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
172 }
173
174 pub(crate) fn visit(mut self) -> Module<'tcx> {
175 let root_module = self.cx.tcx.hir_root_module();
176 self.visit_mod_contents(CRATE_DEF_ID, root_module);
177
178 let mut top_level_module = self.modules.pop().unwrap();
179
180 let mut inserted = FxHashSet::default();
192 for child in self.cx.tcx.module_children_local(CRATE_DEF_ID) {
193 if !child.reexport_chain.is_empty()
194 && let Res::Def(DefKind::Macro(_), def_id) = child.res
195 && let Some(local_def_id) = def_id.as_local()
196 && find_attr!(self.cx.tcx, def_id, MacroExport { .. })
197 && inserted.insert(def_id)
198 {
199 let item = self.cx.tcx.hir_expect_item(local_def_id);
200 let (ident, _, _) = item.expect_macro();
201 top_level_module.items.insert(
202 (local_def_id, Some(ident.name)),
203 ItemEntry { item, renamed: None, import_ids: Vec::new() },
204 );
205 }
206 }
207
208 self.cx.cache.exact_paths = self.exact_paths;
209 top_level_module
210 }
211
212 #[instrument(level = "debug", skip(self))]
216 fn visit_mod_contents(&mut self, def_id: LocalDefId, m: &'tcx hir::Mod<'tcx>) {
217 let orig_inside_public_path = self.inside_public_path;
219 self.inside_public_path &= self.cx.tcx.local_visibility(def_id).is_public();
220
221 let old_glob_mode = mem::replace(&mut self.glob_mode, GlobMode::NoGlob);
224 for &i in m.item_ids {
225 let item = self.cx.tcx.hir_item(i);
226 self.visit_item(item);
227 }
228 self.glob_mode = GlobMode::Only;
229 for &i in m.item_ids {
230 let item = self.cx.tcx.hir_item(i);
231 if matches!(item.kind, hir::ItemKind::Use(..)) {
235 self.visit_item_inner(item, None, None);
236 }
237 }
238 self.glob_mode = old_glob_mode;
239 self.inside_public_path = orig_inside_public_path;
240 }
241
242 #[instrument(level = "debug", skip(self), ret)]
252 fn maybe_inline_local(
253 &mut self,
254 def_id: LocalDefId,
255 res: Res,
256 renamed: Option<Symbol>,
257 please_inline: bool,
258 import_id: Option<LocalDefId>,
259 ) -> bool {
260 fn inherits_hidden(tcx: TyCtxt<'_>, document_hidden: bool, res_did: LocalDefId) -> bool {
261 let inherits_hidden = !document_hidden && inherits_doc_hidden(tcx, res_did, None);
262 debug!(?inherits_hidden);
263 inherits_hidden
264 }
265
266 if renamed == Some(kw::Underscore) {
267 debug!("not inlining `_` reexports");
268 return false;
270 }
271
272 if self.cx.is_json_output() {
273 return false;
274 }
275
276 let tcx = self.cx.tcx;
277 let Some(ori_res_did) = res.opt_def_id() else {
278 debug!("no resolution");
279 return false;
280 };
281
282 let document_hidden = self.cx.document_hidden();
283 let use_attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
284 let is_no_inline = find_attr!(
286 use_attrs,
287 Doc(d)
288 if d.inline.is_some_and(|(inline, _)| inline == DocInline::NoInline)
289 ) || (document_hidden
290 && find_attr!(use_attrs, Doc(rustc_attr_ir::DocAttribute { hidden: Some(_), .. })));
291
292 if is_no_inline {
293 debug!("doc::no_inline or doc::hidden");
294 return false;
295 }
296
297 let is_glob = renamed.is_none();
298 let is_hidden = !document_hidden && tcx.is_doc_hidden(ori_res_did);
299 debug!(?is_hidden, ?is_glob);
300 let Some(res_did) = ori_res_did.as_local() else {
301 crate::visit_lib::lib_embargo_visit_item(self.cx, ori_res_did);
306 if is_hidden || is_glob {
307 return false;
308 }
309 self.modules
315 .last_mut()
316 .unwrap()
317 .inlined_foreigns
318 .insert((ori_res_did, renamed), InlinedForeign { res, import_id: def_id });
319 return true;
320 };
321 let item = tcx.hir_node_by_def_id(res_did);
322
323 if !please_inline {
324 let is_private_and_should_be_inlined = (is_glob || !self.cx.document_private())
325 && !self.cx.cache.effective_visibilities.is_directly_public(tcx, ori_res_did);
326 debug!(?is_private_and_should_be_inlined);
327
328 if (!is_private_and_should_be_inlined && !inherits_hidden(tcx, document_hidden, res_did)) || (
330 is_hidden &&
331 !matches!(item, Node::Item(&hir::Item { kind: hir::ItemKind::Mod(..), .. }))
334 ) ||
335 self.reexport_public_and_not_hidden(def_id, res_did)
337 {
338 return false;
339 }
340 }
341
342 let is_bang_macro = matches!(
343 item,
344 Node::Item(&hir::Item { kind: hir::ItemKind::Macro(_, _, kinds), .. }) if kinds.contains(MacroKinds::BANG)
345 );
346
347 if !self.view_item_stack.insert(res_did) && !is_bang_macro {
348 return false;
349 }
350
351 trace!(?item);
352
353 let inlined = match item {
354 Node::NestedUseTree(..) | Node::Item(_)
358 if is_bang_macro && !please_inline && !is_glob && is_hidden =>
359 {
360 return false;
361 }
362 Node::Item(&hir::Item { kind: hir::ItemKind::Mod(_, m), .. }) if is_glob => {
363 let prev = mem::replace(&mut self.inlining, true);
364 let prev_glob = mem::replace(&mut self.glob_mode, GlobMode::Everything);
365 for &i in m.item_ids {
366 let i = tcx.hir_item(i);
367 self.visit_item_inner(i, None, Some(import_id.unwrap_or(def_id)));
368 }
369 self.glob_mode = prev_glob;
370 self.inlining = prev;
371 true
372 }
373 Node::Item(it) if !is_glob => {
374 debug!("inlining item");
375 let prev = mem::replace(&mut self.inlining, true);
376 self.visit_item_inner(it, renamed, Some(import_id.unwrap_or(def_id)));
377 self.inlining = prev;
378 true
379 }
380 Node::ForeignItem(it) if !is_glob => {
381 let prev = mem::replace(&mut self.inlining, true);
382 self.visit_foreign_item_inner(it, renamed, Some(import_id.unwrap_or(def_id)));
383 self.inlining = prev;
384 true
385 }
386 _ => false,
387 };
388 self.view_item_stack.remove(&res_did);
389 if inlined {
390 self.cx.cache.inlined_items.insert(ori_res_did);
391 }
392 inlined
393 }
394
395 #[instrument(level = "debug", skip(self), ret)]
400 fn reexport_public_and_not_hidden(
401 &self,
402 import_def_id: LocalDefId,
403 target_def_id: LocalDefId,
404 ) -> bool {
405 if self.cx.document_hidden() {
406 return true;
407 }
408 let tcx = self.cx.tcx;
409 let item_def_id = reexport_chain(tcx, import_def_id, target_def_id.to_def_id())
410 .iter()
411 .flat_map(|reexport| reexport.id())
412 .map(|id| id.expect_local())
413 .nth(1)
414 .unwrap_or(target_def_id);
415 debug!(?item_def_id);
416
417 item_def_id != import_def_id
418 && self.cx.cache.effective_visibilities.is_directly_public(tcx, item_def_id.to_def_id())
419 && !tcx.is_doc_hidden(item_def_id)
420 && !inherits_doc_hidden(tcx, item_def_id, None)
421 }
422
423 #[inline]
424 fn add_impl_to_current_mod(&mut self, item: &'tcx hir::Item<'_>, impl_: hir::Impl<'_>) {
425 self.add_to_current_mod(
426 item,
427 if impl_.of_trait.is_none() { None } else { Some(rustc_span::symbol::kw::Impl) },
432 None,
433 );
434 }
435
436 #[inline]
437 #[instrument(level = "debug", skip(self))]
438 fn add_to_current_mod(
439 &mut self,
440 item: &'tcx hir::Item<'_>,
441 mut renamed: Option<Symbol>,
442 import_id: Option<LocalDefId>,
443 ) {
444 if self.is_importable_from_parent
445 || match item.kind {
448 hir::ItemKind::Impl(..) => true,
449 hir::ItemKind::Macro(_, _, _) => {
450 find_attr!(self.cx.tcx, item.owner_id.def_id, MacroExport{..})
451 }
452 _ => false,
453 }
454 {
455 if renamed == item.kind.ident().map(|ident| ident.name) {
456 renamed = None;
457 }
458 let key = (item.owner_id.def_id, renamed);
459 self.modules
460 .last_mut()
461 .unwrap()
462 .items
463 .entry(key)
464 .or_insert_with(|| ItemEntry { item, renamed, import_ids: vec![] })
465 .import_ids
466 .extend(import_id);
467 }
468 }
469
470 #[instrument(level = "debug", skip(self))]
471 fn visit_item_inner(
472 &mut self,
473 item: &'tcx hir::Item<'_>,
474 renamed: Option<Symbol>,
475 import_id: Option<LocalDefId>,
476 ) {
477 if self.inside_body {
478 if let hir::ItemKind::Impl(impl_) = item.kind {
489 self.add_impl_to_current_mod(item, impl_);
490 }
491 return;
492 }
493 let get_name = || renamed.unwrap_or(item.kind.ident().unwrap().name);
494 let tcx = self.cx.tcx;
495
496 let def_id = item.owner_id.to_def_id();
497 let is_pub = tcx.visibility(def_id).is_public()
501 || (self.cx.document_private()
502 && (!matches!(item.kind, hir::ItemKind::Use(..))
503 || def_id.as_local().is_some_and(|def_id| {
504 tcx.visibility(def_id).is_accessible_from(CRATE_DEF_ID, tcx)
505 })));
506
507 if is_pub {
508 self.store_path(item.owner_id.to_def_id());
509 }
510
511 match item.kind {
512 hir::ItemKind::ForeignMod { items, .. } => {
513 for &item in items {
514 let item = tcx.hir_foreign_item(item);
515 self.visit_foreign_item_inner(item, None, None);
516 }
517 }
518 _ if self.inlining && !is_pub => {}
520 hir::ItemKind::GlobalAsm { .. } => {}
521 hir::ItemKind::Use(ref tree) => {
522 self.visit_use_inner(
523 item,
524 renamed,
525 import_id,
526 is_pub,
527 item.owner_id.def_id,
528 item.hir_id(),
529 tree,
530 );
531 }
532 hir::ItemKind::Macro(_, macro_def, _) => {
533 let def_id = item.owner_id.to_def_id();
545 let is_macro_2_0 = !macro_def.macro_rules;
546 let nonexported = !find_attr!(tcx, def_id, MacroExport { .. });
547
548 if is_macro_2_0 || nonexported || self.inlining {
549 self.add_to_current_mod(item, renamed, import_id);
550 }
551 }
552 hir::ItemKind::Mod(_, m) => {
553 self.enter_mod(item.owner_id.def_id, m, get_name(), renamed, import_id);
554 }
555 hir::ItemKind::Fn { .. }
556 | hir::ItemKind::ExternCrate(..)
557 | hir::ItemKind::Enum(..)
558 | hir::ItemKind::Struct(..)
559 | hir::ItemKind::Union(..)
560 | hir::ItemKind::TyAlias(..)
561 | hir::ItemKind::Static(..)
562 | hir::ItemKind::Trait { .. }
563 | hir::ItemKind::TraitAlias(..) => {
564 self.add_to_current_mod(item, renamed, import_id);
565 }
566 hir::ItemKind::Const(..) => {
567 if get_name() != kw::Underscore {
570 self.add_to_current_mod(item, renamed, import_id);
571 }
572 }
573 hir::ItemKind::Impl(impl_) => {
574 if !self.inlining {
577 self.add_impl_to_current_mod(item, impl_);
578 }
579 }
580 hir::ItemKind::TestBinderConstraints { .. } => {}
581 }
582 }
583
584 #[instrument(level = "debug", skip(self))]
585 fn visit_use_inner(
586 &mut self,
587 item: &'tcx hir::Item<'tcx>,
588 renamed: Option<Symbol>,
589 import_id: Option<LocalDefId>,
590 is_pub: bool,
591 def_id: LocalDefId,
592 hir_id: HirId,
593 tree: &hir::UseTree<'tcx>,
594 ) {
595 let tcx = self.cx.tcx;
596 for res in tree.prefix.res.present_items() {
597 if should_ignore_res(res) {
600 continue;
601 }
602
603 let attrs = tcx.hir_attrs(hir_id);
604
605 if is_pub && (self.inside_public_path || self.cx.document_private()) {
608 let please_inline = if let Some(res_did) = res.opt_def_id()
609 && matches!(tcx.def_kind(res_did), DefKind::Macro(MacroKinds::BANG))
610 {
611 crate::clean::macro_reexport_is_inline(tcx, def_id, res_did)
612 } else {
613 find_attr!(
614 attrs,
615 Doc(d)
616 if d.inline.is_some_and(|(inline, _)| inline == DocInline::Inline)
617 )
618 };
619 let ident = match (tree.kind, self.glob_mode) {
620 (hir::UseKind::Single(ident), GlobMode::NoGlob | GlobMode::Everything) => {
621 Some(ident.name)
622 }
623 (hir::UseKind::Glob, GlobMode::Only | GlobMode::Everything) => None,
624 (hir::UseKind::Single(_), GlobMode::Only)
625 | (hir::UseKind::Glob, GlobMode::NoGlob) => continue,
626 (hir::UseKind::Nested { items }, _) => {
627 for (tree, hir_id, def_id) in items {
628 self.visit_use_inner(
629 item, renamed, import_id, is_pub, *def_id, *hir_id, tree,
630 );
631 }
632 continue;
633 }
634 };
635 if self.maybe_inline_local(def_id, res, ident, please_inline, import_id) {
636 debug!("Inlining {:?}", def_id);
637 continue;
638 }
639 }
640 self.add_to_current_mod(item, renamed, import_id);
641 }
642 }
643
644 fn visit_foreign_item_inner(
645 &mut self,
646 item: &'tcx hir::ForeignItem<'_>,
647 renamed: Option<Symbol>,
648 import_id: Option<LocalDefId>,
649 ) {
650 if !self.inlining || self.cx.tcx.visibility(item.owner_id).is_public() {
652 self.modules.last_mut().unwrap().foreigns.push(Foreign { item, renamed, import_id });
653 }
654 }
655
656 fn enter_mod(
660 &mut self,
661 id: LocalDefId,
662 m: &'tcx hir::Mod<'tcx>,
663 name: Symbol,
664 renamed: Option<Symbol>,
665 import_id: Option<LocalDefId>,
666 ) {
667 self.modules.push(Module::new(name, id, m.spans.inner_span, renamed, import_id));
668
669 self.visit_mod_contents(id, m);
670
671 let last = self.modules.pop().unwrap();
672 self.modules.last_mut().unwrap().mods.push(last);
673 }
674}
675
676impl<'tcx> Visitor<'tcx> for RustdocVisitor<'_, 'tcx> {
679 type NestedFilter = nested_filter::All;
680
681 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
682 self.cx.tcx
683 }
684
685 #[instrument(level = "debug", skip(self))]
686 fn visit_item(&mut self, i: &'tcx hir::Item<'tcx>) {
687 self.visit_item_inner(i, None, None);
688 let new_value = self.is_importable_from_parent
689 && matches!(
690 i.kind,
691 hir::ItemKind::Mod(..)
692 | hir::ItemKind::ForeignMod { .. }
693 | hir::ItemKind::Impl(..)
694 | hir::ItemKind::Trait { .. }
695 );
696 let prev = mem::replace(&mut self.is_importable_from_parent, new_value);
697 walk_item(self, i);
698 self.is_importable_from_parent = prev;
699 }
700
701 fn visit_mod(&mut self, _: &hir::Mod<'tcx>, _: Span, _: LocalModId) {
702 }
704
705 fn visit_use(
706 &mut self,
707 _: &hir::UseTree<'tcx>,
708 _: hir::HirId,
709 _: rustc_span::def_id::LocalDefId,
710 ) {
711 }
713
714 fn visit_path(&mut self, _: &hir::Path<'tcx>, _: hir::HirId) {
715 }
717
718 fn visit_label(&mut self, _: &rustc_ast::Label) {
719 }
721
722 fn visit_infer(
723 &mut self,
724 _inf_id: hir::HirId,
725 _inf_span: Span,
726 _kind: hir::intravisit::InferKind<'tcx>,
727 ) -> Self::Result {
728 }
730
731 fn visit_lifetime(&mut self, _: &hir::Lifetime) {
732 }
734
735 fn visit_body(&mut self, b: &hir::Body<'tcx>) {
736 let prev = mem::replace(&mut self.inside_body, true);
737 walk_body(self, b);
738 self.inside_body = prev;
739 }
740}