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, LOCAL_CRATE};
10 use rustc_middle::middle::privacy::AccessLevel;
11 use rustc_middle::ty::TyCtxt;
12 use rustc_span::hygiene::MacroKind;
13 use rustc_span::source_map::Spanned;
14 use rustc_span::symbol::{kw, sym, Ident, Symbol};
15 use rustc_span::{self, Span};
19 use crate::clean::{self, 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 // Also, is there some reason that this doesn't use the 'visit'
35 // framework from syntax?.
37 pub struct RustdocVisitor<'a, 'tcx> {
38 cx: &'a mut core::DocContext<'tcx>,
39 view_item_stack: FxHashSet<hir::HirId>,
41 /// Are the current module and all of its parents public?
42 inside_public_path: bool,
43 exact_paths: FxHashMap<DefId, Vec<String>>,
46 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
47 pub fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
48 // If the root is re-exported, terminate all recursion.
49 let mut stack = FxHashSet::default();
50 stack.insert(hir::CRATE_HIR_ID);
53 view_item_stack: stack,
55 inside_public_path: true,
56 exact_paths: FxHashMap::default(),
60 fn store_path(&mut self, did: DefId) {
61 let tcx = self.cx.tcx;
62 self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
65 pub fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> {
66 let mut module = self.visit_mod_contents(
69 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public },
74 // Attach the crate's exported macros to the top-level module:
77 .extend(krate.exported_macros.iter().map(|def| self.visit_local_macro(def, None)));
78 module.is_crate = true;
80 self.cx.renderinfo.get_mut().exact_paths = self.exact_paths;
85 fn visit_variant_data(
87 item: &'tcx hir::Item<'_>,
89 sd: &'tcx hir::VariantData<'_>,
90 generics: &'tcx hir::Generics<'_>,
92 debug!("visiting struct");
93 let struct_type = struct_type_from_def(&*sd);
108 item: &'tcx hir::Item<'_>,
110 sd: &'tcx hir::VariantData<'_>,
111 generics: &'tcx hir::Generics<'_>,
113 debug!("visiting union");
114 let struct_type = struct_type_from_def(&*sd);
129 it: &'tcx hir::Item<'_>,
131 def: &'tcx hir::EnumDef<'_>,
132 generics: &'tcx hir::Generics<'_>,
134 debug!("visiting enum");
158 om: &mut Module<'tcx>,
159 item: &'tcx hir::Item<'_>,
161 decl: &'tcx hir::FnDecl<'_>,
162 header: hir::FnHeader,
163 generics: &'tcx hir::Generics<'_>,
166 debug!("visiting fn");
167 let macro_kind = item.attrs.iter().find_map(|a| {
168 if a.has_name(sym::proc_macro) {
169 Some(MacroKind::Bang)
170 } else if a.has_name(sym::proc_macro_derive) {
171 Some(MacroKind::Derive)
172 } else if a.has_name(sym::proc_macro_attribute) {
173 Some(MacroKind::Attr)
180 let name = if kind == MacroKind::Derive {
182 .lists(sym::proc_macro_derive)
183 .find_map(|mi| mi.ident())
184 .expect("proc-macro derives require a name")
190 let mut helpers = Vec::new();
191 for mi in item.attrs.lists(sym::proc_macro_derive) {
192 if !mi.has_name(sym::attributes) {
196 if let Some(list) = mi.meta_item_list() {
197 for inner_mi in list {
198 if let Some(ident) = inner_mi.ident() {
199 helpers.push(ident.name);
205 om.proc_macros.push(ProcMacro {
215 om.fns.push(Function {
230 fn visit_mod_contents(
233 attrs: &'tcx [ast::Attribute],
234 vis: &'tcx hir::Visibility<'_>,
236 m: &'tcx hir::Mod<'tcx>,
237 name: Option<Symbol>,
239 let mut om = Module::new(name, attrs, vis);
240 om.where_outer = span;
241 om.where_inner = m.inner;
243 // Keep track of if there were any private modules in the path.
244 let orig_inside_public_path = self.inside_public_path;
245 self.inside_public_path &= vis.node.is_pub();
246 for i in m.item_ids {
247 let item = self.cx.tcx.hir().expect_item(i.id);
248 self.visit_item(item, None, &mut om);
250 self.inside_public_path = orig_inside_public_path;
254 /// Tries to resolve the target of a `pub use` statement and inlines the
255 /// target if it is defined locally and would not be documented otherwise,
256 /// or when it is specifically requested with `please_inline`.
257 /// (the latter is the case when the import is marked `doc(inline)`)
259 /// Cross-crate inlining occurs later on during crate cleaning
260 /// and follows different rules.
262 /// Returns `true` if the target has been inlined.
263 fn maybe_inline_local(
267 renamed: Option<Ident>,
269 om: &mut Module<'tcx>,
272 fn inherits_doc_hidden(cx: &core::DocContext<'_>, mut node: hir::HirId) -> bool {
273 while let Some(id) = cx.tcx.hir().get_enclosing_scope(node) {
275 if cx.tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
278 if node == hir::CRATE_HIR_ID {
285 debug!("maybe_inline_local res: {:?}", res);
287 let tcx = self.cx.tcx;
288 let res_did = if let Some(did) = res.opt_def_id() {
294 let use_attrs = tcx.hir().attrs(id);
295 // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
296 let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
297 || use_attrs.lists(sym::doc).has_word(sym::hidden);
299 // For cross-crate impl inlining we need to know whether items are
300 // reachable in documentation -- a previously nonreachable item can be
301 // made reachable by cross-crate inlining which we're checking here.
302 // (this is done here because we need to know this upfront).
303 if !res_did.is_local() && !is_no_inline {
304 let attrs = clean::inline::load_attrs(self.cx, res_did);
305 let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
307 if let Res::Def(kind, did) = res {
308 if kind == DefKind::Mod {
309 crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did)
311 // All items need to be handled here in case someone wishes to link
312 // to them with intra-doc links
318 .insert(did, AccessLevel::Public);
325 let res_hir_id = match res_did.as_local() {
326 Some(n) => tcx.hir().local_def_id_to_hir_id(n),
327 None => return false,
330 let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(res_did);
331 let is_hidden = inherits_doc_hidden(self.cx, res_hir_id);
333 // Only inline if requested or if the item would otherwise be stripped.
334 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
338 if !self.view_item_stack.insert(res_hir_id) {
342 let ret = match tcx.hir().get(res_hir_id) {
343 Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
344 let prev = mem::replace(&mut self.inlining, true);
345 for i in m.item_ids {
346 let i = self.cx.tcx.hir().expect_item(i.id);
347 self.visit_item(i, None, om);
349 self.inlining = prev;
352 Node::Item(it) if !glob => {
353 let prev = mem::replace(&mut self.inlining, true);
354 self.visit_item(it, renamed, om);
355 self.inlining = prev;
358 Node::ForeignItem(it) if !glob => {
359 let prev = mem::replace(&mut self.inlining, true);
360 self.visit_foreign_item(it, renamed, om);
361 self.inlining = prev;
364 Node::MacroDef(def) if !glob => {
365 om.macros.push(self.visit_local_macro(def, renamed.map(|i| i.name)));
370 self.view_item_stack.remove(&res_hir_id);
376 item: &'tcx hir::Item<'_>,
377 renamed: Option<Ident>,
378 om: &mut Module<'tcx>,
380 debug!("visiting item {:?}", item);
381 let ident = renamed.unwrap_or(item.ident);
383 if item.vis.node.is_pub() {
384 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
385 self.store_path(def_id.to_def_id());
389 hir::ItemKind::ForeignMod(ref fm) => {
390 for item in fm.items {
391 self.visit_foreign_item(item, None, om);
394 // If we're inlining, skip private items.
395 _ if self.inlining && !item.vis.node.is_pub() => {}
396 hir::ItemKind::GlobalAsm(..) => {}
397 hir::ItemKind::ExternCrate(orig_name) => {
398 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
399 om.extern_crates.push(ExternCrate {
400 cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE),
402 path: orig_name.map(|x| x.to_string()),
408 hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
409 hir::ItemKind::Use(ref path, kind) => {
410 let is_glob = kind == hir::UseKind::Glob;
412 // Struct and variant constructors and proc macro stubs always show up alongside
413 // their definitions, we've already processed them so just discard these.
414 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
418 // If there was a private module in the current path then don't bother inlining
419 // anything as it will probably be stripped anyway.
420 if item.vis.node.is_pub() && self.inside_public_path {
421 let please_inline = item.attrs.iter().any(|item| match item.meta_item_list() {
422 Some(ref list) if item.has_name(sym::doc) => {
423 list.iter().any(|i| i.has_name(sym::inline))
427 let ident = if is_glob { None } else { Some(ident) };
428 if self.maybe_inline_local(
440 om.imports.push(Import {
450 hir::ItemKind::Mod(ref m) => {
451 om.mods.push(self.visit_mod_contents(
460 hir::ItemKind::Enum(ref ed, ref gen) => {
461 om.enums.push(self.visit_enum_def(item, ident.name, ed, gen))
463 hir::ItemKind::Struct(ref sd, ref gen) => {
464 om.structs.push(self.visit_variant_data(item, ident.name, sd, gen))
466 hir::ItemKind::Union(ref sd, ref gen) => {
467 om.unions.push(self.visit_union_data(item, ident.name, sd, gen))
469 hir::ItemKind::Fn(ref sig, ref gen, body) => {
470 self.visit_fn(om, item, ident.name, &sig.decl, sig.header, gen, body)
472 hir::ItemKind::TyAlias(ty, ref gen) => {
484 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
493 om.opaque_tys.push(t);
495 hir::ItemKind::Static(type_, mutability, expr) => {
508 hir::ItemKind::Const(type_, expr) => {
509 // Underscore constants do not correspond to a nameable item and
510 // so are never useful in documentation.
511 if ident.name != kw::Underscore {
521 om.constants.push(s);
524 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
525 let items = item_ids.iter().map(|ti| self.cx.tcx.hir().trait_item(ti.id)).collect();
540 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
550 om.trait_aliases.push(t);
553 hir::ItemKind::Impl {
564 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
565 // them up regardless of where they're located.
566 if !self.inlining && of_trait.is_none() {
568 items.iter().map(|item| self.cx.tcx.hir().impl_item(item.id)).collect();
589 fn visit_foreign_item(
591 item: &'tcx hir::ForeignItem<'_>,
592 renamed: Option<Ident>,
593 om: &mut Module<'tcx>,
595 // If inlining we only want to include public functions.
596 if self.inlining && !item.vis.node.is_pub() {
600 om.foreigns.push(ForeignItem {
602 name: renamed.unwrap_or(item.ident).name,
610 // Convert each `exported_macro` into a doc item.
611 fn visit_local_macro(
613 def: &'tcx hir::MacroDef<'_>,
614 renamed: Option<Symbol>,
616 debug!("visit_local_macro: {}", def.ident);
617 let tts = def.ast.body.inner_tokens().trees().collect::<Vec<_>>();
618 // Extract the spans of all matchers. They represent the "interface" of the macro.
619 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
623 def_id: self.cx.tcx.hir().local_def_id(def.hir_id).to_def_id(),
625 name: renamed.unwrap_or(def.ident.name),