1 //! The Rust AST Visitor. Extracts useful information and massages it into a form
2 //! usable for `clean`.
4 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_hir::def::{DefKind, Res};
7 use rustc_hir::def_id::DefId;
9 use rustc_hir::CRATE_HIR_ID;
10 use rustc_middle::middle::privacy::AccessLevel;
11 use rustc_middle::ty::TyCtxt;
12 use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE};
13 use rustc_span::symbol::{kw, sym, Symbol};
18 use crate::clean::{self, cfg::Cfg, AttributesExt, NestedAttributesExt};
21 /// This module is used to store stuff from Rust's AST in a more convenient
22 /// manner (and with prettier names) before cleaning.
24 crate struct Module<'hir> {
26 crate where_inner: Span,
27 crate mods: Vec<Module<'hir>>,
30 crate items: Vec<(&'hir hir::Item<'hir>, Option<Symbol>)>,
31 crate foreigns: Vec<(&'hir hir::ForeignItem<'hir>, Option<Symbol>)>,
35 crate fn new(name: Symbol, id: hir::HirId, where_inner: Span) -> Self {
36 Module { name, id, where_inner, mods: Vec::new(), items: Vec::new(), foreigns: Vec::new() }
39 crate fn where_outer(&self, tcx: TyCtxt<'_>) -> Span {
40 tcx.hir().span(self.id)
44 // FIXME: Should this be replaced with tcx.def_path_str?
45 fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<Symbol> {
46 let crate_name = tcx.crate_name(did.krate);
47 let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| elem.data.get_opt_name());
48 std::iter::once(crate_name).chain(relative).collect()
51 crate fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: hir::HirId) -> bool {
52 while let Some(id) = tcx.hir().get_enclosing_scope(node) {
54 if tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
61 // Also, is there some reason that this doesn't use the 'visit'
62 // framework from syntax?.
64 crate struct RustdocVisitor<'a, 'tcx> {
65 cx: &'a mut core::DocContext<'tcx>,
66 view_item_stack: FxHashSet<hir::HirId>,
68 /// Are the current module and all of its parents public?
69 inside_public_path: bool,
70 exact_paths: FxHashMap<DefId, Vec<Symbol>>,
73 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
74 crate fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
75 // If the root is re-exported, terminate all recursion.
76 let mut stack = FxHashSet::default();
77 stack.insert(hir::CRATE_HIR_ID);
80 view_item_stack: stack,
82 inside_public_path: true,
83 exact_paths: FxHashMap::default(),
87 fn store_path(&mut self, did: DefId) {
88 let tcx = self.cx.tcx;
89 self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
92 crate fn visit(mut self) -> Module<'tcx> {
93 let mut top_level_module = self.visit_mod_contents(
95 self.cx.tcx.hir().root_module(),
96 self.cx.tcx.crate_name(LOCAL_CRATE),
99 // `#[macro_export] macro_rules!` items are reexported at the top level of the
100 // crate, regardless of where they're defined. We want to document the
101 // top level rexport of the macro, not its original definition, since
102 // the rexport defines the path that a user will actually see. Accordingly,
103 // we add the rexport as an item here, and then skip over the original
104 // definition in `visit_item()` below.
106 // We also skip `#[macro_export] macro_rules!` that have already been inserted,
107 // it can happen if within the same module a `#[macro_export] macro_rules!`
108 // is declared but also a reexport of itself producing two exports of the same
109 // macro in the same module.
110 let mut inserted = FxHashSet::default();
111 for export in self.cx.tcx.module_reexports(CRATE_DEF_ID).unwrap_or(&[]) {
112 if let Res::Def(DefKind::Macro(_), def_id) = export.res {
113 if let Some(local_def_id) = def_id.as_local() {
114 if self.cx.tcx.has_attr(def_id, sym::macro_export) {
115 if inserted.insert(def_id) {
116 let item = self.cx.tcx.hir().expect_item(local_def_id);
117 top_level_module.items.push((item, None));
124 self.cx.cache.hidden_cfg = self
130 .filter(|attr| attr.has_name(sym::doc))
131 .flat_map(|attr| attr.meta_item_list().into_iter().flatten())
132 .filter(|attr| attr.has_name(sym::cfg_hide))
134 attr.meta_item_list()
138 Cfg::parse(attr.meta_item()?)
139 .map_err(|e| self.cx.sess().diagnostic().span_err(e.span, e.msg))
144 .chain([Cfg::Cfg(sym::test, None)].into_iter())
147 self.cx.cache.exact_paths = self.exact_paths;
151 fn visit_mod_contents(
154 m: &'tcx hir::Mod<'tcx>,
157 let mut om = Module::new(name, id, m.inner);
158 let def_id = self.cx.tcx.hir().local_def_id(id).to_def_id();
159 // Keep track of if there were any private modules in the path.
160 let orig_inside_public_path = self.inside_public_path;
161 self.inside_public_path &= self.cx.tcx.visibility(def_id).is_public();
162 for &i in m.item_ids {
163 let item = self.cx.tcx.hir().item(i);
164 self.visit_item(item, None, &mut om);
166 self.inside_public_path = orig_inside_public_path;
170 /// Tries to resolve the target of a `pub use` statement and inlines the
171 /// target if it is defined locally and would not be documented otherwise,
172 /// or when it is specifically requested with `please_inline`.
173 /// (the latter is the case when the import is marked `doc(inline)`)
175 /// Cross-crate inlining occurs later on during crate cleaning
176 /// and follows different rules.
178 /// Returns `true` if the target has been inlined.
179 fn maybe_inline_local(
183 renamed: Option<Symbol>,
185 om: &mut Module<'tcx>,
188 debug!("maybe_inline_local res: {:?}", res);
190 let tcx = self.cx.tcx;
191 let res_did = if let Some(did) = res.opt_def_id() {
197 let use_attrs = tcx.hir().attrs(id);
198 // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
199 let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
200 || use_attrs.lists(sym::doc).has_word(sym::hidden);
202 // For cross-crate impl inlining we need to know whether items are
203 // reachable in documentation -- a previously unreachable item can be
204 // made reachable by cross-crate inlining which we're checking here.
205 // (this is done here because we need to know this upfront).
206 if !res_did.is_local() && !is_no_inline {
207 let attrs = clean::inline::load_attrs(self.cx, res_did);
208 let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
210 if let Res::Def(kind, did) = res {
211 if kind == DefKind::Mod {
212 crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did)
214 // All items need to be handled here in case someone wishes to link
215 // to them with intra-doc links
216 self.cx.cache.access_levels.map.insert(did, AccessLevel::Public);
223 let res_hir_id = match res_did.as_local() {
224 Some(n) => tcx.hir().local_def_id_to_hir_id(n),
225 None => return false,
228 let is_private = !self.cx.cache.access_levels.is_public(res_did);
229 let is_hidden = inherits_doc_hidden(self.cx.tcx, res_hir_id);
231 // Only inline if requested or if the item would otherwise be stripped.
232 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
236 if !self.view_item_stack.insert(res_hir_id) {
240 let ret = match tcx.hir().get(res_hir_id) {
241 Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
242 let prev = mem::replace(&mut self.inlining, true);
243 for &i in m.item_ids {
244 let i = self.cx.tcx.hir().item(i);
245 self.visit_item(i, None, om);
247 self.inlining = prev;
250 Node::Item(it) if !glob => {
251 let prev = mem::replace(&mut self.inlining, true);
252 self.visit_item(it, renamed, om);
253 self.inlining = prev;
256 Node::ForeignItem(it) if !glob => {
257 let prev = mem::replace(&mut self.inlining, true);
258 self.visit_foreign_item(it, renamed, om);
259 self.inlining = prev;
264 self.view_item_stack.remove(&res_hir_id);
270 item: &'tcx hir::Item<'_>,
271 renamed: Option<Symbol>,
272 om: &mut Module<'tcx>,
274 debug!("visiting item {:?}", item);
275 let name = renamed.unwrap_or(item.ident.name);
277 let def_id = item.def_id.to_def_id();
278 let is_pub = self.cx.tcx.visibility(def_id).is_public();
281 self.store_path(item.def_id.to_def_id());
285 hir::ItemKind::ForeignMod { items, .. } => {
287 let item = self.cx.tcx.hir().foreign_item(item.id);
288 self.visit_foreign_item(item, None, om);
291 // If we're inlining, skip private items.
292 _ if self.inlining && !is_pub => {}
293 hir::ItemKind::GlobalAsm(..) => {}
294 hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
295 hir::ItemKind::Use(path, kind) => {
296 let is_glob = kind == hir::UseKind::Glob;
298 // Struct and variant constructors and proc macro stubs always show up alongside
299 // their definitions, we've already processed them so just discard these.
300 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
304 let attrs = self.cx.tcx.hir().attrs(item.hir_id());
306 // If there was a private module in the current path then don't bother inlining
307 // anything as it will probably be stripped anyway.
308 if is_pub && self.inside_public_path {
309 let please_inline = attrs.iter().any(|item| match item.meta_item_list() {
310 Some(ref list) if item.has_name(sym::doc) => {
311 list.iter().any(|i| i.has_name(sym::inline))
315 let ident = if is_glob { None } else { Some(name) };
316 if self.maybe_inline_local(
328 om.items.push((item, renamed))
330 hir::ItemKind::Macro(ref macro_def) => {
331 // `#[macro_export] macro_rules!` items are handled seperately in `visit()`,
332 // above, since they need to be documented at the module top level. Accordingly,
333 // we only want to handle macros if one of three conditions holds:
335 // 1. This macro was defined by `macro`, and thus isn't covered by the case
337 // 2. This macro isn't marked with `#[macro_export]`, and thus isn't covered
338 // by the case above.
339 // 3. We're inlining, since a reexport where inlining has been requested
340 // should be inlined even if it is also documented at the top level.
342 let def_id = item.def_id.to_def_id();
343 let is_macro_2_0 = !macro_def.macro_rules;
344 let nonexported = !self.cx.tcx.has_attr(def_id, sym::macro_export);
346 if is_macro_2_0 || nonexported || self.inlining {
347 om.items.push((item, renamed));
350 hir::ItemKind::Mod(ref m) => {
351 om.mods.push(self.visit_mod_contents(item.hir_id(), m, name));
353 hir::ItemKind::Fn(..)
354 | hir::ItemKind::ExternCrate(..)
355 | hir::ItemKind::Enum(..)
356 | hir::ItemKind::Struct(..)
357 | hir::ItemKind::Union(..)
358 | hir::ItemKind::TyAlias(..)
359 | hir::ItemKind::OpaqueTy(..)
360 | hir::ItemKind::Static(..)
361 | hir::ItemKind::Trait(..)
362 | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)),
363 hir::ItemKind::Const(..) => {
364 // Underscore constants do not correspond to a nameable item and
365 // so are never useful in documentation.
366 if name != kw::Underscore {
367 om.items.push((item, renamed));
370 hir::ItemKind::Impl(ref impl_) => {
371 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
372 // them up regardless of where they're located.
373 if !self.inlining && impl_.of_trait.is_none() {
374 om.items.push((item, None));
380 fn visit_foreign_item(
382 item: &'tcx hir::ForeignItem<'_>,
383 renamed: Option<Symbol>,
384 om: &mut Module<'tcx>,
386 // If inlining we only want to include public functions.
387 if !self.inlining || self.cx.tcx.visibility(item.def_id).is_public() {
388 om.foreigns.push((item, renamed));