1 //! The Rust AST Visitor. Extracts useful information and massages it into a form
2 //! usable for `clean`.
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_hir::def::{DefKind, Res};
8 use rustc_hir::def_id::DefId;
10 use rustc_middle::middle::privacy::AccessLevel;
11 use rustc_middle::ty::TyCtxt;
12 use rustc_span::source_map::Spanned;
13 use rustc_span::symbol::{kw, sym, Symbol};
14 use rustc_span::{self, Span};
18 use crate::clean::{self, AttributesExt, NestedAttributesExt};
20 use crate::doctree::*;
22 // FIXME: Should this be replaced with tcx.def_path_str?
23 fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<String> {
24 let crate_name = tcx.crate_name(did.krate).to_string();
25 let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| {
26 // extern blocks have an empty name
27 let s = elem.data.to_string();
28 if !s.is_empty() { Some(s) } else { None }
30 std::iter::once(crate_name).chain(relative).collect()
33 // Also, is there some reason that this doesn't use the 'visit'
34 // framework from syntax?.
36 crate struct RustdocVisitor<'a, 'tcx> {
37 cx: &'a mut core::DocContext<'tcx>,
38 view_item_stack: FxHashSet<hir::HirId>,
40 /// Are the current module and all of its parents public?
41 inside_public_path: bool,
42 exact_paths: FxHashMap<DefId, Vec<String>>,
45 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
46 crate fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
47 // If the root is re-exported, terminate all recursion.
48 let mut stack = FxHashSet::default();
49 stack.insert(hir::CRATE_HIR_ID);
52 view_item_stack: stack,
54 inside_public_path: true,
55 exact_paths: FxHashMap::default(),
59 fn store_path(&mut self, did: DefId) {
60 let tcx = self.cx.tcx;
61 self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
64 crate fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> {
65 let mut module = self.visit_mod_contents(
68 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public },
73 // Attach the crate's exported macros to the top-level module:
74 module.macros.extend(krate.exported_macros.iter().map(|def| (def, None)));
75 module.is_crate = true;
77 self.cx.renderinfo.get_mut().exact_paths = self.exact_paths;
82 fn visit_mod_contents(
85 attrs: &'tcx [ast::Attribute],
86 vis: &'tcx hir::Visibility<'_>,
88 m: &'tcx hir::Mod<'tcx>,
91 let mut om = Module::new(name, attrs);
92 om.where_outer = span;
93 om.where_inner = m.inner;
95 // Keep track of if there were any private modules in the path.
96 let orig_inside_public_path = self.inside_public_path;
97 self.inside_public_path &= vis.node.is_pub();
99 let item = self.cx.tcx.hir().expect_item(i.id);
100 self.visit_item(item, None, &mut om);
102 self.inside_public_path = orig_inside_public_path;
106 /// Tries to resolve the target of a `crate use` statement and inlines the
107 /// target if it is defined locally and would not be documented otherwise,
108 /// or when it is specifically requested with `please_inline`.
109 /// (the latter is the case when the import is marked `doc(inline)`)
111 /// Cross-crate inlining occurs later on during crate cleaning
112 /// and follows different rules.
114 /// Returns `true` if the target has been inlined.
115 fn maybe_inline_local(
119 renamed: Option<Symbol>,
121 om: &mut Module<'tcx>,
124 fn inherits_doc_hidden(cx: &core::DocContext<'_>, mut node: hir::HirId) -> bool {
125 while let Some(id) = cx.tcx.hir().get_enclosing_scope(node) {
127 if cx.tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
130 if node == hir::CRATE_HIR_ID {
137 debug!("maybe_inline_local res: {:?}", res);
139 let tcx = self.cx.tcx;
140 let res_did = if let Some(did) = res.opt_def_id() {
146 let use_attrs = tcx.hir().attrs(id);
147 // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
148 let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
149 || use_attrs.lists(sym::doc).has_word(sym::hidden);
151 // For cross-crate impl inlining we need to know whether items are
152 // reachable in documentation -- a previously nonreachable item can be
153 // made reachable by cross-crate inlining which we're checking here.
154 // (this is done here because we need to know this upfront).
155 if !res_did.is_local() && !is_no_inline {
156 let attrs = clean::inline::load_attrs(self.cx, res_did);
157 let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
159 if let Res::Def(kind, did) = res {
160 if kind == DefKind::Mod {
161 crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did)
163 // All items need to be handled here in case someone wishes to link
164 // to them with intra-doc links
170 .insert(did, AccessLevel::Public);
177 let res_hir_id = match res_did.as_local() {
178 Some(n) => tcx.hir().local_def_id_to_hir_id(n),
179 None => return false,
182 let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(res_did);
183 let is_hidden = inherits_doc_hidden(self.cx, res_hir_id);
185 // Only inline if requested or if the item would otherwise be stripped.
186 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
190 if !self.view_item_stack.insert(res_hir_id) {
194 let ret = match tcx.hir().get(res_hir_id) {
195 Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
196 let prev = mem::replace(&mut self.inlining, true);
197 for i in m.item_ids {
198 let i = self.cx.tcx.hir().expect_item(i.id);
199 self.visit_item(i, None, om);
201 self.inlining = prev;
204 Node::Item(it) if !glob => {
205 let prev = mem::replace(&mut self.inlining, true);
206 self.visit_item(it, renamed, om);
207 self.inlining = prev;
210 Node::ForeignItem(it) if !glob => {
211 let prev = mem::replace(&mut self.inlining, true);
212 self.visit_foreign_item(it, renamed, om);
213 self.inlining = prev;
216 Node::MacroDef(def) if !glob => {
217 om.macros.push((def, renamed));
222 self.view_item_stack.remove(&res_hir_id);
228 item: &'tcx hir::Item<'_>,
229 renamed: Option<Symbol>,
230 om: &mut Module<'tcx>,
232 debug!("visiting item {:?}", item);
233 let name = renamed.unwrap_or(item.ident.name);
235 if item.vis.node.is_pub() {
236 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
237 self.store_path(def_id.to_def_id());
241 hir::ItemKind::ForeignMod { items, .. } => {
243 let item = self.cx.tcx.hir().foreign_item(item.id);
244 self.visit_foreign_item(item, None, om);
247 // If we're inlining, skip private items.
248 _ if self.inlining && !item.vis.node.is_pub() => {}
249 hir::ItemKind::GlobalAsm(..) => {}
250 hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
251 hir::ItemKind::Use(ref path, kind) => {
252 let is_glob = kind == hir::UseKind::Glob;
254 // Struct and variant constructors and proc macro stubs always show up alongside
255 // their definitions, we've already processed them so just discard these.
256 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
260 // If there was a private module in the current path then don't bother inlining
261 // anything as it will probably be stripped anyway.
262 if item.vis.node.is_pub() && self.inside_public_path {
263 let please_inline = item.attrs.iter().any(|item| match item.meta_item_list() {
264 Some(ref list) if item.has_name(sym::doc) => {
265 list.iter().any(|i| i.has_name(sym::inline))
269 let ident = if is_glob { None } else { Some(name) };
270 if self.maybe_inline_local(
282 om.imports.push(Import {
292 hir::ItemKind::Mod(ref m) => {
293 om.mods.push(self.visit_mod_contents(
302 hir::ItemKind::Fn(..)
303 | hir::ItemKind::ExternCrate(..)
304 | hir::ItemKind::Enum(..)
305 | hir::ItemKind::Struct(..)
306 | hir::ItemKind::Union(..)
307 | hir::ItemKind::TyAlias(..)
308 | hir::ItemKind::OpaqueTy(..)
309 | hir::ItemKind::Static(..)
310 | hir::ItemKind::Trait(..)
311 | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)),
312 hir::ItemKind::Const(..) => {
313 // Underscore constants do not correspond to a nameable item and
314 // so are never useful in documentation.
315 if name != kw::Underscore {
316 om.items.push((item, renamed));
319 hir::ItemKind::Impl { ref of_trait, .. } => {
320 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
321 // them up regardless of where they're located.
322 if !self.inlining && of_trait.is_none() {
323 om.items.push((item, None));
329 fn visit_foreign_item(
331 item: &'tcx hir::ForeignItem<'_>,
332 renamed: Option<Symbol>,
333 om: &mut Module<'tcx>,
335 // If inlining we only want to include public functions.
336 if !self.inlining || item.vis.node.is_pub() {
337 om.foreigns.push((item, renamed));