1 //! The Rust AST Visitor. Extracts useful information and massages it into a form
2 //! usable for `clean`.
4 use rustc::hir::{self, Node};
5 use rustc::hir::def::{Res, DefKind};
6 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
7 use rustc::middle::privacy::AccessLevel;
8 use rustc::util::nodemap::{FxHashSet, FxHashMap};
11 use syntax::ext::base::MacroKind;
12 use syntax::source_map::Spanned;
13 use syntax::symbol::sym;
14 use syntax_pos::{self, Span};
19 use crate::clean::{self, AttributesExt, NestedAttributesExt};
20 use crate::doctree::*;
22 // FIXME: Should this be replaced with tcx.def_path_str?
27 let crate_name = tcx.crate_name(did.krate).to_string();
28 let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| {
29 // extern blocks have an empty name
30 let s = elem.data.to_string();
37 std::iter::once(crate_name).chain(relative).collect()
40 // Also, is there some reason that this doesn't use the 'visit'
41 // framework from syntax?.
43 pub struct RustdocVisitor<'a, 'tcx> {
44 cx: &'a core::DocContext<'tcx>,
45 view_item_stack: FxHashSet<hir::HirId>,
47 /// Are the current module and all of its parents public?
48 inside_public_path: bool,
49 exact_paths: FxHashMap<DefId, Vec<String>>,
52 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
54 cx: &'a core::DocContext<'tcx>
55 ) -> 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 pub fn visit(mut self, krate: &'tcx hir::Crate) -> Module<'tcx> {
74 let mut module = self.visit_mod_contents(krate.span,
76 &Spanned { span: syntax_pos::DUMMY_SP,
77 node: hir::VisibilityKind::Public },
81 // Attach the crate's exported macros to the top-level module:
83 krate.exported_macros.iter().map(|def| self.visit_local_macro(def, None)),
85 module.is_crate = true;
87 self.cx.renderinfo.borrow_mut().exact_paths = self.exact_paths;
92 fn visit_variant_data(&mut self, item: &'tcx hir::Item,
93 name: ast::Name, sd: &'tcx hir::VariantData,
94 generics: &'tcx hir::Generics) -> Struct<'tcx> {
95 debug!("visiting struct");
96 let struct_type = struct_type_from_def(&*sd);
109 fn visit_union_data(&mut self, item: &'tcx hir::Item,
110 name: ast::Name, sd: &'tcx hir::VariantData,
111 generics: &'tcx hir::Generics) -> Union<'tcx> {
112 debug!("visiting union");
113 let struct_type = struct_type_from_def(&*sd);
126 fn visit_enum_def(&mut self, it: &'tcx hir::Item,
127 name: ast::Name, def: &'tcx hir::EnumDef,
128 generics: &'tcx hir::Generics) -> Enum<'tcx> {
129 debug!("visiting enum");
132 variants: def.variants.iter().map(|v| Variant {
133 name: v.node.ident.name,
135 attrs: &v.node.attrs,
147 fn visit_fn(&mut self, om: &mut Module<'tcx>, item: &'tcx hir::Item,
148 name: ast::Name, decl: &'tcx hir::FnDecl,
149 header: hir::FnHeader,
150 generics: &'tcx hir::Generics,
152 debug!("visiting fn");
153 let macro_kind = item.attrs.iter().filter_map(|a| {
154 if a.check_name(sym::proc_macro) {
155 Some(MacroKind::Bang)
156 } else if a.check_name(sym::proc_macro_derive) {
157 Some(MacroKind::Derive)
158 } else if a.check_name(sym::proc_macro_attribute) {
159 Some(MacroKind::Attr)
166 let name = if kind == MacroKind::Derive {
167 item.attrs.lists(sym::proc_macro_derive)
168 .filter_map(|mi| mi.ident())
170 .expect("proc-macro derives require a name")
176 let mut helpers = Vec::new();
177 for mi in item.attrs.lists(sym::proc_macro_derive) {
178 if !mi.check_name(sym::attributes) {
182 if let Some(list) = mi.meta_item_list() {
183 for inner_mi in list {
184 if let Some(ident) = inner_mi.ident() {
185 helpers.push(ident.name);
191 om.proc_macros.push(ProcMacro {
201 om.fns.push(Function {
216 fn visit_mod_contents(&mut self, span: Span, attrs: &'tcx hir::HirVec<ast::Attribute>,
217 vis: &'tcx hir::Visibility, id: hir::HirId,
219 name: Option<ast::Name>) -> Module<'tcx> {
220 let mut om = Module::new(name, attrs, vis);
221 om.where_outer = span;
222 om.where_inner = m.inner;
224 // Keep track of if there were any private modules in the path.
225 let orig_inside_public_path = self.inside_public_path;
226 self.inside_public_path &= vis.node.is_pub();
227 for i in &m.item_ids {
228 let item = self.cx.tcx.hir().expect_item(i.id);
229 self.visit_item(item, None, &mut om);
231 self.inside_public_path = orig_inside_public_path;
235 /// Tries to resolve the target of a `pub use` statement and inlines the
236 /// target if it is defined locally and would not be documented otherwise,
237 /// or when it is specifically requested with `please_inline`.
238 /// (the latter is the case when the import is marked `doc(inline)`)
240 /// Cross-crate inlining occurs later on during crate cleaning
241 /// and follows different rules.
243 /// Returns `true` if the target has been inlined.
244 fn maybe_inline_local(&mut self,
247 renamed: Option<ast::Ident>,
249 om: &mut Module<'tcx>,
250 please_inline: bool) -> bool {
252 fn inherits_doc_hidden(cx: &core::DocContext<'_>, mut node: hir::HirId) -> bool {
253 while let Some(id) = cx.tcx.hir().get_enclosing_scope(node) {
255 if cx.tcx.hir().attrs(node)
256 .lists(sym::doc).has_word(sym::hidden) {
259 if node == hir::CRATE_HIR_ID {
266 debug!("maybe_inline_local res: {:?}", res);
268 let tcx = self.cx.tcx;
269 let res_did = if let Some(did) = res.opt_def_id() {
275 let use_attrs = tcx.hir().attrs(id);
276 // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
277 let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline) ||
278 use_attrs.lists(sym::doc).has_word(sym::hidden);
280 // For cross-crate impl inlining we need to know whether items are
281 // reachable in documentation -- a previously nonreachable item can be
282 // made reachable by cross-crate inlining which we're checking here.
283 // (this is done here because we need to know this upfront).
284 if !res_did.is_local() && !is_no_inline {
285 let attrs = clean::inline::load_attrs(self.cx, res_did);
286 let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
288 Res::Def(DefKind::Trait, did) |
289 Res::Def(DefKind::Struct, did) |
290 Res::Def(DefKind::Union, did) |
291 Res::Def(DefKind::Enum, did) |
292 Res::Def(DefKind::ForeignTy, did) |
293 Res::Def(DefKind::TyAlias, did) if !self_is_hidden => {
297 .insert(did, AccessLevel::Public);
299 Res::Def(DefKind::Mod, did) => if !self_is_hidden {
300 crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
308 let res_hir_id = match tcx.hir().as_local_hir_id(res_did) {
309 Some(n) => n, None => return false
312 let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(res_did);
313 let is_hidden = inherits_doc_hidden(self.cx, res_hir_id);
315 // Only inline if requested or if the item would otherwise be stripped.
316 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
320 if !self.view_item_stack.insert(res_hir_id) { return false }
322 let ret = match tcx.hir().get(res_hir_id) {
323 Node::Item(&hir::Item { node: hir::ItemKind::Mod(ref m), .. }) if glob => {
324 let prev = mem::replace(&mut self.inlining, true);
325 for i in &m.item_ids {
326 let i = self.cx.tcx.hir().expect_item(i.id);
327 self.visit_item(i, None, om);
329 self.inlining = prev;
332 Node::Item(it) if !glob => {
333 let prev = mem::replace(&mut self.inlining, true);
334 self.visit_item(it, renamed, om);
335 self.inlining = prev;
338 Node::ForeignItem(it) if !glob => {
339 let prev = mem::replace(&mut self.inlining, true);
340 self.visit_foreign_item(it, renamed, om);
341 self.inlining = prev;
344 Node::MacroDef(def) if !glob => {
345 om.macros.push(self.visit_local_macro(def, renamed.map(|i| i.name)));
350 self.view_item_stack.remove(&res_hir_id);
354 fn visit_item(&mut self, item: &'tcx hir::Item,
355 renamed: Option<ast::Ident>, om: &mut Module<'tcx>) {
356 debug!("visiting item {:?}", item);
357 let ident = renamed.unwrap_or(item.ident);
359 if item.vis.node.is_pub() {
360 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
361 self.store_path(def_id);
365 hir::ItemKind::ForeignMod(ref fm) => {
366 for item in &fm.items {
367 self.visit_foreign_item(item, None, om);
370 // If we're inlining, skip private items.
371 _ if self.inlining && !item.vis.node.is_pub() => {}
372 hir::ItemKind::GlobalAsm(..) => {}
373 hir::ItemKind::ExternCrate(orig_name) => {
374 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
375 om.extern_crates.push(ExternCrate {
376 cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id)
377 .unwrap_or(LOCAL_CRATE),
379 path: orig_name.map(|x|x.to_string()),
385 hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
386 hir::ItemKind::Use(ref path, kind) => {
387 let is_glob = kind == hir::UseKind::Glob;
389 // Struct and variant constructors and proc macro stubs always show up alongside
390 // their definitions, we've already processed them so just discard these.
391 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
395 // If there was a private module in the current path then don't bother inlining
396 // anything as it will probably be stripped anyway.
397 if item.vis.node.is_pub() && self.inside_public_path {
398 let please_inline = item.attrs.iter().any(|item| {
399 match item.meta_item_list() {
400 Some(ref list) if item.check_name(sym::doc) => {
401 list.iter().any(|i| i.check_name(sym::inline))
406 let ident = if is_glob { None } else { Some(ident) };
407 if self.maybe_inline_local(item.hir_id,
417 om.imports.push(Import {
427 hir::ItemKind::Mod(ref m) => {
428 om.mods.push(self.visit_mod_contents(item.span,
435 hir::ItemKind::Enum(ref ed, ref gen) =>
436 om.enums.push(self.visit_enum_def(item, ident.name, ed, gen)),
437 hir::ItemKind::Struct(ref sd, ref gen) =>
438 om.structs.push(self.visit_variant_data(item, ident.name, sd, gen)),
439 hir::ItemKind::Union(ref sd, ref gen) =>
440 om.unions.push(self.visit_union_data(item, ident.name, sd, gen)),
441 hir::ItemKind::Fn(ref fd, header, ref gen, body) =>
442 self.visit_fn(om, item, ident.name, &**fd, header, gen, body),
443 hir::ItemKind::TyAlias(ref ty, ref gen) => {
455 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
464 om.opaque_tys.push(t);
466 hir::ItemKind::Static(ref type_, mutability, expr) => {
479 hir::ItemKind::Const(ref type_, expr) => {
489 om.constants.push(s);
491 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
492 let items = item_ids.iter()
493 .map(|ti| self.cx.tcx.hir().trait_item(ti.id))
509 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
519 om.trait_aliases.push(t);
522 hir::ItemKind::Impl(unsafety,
529 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
530 // them up regardless of where they're located.
531 if !self.inlining && trait_.is_none() {
532 let items = item_ids.iter()
533 .map(|ii| self.cx.tcx.hir().impl_item(ii.id))
554 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem,
555 renamed: Option<ast::Ident>, om: &mut Module<'tcx>) {
556 // If inlining we only want to include public functions.
557 if self.inlining && !item.vis.node.is_pub() {
561 om.foreigns.push(ForeignItem {
563 name: renamed.unwrap_or(item.ident).name,
571 // Convert each `exported_macro` into a doc item.
572 fn visit_local_macro(
574 def: &'tcx hir::MacroDef,
575 renamed: Option<ast::Name>
577 debug!("visit_local_macro: {}", def.name);
578 let tts = def.body.trees().collect::<Vec<_>>();
579 // Extract the spans of all matchers. They represent the "interface" of the macro.
580 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
584 def_id: self.cx.tcx.hir().local_def_id(def.hir_id),
586 name: renamed.unwrap_or(def.name),