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::LOCAL_CRATE;
24 use rustc::middle::cstore::LoadedMacro;
25 use rustc::middle::privacy::AccessLevel;
26 use rustc::util::nodemap::FxHashSet;
31 use clean::{self, AttributesExt, NestedAttributesExt};
34 // looks to me like the first two of these are actually
35 // output parameters, maybe only mutated once; perhaps
36 // better simply to have the visit method return a tuple
39 // also, is there some reason that this doesn't use the 'visit'
40 // framework from syntax?
42 pub struct RustdocVisitor<'a, 'tcx: 'a> {
44 pub attrs: hir::HirVec<ast::Attribute>,
45 pub cx: &'a core::DocContext<'a, 'tcx>,
46 view_item_stack: FxHashSet<ast::NodeId>,
48 /// Is the current module and all of its parents public?
49 inside_public_path: bool,
52 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
53 pub fn new(cx: &'a core::DocContext<'a, 'tcx>) -> RustdocVisitor<'a, 'tcx> {
54 // If the root is reexported, terminate all recursion.
55 let mut stack = FxHashSet();
56 stack.insert(ast::CRATE_NODE_ID);
58 module: Module::new(None),
59 attrs: hir::HirVec::new(),
61 view_item_stack: stack,
63 inside_public_path: true,
67 fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
68 self.cx.tcx.map.opt_local_def_id(id)
69 .and_then(|def_id| self.cx.tcx.lookup_stability(def_id)).cloned()
72 fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
73 self.cx.tcx.map.opt_local_def_id(id)
74 .and_then(|def_id| self.cx.tcx.lookup_deprecation(def_id))
77 pub fn visit(&mut self, krate: &hir::Crate) {
78 self.attrs = krate.attrs.clone();
80 self.module = self.visit_mod_contents(krate.span,
86 // attach the crate's exported macros to the top-level module:
87 let macro_exports: Vec<_> =
88 krate.exported_macros.iter().map(|def| self.visit_macro(def)).collect();
89 self.module.macros.extend(macro_exports);
90 self.module.is_crate = true;
93 pub fn visit_variant_data(&mut self, item: &hir::Item,
94 name: ast::Name, sd: &hir::VariantData,
95 generics: &hir::Generics) -> Struct {
96 debug!("Visiting struct");
97 let struct_type = struct_type_from_def(&*sd);
100 struct_type: struct_type,
102 vis: item.vis.clone(),
103 stab: self.stability(item.id),
104 depr: self.deprecation(item.id),
105 attrs: item.attrs.clone(),
106 generics: generics.clone(),
107 fields: sd.fields().iter().cloned().collect(),
112 pub fn visit_union_data(&mut self, item: &hir::Item,
113 name: ast::Name, sd: &hir::VariantData,
114 generics: &hir::Generics) -> Union {
115 debug!("Visiting union");
116 let struct_type = struct_type_from_def(&*sd);
119 struct_type: struct_type,
121 vis: item.vis.clone(),
122 stab: self.stability(item.id),
123 depr: self.deprecation(item.id),
124 attrs: item.attrs.clone(),
125 generics: generics.clone(),
126 fields: sd.fields().iter().cloned().collect(),
131 pub fn visit_enum_def(&mut self, it: &hir::Item,
132 name: ast::Name, def: &hir::EnumDef,
133 params: &hir::Generics) -> Enum {
134 debug!("Visiting enum");
137 variants: def.variants.iter().map(|v| Variant {
139 attrs: v.node.attrs.clone(),
140 stab: self.stability(v.node.data.id()),
141 depr: self.deprecation(v.node.data.id()),
142 def: v.node.data.clone(),
146 stab: self.stability(it.id),
147 depr: self.deprecation(it.id),
148 generics: params.clone(),
149 attrs: it.attrs.clone(),
155 pub fn visit_fn(&mut self, item: &hir::Item,
156 name: ast::Name, fd: &hir::FnDecl,
157 unsafety: &hir::Unsafety,
158 constness: hir::Constness,
160 gen: &hir::Generics) -> Function {
161 debug!("Visiting fn");
164 vis: item.vis.clone(),
165 stab: self.stability(item.id),
166 depr: self.deprecation(item.id),
167 attrs: item.attrs.clone(),
171 generics: gen.clone(),
173 constness: constness,
178 pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
179 vis: hir::Visibility, id: ast::NodeId,
181 name: Option<ast::Name>) -> Module {
182 let mut om = Module::new(name);
183 om.where_outer = span;
184 om.where_inner = m.inner;
186 om.vis = vis.clone();
187 om.stab = self.stability(id);
188 om.depr = self.deprecation(id);
190 // Keep track of if there were any private modules in the path.
191 let orig_inside_public_path = self.inside_public_path;
192 self.inside_public_path &= vis == hir::Public;
193 for i in &m.item_ids {
194 let item = self.cx.tcx.map.expect_item(i.id);
195 self.visit_item(item, None, &mut om);
197 self.inside_public_path = orig_inside_public_path;
198 if let Some(exports) = self.cx.export_map.get(&id) {
199 for export in exports {
200 if let Def::Macro(def_id) = export.def {
201 if def_id.krate == LOCAL_CRATE {
202 continue // These are `krate.exported_macros`, handled in `self.visit()`.
204 let def = match self.cx.sess().cstore.load_macro(def_id, self.cx.sess()) {
205 LoadedMacro::MacroRules(macro_rules) => macro_rules,
206 // FIXME(jseyfried): document proc macro reexports
207 LoadedMacro::ProcMacro(..) => continue,
210 // FIXME(jseyfried) merge with `self.visit_macro()`
211 let matchers = def.body.chunks(4).map(|arm| arm[0].get_span()).collect();
212 om.macros.push(Macro {
214 attrs: def.attrs.clone().into(),
215 name: def.ident.name,
218 stab: self.stability(def.id),
219 depr: self.deprecation(def.id),
220 imported_from: def.imported_from.map(|ident| ident.name),
228 /// Tries to resolve the target of a `pub use` statement and inlines the
229 /// target if it is defined locally and would not be documented otherwise,
230 /// or when it is specifically requested with `please_inline`.
231 /// (the latter is the case when the import is marked `doc(inline)`)
233 /// Cross-crate inlining occurs later on during crate cleaning
234 /// and follows different rules.
236 /// Returns true if the target has been inlined.
237 fn maybe_inline_local(&mut self, id: ast::NodeId, renamed: Option<ast::Name>,
238 glob: bool, om: &mut Module, please_inline: bool) -> bool {
240 fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
241 while let Some(id) = cx.tcx.map.get_enclosing_scope(node) {
243 if cx.tcx.map.attrs(node).lists("doc").has_word("hidden") {
246 if node == ast::CRATE_NODE_ID {
253 let tcx = self.cx.tcx;
254 let def = tcx.expect_def(id);
255 let def_did = def.def_id();
257 let use_attrs = tcx.map.attrs(id);
258 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
259 let is_no_inline = use_attrs.lists("doc").has_word("no_inline") ||
260 use_attrs.lists("doc").has_word("hidden");
262 // For cross-crate impl inlining we need to know whether items are
263 // reachable in documentation - a previously nonreachable item can be
264 // made reachable by cross-crate inlining which we're checking here.
265 // (this is done here because we need to know this upfront)
266 if !def_did.is_local() && !is_no_inline {
267 let attrs = clean::inline::load_attrs(self.cx, def_did);
268 let self_is_hidden = attrs.lists("doc").has_word("hidden");
274 Def::TyAlias(did) if !self_is_hidden => {
275 self.cx.access_levels.borrow_mut().map.insert(did, AccessLevel::Public);
277 Def::Mod(did) => if !self_is_hidden {
278 ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
285 let def_node_id = match tcx.map.as_local_node_id(def_did) {
286 Some(n) => n, None => return false
289 let is_private = !self.cx.access_levels.borrow().is_public(def_did);
290 let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
292 // Only inline if requested or if the item would otherwise be stripped
293 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
297 if !self.view_item_stack.insert(def_node_id) { return false }
299 let ret = match tcx.map.get(def_node_id) {
300 hir_map::NodeItem(it) => {
301 let prev = mem::replace(&mut self.inlining, true);
304 hir::ItemMod(ref m) => {
305 for i in &m.item_ids {
306 let i = self.cx.tcx.map.expect_item(i.id);
307 self.visit_item(i, None, om);
310 hir::ItemEnum(..) => {}
311 _ => { panic!("glob not mapped to a module or enum"); }
314 self.visit_item(it, renamed, om);
316 self.inlining = prev;
321 self.view_item_stack.remove(&def_node_id);
325 pub fn visit_item(&mut self, item: &hir::Item,
326 renamed: Option<ast::Name>, om: &mut Module) {
327 debug!("Visiting item {:?}", item);
328 let name = renamed.unwrap_or(item.name);
330 hir::ItemForeignMod(ref fm) => {
331 // If inlining we only want to include public functions.
332 om.foreigns.push(if self.inlining {
335 items: fm.items.iter().filter(|i| i.vis == hir::Public).cloned().collect(),
341 // If we're inlining, skip private items.
342 _ if self.inlining && item.vis != hir::Public => {}
343 hir::ItemExternCrate(ref p) => {
344 let cstore = &self.cx.sess().cstore;
345 om.extern_crates.push(ExternCrate {
346 cnum: cstore.extern_mod_stmt_cnum(item.id)
347 .unwrap_or(LOCAL_CRATE),
349 path: p.map(|x|x.to_string()),
350 vis: item.vis.clone(),
351 attrs: item.attrs.clone(),
355 hir::ItemUse(_, hir::UseKind::ListStem) => {}
356 hir::ItemUse(ref path, kind) => {
357 let is_glob = kind == hir::UseKind::Glob;
359 // If there was a private module in the current path then don't bother inlining
360 // anything as it will probably be stripped anyway.
361 if item.vis == hir::Public && self.inside_public_path {
362 let please_inline = item.attrs.iter().any(|item| {
363 match item.meta_item_list() {
364 Some(list) if item.check_name("doc") => {
365 list.iter().any(|i| i.check_name("inline"))
370 let name = if is_glob { None } else { Some(name) };
371 if self.maybe_inline_local(item.id, name, is_glob, om, please_inline) {
376 om.imports.push(Import {
379 vis: item.vis.clone(),
380 attrs: item.attrs.clone(),
381 path: (**path).clone(),
386 hir::ItemMod(ref m) => {
387 om.mods.push(self.visit_mod_contents(item.span,
394 hir::ItemEnum(ref ed, ref gen) =>
395 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
396 hir::ItemStruct(ref sd, ref gen) =>
397 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
398 hir::ItemUnion(ref sd, ref gen) =>
399 om.unions.push(self.visit_union_data(item, name, sd, gen)),
400 hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, _) =>
401 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
402 constness, abi, gen)),
403 hir::ItemTy(ref ty, ref gen) => {
409 attrs: item.attrs.clone(),
411 vis: item.vis.clone(),
412 stab: self.stability(item.id),
413 depr: self.deprecation(item.id),
417 hir::ItemStatic(ref ty, ref mut_, ref exp) => {
420 mutability: mut_.clone(),
424 attrs: item.attrs.clone(),
426 vis: item.vis.clone(),
427 stab: self.stability(item.id),
428 depr: self.deprecation(item.id),
432 hir::ItemConst(ref ty, ref exp) => {
438 attrs: item.attrs.clone(),
440 vis: item.vis.clone(),
441 stab: self.stability(item.id),
442 depr: self.deprecation(item.id),
444 om.constants.push(s);
446 hir::ItemTrait(unsafety, ref gen, ref b, ref items) => {
450 items: items.clone(),
451 generics: gen.clone(),
452 bounds: b.iter().cloned().collect(),
454 attrs: item.attrs.clone(),
456 vis: item.vis.clone(),
457 stab: self.stability(item.id),
458 depr: self.deprecation(item.id),
463 hir::ItemImpl(unsafety, polarity, ref gen, ref tr, ref ty, ref item_ids) => {
464 // Don't duplicate impls when inlining, we'll pick them up
465 // regardless of where they're located.
467 let items = item_ids.iter()
468 .map(|ii| self.cx.tcx.map.impl_item(ii.id).clone())
473 generics: gen.clone(),
477 attrs: item.attrs.clone(),
480 vis: item.vis.clone(),
481 stab: self.stability(item.id),
482 depr: self.deprecation(item.id),
487 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
488 // See comment above about ItemImpl.
490 let i = DefaultImpl {
492 trait_: trait_ref.clone(),
494 attrs: item.attrs.clone(),
497 om.def_traits.push(i);
503 // convert each exported_macro into a doc item
504 fn visit_macro(&self, def: &hir::MacroDef) -> Macro {
505 // Extract the spans of all matchers. They represent the "interface" of the macro.
506 let matchers = def.body.chunks(4).map(|arm| arm[0].get_span()).collect();
510 attrs: def.attrs.clone(),
514 stab: self.stability(def.id),
515 depr: self.deprecation(def.id),
516 imported_from: def.imported_from,