1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Rust AST Visitor. Extracts useful information and massages it into a form
21 use rustc::hir::map as hir_map;
22 use rustc::hir::def::Def;
23 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
24 use rustc::middle::cstore::{LoadedMacro, CrateStore};
25 use rustc::middle::privacy::AccessLevel;
26 use rustc::ty::Visibility;
27 use rustc::util::nodemap::{FxHashSet, FxHashMap};
32 use clean::{self, AttributesExt, NestedAttributesExt, def_id_to_path};
35 // looks to me like the first two of these are actually
36 // output parameters, maybe only mutated once; perhaps
37 // better simply to have the visit method return a tuple
40 // also, is there some reason that this doesn't use the 'visit'
41 // framework from syntax?
43 pub struct RustdocVisitor<'a, 'tcx: 'a, 'rcx: 'a> {
44 pub cstore: &'a CrateStore,
46 pub attrs: hir::HirVec<ast::Attribute>,
47 pub cx: &'a core::DocContext<'a, 'tcx, 'rcx>,
48 view_item_stack: FxHashSet<ast::NodeId>,
50 /// Is the current module and all of its parents public?
51 inside_public_path: bool,
52 reexported_macros: FxHashSet<DefId>,
53 exact_paths: Option<FxHashMap<DefId, Vec<String>>>
56 impl<'a, 'tcx, 'rcx> RustdocVisitor<'a, 'tcx, 'rcx> {
57 pub fn new(cstore: &'a CrateStore,
58 cx: &'a core::DocContext<'a, 'tcx, 'rcx>) -> RustdocVisitor<'a, 'tcx, 'rcx> {
59 // If the root is re-exported, terminate all recursion.
60 let mut stack = FxHashSet();
61 stack.insert(ast::CRATE_NODE_ID);
63 module: Module::new(None),
64 attrs: hir::HirVec::new(),
66 view_item_stack: stack,
68 inside_public_path: true,
69 reexported_macros: FxHashSet(),
70 exact_paths: Some(FxHashMap()),
75 fn store_path(&mut self, did: DefId) {
76 // We can't use the entry api, as that keeps the mutable borrow of self active
77 // when we try to use cx
78 let exact_paths = self.exact_paths.as_mut().unwrap();
79 if exact_paths.get(&did).is_none() {
80 let path = def_id_to_path(self.cx, did, self.cx.crate_name.clone());
81 exact_paths.insert(did, path);
85 fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
86 self.cx.tcx.hir.opt_local_def_id(id)
87 .and_then(|def_id| self.cx.tcx.lookup_stability(def_id)).cloned()
90 fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
91 self.cx.tcx.hir.opt_local_def_id(id)
92 .and_then(|def_id| self.cx.tcx.lookup_deprecation(def_id))
95 pub fn visit(&mut self, krate: &hir::Crate) {
96 self.attrs = krate.attrs.clone();
98 self.module = self.visit_mod_contents(krate.span,
104 // attach the crate's exported macros to the top-level module:
105 let macro_exports: Vec<_> =
106 krate.exported_macros.iter().map(|def| self.visit_local_macro(def)).collect();
107 self.module.macros.extend(macro_exports);
108 self.module.is_crate = true;
110 self.cx.renderinfo.borrow_mut().exact_paths = self.exact_paths.take().unwrap();
113 pub fn visit_variant_data(&mut self, item: &hir::Item,
114 name: ast::Name, sd: &hir::VariantData,
115 generics: &hir::Generics) -> Struct {
116 debug!("Visiting struct");
117 let struct_type = struct_type_from_def(&*sd);
122 vis: item.vis.clone(),
123 stab: self.stability(item.id),
124 depr: self.deprecation(item.id),
125 attrs: item.attrs.clone(),
126 generics: generics.clone(),
127 fields: sd.fields().iter().cloned().collect(),
132 pub fn visit_union_data(&mut self, item: &hir::Item,
133 name: ast::Name, sd: &hir::VariantData,
134 generics: &hir::Generics) -> Union {
135 debug!("Visiting union");
136 let struct_type = struct_type_from_def(&*sd);
141 vis: item.vis.clone(),
142 stab: self.stability(item.id),
143 depr: self.deprecation(item.id),
144 attrs: item.attrs.clone(),
145 generics: generics.clone(),
146 fields: sd.fields().iter().cloned().collect(),
151 pub fn visit_enum_def(&mut self, it: &hir::Item,
152 name: ast::Name, def: &hir::EnumDef,
153 params: &hir::Generics) -> Enum {
154 debug!("Visiting enum");
157 variants: def.variants.iter().map(|v| Variant {
159 attrs: v.node.attrs.clone(),
160 stab: self.stability(v.node.data.id()),
161 depr: self.deprecation(v.node.data.id()),
162 def: v.node.data.clone(),
166 stab: self.stability(it.id),
167 depr: self.deprecation(it.id),
168 generics: params.clone(),
169 attrs: it.attrs.clone(),
175 pub fn visit_fn(&mut self, item: &hir::Item,
176 name: ast::Name, fd: &hir::FnDecl,
177 unsafety: &hir::Unsafety,
178 constness: hir::Constness,
181 body: hir::BodyId) -> Function {
182 debug!("Visiting fn");
185 vis: item.vis.clone(),
186 stab: self.stability(item.id),
187 depr: self.deprecation(item.id),
188 attrs: item.attrs.clone(),
192 generics: gen.clone(),
200 pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
201 vis: hir::Visibility, id: ast::NodeId,
203 name: Option<ast::Name>) -> Module {
204 let mut om = Module::new(name);
205 om.where_outer = span;
206 om.where_inner = m.inner;
208 om.vis = vis.clone();
209 om.stab = self.stability(id);
210 om.depr = self.deprecation(id);
212 // Keep track of if there were any private modules in the path.
213 let orig_inside_public_path = self.inside_public_path;
214 self.inside_public_path &= vis == hir::Public;
215 for i in &m.item_ids {
216 let item = self.cx.tcx.hir.expect_item(i.id);
217 self.visit_item(item, None, &mut om);
219 self.inside_public_path = orig_inside_public_path;
220 let def_id = self.cx.tcx.hir.local_def_id(id);
221 if let Some(exports) = self.cx.tcx.module_exports(def_id) {
222 for export in exports.iter().filter(|e| e.vis == Visibility::Public) {
223 if let Def::Macro(def_id, ..) = export.def {
224 if def_id.krate == LOCAL_CRATE || self.reexported_macros.contains(&def_id) {
225 continue // These are `krate.exported_macros`, handled in `self.visit()`.
228 let imported_from = self.cx.tcx.original_crate_name(def_id.krate);
229 let def = match self.cstore.load_macro_untracked(def_id, self.cx.sess()) {
230 LoadedMacro::MacroDef(macro_def) => macro_def,
231 // FIXME(jseyfried): document proc macro re-exports
232 LoadedMacro::ProcMacro(..) => continue,
235 let matchers = if let ast::ItemKind::MacroDef(ref def) = def.node {
236 let tts: Vec<_> = def.stream().into_trees().collect();
237 tts.chunks(4).map(|arm| arm[0].span()).collect()
242 om.macros.push(Macro {
244 attrs: def.attrs.clone().into(),
245 name: def.ident.name,
248 stab: self.stability(def.id),
249 depr: self.deprecation(def.id),
250 imported_from: Some(imported_from),
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(&mut self,
270 renamed: Option<ast::Name>,
273 please_inline: bool) -> bool {
275 fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
276 while let Some(id) = cx.tcx.hir.get_enclosing_scope(node) {
278 if cx.tcx.hir.attrs(node).lists("doc").has_word("hidden") {
281 if node == ast::CRATE_NODE_ID {
288 debug!("maybe_inline_local def: {:?}", def);
290 let tcx = self.cx.tcx;
294 let def_did = def.def_id();
296 let use_attrs = tcx.hir.attrs(id);
297 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
298 let is_no_inline = use_attrs.lists("doc").has_word("no_inline") ||
299 use_attrs.lists("doc").has_word("hidden");
301 // Memoize the non-inlined `pub use`'d macros so we don't push an extra
302 // declaration in `visit_mod_contents()`
303 if !def_did.is_local() {
304 if let Def::Macro(did, _) = def {
305 if please_inline { return true }
306 debug!("memoizing non-inlined macro export: {:?}", def);
307 self.reexported_macros.insert(did);
312 // For cross-crate impl inlining we need to know whether items are
313 // reachable in documentation - a previously nonreachable item can be
314 // made reachable by cross-crate inlining which we're checking here.
315 // (this is done here because we need to know this upfront)
316 if !def_did.is_local() && !is_no_inline {
317 let attrs = clean::inline::load_attrs(self.cx, def_did);
318 let self_is_hidden = attrs.lists("doc").has_word("hidden");
324 Def::TyForeign(did) |
325 Def::TyAlias(did) if !self_is_hidden => {
326 self.cx.access_levels.borrow_mut().map.insert(did, AccessLevel::Public);
328 Def::Mod(did) => if !self_is_hidden {
329 ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
337 let def_node_id = match tcx.hir.as_local_node_id(def_did) {
338 Some(n) => n, None => return false
341 let is_private = !self.cx.access_levels.borrow().is_public(def_did);
342 let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
344 // Only inline if requested or if the item would otherwise be stripped
345 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
349 if !self.view_item_stack.insert(def_node_id) { return false }
351 let ret = match tcx.hir.get(def_node_id) {
352 hir_map::NodeItem(&hir::Item { node: hir::ItemMod(ref m), .. }) if glob => {
353 let prev = mem::replace(&mut self.inlining, true);
354 for i in &m.item_ids {
355 let i = self.cx.tcx.hir.expect_item(i.id);
356 self.visit_item(i, None, om);
358 self.inlining = prev;
361 hir_map::NodeItem(it) if !glob => {
362 let prev = mem::replace(&mut self.inlining, true);
363 self.visit_item(it, renamed, om);
364 self.inlining = prev;
367 hir_map::NodeForeignItem(it) if !glob => {
368 // generate a fresh `extern {}` block if we want to inline a foreign item.
369 om.foreigns.push(hir::ForeignMod {
370 abi: tcx.hir.get_foreign_abi(it.id),
371 items: vec![hir::ForeignItem {
372 name: renamed.unwrap_or(it.name),
380 self.view_item_stack.remove(&def_node_id);
384 pub fn visit_item(&mut self, item: &hir::Item,
385 renamed: Option<ast::Name>, om: &mut Module) {
386 debug!("Visiting item {:?}", item);
387 let name = renamed.unwrap_or(item.name);
389 if item.vis == hir::Public {
390 let def_id = self.cx.tcx.hir.local_def_id(item.id);
391 self.store_path(def_id);
395 hir::ItemForeignMod(ref fm) => {
396 // If inlining we only want to include public functions.
397 om.foreigns.push(if self.inlining {
400 items: fm.items.iter().filter(|i| i.vis == hir::Public).cloned().collect(),
406 // If we're inlining, skip private items.
407 _ if self.inlining && item.vis != hir::Public => {}
408 hir::ItemGlobalAsm(..) => {}
409 hir::ItemExternCrate(ref p) => {
410 let def_id = self.cx.tcx.hir.local_def_id(item.id);
411 om.extern_crates.push(ExternCrate {
412 cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id)
413 .unwrap_or(LOCAL_CRATE),
415 path: p.map(|x|x.to_string()),
416 vis: item.vis.clone(),
417 attrs: item.attrs.clone(),
421 hir::ItemUse(_, hir::UseKind::ListStem) => {}
422 hir::ItemUse(ref path, kind) => {
423 let is_glob = kind == hir::UseKind::Glob;
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 == hir::Public && self.inside_public_path {
428 let please_inline = item.attrs.iter().any(|item| {
429 match item.meta_item_list() {
430 Some(ref list) if item.check_name("doc") => {
431 list.iter().any(|i| i.check_name("inline"))
436 let name = if is_glob { None } else { Some(name) };
437 if self.maybe_inline_local(item.id,
447 om.imports.push(Import {
450 vis: item.vis.clone(),
451 attrs: item.attrs.clone(),
452 path: (**path).clone(),
457 hir::ItemMod(ref m) => {
458 om.mods.push(self.visit_mod_contents(item.span,
465 hir::ItemEnum(ref ed, ref gen) =>
466 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
467 hir::ItemStruct(ref sd, ref gen) =>
468 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
469 hir::ItemUnion(ref sd, ref gen) =>
470 om.unions.push(self.visit_union_data(item, name, sd, gen)),
471 hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, body) =>
472 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
473 constness, abi, gen, body)),
474 hir::ItemTy(ref ty, ref gen) => {
480 attrs: item.attrs.clone(),
482 vis: item.vis.clone(),
483 stab: self.stability(item.id),
484 depr: self.deprecation(item.id),
488 hir::ItemStatic(ref ty, ref mut_, ref exp) => {
491 mutability: mut_.clone(),
495 attrs: item.attrs.clone(),
497 vis: item.vis.clone(),
498 stab: self.stability(item.id),
499 depr: self.deprecation(item.id),
503 hir::ItemConst(ref ty, ref exp) => {
509 attrs: item.attrs.clone(),
511 vis: item.vis.clone(),
512 stab: self.stability(item.id),
513 depr: self.deprecation(item.id),
515 om.constants.push(s);
517 hir::ItemTrait(is_auto, unsafety, ref gen, ref b, ref item_ids) => {
518 let items = item_ids.iter()
519 .map(|ti| self.cx.tcx.hir.trait_item(ti.id).clone())
526 generics: gen.clone(),
527 bounds: b.iter().cloned().collect(),
529 attrs: item.attrs.clone(),
531 vis: item.vis.clone(),
532 stab: self.stability(item.id),
533 depr: self.deprecation(item.id),
537 hir::ItemTraitAlias(..) => {
538 unimplemented!("trait objects are not yet implemented")
541 hir::ItemImpl(unsafety,
548 // Don't duplicate impls when inlining, we'll pick them up
549 // regardless of where they're located.
551 let items = item_ids.iter()
552 .map(|ii| self.cx.tcx.hir.impl_item(ii.id).clone())
558 generics: gen.clone(),
562 attrs: item.attrs.clone(),
565 vis: item.vis.clone(),
566 stab: self.stability(item.id),
567 depr: self.deprecation(item.id),
575 // convert each exported_macro into a doc item
576 fn visit_local_macro(&self, def: &hir::MacroDef) -> Macro {
577 let tts = def.body.trees().collect::<Vec<_>>();
578 // Extract the spans of all matchers. They represent the "interface" of the macro.
579 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
582 def_id: self.cx.tcx.hir.local_def_id(def.id),
583 attrs: def.attrs.clone(),
587 stab: self.stability(def.id),
588 depr: self.deprecation(def.id),