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
14 use std::collections::HashSet;
20 use syntax::attr::AttrMetaMethods;
23 use rustc::hir::map as hir_map;
24 use rustc::hir::def::Def;
25 use rustc::middle::privacy::AccessLevel;
30 use clean::{self, Clean, Attributes};
33 // looks to me like the first two of these are actually
34 // output parameters, maybe only mutated once; perhaps
35 // better simply to have the visit method return a tuple
38 // also, is there some reason that this doesn't use the 'visit'
39 // framework from syntax?
41 pub struct RustdocVisitor<'a, 'tcx: 'a> {
43 pub attrs: hir::HirVec<ast::Attribute>,
44 pub cx: &'a core::DocContext<'a, 'tcx>,
45 view_item_stack: HashSet<ast::NodeId>,
46 inlining_from_glob: bool,
49 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
50 pub fn new(cx: &'a core::DocContext<'a, 'tcx>) -> RustdocVisitor<'a, 'tcx> {
51 // If the root is reexported, terminate all recursion.
52 let mut stack = HashSet::new();
53 stack.insert(ast::CRATE_NODE_ID);
55 module: Module::new(None),
56 attrs: hir::HirVec::new(),
58 view_item_stack: stack,
59 inlining_from_glob: false,
63 fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
64 self.cx.tcx_opt().and_then(|tcx| {
65 self.cx.map.opt_local_def_id(id)
66 .and_then(|def_id| tcx.lookup_stability(def_id))
71 fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
72 self.cx.tcx_opt().and_then(|tcx| {
73 self.cx.map.opt_local_def_id(id)
74 .and_then(|def_id| tcx.lookup_deprecation(def_id))
78 pub fn visit(&mut self, krate: &hir::Crate) {
79 self.attrs = krate.attrs.clone();
81 self.module = self.visit_mod_contents(krate.span,
87 // attach the crate's exported macros to the top-level module:
88 self.module.macros = krate.exported_macros.iter()
89 .map(|def| self.visit_macro(def)).collect();
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_enum_def(&mut self, it: &hir::Item,
113 name: ast::Name, def: &hir::EnumDef,
114 params: &hir::Generics) -> Enum {
115 debug!("Visiting enum");
118 variants: def.variants.iter().map(|v| Variant {
120 attrs: v.node.attrs.clone(),
121 stab: self.stability(v.node.data.id()),
122 depr: self.deprecation(v.node.data.id()),
123 def: v.node.data.clone(),
127 stab: self.stability(it.id),
128 depr: self.deprecation(it.id),
129 generics: params.clone(),
130 attrs: it.attrs.clone(),
136 pub fn visit_fn(&mut self, item: &hir::Item,
137 name: ast::Name, fd: &hir::FnDecl,
138 unsafety: &hir::Unsafety,
139 constness: hir::Constness,
141 gen: &hir::Generics) -> Function {
142 debug!("Visiting fn");
145 vis: item.vis.clone(),
146 stab: self.stability(item.id),
147 depr: self.deprecation(item.id),
148 attrs: item.attrs.clone(),
152 generics: gen.clone(),
154 constness: constness,
159 pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
160 vis: hir::Visibility, id: ast::NodeId,
162 name: Option<ast::Name>) -> Module {
163 let mut om = Module::new(name);
164 om.where_outer = span;
165 om.where_inner = m.inner;
167 om.vis = vis.clone();
168 om.stab = self.stability(id);
169 om.depr = self.deprecation(id);
171 for i in &m.item_ids {
172 let item = self.cx.map.expect_item(i.id);
173 self.visit_item(item, None, &mut om);
178 fn visit_view_path(&mut self, path: hir::ViewPath_,
181 please_inline: bool) -> Option<hir::ViewPath_> {
183 hir::ViewPathSimple(dst, base) => {
184 if self.maybe_inline_local(id, Some(dst), false, om, please_inline) {
187 Some(hir::ViewPathSimple(dst, base))
190 hir::ViewPathList(p, paths) => {
191 let mine = paths.into_iter().filter(|path| {
192 !self.maybe_inline_local(path.node.id(), path.node.rename(),
193 false, om, please_inline)
194 }).collect::<hir::HirVec<hir::PathListItem>>();
199 Some(hir::ViewPathList(p, mine))
203 hir::ViewPathGlob(base) => {
204 if self.maybe_inline_local(id, None, true, om, please_inline) {
207 Some(hir::ViewPathGlob(base))
214 /// Tries to resolve the target of a `pub use` statement and inlines the
215 /// target if it is defined locally and would not be documented otherwise,
216 /// or when it is specifically requested with `please_inline`.
217 /// (the latter is the case when the import is marked `doc(inline)`)
219 /// Cross-crate inlining occurs later on during crate cleaning
220 /// and follows different rules.
222 /// Returns true if the target has been inlined.
223 fn maybe_inline_local(&mut self, id: ast::NodeId, renamed: Option<ast::Name>,
224 glob: bool, om: &mut Module, please_inline: bool) -> bool {
226 fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
227 while let Some(id) = cx.map.get_enclosing_scope(node) {
229 let attrs = cx.map.attrs(node).clean(cx);
230 if attrs.list("doc").has_word("hidden") {
233 if node == ast::CRATE_NODE_ID {
240 let tcx = match self.cx.tcx_opt() {
244 let def = tcx.expect_def(id);
245 let def_did = def.def_id();
247 let use_attrs = tcx.map.attrs(id).clean(self.cx);
248 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
249 let is_no_inline = use_attrs.list("doc").has_word("no_inline") ||
250 use_attrs.list("doc").has_word("hidden");
252 // For cross-crate impl inlining we need to know whether items are
253 // reachable in documentation - a previously nonreachable item can be
254 // made reachable by cross-crate inlining which we're checking here.
255 // (this is done here because we need to know this upfront)
256 if !def_did.is_local() && !is_no_inline {
257 let attrs = clean::inline::load_attrs(self.cx, tcx, def_did);
258 let self_is_hidden = attrs.list("doc").has_word("hidden");
263 Def::TyAlias(did) if !self_is_hidden => {
264 self.cx.access_levels.borrow_mut().map.insert(did, AccessLevel::Public);
266 Def::Mod(did) => if !self_is_hidden {
267 ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
274 let def_node_id = match tcx.map.as_local_node_id(def_did) {
275 Some(n) => n, None => return false
278 let is_private = !self.cx.access_levels.borrow().is_public(def_did);
279 let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
281 // Only inline if requested or if the item would otherwise be stripped
282 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
286 if !self.view_item_stack.insert(def_node_id) { return false }
288 let ret = match tcx.map.get(def_node_id) {
289 hir_map::NodeItem(it) => {
291 let prev = mem::replace(&mut self.inlining_from_glob, true);
293 hir::ItemMod(ref m) => {
294 for i in &m.item_ids {
295 let i = self.cx.map.expect_item(i.id);
296 self.visit_item(i, None, om);
299 hir::ItemEnum(..) => {}
300 _ => { panic!("glob not mapped to a module or enum"); }
302 self.inlining_from_glob = prev;
304 self.visit_item(it, renamed, om);
310 self.view_item_stack.remove(&def_node_id);
314 pub fn visit_item(&mut self, item: &hir::Item,
315 renamed: Option<ast::Name>, om: &mut Module) {
316 debug!("Visiting item {:?}", item);
317 let name = renamed.unwrap_or(item.name);
319 hir::ItemExternCrate(ref p) => {
320 let cstore = &self.cx.sess().cstore;
321 om.extern_crates.push(ExternCrate {
322 cnum: cstore.extern_mod_stmt_cnum(item.id)
323 .unwrap_or(ast::CrateNum::max_value()),
325 path: p.map(|x|x.to_string()),
326 vis: item.vis.clone(),
327 attrs: item.attrs.clone(),
331 hir::ItemUse(ref vpath) => {
332 let node = vpath.node.clone();
333 let node = if item.vis == hir::Public {
334 let please_inline = item.attrs.iter().any(|item| {
335 match item.meta_item_list() {
336 Some(list) if &item.name()[..] == "doc" => {
337 list.iter().any(|i| &i.name()[..] == "inline")
342 match self.visit_view_path(node, om, item.id, please_inline) {
349 om.imports.push(Import {
351 vis: item.vis.clone(),
352 attrs: item.attrs.clone(),
357 hir::ItemMod(ref m) => {
358 om.mods.push(self.visit_mod_contents(item.span,
365 hir::ItemEnum(ref ed, ref gen) =>
366 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
367 hir::ItemStruct(ref sd, ref gen) =>
368 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
369 hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, _) =>
370 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
371 constness, abi, gen)),
372 hir::ItemTy(ref ty, ref gen) => {
378 attrs: item.attrs.clone(),
380 vis: item.vis.clone(),
381 stab: self.stability(item.id),
382 depr: self.deprecation(item.id),
386 hir::ItemStatic(ref ty, ref mut_, ref exp) => {
389 mutability: mut_.clone(),
393 attrs: item.attrs.clone(),
395 vis: item.vis.clone(),
396 stab: self.stability(item.id),
397 depr: self.deprecation(item.id),
401 hir::ItemConst(ref ty, ref exp) => {
407 attrs: item.attrs.clone(),
409 vis: item.vis.clone(),
410 stab: self.stability(item.id),
411 depr: self.deprecation(item.id),
413 om.constants.push(s);
415 hir::ItemTrait(unsafety, ref gen, ref b, ref items) => {
419 items: items.clone(),
420 generics: gen.clone(),
421 bounds: b.iter().cloned().collect(),
423 attrs: item.attrs.clone(),
425 vis: item.vis.clone(),
426 stab: self.stability(item.id),
427 depr: self.deprecation(item.id),
431 hir::ItemImpl(unsafety, polarity, ref gen, ref tr, ref ty, ref items) => {
435 generics: gen.clone(),
438 items: items.clone(),
439 attrs: item.attrs.clone(),
442 vis: item.vis.clone(),
443 stab: self.stability(item.id),
444 depr: self.deprecation(item.id),
446 // Don't duplicate impls when inlining glob imports, we'll pick
447 // them up regardless of where they're located.
448 if !self.inlining_from_glob {
452 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
453 let i = DefaultImpl {
455 trait_: trait_ref.clone(),
457 attrs: item.attrs.clone(),
460 // see comment above about ItemImpl
461 if !self.inlining_from_glob {
462 om.def_traits.push(i);
465 hir::ItemForeignMod(ref fm) => {
466 om.foreigns.push(fm.clone());
471 // convert each exported_macro into a doc item
472 fn visit_macro(&self, def: &hir::MacroDef) -> Macro {
473 // Extract the spans of all matchers. They represent the "interface" of the macro.
474 let matchers = def.body.chunks(4).map(|arm| arm[0].get_span()).collect();
478 attrs: def.attrs.clone(),
482 stab: self.stability(def.id),
483 depr: self.deprecation(def.id),
484 imported_from: def.imported_from,