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;
13 use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE};
14 use rustc_span::source_map::Spanned;
15 use rustc_span::symbol::{kw, sym, Symbol};
19 use crate::clean::{self, cfg::Cfg, AttributesExt, NestedAttributesExt};
21 use crate::doctree::*;
23 // FIXME: Should this be replaced with tcx.def_path_str?
24 fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<String> {
25 let crate_name = tcx.crate_name(did.krate).to_string();
26 let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| {
27 // extern blocks have an empty name
28 let s = elem.data.to_string();
29 if !s.is_empty() { Some(s) } else { None }
31 std::iter::once(crate_name).chain(relative).collect()
34 crate fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: hir::HirId) -> bool {
35 while let Some(id) = tcx.hir().get_enclosing_scope(node) {
37 if tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
44 // Also, is there some reason that this doesn't use the 'visit'
45 // framework from syntax?.
47 crate struct RustdocVisitor<'a, 'tcx> {
48 cx: &'a mut core::DocContext<'tcx>,
49 view_item_stack: FxHashSet<hir::HirId>,
51 /// Are the current module and all of its parents public?
52 inside_public_path: bool,
53 exact_paths: FxHashMap<DefId, Vec<String>>,
56 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
57 crate fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
58 // If the root is re-exported, terminate all recursion.
59 let mut stack = FxHashSet::default();
60 stack.insert(hir::CRATE_HIR_ID);
63 view_item_stack: stack,
65 inside_public_path: true,
66 exact_paths: FxHashMap::default(),
70 fn store_path(&mut self, did: DefId) {
71 let tcx = self.cx.tcx;
72 self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
75 crate fn visit(mut self) -> Module<'tcx> {
76 let span = self.cx.tcx.def_span(CRATE_DEF_ID);
77 let mut top_level_module = self.visit_mod_contents(
78 &Spanned { span, node: hir::VisibilityKind::Public },
80 self.cx.tcx.hir().root_module(),
81 self.cx.tcx.crate_name(LOCAL_CRATE),
84 // `#[macro_export] macro_rules!` items are reexported at the top level of the
85 // crate, regardless of where they're defined. We want to document the
86 // top level rexport of the macro, not its original definition, since
87 // the rexport defines the path that a user will actually see. Accordingly,
88 // we add the rexport as an item here, and then skip over the original
89 // definition in `visit_item()` below.
91 // We also skip `#[macro_export] macro_rules!` that have already been inserted,
92 // it can happen if within the same module a `#[macro_export] macro_rules!`
93 // is declared but also a reexport of itself producing two exports of the same
94 // macro in the same module.
95 let mut inserted = FxHashSet::default();
96 for export in self.cx.tcx.module_exports(CRATE_DEF_ID).unwrap_or(&[]) {
97 if let Res::Def(DefKind::Macro(_), def_id) = export.res {
98 if let Some(local_def_id) = def_id.as_local() {
99 if self.cx.tcx.has_attr(def_id, sym::macro_export) {
100 if inserted.insert(def_id) {
101 let hir_id = self.cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
102 let item = self.cx.tcx.hir().expect_item(hir_id);
103 top_level_module.items.push((item, None));
110 self.cx.cache.hidden_cfg = self
116 .filter(|attr| attr.has_name(sym::doc))
117 .flat_map(|attr| attr.meta_item_list().into_iter().flatten())
118 .filter(|attr| attr.has_name(sym::cfg_hide))
120 attr.meta_item_list()
124 Cfg::parse(attr.meta_item()?)
125 .map_err(|e| self.cx.sess().diagnostic().span_err(e.span, e.msg))
132 self.cx.cache.exact_paths = self.exact_paths;
136 fn visit_mod_contents(
138 vis: &hir::Visibility<'_>,
140 m: &'tcx hir::Mod<'tcx>,
143 let mut om = Module::new(name, id, m.inner);
144 // Keep track of if there were any private modules in the path.
145 let orig_inside_public_path = self.inside_public_path;
146 self.inside_public_path &= vis.node.is_pub();
147 for &i in m.item_ids {
148 let item = self.cx.tcx.hir().item(i);
149 self.visit_item(item, None, &mut om);
151 self.inside_public_path = orig_inside_public_path;
155 /// Tries to resolve the target of a `pub use` statement and inlines the
156 /// target if it is defined locally and would not be documented otherwise,
157 /// or when it is specifically requested with `please_inline`.
158 /// (the latter is the case when the import is marked `doc(inline)`)
160 /// Cross-crate inlining occurs later on during crate cleaning
161 /// and follows different rules.
163 /// Returns `true` if the target has been inlined.
164 fn maybe_inline_local(
168 renamed: Option<Symbol>,
170 om: &mut Module<'tcx>,
173 debug!("maybe_inline_local res: {:?}", res);
175 let tcx = self.cx.tcx;
176 let res_did = if let Some(did) = res.opt_def_id() {
182 let use_attrs = tcx.hir().attrs(id);
183 // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
184 let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
185 || use_attrs.lists(sym::doc).has_word(sym::hidden);
187 // For cross-crate impl inlining we need to know whether items are
188 // reachable in documentation -- a previously unreachable item can be
189 // made reachable by cross-crate inlining which we're checking here.
190 // (this is done here because we need to know this upfront).
191 if !res_did.is_local() && !is_no_inline {
192 let attrs = clean::inline::load_attrs(self.cx, res_did);
193 let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
195 if let Res::Def(kind, did) = res {
196 if kind == DefKind::Mod {
197 crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did)
199 // All items need to be handled here in case someone wishes to link
200 // to them with intra-doc links
201 self.cx.cache.access_levels.map.insert(did, AccessLevel::Public);
208 let res_hir_id = match res_did.as_local() {
209 Some(n) => tcx.hir().local_def_id_to_hir_id(n),
210 None => return false,
213 let is_private = !self.cx.cache.access_levels.is_public(res_did);
214 let is_hidden = inherits_doc_hidden(self.cx.tcx, res_hir_id);
216 // Only inline if requested or if the item would otherwise be stripped.
217 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
221 if !self.view_item_stack.insert(res_hir_id) {
225 let ret = match tcx.hir().get(res_hir_id) {
226 Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
227 let prev = mem::replace(&mut self.inlining, true);
228 for &i in m.item_ids {
229 let i = self.cx.tcx.hir().item(i);
230 self.visit_item(i, None, om);
232 self.inlining = prev;
235 Node::Item(it) if !glob => {
236 let prev = mem::replace(&mut self.inlining, true);
237 self.visit_item(it, renamed, om);
238 self.inlining = prev;
241 Node::ForeignItem(it) if !glob => {
242 let prev = mem::replace(&mut self.inlining, true);
243 self.visit_foreign_item(it, renamed, om);
244 self.inlining = prev;
249 self.view_item_stack.remove(&res_hir_id);
255 item: &'tcx hir::Item<'_>,
256 renamed: Option<Symbol>,
257 om: &mut Module<'tcx>,
259 debug!("visiting item {:?}", item);
260 let name = renamed.unwrap_or(item.ident.name);
262 let def_id = item.def_id.to_def_id();
263 let is_pub = item.vis.node.is_pub() || self.cx.tcx.has_attr(def_id, sym::macro_export);
266 self.store_path(item.def_id.to_def_id());
270 hir::ItemKind::ForeignMod { items, .. } => {
272 let item = self.cx.tcx.hir().foreign_item(item.id);
273 self.visit_foreign_item(item, None, om);
276 // If we're inlining, skip private items.
277 _ if self.inlining && !is_pub => {}
278 hir::ItemKind::GlobalAsm(..) => {}
279 hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
280 hir::ItemKind::Use(ref path, kind) => {
281 let is_glob = kind == hir::UseKind::Glob;
283 // Struct and variant constructors and proc macro stubs always show up alongside
284 // their definitions, we've already processed them so just discard these.
285 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
289 let attrs = self.cx.tcx.hir().attrs(item.hir_id());
291 // If there was a private module in the current path then don't bother inlining
292 // anything as it will probably be stripped anyway.
293 if is_pub && self.inside_public_path {
294 let please_inline = attrs.iter().any(|item| match item.meta_item_list() {
295 Some(ref list) if item.has_name(sym::doc) => {
296 list.iter().any(|i| i.has_name(sym::inline))
300 let ident = if is_glob { None } else { Some(name) };
301 if self.maybe_inline_local(
313 om.items.push((item, renamed))
315 hir::ItemKind::Macro(ref macro_def) => {
316 // `#[macro_export] macro_rules!` items are handled seperately in `visit()`,
317 // above, since they need to be documented at the module top level. Accordingly,
318 // we only want to handle macros if one of three conditions holds:
320 // 1. This macro was defined by `macro`, and thus isn't covered by the case
322 // 2. This macro isn't marked with `#[macro_export]`, and thus isn't covered
323 // by the case above.
324 // 3. We're inlining, since a reexport where inlining has been requested
325 // should be inlined even if it is also documented at the top level.
327 let def_id = item.def_id.to_def_id();
328 let is_macro_2_0 = !macro_def.macro_rules;
329 let nonexported = !self.cx.tcx.has_attr(def_id, sym::macro_export);
331 if is_macro_2_0 || nonexported || self.inlining {
332 om.items.push((item, renamed));
335 hir::ItemKind::Mod(ref m) => {
336 om.mods.push(self.visit_mod_contents(&item.vis, item.hir_id(), m, name));
338 hir::ItemKind::Fn(..)
339 | hir::ItemKind::ExternCrate(..)
340 | hir::ItemKind::Enum(..)
341 | hir::ItemKind::Struct(..)
342 | hir::ItemKind::Union(..)
343 | hir::ItemKind::TyAlias(..)
344 | hir::ItemKind::OpaqueTy(..)
345 | hir::ItemKind::Static(..)
346 | hir::ItemKind::Trait(..)
347 | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)),
348 hir::ItemKind::Const(..) => {
349 // Underscore constants do not correspond to a nameable item and
350 // so are never useful in documentation.
351 if name != kw::Underscore {
352 om.items.push((item, renamed));
355 hir::ItemKind::Impl(ref impl_) => {
356 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
357 // them up regardless of where they're located.
358 if !self.inlining && impl_.of_trait.is_none() {
359 om.items.push((item, None));
365 fn visit_foreign_item(
367 item: &'tcx hir::ForeignItem<'_>,
368 renamed: Option<Symbol>,
369 om: &mut Module<'tcx>,
371 // If inlining we only want to include public functions.
372 if !self.inlining || item.vis.node.is_pub() {
373 om.foreigns.push((item, renamed));