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;
32 use clean::{self, AttributesExt, NestedAttributesExt};
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> {
44 cstore: &'tcx CrateStore,
46 pub attrs: hir::HirVec<ast::Attribute>,
47 pub cx: &'a core::DocContext<'a, 'tcx>,
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>,
55 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
56 pub fn new(cstore: &'tcx CrateStore,
57 cx: &'a core::DocContext<'a, 'tcx>) -> RustdocVisitor<'a, 'tcx> {
58 // If the root is reexported, terminate all recursion.
59 let mut stack = FxHashSet();
60 stack.insert(ast::CRATE_NODE_ID);
62 module: Module::new(None),
63 attrs: hir::HirVec::new(),
65 view_item_stack: stack,
67 inside_public_path: true,
68 reexported_macros: FxHashSet(),
73 fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
74 self.cx.tcx.hir.opt_local_def_id(id)
75 .and_then(|def_id| self.cx.tcx.lookup_stability(def_id)).cloned()
78 fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
79 self.cx.tcx.hir.opt_local_def_id(id)
80 .and_then(|def_id| self.cx.tcx.lookup_deprecation(def_id))
83 pub fn visit(&mut self, krate: &hir::Crate) {
84 self.attrs = krate.attrs.clone();
86 self.module = self.visit_mod_contents(krate.span,
92 // attach the crate's exported macros to the top-level module:
93 let macro_exports: Vec<_> =
94 krate.exported_macros.iter().map(|def| self.visit_local_macro(def)).collect();
95 self.module.macros.extend(macro_exports);
96 self.module.is_crate = true;
99 pub fn visit_variant_data(&mut self, item: &hir::Item,
100 name: ast::Name, sd: &hir::VariantData,
101 generics: &hir::Generics) -> Struct {
102 debug!("Visiting struct");
103 let struct_type = struct_type_from_def(&*sd);
108 vis: item.vis.clone(),
109 stab: self.stability(item.id),
110 depr: self.deprecation(item.id),
111 attrs: item.attrs.clone(),
112 generics: generics.clone(),
113 fields: sd.fields().iter().cloned().collect(),
118 pub fn visit_union_data(&mut self, item: &hir::Item,
119 name: ast::Name, sd: &hir::VariantData,
120 generics: &hir::Generics) -> Union {
121 debug!("Visiting union");
122 let struct_type = struct_type_from_def(&*sd);
127 vis: item.vis.clone(),
128 stab: self.stability(item.id),
129 depr: self.deprecation(item.id),
130 attrs: item.attrs.clone(),
131 generics: generics.clone(),
132 fields: sd.fields().iter().cloned().collect(),
137 pub fn visit_enum_def(&mut self, it: &hir::Item,
138 name: ast::Name, def: &hir::EnumDef,
139 params: &hir::Generics) -> Enum {
140 debug!("Visiting enum");
143 variants: def.variants.iter().map(|v| Variant {
145 attrs: v.node.attrs.clone(),
146 stab: self.stability(v.node.data.id()),
147 depr: self.deprecation(v.node.data.id()),
148 def: v.node.data.clone(),
152 stab: self.stability(it.id),
153 depr: self.deprecation(it.id),
154 generics: params.clone(),
155 attrs: it.attrs.clone(),
161 pub fn visit_fn(&mut self, item: &hir::Item,
162 name: ast::Name, fd: &hir::FnDecl,
163 unsafety: &hir::Unsafety,
164 constness: hir::Constness,
167 body: hir::BodyId) -> Function {
168 debug!("Visiting fn");
171 vis: item.vis.clone(),
172 stab: self.stability(item.id),
173 depr: self.deprecation(item.id),
174 attrs: item.attrs.clone(),
178 generics: gen.clone(),
186 pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
187 vis: hir::Visibility, id: ast::NodeId,
189 name: Option<ast::Name>) -> Module {
190 let mut om = Module::new(name);
191 om.where_outer = span;
192 om.where_inner = m.inner;
194 om.vis = vis.clone();
195 om.stab = self.stability(id);
196 om.depr = self.deprecation(id);
198 // Keep track of if there were any private modules in the path.
199 let orig_inside_public_path = self.inside_public_path;
200 self.inside_public_path &= vis == hir::Public;
201 for i in &m.item_ids {
202 let item = self.cx.tcx.hir.expect_item(i.id);
203 self.visit_item(item, None, &mut om);
205 self.inside_public_path = orig_inside_public_path;
206 let def_id = self.cx.tcx.hir.local_def_id(id);
207 if let Some(exports) = self.cx.tcx.module_exports(def_id) {
208 for export in exports.iter().filter(|e| e.vis == Visibility::Public) {
209 if let Def::Macro(def_id, ..) = export.def {
210 if def_id.krate == LOCAL_CRATE || self.reexported_macros.contains(&def_id) {
211 continue // These are `krate.exported_macros`, handled in `self.visit()`.
214 let imported_from = self.cx.tcx.original_crate_name(def_id.krate);
215 let def = match self.cstore.load_macro_untracked(def_id, self.cx.sess()) {
216 LoadedMacro::MacroDef(macro_def) => macro_def,
217 // FIXME(jseyfried): document proc macro reexports
218 LoadedMacro::ProcMacro(..) => continue,
221 let matchers = if let ast::ItemKind::MacroDef(ref def) = def.node {
222 let tts: Vec<_> = def.stream().into_trees().collect();
223 tts.chunks(4).map(|arm| arm[0].span()).collect()
228 om.macros.push(Macro {
230 attrs: def.attrs.clone().into(),
231 name: def.ident.name,
234 stab: self.stability(def.id),
235 depr: self.deprecation(def.id),
236 imported_from: Some(imported_from),
244 /// Tries to resolve the target of a `pub use` statement and inlines the
245 /// target if it is defined locally and would not be documented otherwise,
246 /// or when it is specifically requested with `please_inline`.
247 /// (the latter is the case when the import is marked `doc(inline)`)
249 /// Cross-crate inlining occurs later on during crate cleaning
250 /// and follows different rules.
252 /// Returns true if the target has been inlined.
253 fn maybe_inline_local(&mut self,
256 renamed: Option<ast::Name>,
259 please_inline: bool) -> bool {
261 fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
262 while let Some(id) = cx.tcx.hir.get_enclosing_scope(node) {
264 if cx.tcx.hir.attrs(node).lists("doc").has_word("hidden") {
267 if node == ast::CRATE_NODE_ID {
274 debug!("maybe_inline_local def: {:?}", def);
276 let tcx = self.cx.tcx;
280 let def_did = def.def_id();
282 let use_attrs = tcx.hir.attrs(id);
283 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
284 let is_no_inline = use_attrs.lists("doc").has_word("no_inline") ||
285 use_attrs.lists("doc").has_word("hidden");
287 // Memoize the non-inlined `pub use`'d macros so we don't push an extra
288 // declaration in `visit_mod_contents()`
289 if !def_did.is_local() {
290 if let Def::Macro(did, _) = def {
291 if please_inline { return true }
292 debug!("memoizing non-inlined macro export: {:?}", def);
293 self.reexported_macros.insert(did);
298 // For cross-crate impl inlining we need to know whether items are
299 // reachable in documentation - a previously nonreachable item can be
300 // made reachable by cross-crate inlining which we're checking here.
301 // (this is done here because we need to know this upfront)
302 if !def_did.is_local() && !is_no_inline {
303 let attrs = clean::inline::load_attrs(self.cx, def_did);
304 let self_is_hidden = attrs.lists("doc").has_word("hidden");
310 Def::TyForeign(did) |
311 Def::TyAlias(did) if !self_is_hidden => {
312 self.cx.access_levels.borrow_mut().map.insert(did, AccessLevel::Public);
314 Def::Mod(did) => if !self_is_hidden {
315 ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
323 let def_node_id = match tcx.hir.as_local_node_id(def_did) {
324 Some(n) => n, None => return false
327 let is_private = !self.cx.access_levels.borrow().is_public(def_did);
328 let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
330 // Only inline if requested or if the item would otherwise be stripped
331 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
335 if !self.view_item_stack.insert(def_node_id) { return false }
337 let ret = match tcx.hir.get(def_node_id) {
338 hir_map::NodeItem(&hir::Item { node: hir::ItemMod(ref m), .. }) if glob => {
339 let prev = mem::replace(&mut self.inlining, true);
340 for i in &m.item_ids {
341 let i = self.cx.tcx.hir.expect_item(i.id);
342 self.visit_item(i, None, om);
344 self.inlining = prev;
347 hir_map::NodeItem(it) if !glob => {
348 let prev = mem::replace(&mut self.inlining, true);
349 self.visit_item(it, renamed, om);
350 self.inlining = prev;
353 hir_map::NodeForeignItem(it) if !glob => {
354 // generate a fresh `extern {}` block if we want to inline a foreign item.
355 om.foreigns.push(hir::ForeignMod {
356 abi: tcx.hir.get_foreign_abi(it.id),
357 items: vec![hir::ForeignItem {
358 name: renamed.unwrap_or(it.name),
366 self.view_item_stack.remove(&def_node_id);
370 pub fn visit_item(&mut self, item: &hir::Item,
371 renamed: Option<ast::Name>, om: &mut Module) {
372 debug!("Visiting item {:?}", item);
373 let name = renamed.unwrap_or(item.name);
375 hir::ItemForeignMod(ref fm) => {
376 // If inlining we only want to include public functions.
377 om.foreigns.push(if self.inlining {
380 items: fm.items.iter().filter(|i| i.vis == hir::Public).cloned().collect(),
386 // If we're inlining, skip private items.
387 _ if self.inlining && item.vis != hir::Public => {}
388 hir::ItemGlobalAsm(..) => {}
389 hir::ItemExternCrate(ref p) => {
390 let def_id = self.cx.tcx.hir.local_def_id(item.id);
391 om.extern_crates.push(ExternCrate {
392 cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id)
393 .unwrap_or(LOCAL_CRATE),
395 path: p.map(|x|x.to_string()),
396 vis: item.vis.clone(),
397 attrs: item.attrs.clone(),
401 hir::ItemUse(_, hir::UseKind::ListStem) => {}
402 hir::ItemUse(ref path, kind) => {
403 let is_glob = kind == hir::UseKind::Glob;
405 // If there was a private module in the current path then don't bother inlining
406 // anything as it will probably be stripped anyway.
407 if item.vis == hir::Public && self.inside_public_path {
408 let please_inline = item.attrs.iter().any(|item| {
409 match item.meta_item_list() {
410 Some(ref list) if item.check_name("doc") => {
411 list.iter().any(|i| i.check_name("inline"))
416 let name = if is_glob { None } else { Some(name) };
417 if self.maybe_inline_local(item.id,
427 om.imports.push(Import {
430 vis: item.vis.clone(),
431 attrs: item.attrs.clone(),
432 path: (**path).clone(),
437 hir::ItemMod(ref m) => {
438 om.mods.push(self.visit_mod_contents(item.span,
445 hir::ItemEnum(ref ed, ref gen) =>
446 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
447 hir::ItemStruct(ref sd, ref gen) =>
448 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
449 hir::ItemUnion(ref sd, ref gen) =>
450 om.unions.push(self.visit_union_data(item, name, sd, gen)),
451 hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, body) =>
452 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
453 constness, abi, gen, body)),
454 hir::ItemTy(ref ty, ref gen) => {
460 attrs: item.attrs.clone(),
462 vis: item.vis.clone(),
463 stab: self.stability(item.id),
464 depr: self.deprecation(item.id),
468 hir::ItemStatic(ref ty, ref mut_, ref exp) => {
471 mutability: mut_.clone(),
475 attrs: item.attrs.clone(),
477 vis: item.vis.clone(),
478 stab: self.stability(item.id),
479 depr: self.deprecation(item.id),
483 hir::ItemConst(ref ty, ref exp) => {
489 attrs: item.attrs.clone(),
491 vis: item.vis.clone(),
492 stab: self.stability(item.id),
493 depr: self.deprecation(item.id),
495 om.constants.push(s);
497 hir::ItemTrait(_, unsafety, ref gen, ref b, ref item_ids) => {
498 let items = item_ids.iter()
499 .map(|ti| self.cx.tcx.hir.trait_item(ti.id).clone())
505 generics: gen.clone(),
506 bounds: b.iter().cloned().collect(),
508 attrs: item.attrs.clone(),
510 vis: item.vis.clone(),
511 stab: self.stability(item.id),
512 depr: self.deprecation(item.id),
516 hir::ItemTraitAlias(..) => {
517 unimplemented!("trait objects are not yet implemented")
520 hir::ItemImpl(unsafety,
527 // Don't duplicate impls when inlining, we'll pick them up
528 // regardless of where they're located.
530 let items = item_ids.iter()
531 .map(|ii| self.cx.tcx.hir.impl_item(ii.id).clone())
537 generics: gen.clone(),
541 attrs: item.attrs.clone(),
544 vis: item.vis.clone(),
545 stab: self.stability(item.id),
546 depr: self.deprecation(item.id),
551 hir::ItemAutoImpl(unsafety, ref trait_ref) => {
552 // See comment above about ItemImpl.
556 trait_: trait_ref.clone(),
558 attrs: item.attrs.clone(),
561 om.def_traits.push(i);
567 // convert each exported_macro into a doc item
568 fn visit_local_macro(&self, def: &hir::MacroDef) -> Macro {
569 let tts = def.body.trees().collect::<Vec<_>>();
570 // Extract the spans of all matchers. They represent the "interface" of the macro.
571 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
574 def_id: self.cx.tcx.hir.local_def_id(def.id),
575 attrs: def.attrs.clone(),
579 stab: self.stability(def.id),
580 depr: self.deprecation(def.id),