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};
17 use crate::clean::{self, cfg::Cfg, AttributesExt, NestedAttributesExt};
19 use crate::doctree::*;
21 // FIXME: Should this be replaced with tcx.def_path_str?
22 fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<String> {
23 let crate_name = tcx.crate_name(did.krate).to_string();
24 let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| {
25 // extern blocks have an empty name
26 let s = elem.data.to_string();
27 if !s.is_empty() { Some(s) } else { None }
29 std::iter::once(crate_name).chain(relative).collect()
32 crate fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: hir::HirId) -> bool {
33 while let Some(id) = tcx.hir().get_enclosing_scope(node) {
35 if tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
42 // Also, is there some reason that this doesn't use the 'visit'
43 // framework from syntax?.
45 crate struct RustdocVisitor<'a, 'tcx> {
46 cx: &'a mut core::DocContext<'tcx>,
47 view_item_stack: FxHashSet<hir::HirId>,
49 /// Are the current module and all of its parents public?
50 inside_public_path: bool,
51 exact_paths: FxHashMap<DefId, Vec<String>>,
54 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
55 crate fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
56 // If the root is re-exported, terminate all recursion.
57 let mut stack = FxHashSet::default();
58 stack.insert(hir::CRATE_HIR_ID);
61 view_item_stack: stack,
63 inside_public_path: true,
64 exact_paths: FxHashMap::default(),
68 fn store_path(&mut self, did: DefId) {
69 let tcx = self.cx.tcx;
70 self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
73 crate fn visit(mut self) -> Module<'tcx> {
74 let mut top_level_module = self.visit_mod_contents(
76 self.cx.tcx.hir().root_module(),
77 self.cx.tcx.crate_name(LOCAL_CRATE),
80 // `#[macro_export] macro_rules!` items are reexported at the top level of the
81 // crate, regardless of where they're defined. We want to document the
82 // top level rexport of the macro, not its original definition, since
83 // the rexport defines the path that a user will actually see. Accordingly,
84 // we add the rexport as an item here, and then skip over the original
85 // definition in `visit_item()` below.
87 // We also skip `#[macro_export] macro_rules!` that have already been inserted,
88 // it can happen if within the same module a `#[macro_export] macro_rules!`
89 // is declared but also a reexport of itself producing two exports of the same
90 // macro in the same module.
91 let mut inserted = FxHashSet::default();
92 for export in self.cx.tcx.module_exports(CRATE_DEF_ID).unwrap_or(&[]) {
93 if let Res::Def(DefKind::Macro(_), def_id) = export.res {
94 if let Some(local_def_id) = def_id.as_local() {
95 if self.cx.tcx.has_attr(def_id, sym::macro_export) {
96 if inserted.insert(def_id) {
97 let hir_id = self.cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
98 let item = self.cx.tcx.hir().expect_item(hir_id);
99 top_level_module.items.push((item, None));
106 self.cx.cache.hidden_cfg = self
112 .filter(|attr| attr.has_name(sym::doc))
113 .flat_map(|attr| attr.meta_item_list().into_iter().flatten())
114 .filter(|attr| attr.has_name(sym::cfg_hide))
116 attr.meta_item_list()
120 Cfg::parse(attr.meta_item()?)
121 .map_err(|e| self.cx.sess().diagnostic().span_err(e.span, e.msg))
128 self.cx.cache.exact_paths = self.exact_paths;
132 fn visit_mod_contents(
135 m: &'tcx hir::Mod<'tcx>,
138 let mut om = Module::new(name, id, m.inner);
139 let def_id = self.cx.tcx.hir().local_def_id(id).to_def_id();
140 // Keep track of if there were any private modules in the path.
141 let orig_inside_public_path = self.inside_public_path;
142 self.inside_public_path &= self.cx.tcx.visibility(def_id).is_public();
143 for &i in m.item_ids {
144 let item = self.cx.tcx.hir().item(i);
145 self.visit_item(item, None, &mut om);
147 self.inside_public_path = orig_inside_public_path;
151 /// Tries to resolve the target of a `pub use` statement and inlines the
152 /// target if it is defined locally and would not be documented otherwise,
153 /// or when it is specifically requested with `please_inline`.
154 /// (the latter is the case when the import is marked `doc(inline)`)
156 /// Cross-crate inlining occurs later on during crate cleaning
157 /// and follows different rules.
159 /// Returns `true` if the target has been inlined.
160 fn maybe_inline_local(
164 renamed: Option<Symbol>,
166 om: &mut Module<'tcx>,
169 debug!("maybe_inline_local res: {:?}", res);
171 let tcx = self.cx.tcx;
172 let res_did = if let Some(did) = res.opt_def_id() {
178 let use_attrs = tcx.hir().attrs(id);
179 // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
180 let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
181 || use_attrs.lists(sym::doc).has_word(sym::hidden);
183 // For cross-crate impl inlining we need to know whether items are
184 // reachable in documentation -- a previously unreachable item can be
185 // made reachable by cross-crate inlining which we're checking here.
186 // (this is done here because we need to know this upfront).
187 if !res_did.is_local() && !is_no_inline {
188 let attrs = clean::inline::load_attrs(self.cx, res_did);
189 let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
191 if let Res::Def(kind, did) = res {
192 if kind == DefKind::Mod {
193 crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did)
195 // All items need to be handled here in case someone wishes to link
196 // to them with intra-doc links
197 self.cx.cache.access_levels.map.insert(did, AccessLevel::Public);
204 let res_hir_id = match res_did.as_local() {
205 Some(n) => tcx.hir().local_def_id_to_hir_id(n),
206 None => return false,
209 let is_private = !self.cx.cache.access_levels.is_public(res_did);
210 let is_hidden = inherits_doc_hidden(self.cx.tcx, res_hir_id);
212 // Only inline if requested or if the item would otherwise be stripped.
213 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
217 if !self.view_item_stack.insert(res_hir_id) {
221 let ret = match tcx.hir().get(res_hir_id) {
222 Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
223 let prev = mem::replace(&mut self.inlining, true);
224 for &i in m.item_ids {
225 let i = self.cx.tcx.hir().item(i);
226 self.visit_item(i, None, om);
228 self.inlining = prev;
231 Node::Item(it) if !glob => {
232 let prev = mem::replace(&mut self.inlining, true);
233 self.visit_item(it, renamed, om);
234 self.inlining = prev;
237 Node::ForeignItem(it) if !glob => {
238 let prev = mem::replace(&mut self.inlining, true);
239 self.visit_foreign_item(it, renamed, om);
240 self.inlining = prev;
245 self.view_item_stack.remove(&res_hir_id);
251 item: &'tcx hir::Item<'_>,
252 renamed: Option<Symbol>,
253 om: &mut Module<'tcx>,
255 debug!("visiting item {:?}", item);
256 let name = renamed.unwrap_or(item.ident.name);
258 let def_id = item.def_id.to_def_id();
259 let is_pub = self.cx.tcx.visibility(def_id).is_public();
262 self.store_path(item.def_id.to_def_id());
266 hir::ItemKind::ForeignMod { items, .. } => {
268 let item = self.cx.tcx.hir().foreign_item(item.id);
269 self.visit_foreign_item(item, None, om);
272 // If we're inlining, skip private items.
273 _ if self.inlining && !is_pub => {}
274 hir::ItemKind::GlobalAsm(..) => {}
275 hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
276 hir::ItemKind::Use(path, kind) => {
277 let is_glob = kind == hir::UseKind::Glob;
279 // Struct and variant constructors and proc macro stubs always show up alongside
280 // their definitions, we've already processed them so just discard these.
281 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
285 let attrs = self.cx.tcx.hir().attrs(item.hir_id());
287 // If there was a private module in the current path then don't bother inlining
288 // anything as it will probably be stripped anyway.
289 if is_pub && self.inside_public_path {
290 let please_inline = attrs.iter().any(|item| match item.meta_item_list() {
291 Some(ref list) if item.has_name(sym::doc) => {
292 list.iter().any(|i| i.has_name(sym::inline))
296 let ident = if is_glob { None } else { Some(name) };
297 if self.maybe_inline_local(
309 om.items.push((item, renamed))
311 hir::ItemKind::Macro(ref macro_def) => {
312 // `#[macro_export] macro_rules!` items are handled seperately in `visit()`,
313 // above, since they need to be documented at the module top level. Accordingly,
314 // we only want to handle macros if one of three conditions holds:
316 // 1. This macro was defined by `macro`, and thus isn't covered by the case
318 // 2. This macro isn't marked with `#[macro_export]`, and thus isn't covered
319 // by the case above.
320 // 3. We're inlining, since a reexport where inlining has been requested
321 // should be inlined even if it is also documented at the top level.
323 let def_id = item.def_id.to_def_id();
324 let is_macro_2_0 = !macro_def.macro_rules;
325 let nonexported = !self.cx.tcx.has_attr(def_id, sym::macro_export);
327 if is_macro_2_0 || nonexported || self.inlining {
328 om.items.push((item, renamed));
331 hir::ItemKind::Mod(ref m) => {
332 om.mods.push(self.visit_mod_contents(item.hir_id(), m, name));
334 hir::ItemKind::Fn(..)
335 | hir::ItemKind::ExternCrate(..)
336 | hir::ItemKind::Enum(..)
337 | hir::ItemKind::Struct(..)
338 | hir::ItemKind::Union(..)
339 | hir::ItemKind::TyAlias(..)
340 | hir::ItemKind::OpaqueTy(..)
341 | hir::ItemKind::Static(..)
342 | hir::ItemKind::Trait(..)
343 | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)),
344 hir::ItemKind::Const(..) => {
345 // Underscore constants do not correspond to a nameable item and
346 // so are never useful in documentation.
347 if name != kw::Underscore {
348 om.items.push((item, renamed));
351 hir::ItemKind::Impl(ref impl_) => {
352 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
353 // them up regardless of where they're located.
354 if !self.inlining && impl_.of_trait.is_none() {
355 om.items.push((item, None));
361 fn visit_foreign_item(
363 item: &'tcx hir::ForeignItem<'_>,
364 renamed: Option<Symbol>,
365 om: &mut Module<'tcx>,
367 // If inlining we only want to include public functions.
368 if !self.inlining || self.cx.tcx.visibility(item.def_id).is_public() {
369 om.foreigns.push((item, renamed));