Skip to main content

rustdoc/
visit_ast.rs

1//! The Rust AST Visitor. Extracts useful information and massages it into a form
2//! usable for `clean`.
3
4use 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/// This module is used to store stuff from Rust's AST in a more convenient
24/// manner (and with prettier names) before cleaning.
25#[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    /// The key is the item `ItemId`. We use `FxIndexMap` to keep the insert order.
34    ///
35    /// `import_id` needs to be a `Vec` because we live in a dark world where you can have code
36    /// like:
37    ///
38    /// ```
39    /// mod raw {
40    ///     pub fn foo() {}
41    /// }
42    ///
43    /// /// Foobar
44    /// pub use raw::foo;
45    ///
46    /// pub use raw::*;
47    /// ```
48    ///
49    /// So in this case, we don't want to have two items but just one with attributes from all
50    /// non-glob imports to be merged. Glob imports attributes are always ignored, whether they're
51    /// shadowed or not.
52    pub(crate) items: FxIndexMap<(LocalDefId, Option<Symbol>), ItemEntry<'hir>>,
53
54    /// The key is `(def_id, renamed)`.
55    ///
56    /// `inlined_foreigns` only contains `extern` items
57    /// that are cross-crate inlined.
58    ///
59    /// Locally inlined `extern` items are
60    /// stored in `foreigns` with the `import_id` set,
61    /// analogous to how `items` is.
62    pub(crate) inlined_foreigns: FxIndexMap<(DefId, Option<Symbol>), InlinedForeign>,
63    /// (item, renamed, import_id)
64    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
113// FIXME: Should this be replaced with tcx.def_path_str?
114fn 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    // Globs and everything else
123    Everything,
124    // Skip all globs
125    NoGlob,
126    // Skip all items except for globs
127    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    /// Are the current module and all of its parents public?
135    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        // If the root is re-exported, terminate all recursion.
146        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        // `#[macro_export] macro_rules!` items are reexported at the top level of the
181        // crate, regardless of where they're defined. We want to document the
182        // top level re-export of the macro, not its original definition, since
183        // the re-export defines the path that a user will actually see. Accordingly,
184        // we add the re-export as an item here, and then skip over the original
185        // definition in `visit_item()` below.
186        //
187        // We also skip `#[macro_export] macro_rules!` that have already been inserted,
188        // it can happen if within the same module a `#[macro_export] macro_rules!`
189        // is declared but also a reexport of itself producing two exports of the same
190        // macro in the same module.
191        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    /// This method will go through the given module items in two passes:
213    /// 1. The items which are not glob imports/reexports.
214    /// 2. The glob imports/reexports.
215    #[instrument(level = "debug", skip(self))]
216    fn visit_mod_contents(&mut self, def_id: LocalDefId, m: &'tcx hir::Mod<'tcx>) {
217        // Keep track of if there were any private modules in the path.
218        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        // Reimplementation of `walk_mod` because we need to do it in two passes (explanations in
222        // the second loop):
223        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            // To match the way import precedence works, visit glob imports last.
232            // Later passes in rustdoc will de-duplicate by name and kind, so if glob-
233            // imported items appear last, then they'll be the ones that get discarded.
234            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    /// Tries to resolve the target of a `pub use` statement and inlines the
243    /// target if it is defined locally and would not be documented otherwise,
244    /// or when it is specifically requested with `please_inline`.
245    /// (the latter is the case when the import is marked `doc(inline)`)
246    ///
247    /// Cross-crate inlining occurs later on during crate cleaning
248    /// and follows different rules.
249    ///
250    /// Returns `true` if the target has been inlined.
251    #[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            // We never inline `_` reexports.
269            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        // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
285        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            // For cross-crate impl inlining we need to know whether items are
302            // reachable in documentation -- a previously unreachable item can be
303            // made reachable by cross-crate inlining which we're checking here.
304            // (this is done here because we need to know this upfront).
305            crate::visit_lib::lib_embargo_visit_item(self.cx, ori_res_did);
306            if is_hidden || is_glob {
307                return false;
308            }
309            // We store inlined foreign items otherwise, it'd mean that the `use` item would be kept
310            // around. It's not a problem unless this `use` imports both a local AND a foreign item.
311            // If a local item is inlined, its `use` is not supposed to still be around in `clean`,
312            // which would make appear the `use` in the generated documentation like the local item
313            // was not inlined even though it actually was.
314            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            // Only inline if requested or if the item would otherwise be stripped.
329            if (!is_private_and_should_be_inlined && !inherits_hidden(tcx, document_hidden, res_did)) || (
330                is_hidden &&
331                // If it's a doc hidden module, we need to keep it in case some of its inner items
332                // are re-exported.
333                !matches!(item, Node::Item(&hir::Item { kind: hir::ItemKind::Mod(..), .. }))
334            ) ||
335                // The imported item is public and not `doc(hidden)` so no need to inline it.
336                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            // Bang macros are handled a bit on their because of how they are handled by the
355            // compiler. If they have `#[doc(hidden)]` and the re-export doesn't have
356            // `#[doc(inline)]`, then we don't inline it.
357            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    /// Returns `true` if the item is visible, meaning it's not `#[doc(hidden)]` or private.
396    ///
397    /// This function takes into account the entire re-export `use` chain, so it needs the
398    /// ID of the "leaf" `use` and the ID of the "root" item.
399    #[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            // The symbol here is used as a "sentinel" value and has no meaning in
428            // itself. It just tells that this is an inlined impl and that it should not
429            // be cleaned as a normal `ImplItem` but instead as a `PlaceholderImplItem`.
430            // It's to ensure that `doc_cfg` inheritance works as expected.
431            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            // If we're inside an item, only impl blocks and `macro_rules!` with the `macro_export`
446            // attribute can still be visible.
447            || 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            // Only impls can be "seen" outside a body. For example:
479            //
480            // ```
481            // struct Bar;
482            //
483            // fn foo() {
484            //     impl Bar { fn bar() {} }
485            // }
486            // Bar::bar();
487            // ```
488            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        // Explanations: if the item is public, nothing more to check. If not, then we check if
498        // we're documenting private item. If we are, then we want all items, except if it's a
499        // `use`. In this case, we want to check if it's a reexport.
500        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 we're inlining, skip private items.
519            _ 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                // `#[macro_export] macro_rules!` items are handled separately in `visit()`,
534                // above, since they need to be documented at the module top level. Accordingly,
535                // we only want to handle macros if one of three conditions holds:
536                //
537                // 1. This macro was defined by `macro`, and thus isn't covered by the case
538                //    above.
539                // 2. This macro isn't marked with `#[macro_export]`, and thus isn't covered
540                //    by the case above.
541                // 3. We're inlining, since a reexport where inlining has been requested
542                //    should be inlined even if it is also documented at the top level.
543
544                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                // Underscore constants do not correspond to a nameable item and
568                // so are never useful in documentation.
569                if get_name() != kw::Underscore {
570                    self.add_to_current_mod(item, renamed, import_id);
571                }
572            }
573            hir::ItemKind::Impl(impl_) => {
574                // Don't duplicate impls when inlining, we'll pick
575                // them up regardless of where they're located.
576                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            // Struct and variant constructors and proc macro stubs always show up alongside
598            // their definitions, we've already processed them so just discard these.
599            if should_ignore_res(res) {
600                continue;
601            }
602
603            let attrs = tcx.hir_attrs(hir_id);
604
605            // If there was a private module in the current path then don't bother inlining
606            // anything as it will probably be stripped anyway.
607            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 inlining we only want to include public functions.
651        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    /// This method will create a new module and push it onto the "modules stack" then call
657    /// `visit_mod_contents`. Once done, it'll remove it from the "modules stack" and instead
658    /// add into the list of modules of the current module.
659    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
676// We need to implement this visitor so it'll go everywhere and retrieve items we're interested in
677// such as impl blocks in const blocks.
678impl<'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        // Handled in `visit_item_inner`
703    }
704
705    fn visit_use(
706        &mut self,
707        _: &hir::UseTree<'tcx>,
708        _: hir::HirId,
709        _: rustc_span::def_id::LocalDefId,
710    ) {
711        // Handled in `visit_item_inner`
712    }
713
714    fn visit_path(&mut self, _: &hir::Path<'tcx>, _: hir::HirId) {
715        // Handled in `visit_item_inner`
716    }
717
718    fn visit_label(&mut self, _: &rustc_ast::Label) {
719        // Unneeded.
720    }
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        // Unneeded
729    }
730
731    fn visit_lifetime(&mut self, _: &hir::Lifetime) {
732        // Unneeded.
733    }
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}