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, Clean, Attributes};
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_opt().and_then(|tcx| {
69 self.cx.map.opt_local_def_id(id)
70 .and_then(|def_id| tcx.lookup_stability(def_id))
75 fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
76 self.cx.tcx_opt().and_then(|tcx| {
77 self.cx.map.opt_local_def_id(id)
78 .and_then(|def_id| tcx.lookup_deprecation(def_id))
82 pub fn visit(&mut self, krate: &hir::Crate) {
83 self.attrs = krate.attrs.clone();
85 self.module = self.visit_mod_contents(krate.span,
91 // attach the crate's exported macros to the top-level module:
92 let macro_exports: Vec<_> =
93 krate.exported_macros.iter().map(|def| self.visit_macro(def)).collect();
94 self.module.macros.extend(macro_exports);
95 self.module.is_crate = true;
98 pub fn visit_variant_data(&mut self, item: &hir::Item,
99 name: ast::Name, sd: &hir::VariantData,
100 generics: &hir::Generics) -> Struct {
101 debug!("Visiting struct");
102 let struct_type = struct_type_from_def(&*sd);
105 struct_type: struct_type,
107 vis: item.vis.clone(),
108 stab: self.stability(item.id),
109 depr: self.deprecation(item.id),
110 attrs: item.attrs.clone(),
111 generics: generics.clone(),
112 fields: sd.fields().iter().cloned().collect(),
117 pub fn visit_union_data(&mut self, item: &hir::Item,
118 name: ast::Name, sd: &hir::VariantData,
119 generics: &hir::Generics) -> Union {
120 debug!("Visiting union");
121 let struct_type = struct_type_from_def(&*sd);
124 struct_type: struct_type,
126 vis: item.vis.clone(),
127 stab: self.stability(item.id),
128 depr: self.deprecation(item.id),
129 attrs: item.attrs.clone(),
130 generics: generics.clone(),
131 fields: sd.fields().iter().cloned().collect(),
136 pub fn visit_enum_def(&mut self, it: &hir::Item,
137 name: ast::Name, def: &hir::EnumDef,
138 params: &hir::Generics) -> Enum {
139 debug!("Visiting enum");
142 variants: def.variants.iter().map(|v| Variant {
144 attrs: v.node.attrs.clone(),
145 stab: self.stability(v.node.data.id()),
146 depr: self.deprecation(v.node.data.id()),
147 def: v.node.data.clone(),
151 stab: self.stability(it.id),
152 depr: self.deprecation(it.id),
153 generics: params.clone(),
154 attrs: it.attrs.clone(),
160 pub fn visit_fn(&mut self, item: &hir::Item,
161 name: ast::Name, fd: &hir::FnDecl,
162 unsafety: &hir::Unsafety,
163 constness: hir::Constness,
165 gen: &hir::Generics) -> Function {
166 debug!("Visiting fn");
169 vis: item.vis.clone(),
170 stab: self.stability(item.id),
171 depr: self.deprecation(item.id),
172 attrs: item.attrs.clone(),
176 generics: gen.clone(),
178 constness: constness,
183 pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
184 vis: hir::Visibility, id: ast::NodeId,
186 name: Option<ast::Name>) -> Module {
187 let mut om = Module::new(name);
188 om.where_outer = span;
189 om.where_inner = m.inner;
191 om.vis = vis.clone();
192 om.stab = self.stability(id);
193 om.depr = self.deprecation(id);
195 // Keep track of if there were any private modules in the path.
196 let orig_inside_public_path = self.inside_public_path;
197 self.inside_public_path &= vis == hir::Public;
198 for i in &m.item_ids {
199 let item = self.cx.map.expect_item(i.id);
200 self.visit_item(item, None, &mut om);
202 self.inside_public_path = orig_inside_public_path;
203 if let Some(exports) = self.cx.export_map.get(&id) {
204 for export in exports {
205 if let Def::Macro(def_id) = export.def {
206 if def_id.krate == LOCAL_CRATE {
207 continue // These are `krate.exported_macros`, handled in `self.visit()`.
209 let def = match self.cx.sess().cstore.load_macro(def_id, self.cx.sess()) {
210 LoadedMacro::MacroRules(macro_rules) => macro_rules,
211 // FIXME(jseyfried): document proc macro reexports
212 LoadedMacro::ProcMacro(..) => continue,
215 // FIXME(jseyfried) merge with `self.visit_macro()`
216 let matchers = def.body.chunks(4).map(|arm| arm[0].get_span()).collect();
217 om.macros.push(Macro {
219 attrs: def.attrs.clone().into(),
220 name: def.ident.name,
223 stab: self.stability(def.id),
224 depr: self.deprecation(def.id),
225 imported_from: def.imported_from.map(|ident| ident.name),
233 fn visit_view_path(&mut self, path: hir::ViewPath_,
236 please_inline: bool) -> Option<hir::ViewPath_> {
238 hir::ViewPathSimple(dst, base) => {
239 if self.maybe_inline_local(id, Some(dst), false, om, please_inline) {
242 Some(hir::ViewPathSimple(dst, base))
245 hir::ViewPathList(p, paths) => {
246 let mine = paths.into_iter().filter(|path| {
247 !self.maybe_inline_local(path.node.id, path.node.rename,
248 false, om, please_inline)
249 }).collect::<hir::HirVec<hir::PathListItem>>();
254 Some(hir::ViewPathList(p, mine))
258 hir::ViewPathGlob(base) => {
259 if self.maybe_inline_local(id, None, true, om, please_inline) {
262 Some(hir::ViewPathGlob(base))
269 /// Tries to resolve the target of a `pub use` statement and inlines the
270 /// target if it is defined locally and would not be documented otherwise,
271 /// or when it is specifically requested with `please_inline`.
272 /// (the latter is the case when the import is marked `doc(inline)`)
274 /// Cross-crate inlining occurs later on during crate cleaning
275 /// and follows different rules.
277 /// Returns true if the target has been inlined.
278 fn maybe_inline_local(&mut self, id: ast::NodeId, renamed: Option<ast::Name>,
279 glob: bool, om: &mut Module, please_inline: bool) -> bool {
281 fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
282 while let Some(id) = cx.map.get_enclosing_scope(node) {
284 let attrs = cx.map.attrs(node).clean(cx);
285 if attrs.list("doc").has_word("hidden") {
288 if node == ast::CRATE_NODE_ID {
295 let tcx = match self.cx.tcx_opt() {
299 let def = tcx.expect_def(id);
300 let def_did = def.def_id();
302 let use_attrs = tcx.map.attrs(id).clean(self.cx);
303 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
304 let is_no_inline = use_attrs.list("doc").has_word("no_inline") ||
305 use_attrs.list("doc").has_word("hidden");
307 // For cross-crate impl inlining we need to know whether items are
308 // reachable in documentation - a previously nonreachable item can be
309 // made reachable by cross-crate inlining which we're checking here.
310 // (this is done here because we need to know this upfront)
311 if !def_did.is_local() && !is_no_inline {
312 let attrs = clean::inline::load_attrs(self.cx, tcx, def_did);
313 let self_is_hidden = attrs.list("doc").has_word("hidden");
319 Def::TyAlias(did) if !self_is_hidden => {
320 self.cx.access_levels.borrow_mut().map.insert(did, AccessLevel::Public);
322 Def::Mod(did) => if !self_is_hidden {
323 ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
330 let def_node_id = match tcx.map.as_local_node_id(def_did) {
331 Some(n) => n, None => return false
334 let is_private = !self.cx.access_levels.borrow().is_public(def_did);
335 let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
337 // Only inline if requested or if the item would otherwise be stripped
338 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
342 if !self.view_item_stack.insert(def_node_id) { return false }
344 let ret = match tcx.map.get(def_node_id) {
345 hir_map::NodeItem(it) => {
346 let prev = mem::replace(&mut self.inlining, true);
349 hir::ItemMod(ref m) => {
350 for i in &m.item_ids {
351 let i = self.cx.map.expect_item(i.id);
352 self.visit_item(i, None, om);
355 hir::ItemEnum(..) => {}
356 _ => { panic!("glob not mapped to a module or enum"); }
359 self.visit_item(it, renamed, om);
361 self.inlining = prev;
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::ItemExternCrate(ref p) => {
389 let cstore = &self.cx.sess().cstore;
390 om.extern_crates.push(ExternCrate {
391 cnum: cstore.extern_mod_stmt_cnum(item.id)
392 .unwrap_or(LOCAL_CRATE),
394 path: p.map(|x|x.to_string()),
395 vis: item.vis.clone(),
396 attrs: item.attrs.clone(),
400 hir::ItemUse(ref vpath) => {
401 let node = vpath.node.clone();
402 // If there was a private module in the current path then don't bother inlining
403 // anything as it will probably be stripped anyway.
404 let node = if item.vis == hir::Public && self.inside_public_path {
405 let please_inline = item.attrs.iter().any(|item| {
406 match item.meta_item_list() {
407 Some(list) if item.check_name("doc") => {
408 list.iter().any(|i| i.check_name("inline"))
413 match self.visit_view_path(node, om, item.id, please_inline) {
420 om.imports.push(Import {
422 vis: item.vis.clone(),
423 attrs: item.attrs.clone(),
428 hir::ItemMod(ref m) => {
429 om.mods.push(self.visit_mod_contents(item.span,
436 hir::ItemEnum(ref ed, ref gen) =>
437 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
438 hir::ItemStruct(ref sd, ref gen) =>
439 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
440 hir::ItemUnion(ref sd, ref gen) =>
441 om.unions.push(self.visit_union_data(item, name, sd, gen)),
442 hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, _) =>
443 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
444 constness, abi, gen)),
445 hir::ItemTy(ref ty, ref gen) => {
451 attrs: item.attrs.clone(),
453 vis: item.vis.clone(),
454 stab: self.stability(item.id),
455 depr: self.deprecation(item.id),
459 hir::ItemStatic(ref ty, ref mut_, ref exp) => {
462 mutability: mut_.clone(),
466 attrs: item.attrs.clone(),
468 vis: item.vis.clone(),
469 stab: self.stability(item.id),
470 depr: self.deprecation(item.id),
474 hir::ItemConst(ref ty, ref exp) => {
480 attrs: item.attrs.clone(),
482 vis: item.vis.clone(),
483 stab: self.stability(item.id),
484 depr: self.deprecation(item.id),
486 om.constants.push(s);
488 hir::ItemTrait(unsafety, ref gen, ref b, ref items) => {
492 items: items.clone(),
493 generics: gen.clone(),
494 bounds: b.iter().cloned().collect(),
496 attrs: item.attrs.clone(),
498 vis: item.vis.clone(),
499 stab: self.stability(item.id),
500 depr: self.deprecation(item.id),
505 hir::ItemImpl(unsafety, polarity, ref gen, ref tr, ref ty, ref items) => {
506 // Don't duplicate impls when inlining, we'll pick them up
507 // regardless of where they're located.
512 generics: gen.clone(),
515 items: items.clone(),
516 attrs: item.attrs.clone(),
519 vis: item.vis.clone(),
520 stab: self.stability(item.id),
521 depr: self.deprecation(item.id),
526 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
527 // See comment above about ItemImpl.
529 let i = DefaultImpl {
531 trait_: trait_ref.clone(),
533 attrs: item.attrs.clone(),
536 om.def_traits.push(i);
542 // convert each exported_macro into a doc item
543 fn visit_macro(&self, def: &hir::MacroDef) -> Macro {
544 // Extract the spans of all matchers. They represent the "interface" of the macro.
545 let matchers = def.body.chunks(4).map(|arm| arm[0].get_span()).collect();
549 attrs: def.attrs.clone(),
553 stab: self.stability(def.id),
554 depr: self.deprecation(def.id),
555 imported_from: def.imported_from,