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>,
47 inlining_from_glob: bool,
50 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
51 pub fn new(cx: &'a core::DocContext<'a, 'tcx>) -> RustdocVisitor<'a, 'tcx> {
52 // If the root is reexported, terminate all recursion.
53 let mut stack = FxHashSet();
54 stack.insert(ast::CRATE_NODE_ID);
56 module: Module::new(None),
57 attrs: hir::HirVec::new(),
59 view_item_stack: stack,
60 inlining_from_glob: false,
64 fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
65 self.cx.tcx_opt().and_then(|tcx| {
66 self.cx.map.opt_local_def_id(id)
67 .and_then(|def_id| tcx.lookup_stability(def_id))
72 fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
73 self.cx.tcx_opt().and_then(|tcx| {
74 self.cx.map.opt_local_def_id(id)
75 .and_then(|def_id| tcx.lookup_deprecation(def_id))
79 pub fn visit(&mut self, krate: &hir::Crate) {
80 self.attrs = krate.attrs.clone();
82 self.module = self.visit_mod_contents(krate.span,
88 // attach the crate's exported macros to the top-level module:
89 let macro_exports: Vec<_> =
90 krate.exported_macros.iter().map(|def| self.visit_macro(def)).collect();
91 self.module.macros.extend(macro_exports);
92 self.module.is_crate = true;
95 pub fn visit_variant_data(&mut self, item: &hir::Item,
96 name: ast::Name, sd: &hir::VariantData,
97 generics: &hir::Generics) -> Struct {
98 debug!("Visiting struct");
99 let struct_type = struct_type_from_def(&*sd);
102 struct_type: struct_type,
104 vis: item.vis.clone(),
105 stab: self.stability(item.id),
106 depr: self.deprecation(item.id),
107 attrs: item.attrs.clone(),
108 generics: generics.clone(),
109 fields: sd.fields().iter().cloned().collect(),
114 pub fn visit_union_data(&mut self, item: &hir::Item,
115 name: ast::Name, sd: &hir::VariantData,
116 generics: &hir::Generics) -> Union {
117 debug!("Visiting union");
118 let struct_type = struct_type_from_def(&*sd);
121 struct_type: struct_type,
123 vis: item.vis.clone(),
124 stab: self.stability(item.id),
125 depr: self.deprecation(item.id),
126 attrs: item.attrs.clone(),
127 generics: generics.clone(),
128 fields: sd.fields().iter().cloned().collect(),
133 pub fn visit_enum_def(&mut self, it: &hir::Item,
134 name: ast::Name, def: &hir::EnumDef,
135 params: &hir::Generics) -> Enum {
136 debug!("Visiting enum");
139 variants: def.variants.iter().map(|v| Variant {
141 attrs: v.node.attrs.clone(),
142 stab: self.stability(v.node.data.id()),
143 depr: self.deprecation(v.node.data.id()),
144 def: v.node.data.clone(),
148 stab: self.stability(it.id),
149 depr: self.deprecation(it.id),
150 generics: params.clone(),
151 attrs: it.attrs.clone(),
157 pub fn visit_fn(&mut self, item: &hir::Item,
158 name: ast::Name, fd: &hir::FnDecl,
159 unsafety: &hir::Unsafety,
160 constness: hir::Constness,
162 gen: &hir::Generics) -> Function {
163 debug!("Visiting fn");
166 vis: item.vis.clone(),
167 stab: self.stability(item.id),
168 depr: self.deprecation(item.id),
169 attrs: item.attrs.clone(),
173 generics: gen.clone(),
175 constness: constness,
180 pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
181 vis: hir::Visibility, id: ast::NodeId,
183 name: Option<ast::Name>) -> Module {
184 let mut om = Module::new(name);
185 om.where_outer = span;
186 om.where_inner = m.inner;
188 om.vis = vis.clone();
189 om.stab = self.stability(id);
190 om.depr = self.deprecation(id);
192 for i in &m.item_ids {
193 let item = self.cx.map.expect_item(i.id);
194 self.visit_item(item, None, &mut om);
196 if let Some(exports) = self.cx.export_map.get(&id) {
197 for export in exports {
198 if let Def::Macro(def_id) = export.def {
199 if def_id.krate == LOCAL_CRATE {
200 continue // These are `krate.exported_macros`, handled in `self.visit()`.
202 let def = match self.cx.sess().cstore.load_macro(def_id, self.cx.sess()) {
203 LoadedMacro::MacroRules(macro_rules) => macro_rules,
204 // FIXME(jseyfried): document proc macro reexports
205 LoadedMacro::ProcMacro(..) => continue,
208 // FIXME(jseyfried) merge with `self.visit_macro()`
209 let matchers = def.body.chunks(4).map(|arm| arm[0].get_span()).collect();
210 om.macros.push(Macro {
212 attrs: def.attrs.clone().into(),
213 name: def.ident.name,
216 stab: self.stability(def.id),
217 depr: self.deprecation(def.id),
218 imported_from: def.imported_from.map(|ident| ident.name),
226 fn visit_view_path(&mut self, path: hir::ViewPath_,
229 please_inline: bool) -> Option<hir::ViewPath_> {
231 hir::ViewPathSimple(dst, base) => {
232 if self.maybe_inline_local(id, Some(dst), false, om, please_inline) {
235 Some(hir::ViewPathSimple(dst, base))
238 hir::ViewPathList(p, paths) => {
239 let mine = paths.into_iter().filter(|path| {
240 !self.maybe_inline_local(path.node.id, path.node.rename,
241 false, om, please_inline)
242 }).collect::<hir::HirVec<hir::PathListItem>>();
247 Some(hir::ViewPathList(p, mine))
251 hir::ViewPathGlob(base) => {
252 if self.maybe_inline_local(id, None, true, om, please_inline) {
255 Some(hir::ViewPathGlob(base))
262 /// Tries to resolve the target of a `pub use` statement and inlines the
263 /// target if it is defined locally and would not be documented otherwise,
264 /// or when it is specifically requested with `please_inline`.
265 /// (the latter is the case when the import is marked `doc(inline)`)
267 /// Cross-crate inlining occurs later on during crate cleaning
268 /// and follows different rules.
270 /// Returns true if the target has been inlined.
271 fn maybe_inline_local(&mut self, id: ast::NodeId, renamed: Option<ast::Name>,
272 glob: bool, om: &mut Module, please_inline: bool) -> bool {
274 fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
275 while let Some(id) = cx.map.get_enclosing_scope(node) {
277 let attrs = cx.map.attrs(node).clean(cx);
278 if attrs.list("doc").has_word("hidden") {
281 if node == ast::CRATE_NODE_ID {
288 let tcx = match self.cx.tcx_opt() {
292 let def = tcx.expect_def(id);
293 let def_did = def.def_id();
295 let use_attrs = tcx.map.attrs(id).clean(self.cx);
296 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
297 let is_no_inline = use_attrs.list("doc").has_word("no_inline") ||
298 use_attrs.list("doc").has_word("hidden");
300 // For cross-crate impl inlining we need to know whether items are
301 // reachable in documentation - a previously nonreachable item can be
302 // made reachable by cross-crate inlining which we're checking here.
303 // (this is done here because we need to know this upfront)
304 if !def_did.is_local() && !is_no_inline {
305 let attrs = clean::inline::load_attrs(self.cx, tcx, def_did);
306 let self_is_hidden = attrs.list("doc").has_word("hidden");
312 Def::TyAlias(did) if !self_is_hidden => {
313 self.cx.access_levels.borrow_mut().map.insert(did, AccessLevel::Public);
315 Def::Mod(did) => if !self_is_hidden {
316 ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
323 let def_node_id = match tcx.map.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.map.get(def_node_id) {
338 hir_map::NodeItem(it) => {
340 let prev = mem::replace(&mut self.inlining_from_glob, true);
342 hir::ItemMod(ref m) => {
343 for i in &m.item_ids {
344 let i = self.cx.map.expect_item(i.id);
345 self.visit_item(i, None, om);
348 hir::ItemEnum(..) => {}
349 _ => { panic!("glob not mapped to a module or enum"); }
351 self.inlining_from_glob = prev;
353 self.visit_item(it, renamed, om);
359 self.view_item_stack.remove(&def_node_id);
363 pub fn visit_item(&mut self, item: &hir::Item,
364 renamed: Option<ast::Name>, om: &mut Module) {
365 debug!("Visiting item {:?}", item);
366 let name = renamed.unwrap_or(item.name);
368 hir::ItemExternCrate(ref p) => {
369 let cstore = &self.cx.sess().cstore;
370 om.extern_crates.push(ExternCrate {
371 cnum: cstore.extern_mod_stmt_cnum(item.id)
372 .unwrap_or(LOCAL_CRATE),
374 path: p.map(|x|x.to_string()),
375 vis: item.vis.clone(),
376 attrs: item.attrs.clone(),
380 hir::ItemUse(ref vpath) => {
381 let node = vpath.node.clone();
382 let node = if item.vis == hir::Public {
383 let please_inline = item.attrs.iter().any(|item| {
384 match item.meta_item_list() {
385 Some(list) if item.check_name("doc") => {
386 list.iter().any(|i| i.check_name("inline"))
391 match self.visit_view_path(node, om, item.id, please_inline) {
398 om.imports.push(Import {
400 vis: item.vis.clone(),
401 attrs: item.attrs.clone(),
406 hir::ItemMod(ref m) => {
407 om.mods.push(self.visit_mod_contents(item.span,
414 hir::ItemEnum(ref ed, ref gen) =>
415 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
416 hir::ItemStruct(ref sd, ref gen) =>
417 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
418 hir::ItemUnion(ref sd, ref gen) =>
419 om.unions.push(self.visit_union_data(item, name, sd, gen)),
420 hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, _) =>
421 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
422 constness, abi, gen)),
423 hir::ItemTy(ref ty, ref gen) => {
429 attrs: item.attrs.clone(),
431 vis: item.vis.clone(),
432 stab: self.stability(item.id),
433 depr: self.deprecation(item.id),
437 hir::ItemStatic(ref ty, ref mut_, ref exp) => {
440 mutability: mut_.clone(),
444 attrs: item.attrs.clone(),
446 vis: item.vis.clone(),
447 stab: self.stability(item.id),
448 depr: self.deprecation(item.id),
452 hir::ItemConst(ref ty, ref exp) => {
458 attrs: item.attrs.clone(),
460 vis: item.vis.clone(),
461 stab: self.stability(item.id),
462 depr: self.deprecation(item.id),
464 om.constants.push(s);
466 hir::ItemTrait(unsafety, ref gen, ref b, ref items) => {
470 items: items.clone(),
471 generics: gen.clone(),
472 bounds: b.iter().cloned().collect(),
474 attrs: item.attrs.clone(),
476 vis: item.vis.clone(),
477 stab: self.stability(item.id),
478 depr: self.deprecation(item.id),
482 hir::ItemImpl(unsafety, polarity, ref gen, ref tr, ref ty, ref items) => {
486 generics: gen.clone(),
489 items: items.clone(),
490 attrs: item.attrs.clone(),
493 vis: item.vis.clone(),
494 stab: self.stability(item.id),
495 depr: self.deprecation(item.id),
497 // Don't duplicate impls when inlining glob imports, we'll pick
498 // them up regardless of where they're located.
499 if !self.inlining_from_glob {
503 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
504 let i = DefaultImpl {
506 trait_: trait_ref.clone(),
508 attrs: item.attrs.clone(),
511 // see comment above about ItemImpl
512 if !self.inlining_from_glob {
513 om.def_traits.push(i);
516 hir::ItemForeignMod(ref fm) => {
517 om.foreigns.push(fm.clone());
522 // convert each exported_macro into a doc item
523 fn visit_macro(&self, def: &hir::MacroDef) -> Macro {
524 // Extract the spans of all matchers. They represent the "interface" of the macro.
525 let matchers = def.body.chunks(4).map(|arm| arm[0].get_span()).collect();
529 attrs: def.attrs.clone(),
533 stab: self.stability(def.id),
534 depr: self.deprecation(def.id),
535 imported_from: def.imported_from,