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};
8 use rustc_hir::{HirIdSet, Node, CRATE_HIR_ID};
9 use rustc_middle::ty::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) id: hir::HirId,
27 // (item, renamed, import_id)
28 pub(crate) items: Vec<(&'hir hir::Item<'hir>, Option<Symbol>, Option<hir::HirId>)>,
29 pub(crate) foreigns: Vec<(&'hir hir::ForeignItem<'hir>, Option<Symbol>)>,
33 pub(crate) fn new(name: Symbol, id: hir::HirId, where_inner: Span) -> Self {
34 Module { name, id, where_inner, mods: Vec::new(), items: Vec::new(), foreigns: Vec::new() }
37 pub(crate) fn where_outer(&self, tcx: TyCtxt<'_>) -> Span {
38 tcx.hir().span(self.id)
42 // FIXME: Should this be replaced with tcx.def_path_str?
43 fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<Symbol> {
44 let crate_name = tcx.crate_name(did.krate);
45 let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| elem.data.get_opt_name());
46 std::iter::once(crate_name).chain(relative).collect()
49 pub(crate) fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: hir::HirId) -> bool {
50 while let Some(id) = tcx.hir().get_enclosing_scope(node) {
52 if tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
59 // Also, is there some reason that this doesn't use the 'visit'
60 // framework from syntax?.
62 pub(crate) struct RustdocVisitor<'a, 'tcx> {
63 cx: &'a mut core::DocContext<'tcx>,
64 view_item_stack: HirIdSet,
66 /// Are the current module and all of its parents public?
67 inside_public_path: bool,
68 exact_paths: DefIdMap<Vec<Symbol>>,
71 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
72 pub(crate) fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
73 // If the root is re-exported, terminate all recursion.
74 let mut stack = HirIdSet::default();
75 stack.insert(hir::CRATE_HIR_ID);
78 view_item_stack: stack,
80 inside_public_path: true,
81 exact_paths: Default::default(),
85 fn store_path(&mut self, did: DefId) {
86 let tcx = self.cx.tcx;
87 self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
90 pub(crate) fn visit(mut self) -> Module<'tcx> {
91 let mut top_level_module = self.visit_mod_contents(
93 self.cx.tcx.hir().root_module(),
94 self.cx.tcx.crate_name(LOCAL_CRATE),
98 // `#[macro_export] macro_rules!` items are reexported at the top level of the
99 // crate, regardless of where they're defined. We want to document the
100 // top level rexport of the macro, not its original definition, since
101 // the rexport defines the path that a user will actually see. Accordingly,
102 // we add the rexport as an item here, and then skip over the original
103 // definition in `visit_item()` below.
105 // We also skip `#[macro_export] macro_rules!` that have already been inserted,
106 // it can happen if within the same module a `#[macro_export] macro_rules!`
107 // is declared but also a reexport of itself producing two exports of the same
108 // macro in the same module.
109 let mut inserted = FxHashSet::default();
110 for export in self.cx.tcx.module_reexports(CRATE_DEF_ID).unwrap_or(&[]) {
111 if let Res::Def(DefKind::Macro(_), def_id) = export.res {
112 if let Some(local_def_id) = def_id.as_local() {
113 if self.cx.tcx.has_attr(def_id, sym::macro_export) {
114 if inserted.insert(def_id) {
115 let item = self.cx.tcx.hir().expect_item(local_def_id);
116 top_level_module.items.push((item, None, None));
123 self.cx.cache.hidden_cfg = self
129 .filter(|attr| attr.has_name(sym::doc))
130 .flat_map(|attr| attr.meta_item_list().into_iter().flatten())
131 .filter(|attr| attr.has_name(sym::cfg_hide))
133 attr.meta_item_list()
137 Cfg::parse(attr.meta_item()?)
138 .map_err(|e| self.cx.sess().diagnostic().span_err(e.span, e.msg))
144 [Cfg::Cfg(sym::test, None), Cfg::Cfg(sym::doc, None), Cfg::Cfg(sym::doctest, None)]
149 self.cx.cache.exact_paths = self.exact_paths;
153 fn visit_mod_contents(
156 m: &'tcx hir::Mod<'tcx>,
158 parent_id: Option<hir::HirId>,
160 let mut om = Module::new(name, id, m.spans.inner_span);
161 let def_id = self.cx.tcx.hir().local_def_id(id).to_def_id();
162 // Keep track of if there were any private modules in the path.
163 let orig_inside_public_path = self.inside_public_path;
164 self.inside_public_path &= self.cx.tcx.visibility(def_id).is_public();
165 for &i in m.item_ids {
166 let item = self.cx.tcx.hir().item(i);
167 if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) {
170 self.visit_item(item, None, &mut om, parent_id);
172 for &i in m.item_ids {
173 let item = self.cx.tcx.hir().item(i);
174 // To match the way import precedence works, visit glob imports last.
175 // Later passes in rustdoc will de-duplicate by name and kind, so if glob-
176 // imported items appear last, then they'll be the ones that get discarded.
177 if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) {
178 self.visit_item(item, None, &mut om, parent_id);
181 self.inside_public_path = orig_inside_public_path;
185 /// Tries to resolve the target of a `pub use` statement and inlines the
186 /// target if it is defined locally and would not be documented otherwise,
187 /// or when it is specifically requested with `please_inline`.
188 /// (the latter is the case when the import is marked `doc(inline)`)
190 /// Cross-crate inlining occurs later on during crate cleaning
191 /// and follows different rules.
193 /// Returns `true` if the target has been inlined.
194 fn maybe_inline_local(
198 renamed: Option<Symbol>,
200 om: &mut Module<'tcx>,
203 debug!("maybe_inline_local res: {:?}", res);
205 if self.cx.output_format.is_json() {
209 let tcx = self.cx.tcx;
210 let Some(res_did) = res.opt_def_id() else {
214 let use_attrs = tcx.hir().attrs(id);
215 // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
216 let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
217 || use_attrs.lists(sym::doc).has_word(sym::hidden);
219 // For cross-crate impl inlining we need to know whether items are
220 // reachable in documentation -- a previously unreachable item can be
221 // made reachable by cross-crate inlining which we're checking here.
222 // (this is done here because we need to know this upfront).
223 if !res_did.is_local() && !is_no_inline {
224 crate::visit_lib::lib_embargo_visit_item(self.cx, res_did);
228 let res_hir_id = match res_did.as_local() {
229 Some(n) => tcx.hir().local_def_id_to_hir_id(n),
230 None => return false,
234 !self.cx.cache.effective_visibilities.is_directly_public(self.cx.tcx, res_did);
235 let is_hidden = inherits_doc_hidden(self.cx.tcx, res_hir_id);
237 // Only inline if requested or if the item would otherwise be stripped.
238 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
242 if !self.view_item_stack.insert(res_hir_id) {
246 let ret = match tcx.hir().get(res_hir_id) {
247 Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
248 let prev = mem::replace(&mut self.inlining, true);
249 for &i in m.item_ids {
250 let i = self.cx.tcx.hir().item(i);
251 self.visit_item(i, None, om, Some(id));
253 self.inlining = prev;
256 Node::Item(it) if !glob => {
257 let prev = mem::replace(&mut self.inlining, true);
258 self.visit_item(it, renamed, om, Some(id));
259 self.inlining = prev;
262 Node::ForeignItem(it) if !glob => {
263 let prev = mem::replace(&mut self.inlining, true);
264 self.visit_foreign_item(it, renamed, om);
265 self.inlining = prev;
270 self.view_item_stack.remove(&res_hir_id);
276 item: &'tcx hir::Item<'_>,
277 renamed: Option<Symbol>,
278 om: &mut Module<'tcx>,
279 parent_id: Option<hir::HirId>,
281 debug!("visiting item {:?}", item);
282 let name = renamed.unwrap_or(item.ident.name);
284 let def_id = item.owner_id.to_def_id();
285 let is_pub = self.cx.tcx.visibility(def_id).is_public();
288 self.store_path(item.owner_id.to_def_id());
292 hir::ItemKind::ForeignMod { items, .. } => {
294 let item = self.cx.tcx.hir().foreign_item(item.id);
295 self.visit_foreign_item(item, None, om);
298 // If we're inlining, skip private items or item reexported as "_".
299 _ if self.inlining && (!is_pub || renamed == Some(kw::Underscore)) => {}
300 hir::ItemKind::GlobalAsm(..) => {}
301 hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
302 hir::ItemKind::Use(path, kind) => {
303 for &res in &path.res {
304 // Struct and variant constructors and proc macro stubs always show up alongside
305 // their definitions, we've already processed them so just discard these.
306 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
310 let attrs = self.cx.tcx.hir().attrs(item.hir_id());
312 // If there was a private module in the current path then don't bother inlining
313 // anything as it will probably be stripped anyway.
314 if is_pub && self.inside_public_path {
315 let please_inline = attrs.iter().any(|item| match item.meta_item_list() {
316 Some(ref list) if item.has_name(sym::doc) => {
317 list.iter().any(|i| i.has_name(sym::inline))
321 let is_glob = kind == hir::UseKind::Glob;
322 let ident = if is_glob { None } else { Some(name) };
323 if self.maybe_inline_local(
335 om.items.push((item, renamed, parent_id))
338 hir::ItemKind::Macro(ref macro_def, _) => {
339 // `#[macro_export] macro_rules!` items are handled separately in `visit()`,
340 // above, since they need to be documented at the module top level. Accordingly,
341 // we only want to handle macros if one of three conditions holds:
343 // 1. This macro was defined by `macro`, and thus isn't covered by the case
345 // 2. This macro isn't marked with `#[macro_export]`, and thus isn't covered
346 // by the case above.
347 // 3. We're inlining, since a reexport where inlining has been requested
348 // should be inlined even if it is also documented at the top level.
350 let def_id = item.owner_id.to_def_id();
351 let is_macro_2_0 = !macro_def.macro_rules;
352 let nonexported = !self.cx.tcx.has_attr(def_id, sym::macro_export);
354 if is_macro_2_0 || nonexported || self.inlining {
355 om.items.push((item, renamed, None));
358 hir::ItemKind::Mod(ref m) => {
359 om.mods.push(self.visit_mod_contents(item.hir_id(), m, name, parent_id));
361 hir::ItemKind::Fn(..)
362 | hir::ItemKind::ExternCrate(..)
363 | hir::ItemKind::Enum(..)
364 | hir::ItemKind::Struct(..)
365 | hir::ItemKind::Union(..)
366 | hir::ItemKind::TyAlias(..)
367 | hir::ItemKind::OpaqueTy(..)
368 | hir::ItemKind::Static(..)
369 | hir::ItemKind::Trait(..)
370 | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed, parent_id)),
371 hir::ItemKind::Const(..) => {
372 // Underscore constants do not correspond to a nameable item and
373 // so are never useful in documentation.
374 if name != kw::Underscore {
375 om.items.push((item, renamed, parent_id));
378 hir::ItemKind::Impl(impl_) => {
379 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
380 // them up regardless of where they're located.
381 if !self.inlining && impl_.of_trait.is_none() {
382 om.items.push((item, None, None));
388 fn visit_foreign_item(
390 item: &'tcx hir::ForeignItem<'_>,
391 renamed: Option<Symbol>,
392 om: &mut Module<'tcx>,
394 // If inlining we only want to include public functions.
395 if !self.inlining || self.cx.tcx.visibility(item.owner_id).is_public() {
396 om.foreigns.push((item, renamed));