1 //! The Rust AST Visitor. Extracts useful information and massages it into a form
2 //! usable for `clean`.
4 use rustc::hir::def::{DefKind, Res};
5 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
6 use rustc::hir::{self, Node};
7 use rustc::middle::privacy::AccessLevel;
9 use rustc::util::nodemap::{FxHashMap, FxHashSet};
10 use rustc_span::hygiene::MacroKind;
11 use rustc_span::{self, Span};
13 use syntax::source_map::Spanned;
14 use syntax::symbol::sym;
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 pub 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 pub 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 pub 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:
76 .extend(krate.exported_macros.iter().map(|def| self.visit_local_macro(def, None)));
77 module.is_crate = true;
79 self.cx.renderinfo.get_mut().exact_paths = self.exact_paths;
84 fn visit_variant_data(
86 item: &'tcx hir::Item,
88 sd: &'tcx hir::VariantData,
89 generics: &'tcx hir::Generics,
91 debug!("visiting struct");
92 let struct_type = struct_type_from_def(&*sd);
107 item: &'tcx hir::Item,
109 sd: &'tcx hir::VariantData,
110 generics: &'tcx hir::Generics,
112 debug!("visiting union");
113 let struct_type = struct_type_from_def(&*sd);
130 def: &'tcx hir::EnumDef,
131 generics: &'tcx hir::Generics,
133 debug!("visiting enum");
157 om: &mut Module<'tcx>,
158 item: &'tcx hir::Item,
160 decl: &'tcx hir::FnDecl,
161 header: hir::FnHeader,
162 generics: &'tcx hir::Generics,
165 debug!("visiting fn");
166 let macro_kind = item
170 if a.check_name(sym::proc_macro) {
171 Some(MacroKind::Bang)
172 } else if a.check_name(sym::proc_macro_derive) {
173 Some(MacroKind::Derive)
174 } else if a.check_name(sym::proc_macro_attribute) {
175 Some(MacroKind::Attr)
183 let name = if kind == MacroKind::Derive {
185 .lists(sym::proc_macro_derive)
186 .filter_map(|mi| mi.ident())
188 .expect("proc-macro derives require a name")
194 let mut helpers = Vec::new();
195 for mi in item.attrs.lists(sym::proc_macro_derive) {
196 if !mi.check_name(sym::attributes) {
200 if let Some(list) = mi.meta_item_list() {
201 for inner_mi in list {
202 if let Some(ident) = inner_mi.ident() {
203 helpers.push(ident.name);
209 om.proc_macros.push(ProcMacro {
219 om.fns.push(Function {
234 fn visit_mod_contents(
237 attrs: &'tcx [ast::Attribute],
238 vis: &'tcx hir::Visibility,
240 m: &'tcx hir::Mod<'tcx>,
241 name: Option<ast::Name>,
243 let mut om = Module::new(name, attrs, vis);
244 om.where_outer = span;
245 om.where_inner = m.inner;
247 // Keep track of if there were any private modules in the path.
248 let orig_inside_public_path = self.inside_public_path;
249 self.inside_public_path &= vis.node.is_pub();
250 for i in m.item_ids {
251 let item = self.cx.tcx.hir().expect_item(i.id);
252 self.visit_item(item, None, &mut om);
254 self.inside_public_path = orig_inside_public_path;
258 /// Tries to resolve the target of a `pub use` statement and inlines the
259 /// target if it is defined locally and would not be documented otherwise,
260 /// or when it is specifically requested with `please_inline`.
261 /// (the latter is the case when the import is marked `doc(inline)`)
263 /// Cross-crate inlining occurs later on during crate cleaning
264 /// and follows different rules.
266 /// Returns `true` if the target has been inlined.
267 fn maybe_inline_local(
271 renamed: Option<ast::Ident>,
273 om: &mut Module<'tcx>,
276 fn inherits_doc_hidden(cx: &core::DocContext<'_>, mut node: hir::HirId) -> bool {
277 while let Some(id) = cx.tcx.hir().get_enclosing_scope(node) {
279 if cx.tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
282 if node == hir::CRATE_HIR_ID {
289 debug!("maybe_inline_local res: {:?}", res);
291 let tcx = self.cx.tcx;
292 let res_did = if let Some(did) = res.opt_def_id() {
298 let use_attrs = tcx.hir().attrs(id);
299 // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
300 let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
301 || use_attrs.lists(sym::doc).has_word(sym::hidden);
303 // For cross-crate impl inlining we need to know whether items are
304 // reachable in documentation -- a previously nonreachable item can be
305 // made reachable by cross-crate inlining which we're checking here.
306 // (this is done here because we need to know this upfront).
307 if !res_did.is_local() && !is_no_inline {
308 let attrs = clean::inline::load_attrs(self.cx, res_did);
309 let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
311 Res::Def(DefKind::Trait, did)
312 | Res::Def(DefKind::Struct, did)
313 | Res::Def(DefKind::Union, did)
314 | Res::Def(DefKind::Enum, did)
315 | Res::Def(DefKind::ForeignTy, did)
316 | Res::Def(DefKind::TyAlias, did)
317 if !self_is_hidden =>
319 self.cx.renderinfo.get_mut().access_levels.map.insert(did, AccessLevel::Public);
321 Res::Def(DefKind::Mod, did) => {
323 crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
332 let res_hir_id = match tcx.hir().as_local_hir_id(res_did) {
334 None => return false,
337 let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(res_did);
338 let is_hidden = inherits_doc_hidden(self.cx, res_hir_id);
340 // Only inline if requested or if the item would otherwise be stripped.
341 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
345 if !self.view_item_stack.insert(res_hir_id) {
349 let ret = match tcx.hir().get(res_hir_id) {
350 Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
351 let prev = mem::replace(&mut self.inlining, true);
352 for i in m.item_ids {
353 let i = self.cx.tcx.hir().expect_item(i.id);
354 self.visit_item(i, None, om);
356 self.inlining = prev;
359 Node::Item(it) if !glob => {
360 let prev = mem::replace(&mut self.inlining, true);
361 self.visit_item(it, renamed, om);
362 self.inlining = prev;
365 Node::ForeignItem(it) if !glob => {
366 let prev = mem::replace(&mut self.inlining, true);
367 self.visit_foreign_item(it, renamed, om);
368 self.inlining = prev;
371 Node::MacroDef(def) if !glob => {
372 om.macros.push(self.visit_local_macro(def, renamed.map(|i| i.name)));
377 self.view_item_stack.remove(&res_hir_id);
383 item: &'tcx hir::Item,
384 renamed: Option<ast::Ident>,
385 om: &mut Module<'tcx>,
387 debug!("visiting item {:?}", item);
388 let ident = renamed.unwrap_or(item.ident);
390 if item.vis.node.is_pub() {
391 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
392 self.store_path(def_id);
396 hir::ItemKind::ForeignMod(ref fm) => {
397 for item in fm.items {
398 self.visit_foreign_item(item, None, om);
401 // If we're inlining, skip private items.
402 _ if self.inlining && !item.vis.node.is_pub() => {}
403 hir::ItemKind::GlobalAsm(..) => {}
404 hir::ItemKind::ExternCrate(orig_name) => {
405 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
406 om.extern_crates.push(ExternCrate {
407 cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE),
409 path: orig_name.map(|x| x.to_string()),
415 hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
416 hir::ItemKind::Use(ref path, kind) => {
417 let is_glob = kind == hir::UseKind::Glob;
419 // Struct and variant constructors and proc macro stubs always show up alongside
420 // their definitions, we've already processed them so just discard these.
421 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
425 // If there was a private module in the current path then don't bother inlining
426 // anything as it will probably be stripped anyway.
427 if item.vis.node.is_pub() && self.inside_public_path {
428 let please_inline = item.attrs.iter().any(|item| match item.meta_item_list() {
429 Some(ref list) if item.check_name(sym::doc) => {
430 list.iter().any(|i| i.check_name(sym::inline))
434 let ident = if is_glob { None } else { Some(ident) };
435 if self.maybe_inline_local(
447 om.imports.push(Import {
457 hir::ItemKind::Mod(ref m) => {
458 om.mods.push(self.visit_mod_contents(
467 hir::ItemKind::Enum(ref ed, ref gen) => {
468 om.enums.push(self.visit_enum_def(item, ident.name, ed, gen))
470 hir::ItemKind::Struct(ref sd, ref gen) => {
471 om.structs.push(self.visit_variant_data(item, ident.name, sd, gen))
473 hir::ItemKind::Union(ref sd, ref gen) => {
474 om.unions.push(self.visit_union_data(item, ident.name, sd, gen))
476 hir::ItemKind::Fn(ref sig, ref gen, body) => {
477 self.visit_fn(om, item, ident.name, &sig.decl, sig.header, gen, body)
479 hir::ItemKind::TyAlias(ty, ref gen) => {
491 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
500 om.opaque_tys.push(t);
502 hir::ItemKind::Static(type_, mutability, expr) => {
515 hir::ItemKind::Const(type_, expr) => {
525 om.constants.push(s);
527 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
528 let items = item_ids.iter().map(|ti| self.cx.tcx.hir().trait_item(ti.id)).collect();
543 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
553 om.trait_aliases.push(t);
565 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
566 // them up regardless of where they're located.
567 if !self.inlining && trait_.is_none() {
569 item_ids.iter().map(|ii| self.cx.tcx.hir().impl_item(ii.id)).collect();
589 fn visit_foreign_item(
591 item: &'tcx hir::ForeignItem,
592 renamed: Option<ast::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<ast::Name>,
616 debug!("visit_local_macro: {}", def.name);
617 let tts = def.body.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),
625 name: renamed.unwrap_or(def.name),