1 //! The Rust AST Visitor. Extracts useful information and massages it into a form
2 //! usable for `clean`.
4 use rustc_data_structures::fx::FxHashSet;
6 use rustc_hir::def::{DefKind, Res};
7 use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId, LocalDefIdSet};
8 use rustc_hir::{Node, CRATE_HIR_ID};
9 use rustc_middle::ty::{DefIdTree, TyCtxt};
10 use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE};
11 use rustc_span::symbol::{kw, sym, Symbol};
16 use crate::clean::{cfg::Cfg, AttributesExt, NestedAttributesExt};
19 /// This module is used to store stuff from Rust's AST in a more convenient
20 /// manner (and with prettier names) before cleaning.
22 pub(crate) struct Module<'hir> {
23 pub(crate) name: Symbol,
24 pub(crate) where_inner: Span,
25 pub(crate) mods: Vec<Module<'hir>>,
26 pub(crate) def_id: LocalDefId,
27 // (item, renamed, import_id)
28 pub(crate) items: Vec<(&'hir hir::Item<'hir>, Option<Symbol>, Option<LocalDefId>)>,
29 pub(crate) foreigns: Vec<(&'hir hir::ForeignItem<'hir>, Option<Symbol>)>,
33 pub(crate) fn new(name: Symbol, def_id: LocalDefId, where_inner: Span) -> Self {
44 pub(crate) fn where_outer(&self, tcx: TyCtxt<'_>) -> Span {
45 tcx.def_span(self.def_id)
49 // FIXME: Should this be replaced with tcx.def_path_str?
50 fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<Symbol> {
51 let crate_name = tcx.crate_name(did.krate);
52 let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| elem.data.get_opt_name());
53 std::iter::once(crate_name).chain(relative).collect()
56 pub(crate) fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: LocalDefId) -> bool {
57 while let Some(id) = tcx.opt_local_parent(node) {
59 if tcx.is_doc_hidden(node.to_def_id()) {
66 // Also, is there some reason that this doesn't use the 'visit'
67 // framework from syntax?.
69 pub(crate) struct RustdocVisitor<'a, 'tcx> {
70 cx: &'a mut core::DocContext<'tcx>,
71 view_item_stack: LocalDefIdSet,
73 /// Are the current module and all of its parents public?
74 inside_public_path: bool,
75 exact_paths: DefIdMap<Vec<Symbol>>,
78 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
79 pub(crate) fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
80 // If the root is re-exported, terminate all recursion.
81 let mut stack = LocalDefIdSet::default();
82 stack.insert(CRATE_DEF_ID);
85 view_item_stack: stack,
87 inside_public_path: true,
88 exact_paths: Default::default(),
92 fn store_path(&mut self, did: DefId) {
93 let tcx = self.cx.tcx;
94 self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
97 pub(crate) fn visit(mut self) -> Module<'tcx> {
98 let mut top_level_module = self.visit_mod_contents(
100 self.cx.tcx.hir().root_module(),
101 self.cx.tcx.crate_name(LOCAL_CRATE),
105 // `#[macro_export] macro_rules!` items are reexported at the top level of the
106 // crate, regardless of where they're defined. We want to document the
107 // top level rexport of the macro, not its original definition, since
108 // the rexport defines the path that a user will actually see. Accordingly,
109 // we add the rexport as an item here, and then skip over the original
110 // definition in `visit_item()` below.
112 // We also skip `#[macro_export] macro_rules!` that have already been inserted,
113 // it can happen if within the same module a `#[macro_export] macro_rules!`
114 // is declared but also a reexport of itself producing two exports of the same
115 // macro in the same module.
116 let mut inserted = FxHashSet::default();
117 for export in self.cx.tcx.module_reexports(CRATE_DEF_ID).unwrap_or(&[]) {
118 if let Res::Def(DefKind::Macro(_), def_id) = export.res {
119 if let Some(local_def_id) = def_id.as_local() {
120 if self.cx.tcx.has_attr(def_id, sym::macro_export) {
121 if inserted.insert(def_id) {
122 let item = self.cx.tcx.hir().expect_item(local_def_id);
123 top_level_module.items.push((item, None, None));
130 self.cx.cache.hidden_cfg = self
136 .filter(|attr| attr.has_name(sym::doc))
137 .flat_map(|attr| attr.meta_item_list().into_iter().flatten())
138 .filter(|attr| attr.has_name(sym::cfg_hide))
140 attr.meta_item_list()
144 Cfg::parse(attr.meta_item()?)
145 .map_err(|e| self.cx.sess().diagnostic().span_err(e.span, e.msg))
151 [Cfg::Cfg(sym::test, None), Cfg::Cfg(sym::doc, None), Cfg::Cfg(sym::doctest, None)]
156 self.cx.cache.exact_paths = self.exact_paths;
160 fn visit_mod_contents(
163 m: &'tcx hir::Mod<'tcx>,
165 parent_id: Option<LocalDefId>,
167 let mut om = Module::new(name, def_id, m.spans.inner_span);
168 // Keep track of if there were any private modules in the path.
169 let orig_inside_public_path = self.inside_public_path;
170 self.inside_public_path &= self.cx.tcx.local_visibility(def_id).is_public();
171 for &i in m.item_ids {
172 let item = self.cx.tcx.hir().item(i);
173 if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) {
176 self.visit_item(item, None, &mut om, parent_id);
178 for &i in m.item_ids {
179 let item = self.cx.tcx.hir().item(i);
180 // To match the way import precedence works, visit glob imports last.
181 // Later passes in rustdoc will de-duplicate by name and kind, so if glob-
182 // imported items appear last, then they'll be the ones that get discarded.
183 if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) {
184 self.visit_item(item, None, &mut om, parent_id);
187 self.inside_public_path = orig_inside_public_path;
191 /// Tries to resolve the target of a `pub use` statement and inlines the
192 /// target if it is defined locally and would not be documented otherwise,
193 /// or when it is specifically requested with `please_inline`.
194 /// (the latter is the case when the import is marked `doc(inline)`)
196 /// Cross-crate inlining occurs later on during crate cleaning
197 /// and follows different rules.
199 /// Returns `true` if the target has been inlined.
200 fn maybe_inline_local(
204 renamed: Option<Symbol>,
206 om: &mut Module<'tcx>,
209 debug!("maybe_inline_local res: {:?}", res);
211 if self.cx.output_format.is_json() {
215 let tcx = self.cx.tcx;
216 let Some(res_did) = res.opt_def_id() else {
220 let use_attrs = tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(def_id));
221 // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
222 let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
223 || tcx.is_doc_hidden(def_id.to_def_id());
225 // For cross-crate impl inlining we need to know whether items are
226 // reachable in documentation -- a previously unreachable item can be
227 // made reachable by cross-crate inlining which we're checking here.
228 // (this is done here because we need to know this upfront).
229 if !res_did.is_local() && !is_no_inline {
230 crate::visit_lib::lib_embargo_visit_item(self.cx, res_did);
234 let Some(res_did) = res_did.as_local() else {
238 let is_private = !self
241 .effective_visibilities
242 .is_directly_public(self.cx.tcx, res_did.to_def_id());
243 let is_hidden = inherits_doc_hidden(self.cx.tcx, res_did);
245 // Only inline if requested or if the item would otherwise be stripped.
246 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
250 if !self.view_item_stack.insert(res_did) {
254 let ret = match tcx.hir().get_by_def_id(res_did) {
255 Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
256 let prev = mem::replace(&mut self.inlining, true);
257 for &i in m.item_ids {
258 let i = self.cx.tcx.hir().item(i);
259 self.visit_item(i, None, om, Some(def_id));
261 self.inlining = prev;
264 Node::Item(it) if !glob => {
265 let prev = mem::replace(&mut self.inlining, true);
266 self.visit_item(it, renamed, om, Some(def_id));
267 self.inlining = prev;
270 Node::ForeignItem(it) if !glob => {
271 let prev = mem::replace(&mut self.inlining, true);
272 self.visit_foreign_item(it, renamed, om);
273 self.inlining = prev;
278 self.view_item_stack.remove(&res_did);
284 item: &'tcx hir::Item<'_>,
285 renamed: Option<Symbol>,
286 om: &mut Module<'tcx>,
287 parent_id: Option<LocalDefId>,
289 debug!("visiting item {:?}", item);
290 let name = renamed.unwrap_or(item.ident.name);
292 let def_id = item.owner_id.to_def_id();
293 let is_pub = self.cx.tcx.visibility(def_id).is_public();
296 self.store_path(item.owner_id.to_def_id());
300 hir::ItemKind::ForeignMod { items, .. } => {
302 let item = self.cx.tcx.hir().foreign_item(item.id);
303 self.visit_foreign_item(item, None, om);
306 // If we're inlining, skip private items or item reexported as "_".
307 _ if self.inlining && (!is_pub || renamed == Some(kw::Underscore)) => {}
308 hir::ItemKind::GlobalAsm(..) => {}
309 hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
310 hir::ItemKind::Use(path, kind) => {
311 for &res in &path.res {
312 // Struct and variant constructors and proc macro stubs always show up alongside
313 // their definitions, we've already processed them so just discard these.
314 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
318 let attrs = self.cx.tcx.hir().attrs(item.hir_id());
320 // If there was a private module in the current path then don't bother inlining
321 // anything as it will probably be stripped anyway.
322 if is_pub && self.inside_public_path {
323 let please_inline = attrs.iter().any(|item| match item.meta_item_list() {
324 Some(ref list) if item.has_name(sym::doc) => {
325 list.iter().any(|i| i.has_name(sym::inline))
329 let is_glob = kind == hir::UseKind::Glob;
330 let ident = if is_glob { None } else { Some(name) };
331 if self.maybe_inline_local(
332 item.owner_id.def_id,
343 om.items.push((item, renamed, parent_id))
346 hir::ItemKind::Macro(ref macro_def, _) => {
347 // `#[macro_export] macro_rules!` items are handled separately in `visit()`,
348 // above, since they need to be documented at the module top level. Accordingly,
349 // we only want to handle macros if one of three conditions holds:
351 // 1. This macro was defined by `macro`, and thus isn't covered by the case
353 // 2. This macro isn't marked with `#[macro_export]`, and thus isn't covered
354 // by the case above.
355 // 3. We're inlining, since a reexport where inlining has been requested
356 // should be inlined even if it is also documented at the top level.
358 let def_id = item.owner_id.to_def_id();
359 let is_macro_2_0 = !macro_def.macro_rules;
360 let nonexported = !self.cx.tcx.has_attr(def_id, sym::macro_export);
362 if is_macro_2_0 || nonexported || self.inlining {
363 om.items.push((item, renamed, None));
366 hir::ItemKind::Mod(ref m) => {
367 om.mods.push(self.visit_mod_contents(item.owner_id.def_id, m, name, parent_id));
369 hir::ItemKind::Fn(..)
370 | hir::ItemKind::ExternCrate(..)
371 | hir::ItemKind::Enum(..)
372 | hir::ItemKind::Struct(..)
373 | hir::ItemKind::Union(..)
374 | hir::ItemKind::TyAlias(..)
375 | hir::ItemKind::OpaqueTy(..)
376 | hir::ItemKind::Static(..)
377 | hir::ItemKind::Trait(..)
378 | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed, parent_id)),
379 hir::ItemKind::Const(..) => {
380 // Underscore constants do not correspond to a nameable item and
381 // so are never useful in documentation.
382 if name != kw::Underscore {
383 om.items.push((item, renamed, parent_id));
386 hir::ItemKind::Impl(impl_) => {
387 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
388 // them up regardless of where they're located.
389 if !self.inlining && impl_.of_trait.is_none() {
390 om.items.push((item, None, None));
396 fn visit_foreign_item(
398 item: &'tcx hir::ForeignItem<'_>,
399 renamed: Option<Symbol>,
400 om: &mut Module<'tcx>,
402 // If inlining we only want to include public functions.
403 if !self.inlining || self.cx.tcx.visibility(item.owner_id).is_public() {
404 om.foreigns.push((item, renamed));