1 //! The Rust AST Visitor. Extracts useful information and massages it into a form
2 //! usable for `clean`.
4 use rustc::middle::privacy::AccessLevel;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
11 use rustc_span::hygiene::MacroKind;
12 use rustc_span::source_map::Spanned;
13 use rustc_span::symbol::{kw, sym};
14 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);
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
171 if a.check_name(sym::proc_macro) {
172 Some(MacroKind::Bang)
173 } else if a.check_name(sym::proc_macro_derive) {
174 Some(MacroKind::Derive)
175 } else if a.check_name(sym::proc_macro_attribute) {
176 Some(MacroKind::Attr)
184 let name = if kind == MacroKind::Derive {
186 .lists(sym::proc_macro_derive)
187 .filter_map(|mi| mi.ident())
189 .expect("proc-macro derives require a name")
195 let mut helpers = Vec::new();
196 for mi in item.attrs.lists(sym::proc_macro_derive) {
197 if !mi.check_name(sym::attributes) {
201 if let Some(list) = mi.meta_item_list() {
202 for inner_mi in list {
203 if let Some(ident) = inner_mi.ident() {
204 helpers.push(ident.name);
210 om.proc_macros.push(ProcMacro {
220 om.fns.push(Function {
235 fn visit_mod_contents(
238 attrs: &'tcx [ast::Attribute],
239 vis: &'tcx hir::Visibility,
241 m: &'tcx hir::Mod<'tcx>,
242 name: Option<ast::Name>,
244 let mut om = Module::new(name, attrs, vis);
245 om.where_outer = span;
246 om.where_inner = m.inner;
248 // Keep track of if there were any private modules in the path.
249 let orig_inside_public_path = self.inside_public_path;
250 self.inside_public_path &= vis.node.is_pub();
251 for i in m.item_ids {
252 let item = self.cx.tcx.hir().expect_item(i.id);
253 self.visit_item(item, None, &mut om);
255 self.inside_public_path = orig_inside_public_path;
259 /// Tries to resolve the target of a `pub use` statement and inlines the
260 /// target if it is defined locally and would not be documented otherwise,
261 /// or when it is specifically requested with `please_inline`.
262 /// (the latter is the case when the import is marked `doc(inline)`)
264 /// Cross-crate inlining occurs later on during crate cleaning
265 /// and follows different rules.
267 /// Returns `true` if the target has been inlined.
268 fn maybe_inline_local(
272 renamed: Option<ast::Ident>,
274 om: &mut Module<'tcx>,
277 fn inherits_doc_hidden(cx: &core::DocContext<'_>, mut node: hir::HirId) -> bool {
278 while let Some(id) = cx.tcx.hir().get_enclosing_scope(node) {
280 if cx.tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
283 if node == hir::CRATE_HIR_ID {
290 debug!("maybe_inline_local res: {:?}", res);
292 let tcx = self.cx.tcx;
293 let res_did = if let Some(did) = res.opt_def_id() {
299 let use_attrs = tcx.hir().attrs(id);
300 // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
301 let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
302 || use_attrs.lists(sym::doc).has_word(sym::hidden);
304 // For cross-crate impl inlining we need to know whether items are
305 // reachable in documentation -- a previously nonreachable item can be
306 // made reachable by cross-crate inlining which we're checking here.
307 // (this is done here because we need to know this upfront).
308 if !res_did.is_local() && !is_no_inline {
309 let attrs = clean::inline::load_attrs(self.cx, res_did);
310 let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
312 Res::Def(DefKind::Trait, did)
313 | Res::Def(DefKind::Struct, did)
314 | Res::Def(DefKind::Union, did)
315 | Res::Def(DefKind::Enum, did)
316 | Res::Def(DefKind::ForeignTy, did)
317 | Res::Def(DefKind::TyAlias, did)
318 if !self_is_hidden =>
320 self.cx.renderinfo.get_mut().access_levels.map.insert(did, AccessLevel::Public);
322 Res::Def(DefKind::Mod, did) => {
324 crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
333 let res_hir_id = match tcx.hir().as_local_hir_id(res_did) {
335 None => return false,
338 let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(res_did);
339 let is_hidden = inherits_doc_hidden(self.cx, res_hir_id);
341 // Only inline if requested or if the item would otherwise be stripped.
342 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
346 if !self.view_item_stack.insert(res_hir_id) {
350 let ret = match tcx.hir().get(res_hir_id) {
351 Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
352 let prev = mem::replace(&mut self.inlining, true);
353 for i in m.item_ids {
354 let i = self.cx.tcx.hir().expect_item(i.id);
355 self.visit_item(i, None, om);
357 self.inlining = prev;
360 Node::Item(it) if !glob => {
361 let prev = mem::replace(&mut self.inlining, true);
362 self.visit_item(it, renamed, om);
363 self.inlining = prev;
366 Node::ForeignItem(it) if !glob => {
367 let prev = mem::replace(&mut self.inlining, true);
368 self.visit_foreign_item(it, renamed, om);
369 self.inlining = prev;
372 Node::MacroDef(def) if !glob => {
373 om.macros.push(self.visit_local_macro(def, renamed.map(|i| i.name)));
378 self.view_item_stack.remove(&res_hir_id);
384 item: &'tcx hir::Item,
385 renamed: Option<ast::Ident>,
386 om: &mut Module<'tcx>,
388 debug!("visiting item {:?}", item);
389 let ident = renamed.unwrap_or(item.ident);
391 if item.vis.node.is_pub() {
392 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
393 self.store_path(def_id);
397 hir::ItemKind::ForeignMod(ref fm) => {
398 for item in fm.items {
399 self.visit_foreign_item(item, None, om);
402 // If we're inlining, skip private items.
403 _ if self.inlining && !item.vis.node.is_pub() => {}
404 hir::ItemKind::GlobalAsm(..) => {}
405 hir::ItemKind::ExternCrate(orig_name) => {
406 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
407 om.extern_crates.push(ExternCrate {
408 cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE),
410 path: orig_name.map(|x| x.to_string()),
416 hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
417 hir::ItemKind::Use(ref path, kind) => {
418 let is_glob = kind == hir::UseKind::Glob;
420 // Struct and variant constructors and proc macro stubs always show up alongside
421 // their definitions, we've already processed them so just discard these.
422 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
426 // If there was a private module in the current path then don't bother inlining
427 // anything as it will probably be stripped anyway.
428 if item.vis.node.is_pub() && self.inside_public_path {
429 let please_inline = item.attrs.iter().any(|item| match item.meta_item_list() {
430 Some(ref list) if item.check_name(sym::doc) => {
431 list.iter().any(|i| i.check_name(sym::inline))
435 let ident = if is_glob { None } else { Some(ident) };
436 if self.maybe_inline_local(
448 om.imports.push(Import {
458 hir::ItemKind::Mod(ref m) => {
459 om.mods.push(self.visit_mod_contents(
468 hir::ItemKind::Enum(ref ed, ref gen) => {
469 om.enums.push(self.visit_enum_def(item, ident.name, ed, gen))
471 hir::ItemKind::Struct(ref sd, ref gen) => {
472 om.structs.push(self.visit_variant_data(item, ident.name, sd, gen))
474 hir::ItemKind::Union(ref sd, ref gen) => {
475 om.unions.push(self.visit_union_data(item, ident.name, sd, gen))
477 hir::ItemKind::Fn(ref sig, ref gen, body) => {
478 self.visit_fn(om, item, ident.name, &sig.decl, sig.header, gen, body)
480 hir::ItemKind::TyAlias(ty, ref gen) => {
492 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
501 om.opaque_tys.push(t);
503 hir::ItemKind::Static(type_, mutability, expr) => {
516 hir::ItemKind::Const(type_, expr) => {
517 // Underscore constants do not correspond to a nameable item and
518 // so are never useful in documentation.
519 if ident.name != kw::Underscore {
529 om.constants.push(s);
532 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
533 let items = item_ids.iter().map(|ti| self.cx.tcx.hir().trait_item(ti.id)).collect();
548 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
558 om.trait_aliases.push(t);
561 hir::ItemKind::Impl {
570 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
571 // them up regardless of where they're located.
572 if !self.inlining && of_trait.is_none() {
574 items.iter().map(|item| self.cx.tcx.hir().impl_item(item.id)).collect();
594 fn visit_foreign_item(
596 item: &'tcx hir::ForeignItem,
597 renamed: Option<ast::Ident>,
598 om: &mut Module<'tcx>,
600 // If inlining we only want to include public functions.
601 if self.inlining && !item.vis.node.is_pub() {
605 om.foreigns.push(ForeignItem {
607 name: renamed.unwrap_or(item.ident).name,
615 // Convert each `exported_macro` into a doc item.
616 fn visit_local_macro(
618 def: &'tcx hir::MacroDef,
619 renamed: Option<ast::Name>,
621 debug!("visit_local_macro: {}", def.name);
622 let tts = def.body.trees().collect::<Vec<_>>();
623 // Extract the spans of all matchers. They represent the "interface" of the macro.
624 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
628 def_id: self.cx.tcx.hir().local_def_id(def.hir_id),
630 name: renamed.unwrap_or(def.name),